Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
helpviewer.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "helpviewer.h"
6
9#include "tracer.h"
10
11#include <QtCore/QFileInfo>
12#include <QtCore/QMimeDatabase>
13#include <QtCore/QStringBuilder>
14#include <QtCore/QTemporaryFile>
15#include <QtCore/QXmlStreamReader>
16#include <QtCore/QXmlStreamWriter>
17
18#include <QtGui/QDesktopServices>
19#if QT_CONFIG(clipboard)
20#include <QtGui/QClipboard>
21#endif
22#include <QtGui/QGuiApplication>
23#include <QtGui/QImageReader>
24#include <QtGui/QStyleHints>
25#include <QtGui/QWheelEvent>
26
27#include <QtWidgets/QMenu>
28#include <QtWidgets/QScrollBar>
29#include <QtWidgets/QVBoxLayout>
30
31#include <QtHelp/QHelpEngineCore>
32
33#include <qlitehtmlwidget.h>
34
35QT_BEGIN_NAMESPACE
36
37using namespace Qt::StringLiterals;
38
39const int kMaxHistoryItems = 20;
40constexpr bool kHasClipboard = QT_CONFIG(clipboard);
41
42static void setClipboardText(const QString &text)
43{
44#if QT_CONFIG(clipboard)
45 QGuiApplication::clipboard()->setText(text);
46#else
47 Q_UNUSED(text)
48#endif
49}
50
51static void setClipboardImage(const QImage &image)
52{
53#if QT_CONFIG(clipboard)
54 QGuiApplication::clipboard()->setImage(image);
55#else
56 Q_UNUSED(image)
57#endif
58}
59
60const struct ExtensionMap {
61 const char *extension;
62 const char *mimeType;
63} extensionMap[] = {
64 { ".bmp", "image/bmp" },
65 { ".css", "text/css" },
66 { ".gif", "image/gif" },
67 { ".html", "text/html" },
68 { ".htm", "text/html" },
69 { ".ico", "image/x-icon" },
70 { ".jpeg", "image/jpeg" },
71 { ".jpg", "image/jpeg" },
72 { ".js", "application/x-javascript" },
73 { ".mng", "video/x-mng" },
74 { ".pbm", "image/x-portable-bitmap" },
75 { ".pgm", "image/x-portable-graymap" },
76 { ".pdf", nullptr },
77 { ".png", "image/png" },
78 { ".ppm", "image/x-portable-pixmap" },
79 { ".rss", "application/rss+xml" },
80 { ".svg", "image/svg+xml" },
81 { ".svgz", "image/svg+xml" },
82 { ".text", "text/plain" },
83 { ".tif", "image/tiff" },
84 { ".tiff", "image/tiff" },
85 { ".txt", "text/plain" },
86 { ".xbm", "image/x-xbitmap" },
87 { ".xml", "text/xml" },
88 { ".xpm", "image/x-xpm" },
89 { ".xsl", "text/xsl" },
90 { ".xhtml", "application/xhtml+xml" },
91 { ".wml", "text/vnd.wap.wml" },
92 { ".wmlc", "application/vnd.wap.wmlc" },
93 { "about:blank", nullptr },
94 { nullptr, nullptr }
95};
96
97static void setLight(QWidget *widget)
98{
99 // Make docs' contents visible in dark theme
100 QPalette p = widget->palette();
101 p.setColor(QPalette::Inactive, QPalette::Highlight,
102 p.color(QPalette::Active, QPalette::Highlight));
103 p.setColor(QPalette::Inactive, QPalette::HighlightedText,
104 p.color(QPalette::Active, QPalette::HighlightedText));
105 p.setColor(QPalette::Base, Qt::white);
106 p.setColor(QPalette::Text, Qt::black);
107 widget->setPalette(p);
108}
109
110static bool isDarkTheme()
111{
112 // Either Qt realizes that it is dark, or the palette exposes it, by having
113 // the window background darker than the text
114 return QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark
115 || QGuiApplication::palette().color(QPalette::Base).lightnessF()
116 < QGuiApplication::palette().color(QPalette::Text).lightnessF();
117}
118
119static void setPaletteFromApp(QWidget *widget)
120{
121 QPalette appPalette = QGuiApplication::palette();
122 // Detach the palette from the application palette, so it doesn't change directly when the
123 // application palette changes.
124 // That ensures that if the system is dark, and dark documentation is show, and the user
125 // switches the system to a light theme, that the documentation background stays dark for the
126 // visible page until either the we got informed by the change in application palette, or the
127 // user switched pages
128 appPalette.setColor(QPalette::Base, appPalette.color(QPalette::Base));
129 widget->setPalette(appPalette);
130}
131
132static QByteArray addDarkThemeToSvg(const QByteArray &data)
133{
134 // Parse the SVG file and attach an attribute to the svg element.
135 QXmlStreamReader reader(data);
136
137 // Assume that the first element is the svg element.
138 if (reader.readNextStartElement()) {
139 if (reader.name() == "svg") {
140 // The character offset refers to the character after the
141 // element start.
142 qint64 rest = reader.characterOffset();
143
144 // Write the svg element to a new byte array, adding an attribute
145 // if the theme is dark.
146 QByteArray newData;
147 QXmlStreamWriter writer(&newData);
148
149 writer.writeStartDocument();
150 writer.writeStartElement("svg");
151 writer.writeAttributes(reader.attributes());
152 writer.writeAttribute("class", "dark");
153
154 // Ensure that the opening tag for the svg element is closed.
155 writer.writeCharacters("");
156
157 // Return the new document start and the rest of the original,
158 // discarding the processing instructions before the svg element.
159 return newData + data.mid(rest);
160 }
161 }
162
163 // The entire file was read without finding an svg element, or an error
164 // occurred, so just return the original data.
165 return data;
166}
167
168static QByteArray getData(const QUrl &url, QWidget *widget)
169{
170 // This is a hack for Qt documentation,
171 // which decides to use a simpler CSS if the viewer does not have JavaScript
172 // which was a hack to decide if we are viewing in QTextBrowser or QtWebEngine et al.
173 // Force it to use the "normal" offline CSS even without JavaScript, since litehtml can
174 // handle that, and inject a dark themed CSS into Qt documentation for dark Qt Creator themes
175 QUrl actualUrl = url;
176 QString path = url.path(QUrl::FullyEncoded);
177 static const char simpleCss[] = "/offline-simple.css";
178 if (path.endsWith(simpleCss)) {
179 if (isDarkTheme()) {
180 // check if dark CSS is shipped with documentation
181 QString darkPath = path;
182 darkPath.replace(simpleCss, "/offline-dark.css");
183 actualUrl.setPath(darkPath);
184 QByteArray data = HelpEngineWrapper::instance().fileData(actualUrl);
185 if (!data.isEmpty()) {
186 // we found the dark style
187 // set background dark (by using app palette)
188 setPaletteFromApp(widget);
189 return data;
190 }
191 }
192 path.replace(simpleCss, "/offline.css");
193 actualUrl.setPath(path);
194 }
195
196 if (actualUrl.isValid()) {
197 const QByteArray data = HelpEngineWrapper::instance().fileData(actualUrl);
198 if (isDarkTheme() && path.endsWith(".svg"))
199 return addDarkThemeToSvg(data);
200 else
201 return data;
202 }
203
204 const bool isAbout = (actualUrl.toString() == "about:blank"_L1);
205 return isAbout ? HelpViewerImpl::AboutBlank.toUtf8()
206 : HelpViewerImpl::PageNotFoundMessage.arg(url.toString()).toUtf8();
207}
208
210{
211public:
213 {
214 QUrl url;
217 };
219 void setSourceInternal(const QUrl &url, int *vscroll = nullptr, bool reload = false);
220 void incrementZoom(int steps);
221 void applyZoom(int percentage);
222 void openInNewPage(const QUrl &url);
223 void showContextMenu(const QPoint &pos, const QUrl &link, const QUrl &imageUrl);
224
225 HelpViewer *q = nullptr;
229 int m_fontZoom = 100; // zoom percentage
231};
232
234{
235 return { m_viewer->url(), m_viewer->title(), m_viewer->verticalScrollBar()->value() };
236}
237
238void HelpViewerPrivate::setSourceInternal(const QUrl &url, int *vscroll, bool reload)
239{
240 QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
241
242 const bool isHelp = (url.toString() == "help"_L1);
243 const QUrl resolvedUrl = (isHelp ? QUrl(HelpViewerImpl::LocalHelpFile)
244 : HelpEngineWrapper::instance().findFile(url));
245
246 QUrl currentUrlWithoutFragment = m_viewer->url();
247 currentUrlWithoutFragment.setFragment({});
248 QUrl newUrlWithoutFragment = resolvedUrl;
249 newUrlWithoutFragment.setFragment({});
250
251 m_viewer->setUrl(resolvedUrl);
252 if (currentUrlWithoutFragment != newUrlWithoutFragment || reload) {
253 // Users can register arbitrary documentation, so we do not expect the documentation to
254 // support dark themes, and start with light palette.
255 // We override this if we find Qt's dark style
256 setLight(q);
257 QMimeDatabase mimeDb;
258 const QMimeType mimeType = mimeDb.mimeTypeForFile(url.fileName(),
259 QMimeDatabase::MatchExtension);
260 if (QImageReader::supportedMimeTypes().contains(mimeType.name().toUtf8())) {
261 m_viewer->setHtml(QString("<html><head><title>%1</title></head>"
262 "<body><img src=\"%2\"/></body></html>")
263 .arg(url.fileName().toHtmlEscaped(),
264 QString::fromUtf8(url.toEncoded())));
265 } else {
266 m_viewer->setHtml(QString::fromUtf8(getData(resolvedUrl, q)));
267 }
268 }
269 if (vscroll)
270 m_viewer->verticalScrollBar()->setValue(*vscroll);
271 else
272 m_viewer->scrollToAnchor(resolvedUrl.fragment(QUrl::FullyEncoded));
273
274 QGuiApplication::restoreOverrideCursor();
275
276 emit q->sourceChanged(q->source());
277 emit q->loadFinished();
278 emit q->titleChanged();
279}
280
282{
283 const int incrementPercentage = 10 * steps; // 10 percent increase by single step
284 const int previousZoom = m_fontZoom;
285 applyZoom(previousZoom + incrementPercentage);
286}
287
288void HelpViewerPrivate::applyZoom(int percentage)
289{
290 const int newZoom = qBound(10, percentage, 300);
291 if (newZoom == m_fontZoom)
292 return;
293 m_fontZoom = newZoom;
294 m_viewer->setZoomFactor(newZoom / 100.0);
295}
296
297void HelpViewerPrivate::openInNewPage(const QUrl &url)
298{
299 if (!url.isEmpty() && url.isValid())
300 OpenPagesManager::instance()->createPage(url);
301}
302
303void HelpViewerPrivate::showContextMenu(const QPoint &pos, const QUrl &link,
304 const QUrl &imageUrl)
305{
306 QMenu menu;
307 const bool hasLink = !link.isEmpty() && link.isValid();
308 const bool hasImage = !imageUrl.isEmpty() && imageUrl.isValid();
309 if (hasLink) {
310 menu.addAction(HelpViewer::tr("Open Link"), q, [this, link] { q->setSource(link); });
311 menu.addAction(HelpViewer::tr("Open Link in New Tab\tCtrl+LMB"), q,
312 [this, link] { openInNewPage(link); });
313 if (kHasClipboard) {
314 menu.addAction(HelpViewer::tr("Copy &Link Location"), q,
315 [link] { setClipboardText(link.toString()); });
316 }
317 }
318 if (hasImage) {
319 if (hasLink)
320 menu.addSeparator();
321 menu.addAction(HelpViewer::tr("Open Image"), q,
322 [this, imageUrl] { q->setSource(imageUrl); });
323 menu.addAction(HelpViewer::tr("Open Image in New Tab"), q,
324 [this, imageUrl] { openInNewPage(imageUrl); });
325 if (kHasClipboard) {
326 menu.addAction(HelpViewer::tr("Copy Image"), q, [this, imageUrl] {
327 setClipboardImage(QImage::fromData(getData(imageUrl, q)));
328 });
329 menu.addAction(HelpViewer::tr("Copy Image Location"), q,
330 [imageUrl] { setClipboardText(imageUrl.toString()); });
331 }
332 }
333 if (!hasLink && !hasImage) {
334 if (kHasClipboard && !q->selectedText().isEmpty()) {
335 menu.addAction(HelpViewer::tr("Copy"), q,
336 [this] { setClipboardText(q->selectedText()); });
337 } else {
338 menu.addAction(HelpViewer::tr("Reload"), q, &HelpViewer::reload);
339 }
340 }
341 menu.exec(m_viewer->viewport()->mapToGlobal(pos));
342}
343
344HelpViewer::HelpViewer(qreal zoom, QWidget *parent)
345 : QWidget(parent)
346 , d(new HelpViewerPrivate)
347{
348 auto layout = new QVBoxLayout;
349 d->q = this;
350 d->m_viewer = new QLiteHtmlWidget(this);
351 d->m_viewer->setResourceHandler([this](const QUrl &url) { return getData(url, this); });
352 d->m_viewer->viewport()->installEventFilter(this);
353 const int zoomPercentage = zoom == 0 ? 100 : zoom * 100;
354 d->applyZoom(zoomPercentage);
355 connect(d->m_viewer, &QLiteHtmlWidget::linkClicked, this, [this](const QUrl &url) {
356 if (QGuiApplication::keyboardModifiers() & Qt::ControlModifier)
358 else
359 setSource(url);
360 });
361 connect(d->m_viewer, &QLiteHtmlWidget::linkHighlighted, this, [this](const QUrl &url) {
362 d->m_highlightedLink = url;
363 emit highlighted(url);
364 });
365 connect(d->m_viewer, &QLiteHtmlWidget::contextMenuRequested, this,
366 [this](const QPoint &pos, const QUrl &link, const QUrl &imageUrl) {
367 d->showContextMenu(pos, link, imageUrl);
368 });
369#if QT_CONFIG(clipboard)
370 connect(d->m_viewer, &QLiteHtmlWidget::copyAvailable, this, &HelpViewer::copyAvailable);
371#endif
372 setLayout(layout);
373 layout->setContentsMargins(0, 0, 0, 0);
374 layout->addWidget(d->m_viewer, 10);
375
376 // If the platform supports it, changes of color scheme light/dark take effect during runtime:
377 connect(
378 QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, this,
379 [this] {
380 int vscroll = d->m_viewer->verticalScrollBar()->value();
381 d->setSourceInternal(source(), &vscroll, /*reload*/ true);
382 },
383 // Queue to make sure that the palette is actually applied on the application
384 Qt::QueuedConnection);
385}
386
388{
389 delete d;
390}
391
393{
394 return d->m_viewer->defaultFont();
395}
396
397void HelpViewer::setViewerFont(const QFont &font)
398{
399 d->m_viewer->setDefaultFont(font);
400}
401
403{
405}
406
408{
410}
411
413{
414 d->applyZoom(100);
415}
416
418{
419 return d->m_viewer->zoomFactor();
420}
421
423{
424 return d->m_viewer->title();
425}
426
427QUrl HelpViewer::source() const
428{
429 return d->m_viewer->url();
430}
431
433{
434 doSetSource(source(), true);
435}
436
437void HelpViewer::setSource(const QUrl &url)
438{
439 doSetSource(url, false);
440}
441
443{
444 d->m_viewer->setFocus();
445}
446
447void HelpViewer::doSetSource(const QUrl &url, bool reload)
448{
449 if (launchWithExternalApp(url))
450 return;
451
452 d->m_forwardItems.clear();
453 emit forwardAvailable(false);
454 if (d->m_viewer->url().isValid()) {
455 d->m_backItems.push_back(d->currentHistoryItem());
456 while (d->m_backItems.size() > kMaxHistoryItems) // this should trigger only once anyhow
457 d->m_backItems.erase(d->m_backItems.begin());
458 emit backwardAvailable(true);
459 }
460
461 d->setSourceInternal(url, nullptr, reload);
462}
463
464#if defined(QT_PRINTSUPPORT_LIB) && !defined(QT_NO_PRINTER)
465void HelpViewer::print(QPrinter *printer)
466{
467 d->m_viewer->print(printer);
468}
469#endif
470
472{
473 return d->m_viewer->selectedText();
474}
475
477{
478 return !d->m_forwardItems.empty();
479}
480
482{
483 return !d->m_backItems.empty();
484}
485
486static QTextDocument::FindFlags textDocumentFlagsForFindFlags(HelpViewer::FindFlags flags)
487{
488 QTextDocument::FindFlags textDocFlags;
489 if (flags & HelpViewer::FindBackward)
490 textDocFlags |= QTextDocument::FindBackward;
491 if (flags & HelpViewer::FindCaseSensitively)
492 textDocFlags |= QTextDocument::FindCaseSensitively;
493 return textDocFlags;
494}
495
496bool HelpViewer::findText(const QString &text, FindFlags flags, bool incremental, bool fromSearch)
497{
498 Q_UNUSED(fromSearch);
499 return d->m_viewer->findText(text, textDocumentFlagsForFindFlags(flags), incremental);
500}
501
502#if QT_CONFIG(clipboard)
503void HelpViewer::copy()
504{
505 QGuiApplication::clipboard()->setText(selectedText());
506}
507#endif
508
509void HelpViewer::home()
510{
511 setSource(QUrl(HelpEngineWrapper::instance().homePage()));
512}
513
515{
517 if (d->m_forwardItems.empty())
518 return;
519 d->m_backItems.push_back(nextItem);
520 nextItem = d->m_forwardItems.front();
521 d->m_forwardItems.erase(d->m_forwardItems.begin());
522
523 emit backwardAvailable(isBackwardAvailable());
524 emit forwardAvailable(isForwardAvailable());
525 d->setSourceInternal(nextItem.url, &nextItem.vscroll);
526}
527
529{
531 if (d->m_backItems.empty())
532 return;
533 d->m_forwardItems.insert(d->m_forwardItems.begin(), previousItem);
534 previousItem = d->m_backItems.back();
535 d->m_backItems.pop_back();
536
537 emit backwardAvailable(isBackwardAvailable());
538 emit forwardAvailable(isForwardAvailable());
539 d->setSourceInternal(previousItem.url, &previousItem.vscroll);
540}
541
542bool HelpViewer::eventFilter(QObject *src, QEvent *event)
543{
544 if (event->type() == QEvent::Wheel) {
545 auto we = static_cast<QWheelEvent *>(event);
546 if (we->modifiers() == Qt::ControlModifier) {
547 we->accept();
548 const int deltaY = we->angleDelta().y();
549 if (deltaY != 0)
550 d->incrementZoom(deltaY / 120);
551 return true;
552 }
553 } else if (event->type() == QEvent::MouseButtonRelease) {
554 // Ctrl+LMB is handled when the link is clicked, as litehtml only reacts on the left button.
555 auto me = static_cast<QMouseEvent *>(event);
556 if (me->button() == Qt::MiddleButton && !d->m_highlightedLink.isEmpty()
557 && d->m_highlightedLink.isValid()) {
558 me->accept();
559 d->openInNewPage(d->m_highlightedLink);
560 return true;
561 }
562 }
563 return QWidget::eventFilter(src, event);
564}
565
566bool HelpViewer::isLocalUrl(const QUrl &url)
567{
569 const QString &scheme = url.scheme();
570 return scheme.isEmpty()
571 || scheme == "file"_L1
572 || scheme == "qrc"_L1
573 || scheme == "data"_L1
574 || scheme == "qthelp"_L1
575 || scheme == "about"_L1;
576}
577
578bool HelpViewer::canOpenPage(const QString &path)
579{
581 return !mimeFromUrl(QUrl::fromLocalFile(path)).isEmpty();
582}
583
584QString HelpViewer::mimeFromUrl(const QUrl &url)
585{
587 const QString &path = url.path();
588 const int index = path.lastIndexOf(u'.');
589 const QByteArray &ext = path.mid(index).toUtf8().toLower();
590
591 const ExtensionMap *e = extensionMap;
592 while (e->extension) {
593 if (ext == e->extension)
594 return QLatin1StringView(e->mimeType);
595 ++e;
596 }
597 return "application/octet-stream"_L1;
598}
599
600bool HelpViewer::launchWithExternalApp(const QUrl &url)
601{
603 if (isLocalUrl(url)) {
605 const QUrl &resolvedUrl = helpEngine.findFile(url);
606 if (!resolvedUrl.isValid())
607 return false;
608
609 const QString& path = resolvedUrl.toLocalFile();
610 if (!canOpenPage(path)) {
611 QTemporaryFile tmpTmpFile;
612 if (!tmpTmpFile.open())
613 return false;
614
615 const QString &extension = QFileInfo(path).completeSuffix();
616 QFile actualTmpFile(tmpTmpFile.fileName() % "."_L1 % extension);
617 if (!actualTmpFile.open(QIODevice::ReadWrite | QIODevice::Truncate))
618 return false;
619
620 actualTmpFile.write(helpEngine.fileData(resolvedUrl));
621 actualTmpFile.close();
622 return QDesktopServices::openUrl(QUrl::fromLocalFile(actualTmpFile.fileName()));
623 }
624 return false;
625 }
626 return QDesktopServices::openUrl(url);
627}
628
629QT_END_NAMESPACE
static HelpEngineWrapper & instance()
void showContextMenu(const QPoint &pos, const QUrl &link, const QUrl &imageUrl)
HistoryItem currentHistoryItem() const
void openInNewPage(const QUrl &url)
std::vector< HistoryItem > m_backItems
std::vector< HistoryItem > m_forwardItems
void applyZoom(int percentage)
QLiteHtmlWidget * m_viewer
void incrementZoom(int steps)
void setSourceInternal(const QUrl &url, int *vscroll=nullptr, bool reload=false)
void setViewerFont(const QFont &font)
void scaleUp()
QString title() const
void resetScale()
QString selectedText() const
void forward()
void scaleDown()
void reload()
bool isForwardAvailable() const
void backward()
QFont viewerFont() const
~HelpViewer() override
QUrl source() const
bool findText(const QString &text, FindFlags flags, bool incremental, bool fromSearch)
qreal scale() const
bool isBackwardAvailable() const
bool eventFilter(QObject *src, QEvent *event) override
Filters events if this object has been installed as an event filter for the watched object.
void doSetFocus()
static OpenPagesManager * instance()
static void setPaletteFromApp(QWidget *widget)
static QByteArray addDarkThemeToSvg(const QByteArray &data)
static bool isDarkTheme()
static void setLight(QWidget *widget)
static void setClipboardImage(const QImage &image)
static QTextDocument::FindFlags textDocumentFlagsForFindFlags(HelpViewer::FindFlags flags)
static QByteArray getData(const QUrl &url, QWidget *widget)
const int kMaxHistoryItems
static void setClipboardText(const QString &text)
constexpr bool kHasClipboard
const char * mimeType
const char * extension
#define TRACE_OBJ
Definition tracer.h:34