| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "gui/webviewers/qtextbrowser/textbrowserviewer.h" |
| 4 | |
| 5 | #include "3rd-party/boolinq/boolinq.h" |
| 6 | #include "definitions/globals.h" |
| 7 | #include "gui/dialogs/formmain.h" |
| 8 | #include "gui/webbrowser.h" |
| 9 | #include "miscellaneous/application.h" |
| 10 | #include "miscellaneous/externaltool.h" |
| 11 | #include "miscellaneous/iconfactory.h" |
| 12 | #include "miscellaneous/settings.h" |
| 13 | #include "network-web/adblock/adblockrequestinfo.h" |
| 14 | #include "network-web/downloader.h" |
| 15 | #include "network-web/networkfactory.h" |
| 16 | #include "network-web/webfactory.h" |
| 17 | |
| 18 | #include <QBuffer> |
| 19 | #include <QContextMenuEvent> |
| 20 | #include <QFileIconProvider> |
| 21 | #include <QScrollBar> |
| 22 | #include <QTextCodec> |
| 23 | #include <QTimer> |
| 24 | #include <QtConcurrent> |
| 25 | |
| 26 | TextBrowserViewer::TextBrowserViewer(QWidget* parent) |
| 27 | : QTextBrowser(parent), m_resourcesEnabled(false), m_resourceDownloader(new Downloader()), |
| 28 | m_resourceDownloaderThread(new QThread(this)), m_loadedResources({}), |
| 29 | m_placeholderImage(qApp->icons()->miscPixmap(QSL("image-placeholder"))), |
| 30 | m_placeholderImageError(qApp->icons()->miscPixmap(QSL("image-placeholder-error"))), |
| 31 | m_downloader(new Downloader(this)), m_document(new TextBrowserDocument(this)) { |
| 32 | setAutoFillBackground(false); |
| 33 | setFrameShape(QFrame::Shape::NoFrame); |
| 34 | setFrameShadow(QFrame::Shadow::Plain); |
| 35 | setTabChangesFocus(true); |
| 36 | setOpenLinks(false); |
| 37 | setWordWrapMode(QTextOption::WrapMode::WordWrap); |
| 38 | |
| 39 | viewport()->setAutoFillBackground(false); |
| 40 | |
| 41 | setResourcesEnabled(qApp->settings()->value(GROUP(Messages), SETTING(Messages::ShowResourcesInArticles)).toBool()); |
| 42 | setDocument(m_document.data()); |
| 43 | |
| 44 | m_resourceDownloader->moveToThread(m_resourceDownloaderThread); |
| 45 | m_resourceDownloaderThread->start(QThread::Priority::LowPriority); |
| 46 | |
| 47 | connect(this, &TextBrowserViewer::reloadDocument, this, [this]() { |
| 48 | const auto scr = verticalScrollBarPosition(); |
| 49 | setHtmlPrivate(html(), m_currentUrl); |
| 50 | setVerticalScrollBarPosition(scr); |
| 51 | }); |
| 52 | |
| 53 | connect(m_resourceDownloader, &Downloader::completed, this, &TextBrowserViewer::resourceDownloaded); |
| 54 | connect(this, &QTextBrowser::anchorClicked, this, &TextBrowserViewer::onAnchorClicked); |
| 55 | connect(this, QOverload<const QUrl&>::of(&QTextBrowser::highlighted), this, &TextBrowserViewer::linkMouseHighlighted); |
| 56 | } |
| 57 | |
| 58 | TextBrowserViewer::~TextBrowserViewer() { |
| 59 | m_resourceDownloaderThread->quit(); |
| 60 | m_resourceDownloaderThread->wait(); |
| 61 | m_resourceDownloaderThread->deleteLater(); |
| 62 | m_resourceDownloader->deleteLater(); |
| 63 | } |
| 64 | |
| 65 | QSize TextBrowserViewer::sizeHint() const { |
| 66 | auto doc_size = document()->size().toSize(); |
| 67 | |
| 68 | doc_size.setHeight(doc_size.height() + contentsMargins().top() + contentsMargins().bottom()); |
| 69 | return doc_size; |
| 70 | } |
| 71 | |
| 72 | QVariant TextBrowserViewer::loadOneResource(int type, const QUrl& name) { |
| 73 | if (type != QTextDocument::ResourceType::ImageResource) { |
| 74 | return {}; |
| 75 | } |
| 76 | |
| 77 | auto resolved_name = (m_currentUrl.isValid() && name.isRelative()) ? m_currentUrl.resolved(name) : name; |
| 78 | |
| 79 | if (!m_resourcesEnabled || !m_loadedResources.contains(resolved_name)) { |
| 80 | // Resources are not enabled. |
| 81 | return m_placeholderImage; |
| 82 | } |
| 83 | |
| 84 | // Resources are enabled and we already have the resource. |
| 85 | int acceptable_width = int(width() * ACCEPTABLE_IMAGE_PERCENTUAL_WIDTH); |
| 86 | |
| 87 | QMap<int, QByteArray>& resource_data_all_sizes = m_loadedResources[resolved_name]; |
| 88 | QImage img; |
| 89 | |
| 90 | qDebugNN << LOGSEC_GUI << "Picture" << QUOTE_W_SPACE(name) |
| 91 | << "has these sizes cached:" << NONQUOTE_W_SPACE_DOT(resource_data_all_sizes.keys()); |
| 92 | |
| 93 | if (resource_data_all_sizes.isEmpty()) { |
| 94 | img = m_placeholderImageError.toImage(); |
| 95 | } |
| 96 | else { |
| 97 | // Now, we either select specifically sized picture, or default one. |
| 98 | QByteArray resource_data; |
| 99 | |
| 100 | if (resource_data_all_sizes.contains(acceptable_width)) { |
| 101 | // We have picture with this exact size. The picture was likely downsized |
| 102 | // to this size before. |
| 103 | resource_data = resource_data_all_sizes.value(acceptable_width); |
| 104 | } |
| 105 | else { |
| 106 | // We only have default size or not desired size. Return initial picture. |
| 107 | resource_data = resource_data_all_sizes.value(0); |
| 108 | } |
| 109 | |
| 110 | img = QImage::fromData(resource_data); |
| 111 | } |
| 112 | |
| 113 | int img_width = img.width(); |
| 114 | |
| 115 | if (img_width > acceptable_width) { |
| 116 | QElapsedTimer tmr; |
| 117 | |
| 118 | tmr.start(); |
| 119 | img = img.scaledToWidth(acceptable_width, Qt::TransformationMode::SmoothTransformation); |
| 120 | |
| 121 | qWarningNN << LOGSEC_GUI << "Picture" << QUOTE_W_SPACE(name) << "with width" << QUOTE_W_SPACE(img_width) |
| 122 | << "is too wide, down-scaling to prevent horizontal scrollbars. Scaling took" |
| 123 | << NONQUOTE_W_SPACE(tmr.elapsed()) << "miliseconds."; |
| 124 | |
| 125 | QByteArray save_arr; |
| 126 | QBuffer save_buf(&save_arr, this); |
| 127 | |
| 128 | if (img.save(&save_buf, "JPG", 100)) { |
| 129 | save_buf.close(); |
| 130 | |
| 131 | /* |
| 132 | IOFactory::writeFile(QSL("%1%2.jpg") |
| 133 | .arg(name.toString(QUrl::ComponentFormattingOption::FullyEncoded), |
| 134 | QString::number(acceptable_width)) |
| 135 | .remove(QRegularExpression(":|\\/")), |
| 136 | save_arr); |
| 137 | */ |
| 138 | |
| 139 | resource_data_all_sizes.insert(acceptable_width, save_arr); |
| 140 | } |
| 141 | else { |
| 142 | qWarningNN << LOGSEC_GUI << "Failed to save modified image" << QUOTE_W_SPACE(name) << "to cache."; |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | return img; |
| 147 | } |
| 148 | |
| 149 | void TextBrowserViewer::bindToBrowser(WebBrowser* browser) { |
| 150 | installEventFilter(browser); |
| 151 | |
| 152 | browser->m_actionBack = nullptr; |
| 153 | browser->m_actionForward = nullptr; |
| 154 | browser->m_actionReload = nullptr; |
| 155 | browser->m_actionStop = nullptr; |
| 156 | } |
| 157 | |
| 158 | void TextBrowserViewer::findText(const QString& text, bool backwards) { |
| 159 | if (!text.isEmpty()) { |
| 160 | bool found = |
| 161 | QTextBrowser::find(text, backwards ? QTextDocument::FindFlag::FindBackward : QTextDocument::FindFlag(0)); |
| 162 | |
| 163 | if (!found) { |
| 164 | textCursor().clearSelection(); |
| 165 | moveCursor(QTextCursor::MoveOperation::Start); |
| 166 | |
| 167 | QTextBrowser::find(text, backwards ? QTextDocument::FindFlag::FindBackward : QTextDocument::FindFlag(0)); |
| 168 | } |
| 169 | } |
| 170 | else { |
| 171 | textCursor().clearSelection(); |
| 172 | moveCursor(QTextCursor::MoveOperation::Start); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | BlockingResult TextBrowserViewer::blockedWithAdblock(const QUrl& url) { |
| 177 | AdblockRequestInfo block_request(url); |
| 178 | |
| 179 | if (url.path().endsWith(QSL("css"))) { |
| 180 | block_request.setResourceType(QSL("stylesheet")); |
| 181 | } |
| 182 | else { |
| 183 | block_request.setResourceType(QSL("image")); |
| 184 | } |
| 185 | |
| 186 | auto block_result = qApp->web()->adBlock()->block(block_request); |
| 187 | |
| 188 | if (block_result.m_blocked) { |
| 189 | qWarningNN << LOGSEC_ADBLOCK << "Blocked request:" << QUOTE_W_SPACE_DOT(block_request.requestUrl().toString()); |
| 190 | return block_result; |
| 191 | } |
| 192 | else { |
| 193 | return block_result; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | void TextBrowserViewer::setUrl(const QUrl& url) { |
| 198 | emit loadingStarted(); |
| 199 | |
| 200 | QString html_str; |
| 201 | QUrl nonconst_url = url; |
| 202 | bool is_error = false; |
| 203 | auto block_result = blockedWithAdblock(url); |
| 204 | |
| 205 | if (block_result.m_blocked) { |
| 206 | is_error = true; |
| 207 | nonconst_url = QUrl::fromUserInput(QSL(INTERNAL_URL_ADBLOCKED)); |
| 208 | |
| 209 | html_str = QSL("Blocked!!!<br/>%1").arg(url.toString()); |
| 210 | } |
| 211 | else { |
| 212 | QEventLoop loop; |
| 213 | |
| 214 | connect(m_downloader.data(), |
| 215 | &Downloader::completed, |
| 216 | &loop, |
| 217 | &QEventLoop::quit, |
| 218 | Qt::ConnectionType(Qt::ConnectionType::UniqueConnection | Qt::ConnectionType::AutoConnection)); |
| 219 | m_downloader->manipulateData(url.toString(), QNetworkAccessManager::Operation::GetOperation, {}, 5000); |
| 220 | |
| 221 | loop.exec(); |
| 222 | |
| 223 | const auto net_error = m_downloader->lastOutputError(); |
| 224 | const QString content_type = m_downloader->lastContentType(); |
| 225 | |
| 226 | if (net_error != QNetworkReply::NetworkError::NoError) { |
| 227 | is_error = true; |
| 228 | html_str = QSL("Error!<br/>%1").arg(NetworkFactory::networkErrorText(net_error)); |
| 229 | } |
| 230 | else { |
| 231 | if (content_type.startsWith(QSL("image/"))) { |
| 232 | html_str = QSL("<img src=\"%1\">").arg(nonconst_url.toString()); |
| 233 | } |
| 234 | else { |
| 235 | html_str = decodeHtmlData(m_downloader->lastOutputData(), content_type); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | setHtml(html_str, nonconst_url); |
| 241 | |
| 242 | emit loadingFinished(!is_error); |
| 243 | } |
| 244 | |
| 245 | QString TextBrowserViewer::decodeHtmlData(const QByteArray& data, const QString& content_type) const { |
| 246 | QString found_charset = QRegularExpression("charset=([0-9a-zA-Z-_]+)").match(content_type).captured(1); |
| 247 | QTextCodec* codec = QTextCodec::codecForName(found_charset.toLocal8Bit()); |
| 248 | |
| 249 | if (codec == nullptr) { |
| 250 | // No suitable codec for this encoding was found. |
| 251 | // Use UTF-8. |
| 252 | qWarningNN << LOGSEC_GUI << "Did not find charset for content-type" << QUOTE_W_SPACE_DOT(content_type); |
| 253 | return QString::fromUtf8(data); |
| 254 | } |
| 255 | else { |
| 256 | qDebugNN << LOGSEC_GUI << "Found charset for content-type" << QUOTE_W_SPACE_DOT(content_type); |
| 257 | return codec->toUnicode(data); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | QString TextBrowserViewer::html() const { |
| 262 | return m_currentHtml; |
| 263 | } |
| 264 | |
| 265 | QUrl TextBrowserViewer::url() const { |
| 266 | return m_currentUrl; |
| 267 | } |
| 268 | |
| 269 | void TextBrowserViewer::clear() { |
| 270 | setHtml({}); |
| 271 | } |
| 272 | |
| 273 | void TextBrowserViewer::loadMessages(const QList<Message>& messages, RootItem* root) { |
| 274 | emit loadingStarted(); |
| 275 | m_root = root; |
| 276 | |
| 277 | auto html_messages = htmlForMessages(messages, root); |
| 278 | |
| 279 | /* |
| 280 | // Replace base64 images. |
| 281 | QRegularExpression exp_base64("src=\"data: ?image\\/[^;]+;base64,([^\"]+)\""); |
| 282 | QRegularExpressionMatch exp_base64_match; |
| 283 | |
| 284 | while ((exp_base64_match = exp_base64.match(html_messages.m_html)).hasMatch()) { |
| 285 | QString base64_img = exp_base64_match.captured(1); |
| 286 | QByteArray data_img = QByteArray::fromBase64Encoding(base64_img); |
| 287 | } |
| 288 | */ |
| 289 | |
| 290 | #if !defined(NDEBUG) |
| 291 | // IOFactory::writeFile("aaa.html", html_messages.m_html.toUtf8()); |
| 292 | #endif |
| 293 | |
| 294 | setHtml(html_messages.m_html, html_messages.m_baseUrl); |
| 295 | |
| 296 | QTextOption op; |
| 297 | op.setTextDirection((messages.at(0).m_rtlBehavior == RtlBehavior::Everywhere || |
| 298 | messages.at(0).m_rtlBehavior == RtlBehavior::EverywhereExceptFeedList || |
| 299 | messages.at(0).m_rtlBehavior == RtlBehavior::OnlyViewer) |
| 300 | ? Qt::LayoutDirection::RightToLeft |
| 301 | : Qt::LayoutDirection::LeftToRight); |
| 302 | document()->setDefaultTextOption(op); |
| 303 | |
| 304 | emit loadingFinished(true); |
| 305 | } |
| 306 | |
| 307 | PreparedHtml TextBrowserViewer::htmlForMessages(const QList<Message>& messages, RootItem* root) const { |
| 308 | auto html_messages = |
| 309 | qApp->settings()->value(GROUP(Messages), SETTING(Messages::UseLegacyArticleFormat)).toBool() |
| 310 | ? prepareLegacyHtmlForMessage(messages, root) |
| 311 | : qApp->skins()->generateHtmlOfArticles(messages, root, width() * ACCEPTABLE_IMAGE_PERCENTUAL_WIDTH); |
| 312 | |
| 313 | // Remove other characters which cannot be displayed properly. |
| 314 | static QRegularExpression exp_symbols("[0-9A-F]{3};"); |
| 315 | |
| 316 | html_messages.m_html = html_messages.m_html.replace(exp_symbols, QString()); |
| 317 | |
| 318 | return html_messages; |
| 319 | } |
| 320 | |
| 321 | double TextBrowserViewer::verticalScrollBarPosition() const { |
| 322 | return verticalScrollBar()->value(); |
| 323 | } |
| 324 | |
| 325 | void TextBrowserViewer::setVerticalScrollBarPosition(double pos) { |
| 326 | verticalScrollBar()->setValue(int(pos)); |
| 327 | } |
| 328 | |
| 329 | void TextBrowserViewer::applyFont(const QFont& fon) { |
| 330 | m_baseFont = fon; |
| 331 | setFont(fon); |
| 332 | setZoomFactor(zoomFactor()); |
| 333 | } |
| 334 | |
| 335 | qreal TextBrowserViewer::zoomFactor() const { |
| 336 | return m_zoomFactor; |
| 337 | } |
| 338 | |
| 339 | void TextBrowserViewer::setZoomFactor(qreal zoom_factor) { |
| 340 | m_zoomFactor = zoom_factor; |
| 341 | |
| 342 | auto fon = font(); |
| 343 | |
| 344 | fon.setPointSizeF(m_baseFont.pointSizeF() * zoom_factor); |
| 345 | |
| 346 | setFont(fon); |
| 347 | } |
| 348 | |
| 349 | void TextBrowserViewer::contextMenuEvent(QContextMenuEvent* event) { |
| 350 | event->accept(); |
| 351 | |
| 352 | auto* menu = createStandardContextMenu(event->pos()); |
| 353 | |
| 354 | if (menu == nullptr) { |
| 355 | return; |
| 356 | } |
| 357 | |
| 358 | /* |
| 359 | connect(menu, &QMenu::aboutToHide, this, [menu] { |
| 360 | menu->deleteLater(); |
| 361 | });*/ |
| 362 | |
| 363 | if (m_actionEnableResources.isNull()) { |
| 364 | m_actionEnableResources.reset(new QAction(qApp->icons()->fromTheme(QSL("viewimage"), QSL("image-x-generic")), |
| 365 | tr("Enable external resources"), |
| 366 | this)); |
| 367 | m_actionDownloadLink.reset(new QAction(qApp->icons()->fromTheme(QSL("download")), tr("Download"), this)); |
| 368 | |
| 369 | m_actionEnableResources.data()->setCheckable(true); |
| 370 | m_actionEnableResources.data()->setChecked(resourcesEnabled()); |
| 371 | |
| 372 | connect(m_actionDownloadLink.data(), &QAction::triggered, this, &TextBrowserViewer::downloadLink); |
| 373 | connect(m_actionEnableResources.data(), &QAction::toggled, this, &TextBrowserViewer::enableResources); |
| 374 | } |
| 375 | |
| 376 | menu->addAction(m_actionEnableResources.data()); |
| 377 | menu->addAction(m_actionDownloadLink.data()); |
| 378 | |
| 379 | auto anchor = anchorAt(event->pos()); |
| 380 | |
| 381 | m_lastContextMenuPos = event->pos(); |
| 382 | m_actionDownloadLink.data()->setEnabled(!anchor.isEmpty()); |
| 383 | |
| 384 | processContextMenu(menu, event); |
| 385 | |
| 386 | menu->popup(event->globalPos()); |
| 387 | } |
| 388 | |
| 389 | void TextBrowserViewer::resizeEvent(QResizeEvent* event) { |
| 390 | // Notify parents about changed geometry. |
| 391 | updateGeometry(); |
| 392 | QTextBrowser::resizeEvent(event); |
| 393 | } |
| 394 | |
| 395 | void TextBrowserViewer::wheelEvent(QWheelEvent* event) { |
| 396 | // NOTE: Skip base class implemetation. |
| 397 | QAbstractScrollArea::wheelEvent(event); |
| 398 | updateMicroFocus(); |
| 399 | } |
| 400 | |
| 401 | void TextBrowserViewer::enableResources(bool enable) { |
| 402 | qApp->settings()->setValue(GROUP(Messages), Messages::ShowResourcesInArticles, enable); |
| 403 | setResourcesEnabled(enable); |
| 404 | } |
| 405 | |
| 406 | void TextBrowserViewer::downloadLink() { |
| 407 | auto url = QUrl(anchorAt(m_lastContextMenuPos)); |
| 408 | |
| 409 | if (url.isValid()) { |
| 410 | const QUrl resolved_url = (m_currentUrl.isValid() && url.isRelative()) ? m_currentUrl.resolved(url) : url; |
| 411 | |
| 412 | qApp->downloadManager()->download(resolved_url); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | void TextBrowserViewer::onAnchorClicked(const QUrl& url) { |
| 417 | if (!url.isEmpty()) { |
| 418 | const QUrl resolved_url = (m_currentUrl.isValid() && url.isRelative()) ? m_currentUrl.resolved(url) : url; |
| 419 | const bool ctrl_pressed = |
| 420 | Globals::hasFlag(QGuiApplication::keyboardModifiers(), Qt::KeyboardModifier::ControlModifier); |
| 421 | |
| 422 | if (ctrl_pressed) { |
| 423 | // Open in new tab. |
| 424 | qApp->mainForm()->tabWidget()->addLinkedBrowser(resolved_url); |
| 425 | } |
| 426 | else { |
| 427 | bool open_externally_now = |
| 428 | qApp->settings()->value(GROUP(Browser), SETTING(Browser::OpenLinksInExternalBrowserRightAway)).toBool(); |
| 429 | |
| 430 | if (open_externally_now) { |
| 431 | qApp->web()->openUrlInExternalBrowser(resolved_url.toString()); |
| 432 | |
| 433 | if (qApp->settings() |
| 434 | ->value(GROUP(Messages), SETTING(Messages::BringAppToFrontAfterMessageOpenedExternally)) |
| 435 | .toBool()) { |
| 436 | QTimer::singleShot(1000, qApp, []() { |
| 437 | qApp->mainForm()->display(); |
| 438 | }); |
| 439 | } |
| 440 | } |
| 441 | else { |
| 442 | setUrl(resolved_url); |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | void TextBrowserViewer::setHtml(const QString& html, const QUrl& base_url) { |
| 449 | if (m_resourcesEnabled) { |
| 450 | // NOTE: This regex is problematic as it does not work for ALL |
| 451 | // HTMLs, maybe use XML parsing to extract what we need? |
| 452 | static QRegularExpression img_tag_rgx("\\<img[^\\>]*src\\s*=\\s*[\"\']([^\"\']*)[\"\'][^\\>]*\\>", |
| 453 | QRegularExpression::PatternOption::CaseInsensitiveOption); |
| 454 | QRegularExpressionMatchIterator i = img_tag_rgx.globalMatch(html); |
| 455 | QList<QUrl> found_resources; |
| 456 | |
| 457 | while (i.hasNext()) { |
| 458 | QRegularExpressionMatch match = i.next(); |
| 459 | auto captured_url = QUrl(match.captured(1)); |
| 460 | auto resolved_captured_url = |
| 461 | (base_url.isValid() && captured_url.isRelative()) ? base_url.resolved(captured_url) : captured_url; |
| 462 | |
| 463 | if (!found_resources.contains(resolved_captured_url)) { |
| 464 | found_resources.append(resolved_captured_url); |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | auto really_needed_resources = boolinq::from(found_resources) |
| 469 | .where([this](const QUrl& res) { |
| 470 | return !m_loadedResources.contains(res); |
| 471 | }) |
| 472 | .toStdList(); |
| 473 | |
| 474 | m_neededResources = FROM_STD_LIST(QList<QUrl>, really_needed_resources); |
| 475 | } |
| 476 | else { |
| 477 | m_neededResources = {}; |
| 478 | } |
| 479 | |
| 480 | setHtmlPrivate(html, base_url); |
| 481 | |
| 482 | /* |
| 483 | QTextCursor cr(m_document.data()); |
| 484 | |
| 485 | cr.movePosition(QTextCursor::MoveOperation::Start); |
| 486 | |
| 487 | // this can be used instead of regexps, just browse document and collect resource addresses directly |
| 488 | while (!cr.atEnd()) { |
| 489 | if (!cr.movePosition(QTextCursor::MoveOperation::NextBlock)) { |
| 490 | break; |
| 491 | } |
| 492 | |
| 493 | QTextBlock::iterator it; |
| 494 | for (it = cr.block().begin(); !(it.atEnd()); ++it) { |
| 495 | QTextFragment currentFragment = it.fragment(); |
| 496 | if (currentFragment.isValid()) { |
| 497 | auto aa = currentFragment.charFormat().anchorHref(); |
| 498 | |
| 499 | if (!aa.isEmpty()) { |
| 500 | auto xx = 5; |
| 501 | } |
| 502 | else if (currentFragment.charFormat().isImageFormat()) { |
| 503 | aa = currentFragment.charFormat().toImageFormat().name(); |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | } |
| 508 | */ |
| 509 | |
| 510 | if (!m_neededResources.isEmpty()) { |
| 511 | QTimer::singleShot(20, this, &TextBrowserViewer::reloadHtmlDelayed); |
| 512 | } |
| 513 | |
| 514 | setVerticalScrollBarPosition(0.0); |
| 515 | } |
| 516 | |
| 517 | void TextBrowserViewer::setReadabledHtml(const QString& html, const QUrl& base_url) { |
| 518 | setHtml(html, base_url); |
| 519 | } |
| 520 | |
| 521 | void TextBrowserViewer::setHtmlPrivate(const QString& html, const QUrl& base_url) { |
| 522 | m_currentUrl = base_url; |
| 523 | m_currentHtml = html; |
| 524 | |
| 525 | QTextBrowser::setHtml(html); |
| 526 | setZoomFactor(m_zoomFactor); |
| 527 | |
| 528 | emit pageTitleChanged(documentTitle()); |
| 529 | emit pageUrlChanged(base_url); |
| 530 | } |
| 531 | |
| 532 | TextBrowserDocument::TextBrowserDocument(TextBrowserViewer* parent) : QTextDocument(parent) { |
| 533 | m_viewer = parent; |
| 534 | } |
| 535 | |
| 536 | QVariant TextBrowserDocument::loadResource(int type, const QUrl& name) { |
| 537 | return m_viewer->loadOneResource(type, name); |
| 538 | } |
| 539 | |
| 540 | void TextBrowserViewer::reloadHtmlDelayed() { |
| 541 | if (!m_neededResources.isEmpty()) { |
| 542 | downloadNextNeededResource(); |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | void TextBrowserViewer::downloadNextNeededResource() { |
| 547 | if (m_neededResources.isEmpty()) { |
| 548 | // Everything is downloaded. |
| 549 | emit reloadDocument(); |
| 550 | } |
| 551 | else { |
| 552 | QUrl res = m_neededResources.takeFirst(); |
| 553 | |
| 554 | QMetaObject::invokeMethod(m_resourceDownloader, |
| 555 | "manipulateData", |
| 556 | Qt::ConnectionType::QueuedConnection, |
| 557 | Q_ARG(QString, WebFactory::unescapeHtml(res.toString())), |
| 558 | Q_ARG(QNetworkAccessManager::Operation, QNetworkAccessManager::Operation::GetOperation), |
| 559 | Q_ARG(QByteArray, {}), |
| 560 | Q_ARG(int, 5000)); |
| 561 | |
| 562 | /* |
| 563 | m_resourceDownloader.data()->manipulateData(qApp->web()->unescapeHtml(res.toString()), |
| 564 | QNetworkAccessManager::Operation::GetOperation, |
| 565 | {}, |
| 566 | 5000); |
| 567 | */ |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | void TextBrowserViewer::resourceDownloaded(const QUrl& url, |
| 572 | QNetworkReply::NetworkError status, |
| 573 | int http_code, |
| 574 | const QByteArray& contents) { |
| 575 | Q_UNUSED(http_code) |
| 576 | if (!m_loadedResources.contains(url)) { |
| 577 | m_loadedResources.insert(url, QMap<int, QByteArray>()); |
| 578 | } |
| 579 | |
| 580 | QMap<int, QByteArray>& resource_data_all_sizes = m_loadedResources[url]; |
| 581 | |
| 582 | resource_data_all_sizes.clear(); |
| 583 | |
| 584 | if (status == QNetworkReply::NetworkError::NoError) { |
| 585 | resource_data_all_sizes.insert(0, contents); |
| 586 | } |
| 587 | else { |
| 588 | resource_data_all_sizes.insert(0, {}); |
| 589 | } |
| 590 | |
| 591 | downloadNextNeededResource(); |
| 592 | } |
| 593 | |
| 594 | PreparedHtml TextBrowserViewer::prepareLegacyHtmlForMessage(const QList<Message>& messages, |
| 595 | RootItem* selected_item) const { |
| 596 | PreparedHtml html; |
| 597 | bool acc_displays_enclosures = |
| 598 | selected_item == nullptr || selected_item->getParentServiceRoot()->displaysEnclosures(); |
| 599 | |
| 600 | for (const Message& message : messages) { |
| 601 | bool is_plain = !TextFactory::couldBeHtml(message.m_contents); |
| 602 | |
| 603 | // Add title. |
| 604 | if (!message.m_url.isEmpty()) { |
| 605 | html.m_html += QSL("<h2 align=\"center\"><a href=\"%2\">%1</a></h2>").arg(message.m_title, message.m_url); |
| 606 | } |
| 607 | else { |
| 608 | html.m_html += QSL("<h2 align=\"center\">%1</h2>").arg(message.m_title); |
| 609 | } |
| 610 | |
| 611 | // Start contents. |
| 612 | html.m_html += QSL("<div>"); |
| 613 | |
| 614 | // Add links to enclosures. |
| 615 | if (acc_displays_enclosures) { |
| 616 | for (const Enclosure& enc : message.m_enclosures) { |
| 617 | html.m_html += QSL("[<a href=\"%1\">%2</a>]").arg(enc.m_url, enc.m_mimeType); |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | // Display enclosures which are pictures if user has it enabled. |
| 622 | auto first_enc_break_added = false; |
| 623 | |
| 624 | if (acc_displays_enclosures && |
| 625 | qApp->settings()->value(GROUP(Messages), SETTING(Messages::DisplayEnclosuresInMessage)).toBool()) { |
| 626 | for (const Enclosure& enc : message.m_enclosures) { |
| 627 | if (enc.m_mimeType.startsWith(QSL("image/"))) { |
| 628 | if (!first_enc_break_added) { |
| 629 | html.m_html += QSL("<br/>"); |
| 630 | first_enc_break_added = true; |
| 631 | } |
| 632 | |
| 633 | html.m_html += QSL("<img src=\"%1\" /><br/>").arg(enc.m_url); |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | // Append actual contents of article and convert to HTML if needed. |
| 639 | html.m_html += is_plain ? Qt::convertFromPlainText(message.m_contents, Qt::WhiteSpaceMode::WhiteSpaceNormal) |
| 640 | : message.m_contents; |
| 641 | |
| 642 | static QRegularExpression img_tag_rgx(QSL("\\<img[^\\>]*src\\s*=\\s*[\"\']([^\"\']*)[\"\'][^\\>]*\\>"), |
| 643 | QRegularExpression::PatternOption::CaseInsensitiveOption); |
| 644 | |
| 645 | // Extract all images links from article to be appended to end of article. |
| 646 | QRegularExpressionMatchIterator i = img_tag_rgx.globalMatch(html.m_html); |
| 647 | QString pictures_html; |
| 648 | |
| 649 | while (i.hasNext()) { |
| 650 | QRegularExpressionMatch match = i.next(); |
| 651 | auto captured_url = match.captured(1); |
| 652 | |
| 653 | pictures_html += QSL("<br/>[%1] <a href=\"%2\">%2</a>").arg(tr("image"), captured_url); |
| 654 | } |
| 655 | |
| 656 | // Make alla images clickable as links and also resize them if user has it setup. |
| 657 | auto forced_img_size = |
| 658 | qApp->settings()->value(GROUP(Messages), SETTING(Messages::LimitArticleImagesHeight)).toInt(); |
| 659 | |
| 660 | // Fixup all "img" tags. |
| 661 | html.m_html = html.m_html.replace(img_tag_rgx, |
| 662 | QSL("<a href=\"\\1\"><img height=\"%1\" src=\"\\1\" /></a>") |
| 663 | .arg(forced_img_size <= 0 ? QString() : QString::number(forced_img_size))); |
| 664 | |
| 665 | // Append generated list of images. |
| 666 | html.m_html += pictures_html; |
| 667 | } |
| 668 | |
| 669 | // Close contents. |
| 670 | html.m_html += QSL("</div>"); |
| 671 | |
| 672 | QString base_url; |
| 673 | auto* feed = selected_item->getParentServiceRoot() |
| 674 | ->getItemFromSubTree([messages](const RootItem* it) { |
| 675 | return it->kind() == RootItem::Kind::Feed && it->customId() == messages.at(0).m_feedId; |
| 676 | }) |
| 677 | ->toFeed(); |
| 678 | |
| 679 | if (feed != nullptr) { |
| 680 | QUrl url(NetworkFactory::sanitizeUrl(feed->source())); |
| 681 | |
| 682 | if (url.isValid()) { |
| 683 | base_url = url.scheme() + QSL("://") + url.host(); |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | html.m_baseUrl = base_url; |
| 688 | |
| 689 | return html; |
| 690 | } |
| 691 | |
| 692 | bool TextBrowserViewer::resourcesEnabled() const { |
| 693 | return m_resourcesEnabled; |
| 694 | } |
| 695 | |
| 696 | void TextBrowserViewer::setResourcesEnabled(bool enabled) { |
| 697 | m_resourcesEnabled = enabled; |
| 698 | } |
| 699 | |
| 700 | ContextMenuData TextBrowserViewer::provideContextMenuData(QContextMenuEvent* event) const { |
| 701 | ContextMenuData c; |
| 702 | |
| 703 | QString anchor = anchorAt(event->pos()); |
| 704 | |
| 705 | if (!anchor.isEmpty()) { |
| 706 | c.m_linkUrl = anchor; |
| 707 | } |
| 708 | |
| 709 | return c; |
| 710 | } |