markdowneditor.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. #include "markdowneditor.h"
  2. #include <QRegularExpression>
  3. #include <QApplication>
  4. #include <QClipboard>
  5. #include <QMimeData>
  6. #include <QFileInfo>
  7. #include <QDir>
  8. #include <QMimeDatabase>
  9. #include <QClipboard>
  10. #include <QMenu>
  11. #include <QAction>
  12. #include <QShortcut>
  13. #include <QProgressDialog>
  14. #include <QTemporaryFile>
  15. #include <QTimer>
  16. #include <QBuffer>
  17. #include <vtextedit/markdowneditorconfig.h>
  18. #include <vtextedit/previewmgr.h>
  19. #include <vtextedit/markdownutils.h>
  20. #include <vtextedit/vtextedit.h>
  21. #include <vtextedit/texteditutils.h>
  22. #include <vtextedit/markdownutils.h>
  23. #include <vtextedit/networkutils.h>
  24. #include <vtextedit/theme.h>
  25. #include <widgets/dialogs/linkinsertdialog.h>
  26. #include <widgets/dialogs/imageinsertdialog.h>
  27. #include <widgets/dialogs/tableinsertdialog.h>
  28. #include <widgets/messageboxhelper.h>
  29. #include <widgets/dialogs/selectdialog.h>
  30. #include <buffer/buffer.h>
  31. #include <buffer/markdownbuffer.h>
  32. #include <utils/fileutils.h>
  33. #include <utils/pathutils.h>
  34. #include <utils/htmlutils.h>
  35. #include <utils/widgetutils.h>
  36. #include <utils/webutils.h>
  37. #include <utils/imageutils.h>
  38. #include <core/exception.h>
  39. #include <core/markdowneditorconfig.h>
  40. #include <core/texteditorconfig.h>
  41. #include <core/configmgr.h>
  42. #include <core/editorconfig.h>
  43. #include <core/vnotex.h>
  44. #include <imagehost/imagehostutils.h>
  45. #include <imagehost/imagehost.h>
  46. #include <imagehost/imagehostmgr.h>
  47. #include "previewhelper.h"
  48. #include "../outlineprovider.h"
  49. #include "markdowntablehelper.h"
  50. using namespace vnotex;
  51. // We set the property of the clipboard to mark that we are requesting a rich paste.
  52. static const char *c_clipboardPropertyMark = "RichPaste";
  53. MarkdownEditor::Heading::Heading(const QString &p_name,
  54. int p_level,
  55. const QString &p_sectionNumber,
  56. int p_blockNumber)
  57. : m_name(p_name),
  58. m_level(p_level),
  59. m_sectionNumber(p_sectionNumber),
  60. m_blockNumber(p_blockNumber)
  61. {
  62. }
  63. MarkdownEditor::MarkdownEditor(const MarkdownEditorConfig &p_config,
  64. const QSharedPointer<vte::MarkdownEditorConfig> &p_editorConfig,
  65. const QSharedPointer<vte::TextEditorParameters> &p_editorParas,
  66. QWidget *p_parent)
  67. : vte::VMarkdownEditor(p_editorConfig, p_editorParas, p_parent),
  68. m_config(p_config)
  69. {
  70. setupShortcuts();
  71. connect(m_textEdit, &vte::VTextEdit::canInsertFromMimeDataRequested,
  72. this, &MarkdownEditor::handleCanInsertFromMimeData);
  73. connect(m_textEdit, &vte::VTextEdit::insertFromMimeDataRequested,
  74. this, &MarkdownEditor::handleInsertFromMimeData);
  75. connect(m_textEdit, &vte::VTextEdit::contextMenuEventRequested,
  76. this, &MarkdownEditor::handleContextMenuEvent);
  77. connect(getHighlighter(), &vte::PegMarkdownHighlighter::headersUpdated,
  78. this, &MarkdownEditor::updateHeadings);
  79. setupTableHelper();
  80. m_headingTimer = new QTimer(this);
  81. m_headingTimer->setInterval(500);
  82. m_headingTimer->setSingleShot(true);
  83. connect(m_headingTimer, &QTimer::timeout,
  84. this, &MarkdownEditor::currentHeadingChanged);
  85. connect(m_textEdit, &vte::VTextEdit::cursorLineChanged,
  86. m_headingTimer, QOverload<>::of(&QTimer::start));
  87. m_sectionNumberTimer = new QTimer(this);
  88. m_sectionNumberTimer->setInterval(1000);
  89. m_sectionNumberTimer->setSingleShot(true);
  90. connect(m_sectionNumberTimer, &QTimer::timeout,
  91. this, [this]() {
  92. updateSectionNumber(m_headings);
  93. });
  94. updateFromConfig(false);
  95. }
  96. MarkdownEditor::~MarkdownEditor()
  97. {
  98. }
  99. void MarkdownEditor::setPreviewHelper(PreviewHelper *p_helper)
  100. {
  101. auto highlighter = getHighlighter();
  102. connect(highlighter, &vte::PegMarkdownHighlighter::codeBlocksUpdated,
  103. p_helper, &PreviewHelper::codeBlocksUpdated);
  104. connect(highlighter, &vte::PegMarkdownHighlighter::mathBlocksUpdated,
  105. p_helper, &PreviewHelper::mathBlocksUpdated);
  106. auto previewMgr = getPreviewMgr();
  107. connect(p_helper, &PreviewHelper::inplacePreviewCodeBlockUpdated,
  108. previewMgr, &vte::PreviewMgr::updateCodeBlocks);
  109. connect(p_helper, &PreviewHelper::inplacePreviewMathBlockUpdated,
  110. previewMgr, &vte::PreviewMgr::updateMathBlocks);
  111. connect(p_helper, &PreviewHelper::potentialObsoletePreviewBlocksUpdated,
  112. previewMgr, &vte::PreviewMgr::checkBlocksForObsoletePreview);
  113. }
  114. void MarkdownEditor::typeHeading(int p_level)
  115. {
  116. enterInsertModeIfApplicable();
  117. vte::MarkdownUtils::typeHeading(m_textEdit, p_level);
  118. }
  119. void MarkdownEditor::typeBold()
  120. {
  121. enterInsertModeIfApplicable();
  122. vte::MarkdownUtils::typeBold(m_textEdit);
  123. }
  124. void MarkdownEditor::typeItalic()
  125. {
  126. enterInsertModeIfApplicable();
  127. vte::MarkdownUtils::typeItalic(m_textEdit);
  128. }
  129. void MarkdownEditor::typeStrikethrough()
  130. {
  131. enterInsertModeIfApplicable();
  132. vte::MarkdownUtils::typeStrikethrough(m_textEdit);
  133. }
  134. void MarkdownEditor::typeMark()
  135. {
  136. enterInsertModeIfApplicable();
  137. vte::MarkdownUtils::typeMark(m_textEdit);
  138. }
  139. void MarkdownEditor::typeUnorderedList()
  140. {
  141. enterInsertModeIfApplicable();
  142. vte::MarkdownUtils::typeUnorderedList(m_textEdit);
  143. }
  144. void MarkdownEditor::typeOrderedList()
  145. {
  146. enterInsertModeIfApplicable();
  147. vte::MarkdownUtils::typeOrderedList(m_textEdit);
  148. }
  149. void MarkdownEditor::typeTodoList(bool p_checked)
  150. {
  151. enterInsertModeIfApplicable();
  152. vte::MarkdownUtils::typeTodoList(m_textEdit, p_checked);
  153. }
  154. void MarkdownEditor::typeCode()
  155. {
  156. enterInsertModeIfApplicable();
  157. vte::MarkdownUtils::typeCode(m_textEdit);
  158. }
  159. void MarkdownEditor::typeCodeBlock()
  160. {
  161. enterInsertModeIfApplicable();
  162. vte::MarkdownUtils::typeCodeBlock(m_textEdit);
  163. }
  164. void MarkdownEditor::typeMath()
  165. {
  166. enterInsertModeIfApplicable();
  167. vte::MarkdownUtils::typeMath(m_textEdit);
  168. }
  169. void MarkdownEditor::typeMathBlock()
  170. {
  171. enterInsertModeIfApplicable();
  172. vte::MarkdownUtils::typeMathBlock(m_textEdit);
  173. }
  174. void MarkdownEditor::typeQuote()
  175. {
  176. enterInsertModeIfApplicable();
  177. vte::MarkdownUtils::typeQuote(m_textEdit);
  178. }
  179. void MarkdownEditor::typeLink()
  180. {
  181. QString linkText;
  182. QString linkUrl;
  183. // Try get Url or text from selection.
  184. auto cursor = m_textEdit->textCursor();
  185. QRegularExpression urlReg("[\\.\\\\/]");
  186. if (cursor.hasSelection()) {
  187. auto text = vte::TextEditUtils::getSelectedText(cursor).trimmed();
  188. if (!text.isEmpty() && !text.contains(QLatin1Char('\n'))) {
  189. if (text.contains(urlReg) && QUrl::fromUserInput(text).isValid()) {
  190. linkUrl = text;
  191. } else {
  192. linkText = text;
  193. }
  194. }
  195. }
  196. // Fetch link from clipboard.
  197. if (linkUrl.isEmpty() && linkText.isEmpty()) {
  198. const auto clipboard = QApplication::clipboard();
  199. const auto mimeData = clipboard->mimeData();
  200. const QString text = mimeData->text().trimmed();
  201. // No multi-line.
  202. if (!text.isEmpty() && !text.contains(QLatin1Char('\n'))) {
  203. if (text.contains(urlReg) && QUrl::fromUserInput(text).isValid()) {
  204. linkUrl = text;
  205. } else {
  206. linkText = text;
  207. }
  208. }
  209. }
  210. LinkInsertDialog dialog(tr("Insert Link"), linkText, linkUrl, false, this);
  211. if (dialog.exec() == QDialog::Accepted) {
  212. linkText = dialog.getLinkText();
  213. linkUrl = dialog.getLinkUrl();
  214. enterInsertModeIfApplicable();
  215. vte::MarkdownUtils::typeLink(m_textEdit, linkText, linkUrl);
  216. }
  217. }
  218. void MarkdownEditor::typeImage()
  219. {
  220. Q_ASSERT(m_buffer);
  221. ImageInsertDialog dialog(tr("Insert Image"), "", "", "", true, this);
  222. // Try fetch image from clipboard.
  223. {
  224. QClipboard *clipboard = QApplication::clipboard();
  225. const QMimeData *mimeData = clipboard->mimeData();
  226. QUrl url;
  227. if (mimeData->hasImage()) {
  228. QImage im = qvariant_cast<QImage>(mimeData->imageData());
  229. if (im.isNull()) {
  230. return;
  231. }
  232. dialog.setImage(im);
  233. dialog.setImageSource(ImageInsertDialog::Source::ImageData);
  234. } else if (mimeData->hasUrls()) {
  235. QList<QUrl> urls = mimeData->urls();
  236. if (urls.size() == 1) {
  237. url = urls[0];
  238. }
  239. } else if (mimeData->hasText()) {
  240. url = QUrl::fromUserInput(mimeData->text());
  241. }
  242. if (url.isValid()) {
  243. if (url.isLocalFile()) {
  244. dialog.setImagePath(url.toLocalFile());
  245. } else {
  246. dialog.setImagePath(url.toString());
  247. }
  248. }
  249. }
  250. if (dialog.exec() != QDialog::Accepted) {
  251. return;
  252. }
  253. enterInsertModeIfApplicable();
  254. if (dialog.getImageSource() == ImageInsertDialog::Source::LocalFile) {
  255. insertImageToBufferFromLocalFile(dialog.getImageTitle(),
  256. dialog.getImageAltText(),
  257. dialog.getImagePath(),
  258. dialog.getScaledWidth());
  259. } else {
  260. auto image = dialog.getImage();
  261. if (!image.isNull()) {
  262. insertImageToBufferFromData(dialog.getImageTitle(),
  263. dialog.getImageAltText(),
  264. image,
  265. dialog.getScaledWidth());
  266. }
  267. }
  268. }
  269. void MarkdownEditor::typeTable()
  270. {
  271. TableInsertDialog dialog(tr("Insert Table"), this);
  272. if (dialog.exec() != QDialog::Accepted) {
  273. return;
  274. }
  275. auto cursor = m_textEdit->textCursor();
  276. cursor.beginEditBlock();
  277. if (cursor.hasSelection()) {
  278. cursor.setPosition(qMax(cursor.selectionStart(), cursor.selectionEnd()));
  279. }
  280. bool newBlock = !cursor.atBlockEnd();
  281. if (!newBlock && !cursor.atBlockStart()) {
  282. QString text = cursor.block().text().trimmed();
  283. if (!text.isEmpty() && text != QStringLiteral(">")) {
  284. // Insert a new block before inserting table.
  285. newBlock = true;
  286. }
  287. }
  288. if (newBlock) {
  289. auto indentationStr = vte::TextEditUtils::fetchIndentationSpaces(cursor.block());
  290. vte::TextEditUtils::insertBlock(cursor, false);
  291. cursor.insertText(indentationStr);
  292. }
  293. cursor.endEditBlock();
  294. m_textEdit->setTextCursor(cursor);
  295. // Insert table.
  296. m_tableHelper->insertTable(dialog.getRowCount(), dialog.getColumnCount(), dialog.getAlignment());
  297. }
  298. void MarkdownEditor::setBuffer(Buffer *p_buffer)
  299. {
  300. m_buffer = p_buffer;
  301. }
  302. bool MarkdownEditor::insertImageToBufferFromLocalFile(const QString &p_title,
  303. const QString &p_altText,
  304. const QString &p_srcImagePath,
  305. int p_scaledWidth,
  306. int p_scaledHeight,
  307. bool p_insertText,
  308. QString *p_urlInLink)
  309. {
  310. auto destFileName = generateImageFileNameToInsertAs(p_title, QFileInfo(p_srcImagePath).suffix());
  311. QString destFilePath;
  312. if (m_imageHost) {
  313. // Save to image host.
  314. QByteArray ba;
  315. try {
  316. ba = FileUtils::readFile(p_srcImagePath);
  317. } catch (Exception &e) {
  318. MessageBoxHelper::notify(MessageBoxHelper::Warning,
  319. QString("Failed to read local image file (%1) (%2).").arg(p_srcImagePath, e.what()),
  320. this);
  321. return false;
  322. }
  323. destFilePath = saveToImageHost(ba, destFileName);
  324. if (destFilePath.isEmpty()) {
  325. return false;
  326. }
  327. } else {
  328. try {
  329. destFilePath = m_buffer->insertImage(p_srcImagePath, destFileName);
  330. } catch (Exception &e) {
  331. MessageBoxHelper::notify(MessageBoxHelper::Warning,
  332. QString("Failed to insert image from local file (%1) (%2).").arg(p_srcImagePath, e.what()),
  333. this);
  334. return false;
  335. }
  336. }
  337. insertImageLink(p_title, p_altText, destFilePath, p_scaledWidth, p_scaledHeight, p_insertText, p_urlInLink);
  338. return true;
  339. }
  340. QString MarkdownEditor::generateImageFileNameToInsertAs(const QString &p_title, const QString &p_suffix)
  341. {
  342. return FileUtils::generateRandomFileName(p_title, p_suffix);
  343. }
  344. bool MarkdownEditor::insertImageToBufferFromData(const QString &p_title,
  345. const QString &p_altText,
  346. const QImage &p_image,
  347. int p_scaledWidth,
  348. int p_scaledHeight)
  349. {
  350. // Save as PNG by default.
  351. const QString format("png");
  352. const auto destFileName = generateImageFileNameToInsertAs(p_title, format);
  353. QString destFilePath;
  354. if (m_imageHost) {
  355. // Save to image host.
  356. QByteArray ba;
  357. QBuffer buffer(&ba);
  358. buffer.open(QIODevice::WriteOnly);
  359. p_image.save(&buffer, format.toStdString().c_str());
  360. destFilePath = saveToImageHost(ba, destFileName);
  361. if (destFilePath.isEmpty()) {
  362. return false;
  363. }
  364. } else {
  365. try {
  366. destFilePath = m_buffer->insertImage(p_image, destFileName);
  367. } catch (Exception &e) {
  368. MessageBoxHelper::notify(MessageBoxHelper::Warning,
  369. QString("Failed to insert image from data (%1).").arg(e.what()),
  370. this);
  371. return false;
  372. }
  373. }
  374. insertImageLink(p_title, p_altText, destFilePath, p_scaledWidth, p_scaledHeight);
  375. return true;
  376. }
  377. void MarkdownEditor::insertImageLink(const QString &p_title,
  378. const QString &p_altText,
  379. const QString &p_destImagePath,
  380. int p_scaledWidth,
  381. int p_scaledHeight,
  382. bool p_insertText,
  383. QString *p_urlInLink)
  384. {
  385. const auto urlInLink = getRelativeLink(p_destImagePath);
  386. if (p_urlInLink) {
  387. *p_urlInLink = urlInLink;
  388. }
  389. static_cast<MarkdownBuffer *>(m_buffer)->addInsertedImage(p_destImagePath, urlInLink);
  390. if (p_insertText) {
  391. const auto imageLink = vte::MarkdownUtils::generateImageLink(p_title,
  392. urlInLink,
  393. p_altText,
  394. p_scaledWidth,
  395. p_scaledHeight);
  396. m_textEdit->insertPlainText(imageLink);
  397. }
  398. }
  399. void MarkdownEditor::handleCanInsertFromMimeData(const QMimeData *p_source, bool *p_handled, bool *p_allowed)
  400. {
  401. if (p_source->hasImage() || p_source->hasUrls()) {
  402. if (p_source->hasImage()
  403. || (!p_source->hasText() && !p_source->hasHtml())
  404. || QGuiApplication::keyboardModifiers() == Qt::ShiftModifier) {
  405. // Change to Rich Paste.
  406. QClipboard *clipboard = QApplication::clipboard();
  407. clipboard->setProperty(c_clipboardPropertyMark, true);
  408. }
  409. *p_handled = true;
  410. *p_allowed = true;
  411. }
  412. }
  413. void MarkdownEditor::handleInsertFromMimeData(const QMimeData *p_source, bool *p_handled)
  414. {
  415. QClipboard *clipboard = QApplication::clipboard();
  416. if (!clipboard->property(c_clipboardPropertyMark).toBool()) {
  417. // Default paste.
  418. // Give tips about the Rich Paste and Parse As Markdown And Paste features.
  419. VNoteX::getInst().showStatusMessageShort(
  420. tr("For advanced paste, try the \"Rich Paste\" and \"Parse to Markdown and Paste\" on the editor's context menu"));
  421. return;
  422. } else {
  423. clipboard->setProperty(c_clipboardPropertyMark, false);
  424. }
  425. if (processHtmlFromMimeData(p_source)) {
  426. *p_handled = true;
  427. return;
  428. }
  429. if (processImageFromMimeData(p_source)) {
  430. *p_handled = true;
  431. return;
  432. }
  433. if (processUrlFromMimeData(p_source)) {
  434. *p_handled = true;
  435. return;
  436. }
  437. }
  438. bool MarkdownEditor::processHtmlFromMimeData(const QMimeData *p_source)
  439. {
  440. if (!p_source->hasHtml()) {
  441. return false;
  442. }
  443. // Process <img>.
  444. QRegExp reg("<img ([^>]*)src=\"([^\"]+)\"([^>]*)>");
  445. const QString html(p_source->html());
  446. if (reg.indexIn(html) != -1 && HtmlUtils::hasOnlyImgTag(html)) {
  447. if (p_source->hasImage()) {
  448. // Both image data and URL are embedded.
  449. SelectDialog dialog(tr("Insert From Clipboard"), this);
  450. dialog.addSelection(tr("Insert From URL"), 0);
  451. dialog.addSelection(tr("Insert From Image Data"), 1);
  452. dialog.addSelection(tr("Insert As Image Link"), 2);
  453. if (dialog.exec() == QDialog::Accepted) {
  454. int selection = dialog.getSelection();
  455. if (selection == 1) {
  456. // Insert from image data.
  457. insertImageFromMimeData(p_source);
  458. return true;
  459. } else if (selection == 2) {
  460. // Insert as link.
  461. auto imageLink = vte::MarkdownUtils::generateImageLink("", reg.cap(2), "");
  462. m_textEdit->insertPlainText(imageLink);
  463. return true;
  464. }
  465. } else {
  466. return true;
  467. }
  468. }
  469. insertImageFromUrl(reg.cap(2));
  470. return true;
  471. }
  472. return false;
  473. }
  474. bool MarkdownEditor::processImageFromMimeData(const QMimeData *p_source)
  475. {
  476. if (!p_source->hasImage()) {
  477. return false;
  478. }
  479. // Image url in the clipboard.
  480. if (p_source->hasText()) {
  481. SelectDialog dialog(tr("Insert From Clipboard"), this);
  482. dialog.addSelection(tr("Insert As Image"), 0);
  483. dialog.addSelection(tr("Insert As Text"), 1);
  484. dialog.addSelection(tr("Insert As Image Link"), 2);
  485. if (dialog.exec() == QDialog::Accepted) {
  486. int selection = dialog.getSelection();
  487. if (selection == 1) {
  488. // Insert as text.
  489. Q_ASSERT(p_source->hasText() && p_source->hasImage());
  490. m_textEdit->insertFromMimeDataOfBase(p_source);
  491. return true;
  492. } else if (selection == 2) {
  493. // Insert as link.
  494. auto imageLink = vte::MarkdownUtils::generateImageLink("", p_source->text(), "");
  495. m_textEdit->insertPlainText(imageLink);
  496. return true;
  497. }
  498. } else {
  499. return true;
  500. }
  501. }
  502. insertImageFromMimeData(p_source);
  503. return true;
  504. }
  505. bool MarkdownEditor::processUrlFromMimeData(const QMimeData *p_source)
  506. {
  507. QUrl url;
  508. if (p_source->hasUrls()) {
  509. const auto urls = p_source->urls();
  510. if (urls.size() == 1) {
  511. url = urls[0];
  512. }
  513. } else if (p_source->hasText()) {
  514. // Try to get URL from text.
  515. const QString text = p_source->text();
  516. if (QFileInfo::exists(text)) {
  517. url = QUrl::fromLocalFile(text);
  518. } else {
  519. url = QUrl::fromUserInput(text);
  520. if (url.scheme() != QStringLiteral("https") && url.scheme() != QStringLiteral("http")) {
  521. url.clear();
  522. }
  523. }
  524. }
  525. if (!url.isValid()) {
  526. return false;
  527. }
  528. const bool isImage = PathUtils::isImageUrl(PathUtils::urlToPath(url));
  529. QString localFile = url.toLocalFile();
  530. if (!url.isLocalFile() || !QFileInfo::exists(localFile)) {
  531. localFile.clear();
  532. }
  533. bool isTextFile = false;
  534. if (!isImage && !localFile.isEmpty()) {
  535. const auto mimeType = QMimeDatabase().mimeTypeForFile(localFile);
  536. if (mimeType.isValid() && mimeType.inherits(QStringLiteral("text/plain"))) {
  537. isTextFile = true;
  538. }
  539. }
  540. SelectDialog dialog(tr("Insert From Clipboard"), this);
  541. if (isImage) {
  542. dialog.addSelection(tr("Insert As Image"), 0);
  543. dialog.addSelection(tr("Insert As Image Link"), 1);
  544. if (!localFile.isEmpty()) {
  545. dialog.addSelection(tr("Insert As Relative Image Link"), 7);
  546. }
  547. }
  548. dialog.addSelection(tr("Insert As Link"), 2);
  549. if (!localFile.isEmpty()) {
  550. dialog.addSelection(tr("Insert As Relative Link"), 3);
  551. if (m_buffer->isAttachmentSupported() && !m_buffer->isAttachment(localFile) && !PathUtils::isDir(localFile)) {
  552. dialog.addSelection(tr("Attach And Insert Link"), 6);
  553. }
  554. }
  555. dialog.addSelection(tr("Insert As Text"), 4);
  556. if (!localFile.isEmpty() && isTextFile) {
  557. dialog.addSelection(tr("Insert File Content"), 5);
  558. }
  559. // FIXME: After calling dialog.exec(), p_source->hasUrl() returns false.
  560. if (dialog.exec() == QDialog::Accepted) {
  561. bool relativeLink = false;
  562. switch (dialog.getSelection()) {
  563. case 0:
  564. {
  565. // Insert As Image.
  566. insertImageFromUrl(PathUtils::urlToPath(url));
  567. return true;
  568. }
  569. case 7:
  570. // Insert As Relative Image Link.
  571. relativeLink = true;
  572. Q_FALLTHROUGH();
  573. case 1:
  574. {
  575. // Insert As Image Link.
  576. QString urlInLink;
  577. if (relativeLink) {
  578. urlInLink = getRelativeLink(localFile);
  579. } else {
  580. urlInLink = url.toString(QUrl::EncodeSpaces);
  581. }
  582. enterInsertModeIfApplicable();
  583. const auto imageLink = vte::MarkdownUtils::generateImageLink("", urlInLink, "");
  584. m_textEdit->insertPlainText(imageLink);
  585. return true;
  586. }
  587. case 6:
  588. {
  589. // Attach And Insert Link.
  590. QStringList fileList;
  591. fileList << localFile;
  592. fileList = m_buffer->addAttachment(QString(), fileList);
  593. // Update localFile to point to the attachment file.
  594. localFile = fileList[0];
  595. Q_FALLTHROUGH();
  596. }
  597. case 3:
  598. // Insert As Relative link.
  599. relativeLink = true;
  600. Q_FALLTHROUGH();
  601. case 2:
  602. {
  603. // Insert As Link.
  604. QString linkText;
  605. if (!localFile.isEmpty()) {
  606. linkText = QFileInfo(localFile).fileName();
  607. }
  608. QString linkUrl;
  609. if (relativeLink) {
  610. Q_ASSERT(!localFile.isEmpty());
  611. linkUrl = getRelativeLink(localFile);
  612. } else {
  613. linkUrl = url.toString(QUrl::EncodeSpaces);
  614. }
  615. LinkInsertDialog linkDialog(tr("Insert Link"), linkText, linkUrl, false, this);
  616. if (linkDialog.exec() == QDialog::Accepted) {
  617. linkText = linkDialog.getLinkText();
  618. linkUrl = linkDialog.getLinkUrl();
  619. enterInsertModeIfApplicable();
  620. vte::MarkdownUtils::typeLink(m_textEdit, linkText, linkUrl);
  621. }
  622. return true;
  623. }
  624. case 4:
  625. {
  626. // Insert As Text.
  627. enterInsertModeIfApplicable();
  628. if (p_source->hasText()) {
  629. m_textEdit->insertPlainText(p_source->text());
  630. } else {
  631. m_textEdit->insertPlainText(url.toString());
  632. }
  633. return true;
  634. }
  635. case 5:
  636. {
  637. // Insert File Content.
  638. Q_ASSERT(!localFile.isEmpty() && isTextFile);
  639. enterInsertModeIfApplicable();
  640. m_textEdit->insertPlainText(FileUtils::readTextFile(localFile));
  641. return true;
  642. }
  643. default:
  644. Q_ASSERT(false);
  645. break;
  646. }
  647. } else {
  648. // Nothing happens.
  649. return true;
  650. }
  651. return false;
  652. }
  653. void MarkdownEditor::insertImageFromMimeData(const QMimeData *p_source)
  654. {
  655. QImage image = qvariant_cast<QImage>(p_source->imageData());
  656. if (image.isNull()) {
  657. return;
  658. }
  659. ImageInsertDialog dialog(tr("Insert Image From Clipboard"), "", "", "", false, this);
  660. dialog.setImage(image);
  661. if (dialog.exec() == QDialog::Accepted) {
  662. enterInsertModeIfApplicable();
  663. insertImageToBufferFromData(dialog.getImageTitle(),
  664. dialog.getImageAltText(),
  665. image,
  666. dialog.getScaledWidth());
  667. }
  668. }
  669. void MarkdownEditor::insertImageFromUrl(const QString &p_url)
  670. {
  671. ImageInsertDialog dialog(tr("Insert Image From URL"), "", "", "", false, this);
  672. dialog.setImagePath(p_url);
  673. if (dialog.exec() == QDialog::Accepted) {
  674. enterInsertModeIfApplicable();
  675. if (dialog.getImageSource() == ImageInsertDialog::Source::LocalFile) {
  676. insertImageToBufferFromLocalFile(dialog.getImageTitle(),
  677. dialog.getImageAltText(),
  678. dialog.getImagePath(),
  679. dialog.getScaledWidth());
  680. } else {
  681. auto image = dialog.getImage();
  682. if (!image.isNull()) {
  683. insertImageToBufferFromData(dialog.getImageTitle(),
  684. dialog.getImageAltText(),
  685. image,
  686. dialog.getScaledWidth());
  687. }
  688. }
  689. }
  690. }
  691. QString MarkdownEditor::getRelativeLink(const QString &p_path)
  692. {
  693. if (PathUtils::isLocalFile(p_path)) {
  694. auto relativePath = PathUtils::relativePath(PathUtils::parentDirPath(m_buffer->getContentPath()), p_path);
  695. auto link = PathUtils::encodeSpacesInPath(QDir::fromNativeSeparators(relativePath));
  696. if (m_config.getPrependDotInRelativeLink()) {
  697. PathUtils::prependDotIfRelative(link);
  698. }
  699. return link;
  700. } else {
  701. return p_path;
  702. }
  703. }
  704. const QVector<MarkdownEditor::Heading> &MarkdownEditor::getHeadings() const
  705. {
  706. return m_headings;
  707. }
  708. int MarkdownEditor::getCurrentHeadingIndex() const
  709. {
  710. int blockNumber = m_textEdit->textCursor().blockNumber();
  711. return getHeadingIndexByBlockNumber(blockNumber);
  712. }
  713. void MarkdownEditor::updateHeadings(const QVector<vte::peg::ElementRegion> &p_headerRegions)
  714. {
  715. bool needUpdateSectionNumber = false;
  716. if (isReadOnly()) {
  717. m_sectionNumberEnabled = false;
  718. } else {
  719. needUpdateSectionNumber = m_config.getSectionNumberMode() == MarkdownEditorConfig::SectionNumberMode::Edit;
  720. if (m_overriddenSectionNumber != OverrideState::NoOverride) {
  721. needUpdateSectionNumber = m_overriddenSectionNumber == OverrideState::ForceEnable;
  722. }
  723. if (needUpdateSectionNumber) {
  724. m_sectionNumberEnabled = true;
  725. } else if (m_sectionNumberEnabled) {
  726. // On -> Off. We still need to do the clean up.
  727. needUpdateSectionNumber = true;
  728. m_sectionNumberEnabled = false;
  729. }
  730. }
  731. QVector<Heading> headings;
  732. headings.reserve(p_headerRegions.size());
  733. // Assume that each block contains only one line.
  734. // Only support # syntax for now.
  735. auto doc = document();
  736. for (auto const &reg : p_headerRegions) {
  737. auto block = doc->findBlock(reg.m_startPos);
  738. if (!block.isValid()) {
  739. continue;
  740. }
  741. if (!block.contains(reg.m_endPos - 1)) {
  742. qWarning() << "header accross multiple blocks, starting from block" << block.blockNumber() << block.text();
  743. }
  744. auto match = vte::MarkdownUtils::matchHeader(block.text());
  745. if (match.m_matched) {
  746. Heading heading(match.m_header,
  747. match.m_level,
  748. match.m_sequence,
  749. block.blockNumber());
  750. headings.append(heading);
  751. }
  752. }
  753. OutlineProvider::makePerfectHeadings(headings, m_headings);
  754. if (needUpdateSectionNumber) {
  755. // Use a timer to kick off the update to let user have time to undo.
  756. m_sectionNumberTimer->start();
  757. }
  758. emit headingsChanged();
  759. emit currentHeadingChanged();
  760. }
  761. int MarkdownEditor::getHeadingIndexByBlockNumber(int p_blockNumber) const
  762. {
  763. if (m_headings.isEmpty()) {
  764. return -1;
  765. }
  766. int left = 0, right = m_headings.size() - 1;
  767. while (left < right) {
  768. int mid = left + (right - left + 1) / 2;
  769. int val = m_headings[mid].m_blockNumber;
  770. if (val == -1) {
  771. // Search to right.
  772. for (int i = mid + 1; i <= right; ++i) {
  773. if (m_headings[i].m_blockNumber != -1) {
  774. mid = i;
  775. val = m_headings[i].m_blockNumber;
  776. break;
  777. }
  778. }
  779. if (val == -1) {
  780. // Search to left.
  781. for (int i = mid - 1; i >= left; --i) {
  782. if (m_headings[i].m_blockNumber != -1) {
  783. mid = i;
  784. val = m_headings[i].m_blockNumber;
  785. break;
  786. }
  787. }
  788. }
  789. }
  790. if (val == -1) {
  791. // No more valid values.
  792. break;
  793. }
  794. if (val == p_blockNumber) {
  795. return mid;
  796. } else if (val > p_blockNumber) {
  797. // Skip the -1 headings.
  798. // Bad case: [0, 2, 3, 43, 44, -1, 46, 60].
  799. // If not skipped, [left, right] will be stuck at [4, 5].
  800. right = mid - 1;
  801. while (right >= left && m_headings[right].m_blockNumber == -1) {
  802. --right;
  803. }
  804. } else {
  805. left = mid;
  806. }
  807. }
  808. if (m_headings[left].m_blockNumber <= p_blockNumber && m_headings[left].m_blockNumber != -1) {
  809. return left;
  810. }
  811. return -1;
  812. }
  813. void MarkdownEditor::scrollToHeading(int p_idx)
  814. {
  815. if (p_idx < 0 || p_idx >= m_headings.size()) {
  816. return;
  817. }
  818. if (m_headings[p_idx].m_blockNumber == -1) {
  819. return;
  820. }
  821. scrollToLine(m_headings[p_idx].m_blockNumber, true);
  822. }
  823. void MarkdownEditor::handleContextMenuEvent(QContextMenuEvent *p_event, bool *p_handled, QScopedPointer<QMenu> *p_menu)
  824. {
  825. *p_handled = true;
  826. p_menu->reset(m_textEdit->createStandardContextMenu(p_event->pos()));
  827. auto menu = p_menu->data();
  828. const auto actions = menu->actions();
  829. QAction *firstAct = actions.isEmpty() ? nullptr : actions.first();
  830. // QAction *copyAct = WidgetUtils::findActionByObjectName(actions, "edit-copy");
  831. QAction *pasteAct = WidgetUtils::findActionByObjectName(actions, "edit-paste");
  832. if (!m_textEdit->hasSelection()) {
  833. auto readAct = new QAction(tr("&Read"), menu);
  834. WidgetUtils::addActionShortcutText(readAct,
  835. ConfigMgr::getInst().getEditorConfig().getShortcut(EditorConfig::Shortcut::EditRead));
  836. connect(readAct, &QAction::triggered,
  837. this, &MarkdownEditor::readRequested);
  838. menu->insertAction(firstAct, readAct);
  839. if (firstAct) {
  840. menu->insertSeparator(firstAct);
  841. }
  842. }
  843. if (pasteAct && pasteAct->isEnabled()) {
  844. QClipboard *clipboard = QApplication::clipboard();
  845. const QMimeData *mimeData = clipboard->mimeData();
  846. // Rich Paste.
  847. auto richPasteAct = new QAction(tr("Rich Paste"), menu);
  848. WidgetUtils::addActionShortcutText(richPasteAct,
  849. ConfigMgr::getInst().getEditorConfig().getShortcut(EditorConfig::Shortcut::RichPaste));
  850. connect(richPasteAct, &QAction::triggered,
  851. this, &MarkdownEditor::richPaste);
  852. WidgetUtils::insertActionAfter(menu, pasteAct, richPasteAct);
  853. if (mimeData->hasHtml()) {
  854. // Parse to Markdown and Paste.
  855. auto parsePasteAct = new QAction(tr("Parse to Markdown and Paste"), menu);
  856. connect(parsePasteAct, &QAction::triggered,
  857. this, &MarkdownEditor::parseToMarkdownAndPaste);
  858. WidgetUtils::insertActionAfter(menu, richPasteAct, parsePasteAct);
  859. }
  860. }
  861. {
  862. menu->addSeparator();
  863. auto snippetAct = menu->addAction(tr("Insert Snippet"), this, &MarkdownEditor::applySnippetRequested);
  864. WidgetUtils::addActionShortcutText(snippetAct,
  865. ConfigMgr::getInst().getEditorConfig().getShortcut(EditorConfig::Shortcut::ApplySnippet));
  866. }
  867. appendImageHostMenu(menu);
  868. appendSpellCheckMenu(p_event, menu);
  869. }
  870. void MarkdownEditor::richPaste()
  871. {
  872. QClipboard *clipboard = QApplication::clipboard();
  873. clipboard->setProperty(c_clipboardPropertyMark, true);
  874. m_textEdit->paste();
  875. clipboard->setProperty(c_clipboardPropertyMark, false);
  876. }
  877. void MarkdownEditor::setupShortcuts()
  878. {
  879. const auto &editorConfig = ConfigMgr::getInst().getEditorConfig();
  880. {
  881. auto shortcut = WidgetUtils::createShortcut(editorConfig.getShortcut(EditorConfig::Shortcut::RichPaste),
  882. this);
  883. if (shortcut) {
  884. connect(shortcut, &QShortcut::activated,
  885. this, &MarkdownEditor::richPaste);
  886. }
  887. }
  888. }
  889. void MarkdownEditor::parseToMarkdownAndPaste()
  890. {
  891. if (isReadOnly()) {
  892. return;
  893. }
  894. QClipboard *clipboard = QApplication::clipboard();
  895. const QMimeData *mimeData = clipboard->mimeData();
  896. QString html(mimeData->html());
  897. if (!html.isEmpty()) {
  898. emit htmlToMarkdownRequested(0, ++m_timeStamp, html);
  899. }
  900. }
  901. void MarkdownEditor::handleHtmlToMarkdownData(quint64 p_id, TimeStamp p_timeStamp, const QString &p_text)
  902. {
  903. Q_UNUSED(p_id);
  904. qDebug() << "htmlToMarkdownData" << p_timeStamp;
  905. if (m_timeStamp == p_timeStamp && !p_text.isEmpty()) {
  906. QString text(p_text);
  907. const auto &editorConfig = ConfigMgr::getInst().getEditorConfig().getMarkdownEditorConfig();
  908. if (editorConfig.getFetchImagesInParseAndPaste()) {
  909. fetchImagesToLocalAndReplace(text);
  910. }
  911. insertText(text);
  912. }
  913. }
  914. static QString purifyImageTitle(QString p_title)
  915. {
  916. return p_title.remove(QRegExp("[\\r\\n\\[\\]]"));
  917. }
  918. void MarkdownEditor::fetchImagesToLocalAndReplace(QString &p_text)
  919. {
  920. auto regs = vte::MarkdownUtils::fetchImageRegionsViaParser(p_text);
  921. if (regs.isEmpty()) {
  922. return;
  923. }
  924. // Sort it in ascending order.
  925. std::sort(regs.begin(), regs.end());
  926. QProgressDialog proDlg(tr("Fetching images to local..."),
  927. tr("Abort"),
  928. 0,
  929. regs.size(),
  930. this);
  931. proDlg.setWindowModality(Qt::WindowModal);
  932. proDlg.setWindowTitle(tr("Fetch Images To Local"));
  933. QRegExp zhihuRegExp("^https?://www\\.zhihu\\.com/equation\\?tex=(.+)$");
  934. QRegExp regExp(vte::MarkdownUtils::c_imageLinkRegExp);
  935. for (int i = regs.size() - 1; i >= 0; --i) {
  936. proDlg.setValue(regs.size() - 1 - i);
  937. if (proDlg.wasCanceled()) {
  938. break;
  939. }
  940. const auto &reg = regs[i];
  941. QString linkText = p_text.mid(reg.m_startPos, reg.m_endPos - reg.m_startPos);
  942. if (regExp.indexIn(linkText) == -1) {
  943. continue;
  944. }
  945. qDebug() << "fetching image link" << linkText;
  946. const QString imageTitle = purifyImageTitle(regExp.cap(1).trimmed());
  947. QString imageUrl = regExp.cap(2).trimmed();
  948. const int maxUrlLength = 100;
  949. QString urlToDisplay(imageUrl);
  950. if (urlToDisplay.size() > maxUrlLength) {
  951. urlToDisplay = urlToDisplay.left(maxUrlLength) + "...";
  952. }
  953. proDlg.setLabelText(tr("Fetching image (%1)").arg(urlToDisplay));
  954. // Handle equation from zhihu.com like http://www.zhihu.com/equation?tex=P.
  955. if (zhihuRegExp.indexIn(imageUrl) != -1) {
  956. QString tex = zhihuRegExp.cap(1).trimmed();
  957. // Remove the +.
  958. tex.replace(QChar('+'), " ");
  959. tex = QUrl::fromPercentEncoding(tex.toUtf8());
  960. if (tex.isEmpty()) {
  961. continue;
  962. }
  963. tex = "$" + tex + "$";
  964. p_text.replace(reg.m_startPos,
  965. reg.m_endPos - reg.m_startPos,
  966. tex);
  967. continue;
  968. }
  969. // Only handle absolute file path or network path.
  970. QString srcImagePath;
  971. QFileInfo info(WebUtils::purifyUrl(imageUrl));
  972. // For network image.
  973. QScopedPointer<QTemporaryFile> tmpFile;
  974. if (info.exists()) {
  975. if (info.isAbsolute()) {
  976. // Absolute local path.
  977. srcImagePath = info.absoluteFilePath();
  978. }
  979. } else {
  980. // Network path.
  981. // Prepend the protocol if missing.
  982. if (imageUrl.startsWith(QStringLiteral("//"))) {
  983. imageUrl.prepend(QStringLiteral("https:"));
  984. }
  985. QByteArray data = vte::NetworkAccess::request(QUrl(imageUrl)).m_data;
  986. if (!data.isEmpty()) {
  987. // Prefer the suffix from the real data.
  988. auto suffix = ImageUtils::guessImageSuffix(data);
  989. if (suffix.isEmpty()) {
  990. suffix = info.suffix();
  991. } else if (info.suffix() != suffix) {
  992. qWarning() << "guess a different suffix from image data" << info.suffix() << suffix;
  993. }
  994. tmpFile.reset(FileUtils::createTemporaryFile(suffix));
  995. if (tmpFile->open() && tmpFile->write(data) > -1) {
  996. srcImagePath = tmpFile->fileName();
  997. }
  998. // Need to close it explicitly to flush cache of small file.
  999. tmpFile->close();
  1000. }
  1001. }
  1002. if (srcImagePath.isEmpty()) {
  1003. continue;
  1004. }
  1005. // Insert image without inserting text.
  1006. QString urlInLink;
  1007. bool ret = insertImageToBufferFromLocalFile(imageTitle,
  1008. QString(),
  1009. srcImagePath,
  1010. 0,
  1011. 0,
  1012. false,
  1013. &urlInLink);
  1014. if (!ret || urlInLink.isEmpty()) {
  1015. continue;
  1016. }
  1017. // Replace URL in link.
  1018. QString newLink = QString("![%1](%2%3%4)")
  1019. .arg(imageTitle, urlInLink, regExp.cap(3), regExp.cap(6));
  1020. p_text.replace(reg.m_startPos,
  1021. reg.m_endPos - reg.m_startPos,
  1022. newLink);
  1023. }
  1024. proDlg.setValue(regs.size());
  1025. }
  1026. static bool updateHeadingSectionNumber(QTextCursor &p_cursor,
  1027. const QTextBlock &p_block,
  1028. const QString &p_sectionNumber,
  1029. bool p_endingDot)
  1030. {
  1031. if (!p_block.isValid()) {
  1032. return false;
  1033. }
  1034. QString text = p_block.text();
  1035. auto match = vte::MarkdownUtils::matchHeader(text);
  1036. Q_ASSERT(match.m_matched);
  1037. bool isSequence = false;
  1038. if (!match.m_sequence.isEmpty()) {
  1039. // Check if this sequence is the real sequence matching current style.
  1040. if (match.m_sequence.endsWith('.')) {
  1041. isSequence = p_endingDot;
  1042. } else {
  1043. isSequence = !p_endingDot;
  1044. }
  1045. }
  1046. int start = match.m_level + 1;
  1047. int end = match.m_level + match.m_spacesAfterMarker;
  1048. if (isSequence) {
  1049. end += match.m_sequence.size() + match.m_spacesAfterSequence;
  1050. }
  1051. Q_ASSERT(start <= end);
  1052. p_cursor.setPosition(p_block.position() + start);
  1053. if (start != end) {
  1054. p_cursor.setPosition(p_block.position() + end, QTextCursor::KeepAnchor);
  1055. }
  1056. if (p_sectionNumber.isEmpty()) {
  1057. p_cursor.removeSelectedText();
  1058. } else {
  1059. p_cursor.insertText(p_sectionNumber + ' ');
  1060. }
  1061. return true;
  1062. }
  1063. bool MarkdownEditor::updateSectionNumber(const QVector<Heading> &p_headings)
  1064. {
  1065. SectionNumber sectionNumber(7, 0);
  1066. int baseLevel = m_config.getSectionNumberBaseLevel();
  1067. if (baseLevel < 1 || baseLevel > 6) {
  1068. baseLevel = 1;
  1069. }
  1070. bool changed = false;
  1071. bool endingDot = m_config.getSectionNumberStyle() == MarkdownEditorConfig::SectionNumberStyle::DigDotDigDot;
  1072. auto doc = document();
  1073. QTextCursor cursor(doc);
  1074. cursor.beginEditBlock();
  1075. for (const auto &heading : p_headings) {
  1076. OutlineProvider::increaseSectionNumber(sectionNumber, heading.m_level, baseLevel);
  1077. auto sectionStr = m_sectionNumberEnabled ? OutlineProvider::joinSectionNumber(sectionNumber, endingDot) : QString();
  1078. if (heading.m_blockNumber > -1 && sectionStr != heading.m_sectionNumber) {
  1079. if (updateHeadingSectionNumber(cursor,
  1080. doc->findBlockByNumber(heading.m_blockNumber),
  1081. sectionStr,
  1082. endingDot)) {
  1083. changed = true;
  1084. }
  1085. }
  1086. }
  1087. cursor.endEditBlock();
  1088. return changed;
  1089. }
  1090. void MarkdownEditor::overrideSectionNumber(OverrideState p_state)
  1091. {
  1092. if (m_overriddenSectionNumber == p_state) {
  1093. return;
  1094. }
  1095. m_overriddenSectionNumber = p_state;
  1096. getHighlighter()->updateHighlight();
  1097. }
  1098. void MarkdownEditor::updateFromConfig(bool p_initialized)
  1099. {
  1100. if (m_config.getTextEditorConfig().getZoomDelta() != 0) {
  1101. zoom(m_config.getTextEditorConfig().getZoomDelta());
  1102. }
  1103. if (p_initialized) {
  1104. getHighlighter()->updateHighlight();
  1105. }
  1106. }
  1107. void MarkdownEditor::setupTableHelper()
  1108. {
  1109. m_tableHelper = new MarkdownTableHelper(this, this);
  1110. connect(getHighlighter(), &vte::PegMarkdownHighlighter::tableBlocksUpdated,
  1111. m_tableHelper, &MarkdownTableHelper::updateTableBlocks);
  1112. }
  1113. QRgb MarkdownEditor::getPreviewBackground() const
  1114. {
  1115. auto th = theme();
  1116. const auto &fmt = th->editorStyle(vte::Theme::EditorStyle::Preview);
  1117. return fmt.m_backgroundColor;
  1118. }
  1119. void MarkdownEditor::setImageHost(ImageHost *p_host)
  1120. {
  1121. // It may be different than the global default image host.
  1122. m_imageHost = p_host;
  1123. }
  1124. static QString generateImageHostFileName(const Buffer *p_buffer, const QString &p_destFileName)
  1125. {
  1126. auto destPath = ImageHostUtils::generateRelativePath(p_buffer);
  1127. if (destPath.isEmpty()) {
  1128. destPath = p_destFileName;
  1129. } else {
  1130. destPath += "/" + p_destFileName;
  1131. }
  1132. return destPath;
  1133. }
  1134. QString MarkdownEditor::saveToImageHost(const QByteArray &p_imageData, const QString &p_destFileName)
  1135. {
  1136. Q_ASSERT(m_imageHost);
  1137. const auto destPath = generateImageHostFileName(m_buffer, p_destFileName);
  1138. QString errMsg;
  1139. QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  1140. auto targetUrl = m_imageHost->create(p_imageData, destPath, errMsg);
  1141. QApplication::restoreOverrideCursor();
  1142. if (targetUrl.isEmpty()) {
  1143. MessageBoxHelper::notify(MessageBoxHelper::Warning,
  1144. QString("Failed to upload image to image host (%1) as (%2).").arg(m_imageHost->getName(), destPath),
  1145. QString(),
  1146. errMsg,
  1147. this);
  1148. }
  1149. return targetUrl;
  1150. }
  1151. void MarkdownEditor::appendImageHostMenu(QMenu *p_menu)
  1152. {
  1153. p_menu->addSeparator();
  1154. auto subMenu = p_menu->addMenu(tr("Upload Images To Image Host"));
  1155. const auto &hosts = ImageHostMgr::getInst().getImageHosts();
  1156. if (hosts.isEmpty()) {
  1157. auto act = subMenu->addAction(tr("None"));
  1158. act->setEnabled(false);
  1159. return;
  1160. }
  1161. for (const auto &host : hosts) {
  1162. auto act = subMenu->addAction(host->getName(),
  1163. this,
  1164. &MarkdownEditor::uploadImagesToImageHost);
  1165. act->setData(host->getName());
  1166. }
  1167. }
  1168. void MarkdownEditor::uploadImagesToImageHost()
  1169. {
  1170. auto act = static_cast<QAction *>(sender());
  1171. auto host = ImageHostMgr::getInst().find(act->data().toString());
  1172. Q_ASSERT(host);
  1173. // Only LocalRelativeInternal images.
  1174. // Descending order of the link position.
  1175. auto images = vte::MarkdownUtils::fetchImagesFromMarkdownText(m_buffer->getContent(),
  1176. m_buffer->getResourcePath(),
  1177. vte::MarkdownLink::TypeFlag::LocalRelativeInternal);
  1178. if (images.isEmpty()) {
  1179. return;
  1180. }
  1181. QProgressDialog proDlg(tr("Uploading local images..."),
  1182. tr("Abort"),
  1183. 0,
  1184. images.size(),
  1185. this);
  1186. proDlg.setWindowModality(Qt::WindowModal);
  1187. proDlg.setWindowTitle(tr("Upload Images To Image Host"));
  1188. int cnt = 0;
  1189. auto cursor = m_textEdit->textCursor();
  1190. cursor.beginEditBlock();
  1191. for (int i = 0; i < images.size(); ++i) {
  1192. const auto &link = images[i];
  1193. proDlg.setValue(i + 1);
  1194. if (proDlg.wasCanceled()) {
  1195. break;
  1196. }
  1197. proDlg.setLabelText(tr("Upload image (%1)").arg(link.m_path));
  1198. Q_ASSERT(i == 0 || link.m_urlInLinkPos < images[i - 1].m_urlInLinkPos);
  1199. QByteArray ba;
  1200. try {
  1201. ba = FileUtils::readFile(link.m_path);
  1202. } catch (Exception &e) {
  1203. MessageBoxHelper::notify(MessageBoxHelper::Warning,
  1204. QString("Failed to read local image file (%1) (%2).").arg(link.m_path, e.what()),
  1205. this);
  1206. continue;
  1207. }
  1208. if (ba.isEmpty()) {
  1209. qWarning() << "Skipped uploading empty image" << link.m_path;
  1210. continue;
  1211. }
  1212. const auto destPath = generateImageHostFileName(m_buffer, PathUtils::fileName(link.m_path));
  1213. QString errMsg;
  1214. QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  1215. const auto targetUrl = host->create(ba, destPath, errMsg);
  1216. QApplication::restoreOverrideCursor();
  1217. if (targetUrl.isEmpty()) {
  1218. MessageBoxHelper::notify(MessageBoxHelper::Warning,
  1219. QString("Failed to upload image to image host (%1) as (%2).").arg(host->getName(), destPath),
  1220. QString(),
  1221. errMsg,
  1222. this);
  1223. continue;
  1224. }
  1225. // Update the link URL.
  1226. cursor.setPosition(link.m_urlInLinkPos);
  1227. cursor.setPosition(link.m_urlInLinkPos + link.m_urlInLink.size(), QTextCursor::KeepAnchor);
  1228. cursor.insertText(targetUrl);
  1229. ++cnt;
  1230. }
  1231. cursor.endEditBlock();
  1232. proDlg.setValue(images.size());
  1233. if (cnt > 0) {
  1234. m_textEdit->setTextCursor(cursor);
  1235. }
  1236. }