vwebview.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #include "vwebview.h"
  2. #include <QMenu>
  3. #include <QPoint>
  4. #include <QContextMenuEvent>
  5. #include <QWebEnginePage>
  6. #include <QAction>
  7. #include <QList>
  8. #include <QClipboard>
  9. #include <QMimeData>
  10. #include <QApplication>
  11. #include <QImage>
  12. #include <QFileInfo>
  13. #include "vfile.h"
  14. #include "utils/vclipboardutils.h"
  15. #include "utils/viconutils.h"
  16. #include "vconfigmanager.h"
  17. #include "utils/vwebutils.h"
  18. extern VConfigManager *g_config;
  19. // We set the property of the clipboard to mark that the URL copied in the
  20. // clipboard has been altered.
  21. static const QString c_ClipboardPropertyMark = "CopiedImageURLAltered";
  22. VWebView::VWebView(VFile *p_file, QWidget *p_parent)
  23. : QWebEngineView(p_parent),
  24. m_file(p_file),
  25. m_copyImageUrlActionHooked(false),
  26. m_needRemoveBackground(false),
  27. m_fixImgSrc(g_config->getFixImageSrcInWebWhenCopied()),
  28. m_afterCopyImage(false)
  29. {
  30. setAcceptDrops(false);
  31. connect(QApplication::clipboard(), &QClipboard::changed,
  32. this, &VWebView::handleClipboardChanged);
  33. }
  34. void VWebView::contextMenuEvent(QContextMenuEvent *p_event)
  35. {
  36. QMenu *menu = page()->createStandardContextMenu();
  37. menu->setToolTipsVisible(true);
  38. const QList<QAction *> actions = menu->actions();
  39. #if defined(Q_OS_WIN)
  40. if (!m_copyImageUrlActionHooked) {
  41. // "Copy Image URL" action will put the encoded URL to the clipboard as text
  42. // and the URL as URLs. If the URL contains Chinese, OneNote or Word could not
  43. // recognize it.
  44. // We need to change it to only-space-encoded text.
  45. QAction *copyImageUrlAct = pageAction(QWebEnginePage::CopyImageUrlToClipboard);
  46. if (actions.contains(copyImageUrlAct)) {
  47. connect(copyImageUrlAct, &QAction::triggered,
  48. this, &VWebView::handleCopyImageUrlAction);
  49. m_copyImageUrlActionHooked = true;
  50. qDebug() << "hooked CopyImageUrl action" << copyImageUrlAct;
  51. }
  52. }
  53. #endif
  54. if (!hasSelection() && m_file && m_file->isModifiable()) {
  55. QAction *editAct= new QAction(VIconUtils::menuIcon(":/resources/icons/edit_note.svg"),
  56. tr("&Edit"), menu);
  57. editAct->setToolTip(tr("Edit current note"));
  58. connect(editAct, &QAction::triggered,
  59. this, &VWebView::handleEditAction);
  60. menu->insertAction(actions.isEmpty() ? NULL : actions[0], editAct);
  61. // actions does not contain editAction.
  62. if (!actions.isEmpty()) {
  63. menu->insertSeparator(actions[0]);
  64. }
  65. }
  66. // Add Copy without Background action.
  67. QAction *copyAct = pageAction(QWebEnginePage::Copy);
  68. if (actions.contains(copyAct)) {
  69. QAction *copyWithoutBgAct = new QAction(tr("Copy &without Background"), menu);
  70. copyWithoutBgAct->setToolTip(tr("Copy selected content without background styles"));
  71. connect(copyWithoutBgAct, &QAction::triggered,
  72. this, &VWebView::handleCopyWithoutBackgroundAction);
  73. menu->insertAction(copyAct, copyWithoutBgAct);
  74. menu->removeAction(copyAct);
  75. menu->insertAction(copyWithoutBgAct, copyAct);
  76. }
  77. // We need to replace the "Copy Image" action:
  78. // - the default one use the fully-encoded URL to fetch the image while
  79. // Windows seems to not recognize it.
  80. // - We need to remove the html to let it be recognized by some web pages.
  81. QAction *defaultCopyImageAct = pageAction(QWebEnginePage::CopyImageToClipboard);
  82. if (actions.contains(defaultCopyImageAct)) {
  83. QAction *copyImageAct = new QAction(defaultCopyImageAct->text(), menu);
  84. copyImageAct->setToolTip(defaultCopyImageAct->toolTip());
  85. connect(copyImageAct, &QAction::triggered,
  86. this, &VWebView::copyImage);
  87. menu->insertAction(defaultCopyImageAct, copyImageAct);
  88. defaultCopyImageAct->setVisible(false);
  89. }
  90. // Add Copy All without Background action.
  91. QAction *copyAllWithoutBgAct = new QAction(tr("Copy &All without Background"), menu);
  92. copyAllWithoutBgAct->setToolTip(tr("Copy all contents without background styles"));
  93. connect(copyAllWithoutBgAct, &QAction::triggered,
  94. this, &VWebView::handleCopyAllWithoutBackgroundAction);
  95. // Add it to the back.
  96. menu->addSeparator();
  97. menu->addAction(copyAllWithoutBgAct);
  98. hideUnusedActions(menu);
  99. menu->exec(p_event->globalPos());
  100. delete menu;
  101. }
  102. void VWebView::handleEditAction()
  103. {
  104. emit editNote();
  105. }
  106. void VWebView::copyImage()
  107. {
  108. m_afterCopyImage = true;
  109. #if defined(Q_OS_WIN)
  110. Q_ASSERT(m_copyImageUrlActionHooked);
  111. // triggerPageAction(QWebEnginePage::CopyImageUrlToClipboard) will not really
  112. // trigger the corresponding action. It just do the stuff directly.
  113. QAction *copyImageUrlAct = pageAction(QWebEnginePage::CopyImageUrlToClipboard);
  114. copyImageUrlAct->trigger();
  115. QCoreApplication::processEvents();
  116. QClipboard *clipboard = QApplication::clipboard();
  117. if (clipboard->property(c_ClipboardPropertyMark.toLatin1()).toBool()) {
  118. const QMimeData *mimeData = clipboard->mimeData();
  119. QString imgPath;
  120. if (mimeData->hasUrls()) {
  121. QList<QUrl> urls = mimeData->urls();
  122. if (!urls.isEmpty() && urls[0].isLocalFile()) {
  123. imgPath = urls[0].toLocalFile();
  124. }
  125. }
  126. if (!imgPath.isEmpty()) {
  127. QImage img(imgPath);
  128. if (!img.isNull()) {
  129. m_afterCopyImage = false;
  130. VClipboardUtils::setImageToClipboard(clipboard, img, QClipboard::Clipboard);
  131. qDebug() << "clipboard copy image via URL" << imgPath;
  132. return;
  133. }
  134. }
  135. }
  136. #endif
  137. // Fall back.
  138. triggerPageAction(QWebEnginePage::CopyImageToClipboard);
  139. }
  140. void VWebView::handleCopyImageUrlAction()
  141. {
  142. // To avoid failure of setting clipboard mime data.
  143. QCoreApplication::processEvents();
  144. QClipboard *clipboard = QApplication::clipboard();
  145. const QMimeData *mimeData = clipboard->mimeData();
  146. clipboard->setProperty(c_ClipboardPropertyMark.toLatin1(), false);
  147. if (clipboard->ownsClipboard()
  148. && mimeData->hasText()
  149. && mimeData->hasUrls()) {
  150. QString text = mimeData->text();
  151. QList<QUrl> urls = mimeData->urls();
  152. if (urls.size() == 1
  153. && urls[0].isLocalFile()
  154. && urls[0].toEncoded() == text) {
  155. QString spaceOnlyText = urls[0].toString(QUrl::EncodeSpaces);
  156. if (spaceOnlyText != text) {
  157. // Set new mime data.
  158. QMimeData *data = new QMimeData();
  159. data->setUrls(urls);
  160. data->setText(spaceOnlyText);
  161. VClipboardUtils::setMimeDataToClipboard(clipboard, data, QClipboard::Clipboard);
  162. clipboard->setProperty(c_ClipboardPropertyMark.toLatin1(), true);
  163. qDebug() << "clipboard copy image URL altered" << spaceOnlyText;
  164. }
  165. }
  166. }
  167. }
  168. void VWebView::hideUnusedActions(QMenu *p_menu)
  169. {
  170. QList<QAction *> unusedActions;
  171. // QWebEnginePage uses different actions of Back/Forward/Reload.
  172. // [Woboq](https://code.woboq.org/qt5/qtwebengine/src/webenginewidgets/api/qwebenginepage.cpp.html#1652)
  173. // We tell these three actions by name.
  174. const QStringList actionNames({QWebEnginePage::tr("&Back"),
  175. QWebEnginePage::tr("&Forward"),
  176. QWebEnginePage::tr("&Reload")});
  177. const QList<QAction *> actions = p_menu->actions();
  178. for (auto it : actions) {
  179. if (actionNames.contains(it->text())) {
  180. unusedActions.append(it);
  181. }
  182. }
  183. // ViewSource.
  184. QAction *act = pageAction(QWebEnginePage::ViewSource);
  185. unusedActions.append(act);
  186. // DownloadImageToDisk.
  187. act = pageAction(QWebEnginePage::DownloadImageToDisk);
  188. unusedActions.append(act);
  189. // DownloadLinkToDisk.
  190. act = pageAction(QWebEnginePage::DownloadLinkToDisk);
  191. unusedActions.append(act);
  192. for (auto it : unusedActions) {
  193. if (it) {
  194. it->setVisible(false);
  195. }
  196. }
  197. }
  198. static bool removeBackgroundColor(QString &p_html)
  199. {
  200. QRegExp reg("(<[^>]+\\sstyle=[^>]*(\\s|\"))background(-color)?:[^;]+;([^>]*>)");
  201. int size = p_html.size();
  202. p_html.replace(reg, "\\1\\4");
  203. return p_html.size() != size;
  204. }
  205. bool VWebView::removeStyles(QString &p_html)
  206. {
  207. bool changed = false;
  208. const QStringList &styles = g_config->getStylesToRemoveWhenCopied();
  209. if (styles.isEmpty()) {
  210. return changed;
  211. }
  212. QRegExp tagReg("(<[^>]+\\sstyle=[^>]*>)");
  213. int pos = 0;
  214. while (pos < p_html.size()) {
  215. int idx = p_html.indexOf(tagReg, pos);
  216. if (idx == -1) {
  217. break;
  218. }
  219. QString styleStr = tagReg.cap(1);
  220. QString alteredStyleStr = styleStr;
  221. QString regPatt("(\\s|\")%1:[^;]+;");
  222. for (auto const & sty : styles) {
  223. QRegExp reg(regPatt.arg(sty));
  224. alteredStyleStr.replace(reg, "\\1");
  225. }
  226. pos = idx + tagReg.matchedLength();
  227. if (styleStr != alteredStyleStr) {
  228. pos = pos + alteredStyleStr.size() - styleStr.size();
  229. p_html.replace(idx, tagReg.matchedLength(), alteredStyleStr);
  230. changed = true;
  231. }
  232. }
  233. return changed;
  234. }
  235. void VWebView::handleCopyWithoutBackgroundAction()
  236. {
  237. m_needRemoveBackground = true;
  238. triggerPageAction(QWebEnginePage::Copy);
  239. }
  240. void VWebView::handleCopyAllWithoutBackgroundAction()
  241. {
  242. triggerPageAction(QWebEnginePage::SelectAll);
  243. m_needRemoveBackground = true;
  244. triggerPageAction(QWebEnginePage::Copy);
  245. triggerPageAction(QWebEnginePage::Unselect);
  246. }
  247. void VWebView::handleClipboardChanged(QClipboard::Mode p_mode)
  248. {
  249. bool removeBackground = m_needRemoveBackground;
  250. m_needRemoveBackground = false;
  251. bool afterCopyImage = m_afterCopyImage;
  252. m_afterCopyImage = false;
  253. if (!hasFocus()
  254. || p_mode != QClipboard::Clipboard) {
  255. return;
  256. }
  257. QClipboard *clipboard = QApplication::clipboard();
  258. const QMimeData *mimeData = clipboard->mimeData();
  259. if (!clipboard->ownsClipboard()) {
  260. return;
  261. }
  262. if (afterCopyImage) {
  263. removeHtmlFromImageData(clipboard, mimeData);
  264. } else {
  265. alterHtmlMimeData(clipboard, mimeData, removeBackground);
  266. }
  267. }
  268. void VWebView::alterHtmlMimeData(QClipboard *p_clipboard,
  269. const QMimeData *p_mimeData,
  270. bool p_removeBackground)
  271. {
  272. if (!p_mimeData->hasHtml() || p_mimeData->hasImage()) {
  273. return;
  274. }
  275. bool altered = false;
  276. QString html = p_mimeData->html();
  277. // Add surrounded tags.
  278. if (!html.startsWith("<html>")) {
  279. altered = true;
  280. html = QString("<html><body>%1</body></html>").arg(html);
  281. }
  282. // Remove background color.
  283. if (p_removeBackground && removeBackgroundColor(html)) {
  284. altered = true;
  285. }
  286. // Fix local relative images.
  287. if (m_fixImgSrc && VWebUtils::fixImageSrcInHtml(url(), html)) {
  288. altered = true;
  289. }
  290. // Fix margin and padding.
  291. if (removeStyles(html)) {
  292. altered = true;
  293. }
  294. if (!altered) {
  295. return;
  296. }
  297. // Set new mime data.
  298. QMimeData *data = VClipboardUtils::cloneMimeData(p_mimeData);
  299. data->setHtml(html);
  300. VClipboardUtils::setMimeDataToClipboard(p_clipboard, data, QClipboard::Clipboard);
  301. qDebug() << "altered clipboard's Html";
  302. }
  303. void VWebView::removeHtmlFromImageData(QClipboard *p_clipboard,
  304. const QMimeData *p_mimeData)
  305. {
  306. if (!p_mimeData->hasImage()) {
  307. return;
  308. }
  309. if (p_mimeData->hasHtml()) {
  310. qDebug() << "remove html from image data" << p_mimeData->html();
  311. QMimeData *data = new QMimeData();
  312. data->setImageData(p_mimeData->imageData());
  313. VClipboardUtils::setMimeDataToClipboard(p_clipboard, data, QClipboard::Clipboard);
  314. }
  315. }