markdowneditor.cpp 54 KB

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