vmdeditor.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  1. #include "vmdeditor.h"
  2. #include <QtWidgets>
  3. #include <QMenu>
  4. #include <QDebug>
  5. #include <QScopedPointer>
  6. #include <QClipboard>
  7. #include <QMimeDatabase>
  8. #include <QTemporaryFile>
  9. #include <QProgressDialog>
  10. #include "vdocument.h"
  11. #include "utils/veditutils.h"
  12. #include "vedittab.h"
  13. #include "pegmarkdownhighlighter.h"
  14. #include "vcodeblockhighlighthelper.h"
  15. #include "vmdeditoperations.h"
  16. #include "vtableofcontent.h"
  17. #include "utils/veditutils.h"
  18. #include "dialog/vselectdialog.h"
  19. #include "dialog/vconfirmdeletiondialog.h"
  20. #include "vtextblockdata.h"
  21. #include "vorphanfile.h"
  22. #include "vnotefile.h"
  23. #include "vpreviewmanager.h"
  24. #include "utils/viconutils.h"
  25. #include "dialog/vcopytextashtmldialog.h"
  26. #include "utils/vwebutils.h"
  27. #include "dialog/vinsertlinkdialog.h"
  28. #include "utils/vclipboardutils.h"
  29. #include "vplantumlhelper.h"
  30. #include "vgraphvizhelper.h"
  31. #include "vmdtab.h"
  32. #include "vdownloader.h"
  33. extern VWebUtils *g_webUtils;
  34. extern VConfigManager *g_config;
  35. #define LINE_NUMBER_AREA_FONT_DELTA -2
  36. VMdEditor::VMdEditor(VFile *p_file,
  37. VDocument *p_doc,
  38. MarkdownConverterType p_type,
  39. const QSharedPointer<VTextEditCompleter> &p_completer,
  40. QWidget *p_parent)
  41. : VTextEdit(p_parent),
  42. VEditor(p_file, this, p_completer),
  43. m_pegHighlighter(NULL),
  44. m_freshEdit(true),
  45. m_textToHtmlDialog(NULL),
  46. m_zoomDelta(0),
  47. m_editTab(NULL),
  48. m_copyTimeStamp(0)
  49. {
  50. Q_ASSERT(p_file->getDocType() == DocType::Markdown);
  51. VEditor::init();
  52. // Hook functions from VEditor.
  53. connect(this, &VTextEdit::cursorPositionChanged,
  54. this, [this]() {
  55. highlightOnCursorPositionChanged();
  56. });
  57. connect(document(), &QTextDocument::contentsChange,
  58. this, [this](int p_position, int p_charsRemoved, int p_charsAdded) {
  59. Q_UNUSED(p_position);
  60. if (p_charsRemoved > 0 || p_charsAdded > 0) {
  61. updateTimeStamp();
  62. }
  63. });
  64. connect(this, &VTextEdit::selectionChanged,
  65. this, [this]() {
  66. highlightSelectedWord();
  67. });
  68. // End.
  69. setReadOnly(true);
  70. m_pegHighlighter = new PegMarkdownHighlighter(document(), this);
  71. m_pegHighlighter->init(g_config->getMdHighlightingStyles(),
  72. g_config->getCodeBlockStyles(),
  73. g_config->getEnableMathjax(),
  74. g_config->getMarkdownHighlightInterval());
  75. connect(m_pegHighlighter, &PegMarkdownHighlighter::headersUpdated,
  76. this, &VMdEditor::updateHeaders);
  77. // After highlight, the cursor may trun into non-visible. We should make it visible
  78. // in this case.
  79. connect(m_pegHighlighter, &PegMarkdownHighlighter::highlightCompleted,
  80. this, [this]() {
  81. scrollCursorLineIfNecessary();
  82. if (m_freshEdit) {
  83. m_freshEdit = false;
  84. emit m_object->ready();
  85. }
  86. });
  87. m_cbHighlighter = new VCodeBlockHighlightHelper(m_pegHighlighter,
  88. p_doc,
  89. p_type);
  90. m_previewMgr = new VPreviewManager(this, m_pegHighlighter);
  91. connect(m_pegHighlighter, &PegMarkdownHighlighter::imageLinksUpdated,
  92. m_previewMgr, &VPreviewManager::updateImageLinks);
  93. connect(m_previewMgr, &VPreviewManager::requestUpdateImageLinks,
  94. m_pegHighlighter, &PegMarkdownHighlighter::updateHighlight);
  95. m_editOps = new VMdEditOperations(this, m_file);
  96. connect(m_editOps, &VEditOperations::statusMessage,
  97. m_object, &VEditorObject::statusMessage);
  98. connect(m_editOps, &VEditOperations::vimStatusUpdated,
  99. m_object, &VEditorObject::vimStatusUpdated);
  100. connect(this, &VTextEdit::cursorPositionChanged,
  101. this, &VMdEditor::updateCurrentHeader);
  102. connect(this, &VTextEdit::cursorPositionChanged,
  103. m_object, &VEditorObject::cursorPositionChanged);
  104. setDisplayScaleFactor(VUtils::calculateScaleFactor());
  105. updateFontAndPalette();
  106. updateConfig();
  107. }
  108. void VMdEditor::updateFontAndPalette()
  109. {
  110. QFont font(g_config->getMdEditFont());
  111. setFont(font);
  112. const QPalette &palette = g_config->getMdEditPalette();
  113. /*
  114. Do not use this function in conjunction with Qt Style Sheets. When
  115. using style sheets, the palette of a widget can be customized using
  116. the "color", "background-color", "selection-color",
  117. "selection-background-color" and "alternate-background-color".
  118. */
  119. // setPalette(palette);
  120. // setTextColor(palette.color(QPalette::Text));
  121. // Only this could override the font-family set of QWidget in QSS.
  122. setFontAndPaletteByStyleSheet(font, palette);
  123. font.setPointSize(font.pointSize() + LINE_NUMBER_AREA_FONT_DELTA);
  124. updateLineNumberAreaWidth(QFontMetrics(font));
  125. }
  126. void VMdEditor::beginEdit()
  127. {
  128. updateConfig();
  129. initInitImages();
  130. setModified(false);
  131. setReadOnlyAndHighlightCurrentLine(false);
  132. emit statusChanged();
  133. if (m_freshEdit) {
  134. m_pegHighlighter->updateHighlight();
  135. relayout();
  136. } else {
  137. updateHeaders(m_pegHighlighter->getHeaderRegions());
  138. }
  139. }
  140. void VMdEditor::endEdit()
  141. {
  142. setReadOnlyAndHighlightCurrentLine(true);
  143. clearUnusedImages();
  144. }
  145. void VMdEditor::saveFile()
  146. {
  147. Q_ASSERT(m_file->isModifiable());
  148. if (!document()->isModified()) {
  149. return;
  150. }
  151. m_file->setContent(toPlainText());
  152. setModified(false);
  153. clearUnusedImages();
  154. initInitImages();
  155. }
  156. void VMdEditor::reloadFile()
  157. {
  158. bool readonly = isReadOnly();
  159. setReadOnly(true);
  160. const QString &content = m_file->getContent();
  161. setPlainText(content);
  162. setModified(false);
  163. setReadOnly(readonly);
  164. if (!m_freshEdit) {
  165. m_freshEdit = true;
  166. refreshPreview();
  167. }
  168. }
  169. bool VMdEditor::scrollToBlock(int p_blockNumber)
  170. {
  171. QTextBlock block = document()->findBlockByNumber(p_blockNumber);
  172. if (block.isValid()) {
  173. scrollBlockInPage(block.blockNumber(), 0);
  174. moveCursor(QTextCursor::EndOfBlock);
  175. return true;
  176. }
  177. return false;
  178. }
  179. // Get the visual offset of a block.
  180. #define GETVISUALOFFSETY(x) (contentOffsetY() + (int)(x).y())
  181. void VMdEditor::makeBlockVisible(const QTextBlock &p_block)
  182. {
  183. if (!p_block.isValid() || !p_block.isVisible()) {
  184. return;
  185. }
  186. QScrollBar *vbar = verticalScrollBar();
  187. if (!vbar || (vbar->minimum() == vbar->maximum())) {
  188. // No vertical scrollbar. No need to scroll.
  189. return;
  190. }
  191. int height = rect().height();
  192. QScrollBar *hbar = horizontalScrollBar();
  193. if (hbar && (hbar->minimum() != hbar->maximum())) {
  194. height -= hbar->height();
  195. }
  196. bool moved = false;
  197. QAbstractTextDocumentLayout *layout = document()->documentLayout();
  198. QRectF rt = layout->blockBoundingRect(p_block);
  199. int y = GETVISUALOFFSETY(rt);
  200. int rectHeight = (int)rt.height();
  201. // Handle the case rectHeight >= height.
  202. if (rectHeight >= height) {
  203. if (y < 0) {
  204. // Need to scroll up.
  205. while (y + rectHeight < height && vbar->value() > vbar->minimum()) {
  206. moved = true;
  207. vbar->setValue(vbar->value() - vbar->singleStep());
  208. rt = layout->blockBoundingRect(p_block);
  209. rectHeight = (int)rt.height();
  210. y = GETVISUALOFFSETY(rt);
  211. }
  212. } else if (y > 0) {
  213. // Need to scroll down.
  214. while (y > 0 && vbar->value() < vbar->maximum()) {
  215. moved = true;
  216. vbar->setValue(vbar->value() + vbar->singleStep());
  217. rt = layout->blockBoundingRect(p_block);
  218. rectHeight = (int)rt.height();
  219. y = GETVISUALOFFSETY(rt);
  220. }
  221. if (y < 0) {
  222. // One step back.
  223. moved = true;
  224. vbar->setValue(vbar->value() - vbar->singleStep());
  225. }
  226. }
  227. return;
  228. }
  229. // There is an extra line leading in the layout, so there will always be a scroll
  230. // action to scroll the page down.
  231. while (y < 0 && vbar->value() > vbar->minimum()) {
  232. moved = true;
  233. vbar->setValue(vbar->value() - vbar->singleStep());
  234. rt = layout->blockBoundingRect(p_block);
  235. y = GETVISUALOFFSETY(rt);
  236. }
  237. if (moved) {
  238. return;
  239. }
  240. while (y + rectHeight > height && vbar->value() < vbar->maximum()) {
  241. vbar->setValue(vbar->value() + vbar->singleStep());
  242. rt = layout->blockBoundingRect(p_block);
  243. rectHeight = (int)rt.height();
  244. y = GETVISUALOFFSETY(rt);
  245. }
  246. }
  247. static QAction *getActionByObjectName(const QList<QAction *> &p_actions,
  248. const QString &p_objName)
  249. {
  250. for (auto act : p_actions) {
  251. if (act->objectName() == p_objName) {
  252. return act;
  253. }
  254. }
  255. return NULL;
  256. }
  257. // Insert @p_action into @p_menu after action @p_after.
  258. static void insertActionAfter(QAction *p_after, QAction *p_action, QMenu *p_menu)
  259. {
  260. p_menu->insertAction(p_after, p_action);
  261. if (p_after) {
  262. p_menu->removeAction(p_after);
  263. p_menu->insertAction(p_action, p_after);
  264. }
  265. }
  266. static QAction *insertMenuAfter(QAction *p_after, QMenu *p_subMenu, QMenu *p_menu)
  267. {
  268. QAction *menuAct = p_menu->insertMenu(p_after, p_subMenu);
  269. if (p_after) {
  270. p_menu->removeAction(p_after);
  271. p_menu->insertAction(menuAct, p_after);
  272. }
  273. return menuAct;
  274. }
  275. void VMdEditor::contextMenuEvent(QContextMenuEvent *p_event)
  276. {
  277. if (!m_editTab || !m_editTab->isEditMode()) {
  278. return;
  279. }
  280. QScopedPointer<QMenu> menu(createStandardContextMenu());
  281. menu->setToolTipsVisible(true);
  282. QAction *copyAct, *pasteAct, *firstAct;
  283. {
  284. const QList<QAction *> actions = menu->actions();
  285. firstAct = actions.isEmpty() ? NULL : actions.first();
  286. copyAct = getActionByObjectName(actions, "edit-copy");
  287. pasteAct = getActionByObjectName(actions, "edit-paste");
  288. }
  289. if (copyAct && copyAct->isEnabled()) {
  290. initCopyAsMenu(copyAct, menu.data());
  291. }
  292. if (pasteAct && pasteAct->isEnabled()) {
  293. QClipboard *clipboard = QApplication::clipboard();
  294. const QMimeData *mimeData = clipboard->mimeData();
  295. if (mimeData->hasText()) {
  296. initPasteAsBlockQuoteMenu(pasteAct, menu.data());
  297. }
  298. if (mimeData->hasHtml()) {
  299. initPasteAfterParseMenu(pasteAct, menu.data());
  300. }
  301. QAction *pptAct = new QAction(tr("Paste As Plain Text"), menu.data());
  302. VUtils::fixTextWithShortcut(pptAct, "PastePlainText");
  303. connect(pptAct, &QAction::triggered,
  304. this, [this]() {
  305. pastePlainText();
  306. });
  307. insertActionAfter(pasteAct, pptAct, menu.data());
  308. }
  309. if (!textCursor().hasSelection()) {
  310. initLinkAndPreviewMenu(firstAct, menu.data(), p_event->pos());
  311. QAction *saveExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/save_exit.svg"),
  312. tr("&Save Changes And Read"),
  313. menu.data());
  314. saveExitAct->setToolTip(tr("Save changes and exit edit mode"));
  315. connect(saveExitAct, &QAction::triggered,
  316. this, [this]() {
  317. emit m_object->saveAndRead();
  318. });
  319. QAction *discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"),
  320. tr("&Discard Changes And Read"),
  321. menu.data());
  322. discardExitAct->setToolTip(tr("Discard changes and exit edit mode"));
  323. connect(discardExitAct, &QAction::triggered,
  324. this, [this]() {
  325. emit m_object->discardAndRead();
  326. });
  327. VMdTab *mdtab = dynamic_cast<VMdTab *>(m_editTab);
  328. if (mdtab) {
  329. QAction *toggleLivePreviewAct = new QAction(tr("Live Preview For Graphs"), menu.data());
  330. toggleLivePreviewAct->setToolTip(tr("Toggle live preview panel for graphs"));
  331. VUtils::fixTextWithCaptainShortcut(toggleLivePreviewAct, "LivePreview");
  332. connect(toggleLivePreviewAct, &QAction::triggered,
  333. this, [this, mdtab]() {
  334. mdtab->toggleLivePreview();
  335. });
  336. menu->insertAction(firstAct, toggleLivePreviewAct);
  337. menu->insertAction(toggleLivePreviewAct, discardExitAct);
  338. menu->insertAction(discardExitAct, saveExitAct);
  339. menu->insertSeparator(toggleLivePreviewAct);
  340. } else {
  341. menu->insertAction(firstAct, discardExitAct);
  342. menu->insertAction(discardExitAct, saveExitAct);
  343. menu->insertSeparator(discardExitAct);
  344. }
  345. if (firstAct) {
  346. menu->insertSeparator(firstAct);
  347. }
  348. initAttachmentMenu(menu.data());
  349. }
  350. menu->exec(p_event->globalPos());
  351. }
  352. void VMdEditor::mousePressEvent(QMouseEvent *p_event)
  353. {
  354. if (handleMousePressEvent(p_event)) {
  355. return;
  356. }
  357. VTextEdit::mousePressEvent(p_event);
  358. emit m_object->mousePressed(p_event);
  359. }
  360. void VMdEditor::mouseDoubleClickEvent(QMouseEvent *p_event)
  361. {
  362. VTextEdit::mouseDoubleClickEvent(p_event);
  363. emit m_object->mouseDoubleClicked(p_event);
  364. }
  365. void VMdEditor::mouseReleaseEvent(QMouseEvent *p_event)
  366. {
  367. if (handleMouseReleaseEvent(p_event)) {
  368. return;
  369. }
  370. VTextEdit::mouseReleaseEvent(p_event);
  371. emit m_object->mouseReleased(p_event);
  372. }
  373. void VMdEditor::mouseMoveEvent(QMouseEvent *p_event)
  374. {
  375. if (handleMouseMoveEvent(p_event)) {
  376. return;
  377. }
  378. VTextEdit::mouseMoveEvent(p_event);
  379. emit m_object->mouseMoved(p_event);
  380. }
  381. QVariant VMdEditor::inputMethodQuery(Qt::InputMethodQuery p_query) const
  382. {
  383. QVariant ret;
  384. if (handleInputMethodQuery(p_query, ret)) {
  385. return ret;
  386. }
  387. return VTextEdit::inputMethodQuery(p_query);
  388. }
  389. bool VMdEditor::isBlockVisible(const QTextBlock &p_block)
  390. {
  391. if (!p_block.isValid() || !p_block.isVisible()) {
  392. return false;
  393. }
  394. QScrollBar *vbar = verticalScrollBar();
  395. if (!vbar || !vbar->isVisible()) {
  396. // No vertical scrollbar.
  397. return true;
  398. }
  399. int height = rect().height();
  400. QScrollBar *hbar = horizontalScrollBar();
  401. if (hbar && hbar->isVisible()) {
  402. height -= hbar->height();
  403. }
  404. QAbstractTextDocumentLayout *layout = document()->documentLayout();
  405. QRectF rt = layout->blockBoundingRect(p_block);
  406. int y = GETVISUALOFFSETY(rt);
  407. int rectHeight = (int)rt.height();
  408. return (y >= 0 && y < height) || (y < 0 && y + rectHeight > 0);
  409. }
  410. static void addHeaderSequence(QVector<int> &p_sequence, int p_level, int p_baseLevel)
  411. {
  412. Q_ASSERT(p_level >= 1 && p_level < p_sequence.size());
  413. if (p_level < p_baseLevel) {
  414. p_sequence.fill(0);
  415. return;
  416. }
  417. ++p_sequence[p_level];
  418. for (int i = p_level + 1; i < p_sequence.size(); ++i) {
  419. p_sequence[i] = 0;
  420. }
  421. }
  422. static QString headerSequenceStr(const QVector<int> &p_sequence)
  423. {
  424. QString res;
  425. for (int i = 1; i < p_sequence.size(); ++i) {
  426. if (p_sequence[i] != 0) {
  427. res = res + QString::number(p_sequence[i]) + '.';
  428. } else if (res.isEmpty()) {
  429. continue;
  430. } else {
  431. break;
  432. }
  433. }
  434. return res;
  435. }
  436. static void insertSequenceToHeader(QTextCursor& p_cursor,
  437. const QTextBlock &p_block,
  438. QRegExp &p_reg,
  439. QRegExp &p_preReg,
  440. const QString &p_seq)
  441. {
  442. if (!p_block.isValid()) {
  443. return;
  444. }
  445. QString text = p_block.text();
  446. bool matched = p_reg.exactMatch(text);
  447. Q_ASSERT(matched);
  448. matched = p_preReg.exactMatch(text);
  449. Q_ASSERT(matched);
  450. int start = p_reg.cap(1).length() + 1;
  451. int end = p_preReg.cap(1).length();
  452. Q_ASSERT(start <= end);
  453. p_cursor.setPosition(p_block.position() + start);
  454. if (start != end) {
  455. p_cursor.setPosition(p_block.position() + end, QTextCursor::KeepAnchor);
  456. }
  457. if (p_seq.isEmpty()) {
  458. p_cursor.removeSelectedText();
  459. } else {
  460. p_cursor.insertText(p_seq + ' ');
  461. }
  462. }
  463. void VMdEditor::updateHeaderSequenceByConfigChange()
  464. {
  465. updateHeadersHelper(m_pegHighlighter->getHeaderRegions(), true);
  466. }
  467. void VMdEditor::updateHeadersHelper(const QVector<VElementRegion> &p_headerRegions, bool p_configChanged)
  468. {
  469. QTextDocument *doc = document();
  470. QVector<VTableOfContentItem> headers;
  471. QVector<int> headerBlockNumbers;
  472. QVector<QString> headerSequences;
  473. if (!p_headerRegions.isEmpty()) {
  474. headers.reserve(p_headerRegions.size());
  475. headerBlockNumbers.reserve(p_headerRegions.size());
  476. headerSequences.reserve(p_headerRegions.size());
  477. }
  478. // Assume that each block contains only one line
  479. // Only support # syntax for now
  480. QRegExp headerReg(VUtils::c_headerRegExp);
  481. int baseLevel = -1;
  482. for (auto const & reg : p_headerRegions) {
  483. QTextBlock block = doc->findBlock(reg.m_startPos);
  484. if (!block.isValid()) {
  485. continue;
  486. }
  487. if (!block.contains(reg.m_endPos - 1)) {
  488. qWarning() << "header accross multiple blocks, starting from block"
  489. << block.blockNumber()
  490. << block.text();
  491. }
  492. if (headerReg.exactMatch(block.text())) {
  493. int level = headerReg.cap(1).length();
  494. VTableOfContentItem header(headerReg.cap(2).trimmed(),
  495. level,
  496. block.blockNumber(),
  497. headers.size());
  498. headers.append(header);
  499. headerBlockNumbers.append(block.blockNumber());
  500. headerSequences.append(headerReg.cap(3));
  501. if (baseLevel == -1) {
  502. baseLevel = level;
  503. } else if (baseLevel > level) {
  504. baseLevel = level;
  505. }
  506. }
  507. }
  508. m_headers.clear();
  509. bool autoSequence = m_config.m_enableHeadingSequence
  510. && !isReadOnly()
  511. && m_file->isModifiable();
  512. int headingSequenceBaseLevel = g_config->getHeadingSequenceBaseLevel();
  513. if (headingSequenceBaseLevel < 1 || headingSequenceBaseLevel > 6) {
  514. headingSequenceBaseLevel = 1;
  515. }
  516. QVector<int> seqs(7, 0);
  517. QRegExp preReg(VUtils::c_headerPrefixRegExp);
  518. int curLevel = baseLevel - 1;
  519. QTextCursor cursor(doc);
  520. if(autoSequence || p_configChanged) {
  521. cursor.beginEditBlock();
  522. }
  523. for (int i = 0; i < headers.size(); ++i) {
  524. VTableOfContentItem &item = headers[i];
  525. while (item.m_level > curLevel + 1) {
  526. curLevel += 1;
  527. // Insert empty level which is an invalid header.
  528. m_headers.append(VTableOfContentItem(c_emptyHeaderName,
  529. curLevel,
  530. -1,
  531. m_headers.size()));
  532. if (autoSequence || p_configChanged) {
  533. addHeaderSequence(seqs, curLevel, headingSequenceBaseLevel);
  534. }
  535. }
  536. item.m_index = m_headers.size();
  537. m_headers.append(item);
  538. curLevel = item.m_level;
  539. if (autoSequence || p_configChanged) {
  540. addHeaderSequence(seqs, item.m_level, headingSequenceBaseLevel);
  541. QString seqStr = autoSequence ? headerSequenceStr(seqs) : "";
  542. if (headerSequences[i] != seqStr) {
  543. // Insert correct sequence.
  544. insertSequenceToHeader(cursor,
  545. doc->findBlockByNumber(headerBlockNumbers[i]),
  546. headerReg,
  547. preReg,
  548. seqStr);
  549. }
  550. }
  551. }
  552. if (autoSequence || p_configChanged) {
  553. cursor.endEditBlock();
  554. }
  555. emit headersChanged(m_headers);
  556. updateCurrentHeader();
  557. }
  558. void VMdEditor::updateHeaders(const QVector<VElementRegion> &p_headerRegions)
  559. {
  560. updateHeadersHelper(p_headerRegions, false);
  561. }
  562. void VMdEditor::updateCurrentHeader()
  563. {
  564. emit currentHeaderChanged(textCursor().block().blockNumber());
  565. }
  566. void VMdEditor::initInitImages()
  567. {
  568. m_initImages = VUtils::fetchImagesFromMarkdownFile(m_file,
  569. ImageLink::LocalRelativeInternal);
  570. }
  571. void VMdEditor::clearUnusedImages()
  572. {
  573. QVector<ImageLink> images = VUtils::fetchImagesFromMarkdownFile(m_file,
  574. ImageLink::LocalRelativeInternal);
  575. QSet<QString> unusedImages;
  576. if (!m_insertedImages.isEmpty()) {
  577. for (int i = 0; i < m_insertedImages.size(); ++i) {
  578. const ImageLink &link = m_insertedImages[i];
  579. if (link.m_type != ImageLink::LocalRelativeInternal) {
  580. continue;
  581. }
  582. int j;
  583. for (j = 0; j < images.size(); ++j) {
  584. if (VUtils::equalPath(link.m_path, images[j].m_path)) {
  585. break;
  586. }
  587. }
  588. // This inserted image is no longer in the file.
  589. if (j == images.size()) {
  590. unusedImages.insert(link.m_path);
  591. }
  592. }
  593. m_insertedImages.clear();
  594. }
  595. for (int i = 0; i < m_initImages.size(); ++i) {
  596. const ImageLink &link = m_initImages[i];
  597. V_ASSERT(link.m_type == ImageLink::LocalRelativeInternal);
  598. int j;
  599. for (j = 0; j < images.size(); ++j) {
  600. if (VUtils::equalPath(link.m_path, images[j].m_path)) {
  601. break;
  602. }
  603. }
  604. // Original local relative image is no longer in the file.
  605. if (j == images.size()) {
  606. unusedImages.insert(link.m_path);
  607. }
  608. }
  609. if (!unusedImages.isEmpty()) {
  610. if (g_config->getConfirmImagesCleanUp()) {
  611. QVector<ConfirmItemInfo> items;
  612. for (auto const & img : unusedImages) {
  613. items.push_back(ConfirmItemInfo(img,
  614. img,
  615. img,
  616. NULL));
  617. }
  618. QString text = tr("Following images seems not to be used in this note anymore. "
  619. "Please confirm the deletion of these images.");
  620. QString info = tr("Deleted files could be found in the recycle "
  621. "bin of this note.<br>"
  622. "Click \"Cancel\" to leave them untouched.");
  623. VConfirmDeletionDialog dialog(tr("Confirm Cleaning Up Unused Images"),
  624. text,
  625. info,
  626. items,
  627. true,
  628. true,
  629. true,
  630. this);
  631. unusedImages.clear();
  632. if (dialog.exec()) {
  633. items = dialog.getConfirmedItems();
  634. g_config->setConfirmImagesCleanUp(dialog.getAskAgainEnabled());
  635. for (auto const & item : items) {
  636. unusedImages.insert(item.m_name);
  637. }
  638. }
  639. }
  640. for (auto const & item : unusedImages) {
  641. bool ret = false;
  642. if (m_file->getType() == FileType::Note) {
  643. const VNoteFile *tmpFile = static_cast<const VNoteFile *>((VFile *)m_file);
  644. ret = VUtils::deleteFile(tmpFile->getNotebook(), item, false);
  645. } else if (m_file->getType() == FileType::Orphan) {
  646. const VOrphanFile *tmpFile = static_cast<const VOrphanFile *>((VFile *)m_file);
  647. ret = VUtils::deleteFile(tmpFile, item, false);
  648. } else {
  649. Q_ASSERT(false);
  650. }
  651. if (!ret) {
  652. qWarning() << "fail to delete unused original image" << item;
  653. } else {
  654. qDebug() << "delete unused image" << item;
  655. }
  656. }
  657. }
  658. m_initImages.clear();
  659. }
  660. void VMdEditor::keyPressEvent(QKeyEvent *p_event)
  661. {
  662. int key = p_event->key();
  663. int modifiers = p_event->modifiers();
  664. switch (key) {
  665. case Qt::Key_Minus:
  666. case Qt::Key_Underscore:
  667. // Zoom out.
  668. if (modifiers & Qt::ControlModifier) {
  669. zoomPage(false);
  670. return;
  671. }
  672. break;
  673. case Qt::Key_Plus:
  674. case Qt::Key_Equal:
  675. // Zoom in.
  676. if (modifiers & Qt::ControlModifier) {
  677. zoomPage(true);
  678. return;
  679. }
  680. break;
  681. case Qt::Key_0:
  682. // Restore zoom.
  683. if (modifiers & Qt::ControlModifier) {
  684. if (m_zoomDelta > 0) {
  685. zoomPage(false, m_zoomDelta);
  686. } else if (m_zoomDelta < 0) {
  687. zoomPage(true, -m_zoomDelta);
  688. }
  689. return;
  690. }
  691. break;
  692. default:
  693. break;
  694. }
  695. if (m_editOps && m_editOps->handleKeyPressEvent(p_event)) {
  696. return;
  697. }
  698. // Esc to exit edit mode when Vim is disabled.
  699. if (key == Qt::Key_Escape) {
  700. emit m_object->discardAndRead();
  701. return;
  702. }
  703. VTextEdit::keyPressEvent(p_event);
  704. }
  705. bool VMdEditor::canInsertFromMimeData(const QMimeData *p_source) const
  706. {
  707. return p_source->hasImage()
  708. || p_source->hasUrls()
  709. || VTextEdit::canInsertFromMimeData(p_source);
  710. }
  711. void VMdEditor::insertFromMimeData(const QMimeData *p_source)
  712. {
  713. if (processHtmlFromMimeData(p_source)) {
  714. return;
  715. }
  716. if (processImageFromMimeData(p_source)) {
  717. return;
  718. }
  719. if (processUrlFromMimeData(p_source)) {
  720. return;
  721. }
  722. VTextEdit::insertFromMimeData(p_source);
  723. }
  724. void VMdEditor::imageInserted(const QString &p_path, const QString &p_url)
  725. {
  726. ImageLink link;
  727. link.m_path = p_path;
  728. link.m_url = p_url;
  729. if (m_file->useRelativeImageFolder()) {
  730. link.m_type = ImageLink::LocalRelativeInternal;
  731. } else {
  732. link.m_type = ImageLink::LocalAbsolute;
  733. }
  734. m_insertedImages.append(link);
  735. }
  736. bool VMdEditor::scrollToHeader(int p_blockNumber)
  737. {
  738. if (p_blockNumber < 0) {
  739. return false;
  740. }
  741. return scrollToBlock(p_blockNumber);
  742. }
  743. int VMdEditor::indexOfCurrentHeader() const
  744. {
  745. if (m_headers.isEmpty()) {
  746. return -1;
  747. }
  748. int blockNumber = textCursor().block().blockNumber();
  749. for (int i = m_headers.size() - 1; i >= 0; --i) {
  750. if (!m_headers[i].isEmpty()
  751. && m_headers[i].m_blockNumber <= blockNumber) {
  752. return i;
  753. }
  754. }
  755. return -1;
  756. }
  757. bool VMdEditor::jumpTitle(bool p_forward, int p_relativeLevel, int p_repeat)
  758. {
  759. if (m_headers.isEmpty()) {
  760. return false;
  761. }
  762. QTextCursor cursor = textCursor();
  763. int cursorLine = cursor.block().blockNumber();
  764. int targetIdx = -1;
  765. // -1: skip level check.
  766. int targetLevel = 0;
  767. int idx = indexOfCurrentHeader();
  768. if (idx == -1) {
  769. // Cursor locates at the beginning, before any headers.
  770. if (p_relativeLevel < 0 || !p_forward) {
  771. return false;
  772. }
  773. }
  774. int delta = 1;
  775. if (!p_forward) {
  776. delta = -1;
  777. }
  778. bool firstHeader = true;
  779. for (targetIdx = idx == -1 ? 0 : idx;
  780. targetIdx >= 0 && targetIdx < m_headers.size();
  781. targetIdx += delta) {
  782. const VTableOfContentItem &header = m_headers[targetIdx];
  783. if (header.isEmpty()) {
  784. continue;
  785. }
  786. if (targetLevel == 0) {
  787. // The target level has not been init yet.
  788. Q_ASSERT(firstHeader);
  789. targetLevel = header.m_level;
  790. if (p_relativeLevel < 0) {
  791. targetLevel += p_relativeLevel;
  792. if (targetLevel < 1) {
  793. // Invalid level.
  794. return false;
  795. }
  796. } else if (p_relativeLevel > 0) {
  797. targetLevel = -1;
  798. }
  799. }
  800. if (targetLevel == -1 || header.m_level == targetLevel) {
  801. if (firstHeader
  802. && (cursorLine == header.m_blockNumber
  803. || p_forward)
  804. && idx != -1) {
  805. // This header is not counted for the repeat.
  806. firstHeader = false;
  807. continue;
  808. }
  809. if (--p_repeat == 0) {
  810. // Found.
  811. break;
  812. }
  813. } else if (header.m_level < targetLevel) {
  814. // Stop by higher level.
  815. return false;
  816. }
  817. firstHeader = false;
  818. }
  819. if (targetIdx < 0 || targetIdx >= m_headers.size()) {
  820. return false;
  821. }
  822. // Jump to target header.
  823. int line = m_headers[targetIdx].m_blockNumber;
  824. if (line > -1) {
  825. QTextBlock block = document()->findBlockByNumber(line);
  826. if (block.isValid()) {
  827. cursor.setPosition(block.position());
  828. setTextCursor(cursor);
  829. return true;
  830. }
  831. }
  832. return false;
  833. }
  834. void VMdEditor::scrollBlockInPage(int p_blockNum, int p_dest, int p_margin)
  835. {
  836. VEditUtils::scrollBlockInPage(this, p_blockNum, p_dest, p_margin);
  837. }
  838. void VMdEditor::updateTextEditConfig()
  839. {
  840. setBlockImageEnabled(g_config->getEnablePreviewImages());
  841. setImageWidthConstrainted(g_config->getEnablePreviewImageConstraint());
  842. setLineLeading(m_config.m_lineDistanceHeight);
  843. setImageLineColor(g_config->getEditorPreviewImageLineFg());
  844. setEnableExtraBuffer(g_config->getEnableExtraBuffer());
  845. int lineNumber = g_config->getEditorLineNumber();
  846. if (lineNumber < (int)LineNumberType::None || lineNumber >= (int)LineNumberType::Invalid) {
  847. lineNumber = (int)LineNumberType::None;
  848. }
  849. setLineNumberType((LineNumberType)lineNumber);
  850. setLineNumberColor(g_config->getEditorLineNumberFg(),
  851. g_config->getEditorLineNumberBg());
  852. m_previewMgr->setPreviewEnabled(g_config->getEnablePreviewImages());
  853. }
  854. void VMdEditor::updateConfig()
  855. {
  856. updateEditConfig();
  857. updateTextEditConfig();
  858. }
  859. QString VMdEditor::getContent() const
  860. {
  861. return toPlainText();
  862. }
  863. void VMdEditor::setContent(const QString &p_content, bool p_modified)
  864. {
  865. if (p_modified) {
  866. QTextCursor cursor = textCursor();
  867. cursor.select(QTextCursor::Document);
  868. cursor.insertText(p_content);
  869. setTextCursor(cursor);
  870. } else {
  871. setPlainText(p_content);
  872. }
  873. }
  874. void VMdEditor::refreshPreview()
  875. {
  876. m_previewMgr->refreshPreview();
  877. }
  878. void VMdEditor::updateInitAndInsertedImages(bool p_fileChanged, UpdateAction p_act)
  879. {
  880. if (p_fileChanged && p_act == UpdateAction::InfoChanged) {
  881. return;
  882. }
  883. if (!isModified()) {
  884. Q_ASSERT(m_insertedImages.isEmpty());
  885. m_insertedImages.clear();
  886. if (!m_initImages.isEmpty()) {
  887. // Re-generate init images.
  888. initInitImages();
  889. }
  890. return;
  891. }
  892. // Update init images.
  893. QVector<ImageLink> tmp = m_initImages;
  894. initInitImages();
  895. Q_ASSERT(tmp.size() == m_initImages.size());
  896. QDir dir(m_file->fetchBasePath());
  897. // File has been moved.
  898. if (p_fileChanged) {
  899. // Since we clear unused images once user save the note, all images
  900. // in m_initImages now are moved already.
  901. // Update inserted images.
  902. // Inserted images should be moved manually here. Then update all the
  903. // paths.
  904. for (auto & link : m_insertedImages) {
  905. if (link.m_type == ImageLink::LocalAbsolute) {
  906. continue;
  907. }
  908. QString newPath = QDir::cleanPath(dir.absoluteFilePath(link.m_url));
  909. if (VUtils::equalPath(link.m_path, newPath)) {
  910. continue;
  911. }
  912. if (!VUtils::copyFile(link.m_path, newPath, true)) {
  913. VUtils::showMessage(QMessageBox::Warning,
  914. tr("Warning"),
  915. tr("Fail to move unsaved inserted image %1 to %2.")
  916. .arg(link.m_path)
  917. .arg(newPath),
  918. tr("Please check it manually to avoid image loss."),
  919. QMessageBox::Ok,
  920. QMessageBox::Ok,
  921. this);
  922. continue;
  923. }
  924. link.m_path = newPath;
  925. }
  926. } else {
  927. // Directory changed.
  928. // Update inserted images.
  929. for (auto & link : m_insertedImages) {
  930. if (link.m_type == ImageLink::LocalAbsolute) {
  931. continue;
  932. }
  933. QString newPath = QDir::cleanPath(dir.absoluteFilePath(link.m_url));
  934. link.m_path = newPath;
  935. }
  936. }
  937. }
  938. void VMdEditor::handleCopyAsAction(QAction *p_act)
  939. {
  940. ++m_copyTimeStamp;
  941. QTextCursor cursor = textCursor();
  942. Q_ASSERT(cursor.hasSelection());
  943. QString text = VEditUtils::selectedText(cursor);
  944. Q_ASSERT(!text.isEmpty());
  945. Q_ASSERT(!m_textToHtmlDialog);
  946. m_textToHtmlDialog = new VCopyTextAsHtmlDialog(text, p_act->data().toString(), this);
  947. // For Hoedown, we use marked.js to convert the text to have a general interface.
  948. emit requestTextToHtml(text, 0, m_copyTimeStamp);
  949. m_textToHtmlDialog->exec();
  950. delete m_textToHtmlDialog;
  951. m_textToHtmlDialog = NULL;
  952. }
  953. void VMdEditor::textToHtmlFinished(int p_id,
  954. int p_timeStamp,
  955. const QUrl &p_baseUrl,
  956. const QString &p_html)
  957. {
  958. Q_UNUSED(p_id);
  959. if (m_textToHtmlDialog && p_timeStamp == m_copyTimeStamp) {
  960. m_textToHtmlDialog->setConvertedHtml(p_baseUrl, p_html);
  961. }
  962. }
  963. void VMdEditor::htmlToTextFinished(int p_id, int p_timeStamp, const QString &p_text)
  964. {
  965. Q_UNUSED(p_id);
  966. if (m_copyTimeStamp == p_timeStamp && !p_text.isEmpty()) {
  967. emit m_object->statusMessage(tr("Inserting parsed Markdown text"));
  968. QString text(p_text);
  969. if (g_config->getParsePasteLocalImage()) {
  970. // May take long time.
  971. replaceTextWithLocalImages(text);
  972. }
  973. m_editOps->insertText(text);
  974. emit m_object->statusMessage(tr("Parsed Markdown text inserted"));
  975. }
  976. }
  977. void VMdEditor::wheelEvent(QWheelEvent *p_event)
  978. {
  979. if (handleWheelEvent(p_event)) {
  980. return;
  981. }
  982. VTextEdit::wheelEvent(p_event);
  983. }
  984. void VMdEditor::zoomPage(bool p_zoomIn, int p_range)
  985. {
  986. const int minSize = 2;
  987. int delta = p_zoomIn ? p_range : -p_range;
  988. // zoomIn() and zoomOut() does not work if we set stylesheet of VMdEditor.
  989. int ptSz = font().pointSize() + delta;
  990. if (ptSz < minSize) {
  991. ptSz = minSize;
  992. }
  993. setFontPointSizeByStyleSheet(ptSz);
  994. emit m_object->statusMessage(QObject::tr("Set base font point size %1").arg(ptSz));
  995. m_zoomDelta += delta;
  996. QVector<HighlightingStyle> &styles = m_pegHighlighter->getStyles();
  997. for (auto & it : styles) {
  998. int size = it.format.fontPointSize();
  999. if (size == 0) {
  1000. // It contains no font size format.
  1001. continue;
  1002. }
  1003. size += delta;
  1004. if (size < minSize) {
  1005. size = minSize;
  1006. }
  1007. it.format.setFontPointSize(size);
  1008. }
  1009. QHash<QString, QTextCharFormat> &cbStyles = m_pegHighlighter->getCodeBlockStyles();
  1010. for (auto it = cbStyles.begin(); it != cbStyles.end(); ++it) {
  1011. int size = it.value().fontPointSize();
  1012. if (size == 0) {
  1013. // It contains no font size format.
  1014. continue;
  1015. }
  1016. size += delta;
  1017. if (size < minSize) {
  1018. size = minSize;
  1019. }
  1020. it.value().setFontPointSize(size);
  1021. }
  1022. m_pegHighlighter->rehighlight();
  1023. }
  1024. QAction *VMdEditor::initCopyAsMenu(QAction *p_after, QMenu *p_menu)
  1025. {
  1026. QStringList targets = g_webUtils->getCopyTargetsName();
  1027. if (targets.isEmpty()) {
  1028. return NULL;
  1029. }
  1030. QMenu *subMenu = new QMenu(tr("Copy HTML As"), p_menu);
  1031. subMenu->setToolTipsVisible(true);
  1032. for (auto const & target : targets) {
  1033. QAction *act = new QAction(target, subMenu);
  1034. act->setData(target);
  1035. act->setToolTip(tr("Copy selected content as HTML using rules specified by target %1").arg(target));
  1036. subMenu->addAction(act);
  1037. }
  1038. connect(subMenu, &QMenu::triggered,
  1039. this, &VMdEditor::handleCopyAsAction);
  1040. return insertMenuAfter(p_after, subMenu, p_menu);
  1041. }
  1042. QAction *VMdEditor::initPasteAsBlockQuoteMenu(QAction *p_after, QMenu *p_menu)
  1043. {
  1044. QAction *pbqAct = new QAction(tr("Paste As Block &Quote"), p_menu);
  1045. pbqAct->setToolTip(tr("Paste text from clipboard as block quote"));
  1046. connect(pbqAct, &QAction::triggered,
  1047. this, [this]() {
  1048. QClipboard *clipboard = QApplication::clipboard();
  1049. const QMimeData *mimeData = clipboard->mimeData();
  1050. QString text = mimeData->text();
  1051. QTextCursor cursor = textCursor();
  1052. cursor.removeSelectedText();
  1053. QTextBlock block = cursor.block();
  1054. QString indent = VEditUtils::fetchIndentSpaces(block);
  1055. // Insert '> ' in front of each line.
  1056. VEditUtils::insertBeforeEachLine(text, indent + QStringLiteral("> "));
  1057. if (VEditUtils::isSpaceBlock(block)) {
  1058. if (!indent.isEmpty()) {
  1059. // Remove the indent.
  1060. cursor.movePosition(QTextCursor::StartOfBlock);
  1061. cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
  1062. cursor.removeSelectedText();
  1063. }
  1064. } else {
  1065. // Insert a new block.
  1066. VEditUtils::insertBlock(cursor, false);
  1067. }
  1068. cursor.insertText(text);
  1069. setTextCursor(cursor);
  1070. });
  1071. insertActionAfter(p_after, pbqAct, p_menu);
  1072. return pbqAct;
  1073. }
  1074. QAction *VMdEditor::initPasteAfterParseMenu(QAction *p_after, QMenu *p_menu)
  1075. {
  1076. QAction *papAct = new QAction(tr("Paste Parsed &Markdown Text"), p_menu);
  1077. VUtils::fixTextWithCaptainShortcut(papAct, "ParseAndPaste");
  1078. papAct->setToolTip(tr("Parse HTML to Markdown text and paste"));
  1079. connect(papAct, &QAction::triggered,
  1080. this, &VMdEditor::parseAndPaste);
  1081. insertActionAfter(p_after, papAct, p_menu);
  1082. return papAct;
  1083. }
  1084. void VMdEditor::insertImageLink(const QString &p_text, const QString &p_url)
  1085. {
  1086. VInsertLinkDialog dialog(tr("Insert Image Link"),
  1087. "",
  1088. "",
  1089. p_text,
  1090. p_url,
  1091. true,
  1092. this);
  1093. if (dialog.exec() == QDialog::Accepted) {
  1094. QString linkText = dialog.getLinkText();
  1095. QString linkUrl = dialog.getLinkUrl();
  1096. static_cast<VMdEditOperations *>(m_editOps)->insertImageLink(linkText, linkUrl);
  1097. }
  1098. }
  1099. VWordCountInfo VMdEditor::fetchWordCountInfo() const
  1100. {
  1101. VWordCountInfo info;
  1102. QTextDocument *doc = document();
  1103. // Char without spaces.
  1104. int cns = 0;
  1105. int wc = 0;
  1106. // Remove th ending new line.
  1107. int cc = doc->characterCount() - 1;
  1108. // 0 - not in word;
  1109. // 1 - in English word;
  1110. // 2 - in non-English word;
  1111. int state = 0;
  1112. for (int i = 0; i < cc; ++i) {
  1113. QChar ch = doc->characterAt(i);
  1114. if (ch.isSpace()) {
  1115. if (state) {
  1116. state = 0;
  1117. }
  1118. continue;
  1119. } else if (ch.unicode() < 128) {
  1120. if (state != 1) {
  1121. state = 1;
  1122. ++wc;
  1123. }
  1124. } else {
  1125. state = 2;
  1126. ++wc;
  1127. }
  1128. ++cns;
  1129. }
  1130. info.m_mode = VWordCountInfo::Edit;
  1131. info.m_wordCount = wc;
  1132. info.m_charWithoutSpacesCount = cns;
  1133. info.m_charWithSpacesCount = cc;
  1134. return info;
  1135. }
  1136. void VMdEditor::setEditTab(VEditTab *p_editTab)
  1137. {
  1138. m_editTab = p_editTab;
  1139. }
  1140. void VMdEditor::setFontPointSizeByStyleSheet(int p_ptSize)
  1141. {
  1142. QFont ft = font();
  1143. ft.setPointSize(p_ptSize);
  1144. const QPalette &palette = g_config->getMdEditPalette();
  1145. setFontAndPaletteByStyleSheet(ft, palette);
  1146. ensurePolished();
  1147. ft.setPointSize(p_ptSize + LINE_NUMBER_AREA_FONT_DELTA);
  1148. updateLineNumberAreaWidth(QFontMetrics(ft));
  1149. }
  1150. void VMdEditor::setFontAndPaletteByStyleSheet(const QFont &p_font, const QPalette &p_palette)
  1151. {
  1152. QString styles(QString("VMdEditor, VLineNumberArea {"
  1153. "font-family: \"%1\";"
  1154. "font-size: %2pt;"
  1155. "color: %3;"
  1156. "background-color: %4; } "
  1157. "VLineNumberArea {"
  1158. "font-size: %5pt; }")
  1159. .arg(p_font.family())
  1160. .arg(p_font.pointSize())
  1161. .arg(p_palette.color(QPalette::Text).name())
  1162. .arg(p_palette.color(QPalette::Base).name())
  1163. .arg(p_font.pointSize() + LINE_NUMBER_AREA_FONT_DELTA));
  1164. setStyleSheet(styles);
  1165. }
  1166. int VMdEditor::lineNumberAreaWidth() const
  1167. {
  1168. return VTextEdit::lineNumberAreaWidth();
  1169. }
  1170. void VMdEditor::initLinkAndPreviewMenu(QAction *p_before, QMenu *p_menu, const QPoint &p_pos)
  1171. {
  1172. QTextCursor cursor = cursorForPosition(p_pos);
  1173. const int pos = cursor.position();
  1174. QTextBlock block = cursor.block();
  1175. const QString text(block.text());
  1176. // Image.
  1177. QRegExp regExp(VUtils::c_imageLinkRegExp);
  1178. if (regExp.indexIn(text) > -1) {
  1179. const QVector<VElementRegion> &imgRegs = m_pegHighlighter->getImageRegions();
  1180. for (auto const & reg : imgRegs) {
  1181. if (!reg.contains(pos)) {
  1182. continue;
  1183. }
  1184. if (reg.m_endPos > block.position() + text.length()) {
  1185. return;
  1186. }
  1187. QString linkText = text.mid(reg.m_startPos - block.position(),
  1188. reg.m_endPos - reg.m_startPos);
  1189. QString surl = VUtils::fetchImageLinkUrl(linkText);
  1190. if (surl.isEmpty()) {
  1191. return;
  1192. }
  1193. QString imgPath = VUtils::linkUrlToPath(m_file->fetchBasePath(), surl);
  1194. bool isLocalFile = QFileInfo::exists(imgPath);
  1195. QAction *viewImageAct = new QAction(tr("View Image"), p_menu);
  1196. connect(viewImageAct, &QAction::triggered,
  1197. this, [this, imgPath]() {
  1198. QDesktopServices::openUrl(VUtils::pathToUrl(imgPath));
  1199. });
  1200. p_menu->insertAction(p_before, viewImageAct);
  1201. QAction *copyImageLinkAct = new QAction(tr("Copy Image URL"), p_menu);
  1202. connect(copyImageLinkAct, &QAction::triggered,
  1203. this, [this, imgPath]() {
  1204. QClipboard *clipboard = QApplication::clipboard();
  1205. VClipboardUtils::setLinkToClipboard(clipboard,
  1206. imgPath,
  1207. QClipboard::Clipboard);
  1208. });
  1209. p_menu->insertAction(p_before, copyImageLinkAct);
  1210. if (isLocalFile) {
  1211. QAction *copyImagePathAct = new QAction(tr("Copy Image Path"), p_menu);
  1212. connect(copyImagePathAct, &QAction::triggered,
  1213. this, [this, imgPath]() {
  1214. QClipboard *clipboard = QApplication::clipboard();
  1215. QMimeData *data = new QMimeData();
  1216. data->setText(imgPath);
  1217. VClipboardUtils::setMimeDataToClipboard(clipboard,
  1218. data,
  1219. QClipboard::Clipboard);
  1220. });
  1221. p_menu->insertAction(p_before, copyImagePathAct);
  1222. QAction *copyImageAct = new QAction(tr("Copy Image"), p_menu);
  1223. connect(copyImageAct, &QAction::triggered,
  1224. this, [this, imgPath]() {
  1225. QClipboard *clipboard = QApplication::clipboard();
  1226. clipboard->clear();
  1227. QImage img = VUtils::imageFromFile(imgPath);
  1228. if (!img.isNull()) {
  1229. VClipboardUtils::setImageToClipboard(clipboard,
  1230. img,
  1231. QClipboard::Clipboard);
  1232. }
  1233. });
  1234. p_menu->insertAction(p_before, copyImageAct);
  1235. } else {
  1236. // Copy in-place preview.
  1237. initInPlacePreviewMenu(p_before, p_menu, block, pos);
  1238. }
  1239. p_menu->insertSeparator(p_before);
  1240. return;
  1241. }
  1242. }
  1243. // Link.
  1244. QRegExp regExp2(VUtils::c_linkRegExp);
  1245. QString linkText;
  1246. int p = 0;
  1247. const int pib = pos - block.position();
  1248. while (p < text.size()) {
  1249. int idx = text.indexOf(regExp2, p);
  1250. if (idx == -1) {
  1251. break;
  1252. }
  1253. p = idx + regExp2.matchedLength();
  1254. if (pib >= idx && pib < p) {
  1255. linkText = regExp2.cap(2);
  1256. break;
  1257. }
  1258. }
  1259. if (!linkText.isEmpty()) {
  1260. QString linkUrl = VUtils::linkUrlToPath(m_file->fetchBasePath(), linkText);
  1261. bool isLocalFile = QFileInfo::exists(linkUrl);
  1262. QAction *viewLinkAct = new QAction(tr("View Link"), p_menu);
  1263. connect(viewLinkAct, &QAction::triggered,
  1264. this, [this, linkUrl]() {
  1265. QDesktopServices::openUrl(VUtils::pathToUrl(linkUrl));
  1266. });
  1267. p_menu->insertAction(p_before, viewLinkAct);
  1268. QAction *copyLinkAct = new QAction(tr("Copy Link URL"), p_menu);
  1269. connect(copyLinkAct, &QAction::triggered,
  1270. this, [this, linkUrl]() {
  1271. QClipboard *clipboard = QApplication::clipboard();
  1272. VClipboardUtils::setLinkToClipboard(clipboard,
  1273. linkUrl,
  1274. QClipboard::Clipboard);
  1275. });
  1276. p_menu->insertAction(p_before, copyLinkAct);
  1277. if (isLocalFile) {
  1278. QAction *copyLinkPathAct = new QAction(tr("Copy Link Path"), p_menu);
  1279. connect(copyLinkPathAct, &QAction::triggered,
  1280. this, [this, linkUrl]() {
  1281. QClipboard *clipboard = QApplication::clipboard();
  1282. QMimeData *data = new QMimeData();
  1283. data->setText(linkUrl);
  1284. VClipboardUtils::setMimeDataToClipboard(clipboard,
  1285. data,
  1286. QClipboard::Clipboard);
  1287. });
  1288. p_menu->insertAction(p_before, copyLinkPathAct);
  1289. }
  1290. p_menu->insertSeparator(p_before);
  1291. return;
  1292. }
  1293. bool needSeparator = false;
  1294. if (initInPlacePreviewMenu(p_before, p_menu, block, pos)) {
  1295. needSeparator = true;
  1296. }
  1297. if (initExportAndCopyMenu(p_before, p_menu, block, pos)) {
  1298. needSeparator = true;
  1299. }
  1300. if (needSeparator) {
  1301. p_menu->insertSeparator(p_before);
  1302. }
  1303. }
  1304. bool VMdEditor::initInPlacePreviewMenu(QAction *p_before,
  1305. QMenu *p_menu,
  1306. const QTextBlock &p_block,
  1307. int p_pos)
  1308. {
  1309. VTextBlockData *data = VTextBlockData::blockData(p_block);
  1310. if (!data) {
  1311. return false;
  1312. }
  1313. const QVector<VPreviewInfo *> &previews = data->getPreviews();
  1314. if (previews.isEmpty()) {
  1315. return false;
  1316. }
  1317. QPixmap image;
  1318. QString background;
  1319. int pib = p_pos - p_block.position();
  1320. for (auto info : previews) {
  1321. const VPreviewedImageInfo &pii = info->m_imageInfo;
  1322. if (pii.contains(pib)) {
  1323. const QPixmap *img = findImage(pii.m_imageName);
  1324. if (img) {
  1325. image = *img;
  1326. background = pii.m_background;
  1327. }
  1328. break;
  1329. }
  1330. }
  1331. if (image.isNull()) {
  1332. return false;
  1333. }
  1334. QAction *copyImageAct = new QAction(tr("Copy In-Place Preview"), p_menu);
  1335. connect(copyImageAct, &QAction::triggered,
  1336. this, [this, image, background]() {
  1337. QColor co(background);
  1338. if (!co.isValid()) {
  1339. co = palette().color(QPalette::Base);
  1340. }
  1341. QImage img(image.size(), QImage::Format_ARGB32);
  1342. img.fill(co);
  1343. QPainter pter(&img);
  1344. pter.drawPixmap(img.rect(), image);
  1345. QClipboard *clipboard = QApplication::clipboard();
  1346. VClipboardUtils::setImageToClipboard(clipboard,
  1347. img,
  1348. QClipboard::Clipboard);
  1349. });
  1350. p_menu->insertAction(p_before, copyImageAct);
  1351. return true;
  1352. }
  1353. bool VMdEditor::initExportAndCopyMenu(QAction *p_before,
  1354. QMenu *p_menu,
  1355. const QTextBlock &p_block,
  1356. int p_pos)
  1357. {
  1358. Q_UNUSED(p_pos);
  1359. int state = p_block.userState();
  1360. if (state != HighlightBlockState::CodeBlockStart
  1361. && state != HighlightBlockState::CodeBlock
  1362. && state != HighlightBlockState::CodeBlockEnd) {
  1363. return false;
  1364. }
  1365. int blockNum = p_block.blockNumber();
  1366. const QVector<VCodeBlock> &cbs = m_pegHighlighter->getCodeBlocks();
  1367. int idx = 0;
  1368. for (idx = 0; idx < cbs.size(); ++idx) {
  1369. if (cbs[idx].m_startBlock <= blockNum
  1370. && cbs[idx].m_endBlock >= blockNum) {
  1371. break;
  1372. }
  1373. }
  1374. if (idx >= cbs.size()) {
  1375. return false;
  1376. }
  1377. const VCodeBlock &cb = cbs[idx];
  1378. if (cb.m_lang != "puml" && cb.m_lang != "dot") {
  1379. return false;
  1380. }
  1381. QMenu *subMenu = new QMenu(tr("Copy Graph"), p_menu);
  1382. subMenu->setToolTipsVisible(true);
  1383. QAction *pngAct = new QAction(tr("PNG"), subMenu);
  1384. pngAct->setToolTip(tr("Export graph as PNG to a temporary file and copy"));
  1385. connect(pngAct, &QAction::triggered,
  1386. this, [this, lang = cb.m_lang, text = cb.m_text]() {
  1387. exportGraphAndCopy(lang, text, "png");
  1388. });
  1389. subMenu->addAction(pngAct);
  1390. QAction *svgAct = new QAction(tr("SVG"), subMenu);
  1391. svgAct->setToolTip(tr("Export graph as SVG to a temporary file and copy"));
  1392. connect(svgAct, &QAction::triggered,
  1393. this, [this, lang = cb.m_lang, text = cb.m_text]() {
  1394. exportGraphAndCopy(lang, text, "svg");
  1395. });
  1396. subMenu->addAction(svgAct);
  1397. p_menu->insertMenu(p_before, subMenu);
  1398. return true;
  1399. }
  1400. void VMdEditor::exportGraphAndCopy(const QString &p_lang,
  1401. const QString &p_text,
  1402. const QString &p_format)
  1403. {
  1404. m_exportTempFile.reset(VUtils::createTemporaryFile(p_format));
  1405. if (!m_exportTempFile->open()) {
  1406. VUtils::showMessage(QMessageBox::Warning,
  1407. tr("Warning"),
  1408. tr("Fail to open a temporary file for export."),
  1409. "",
  1410. QMessageBox::Ok,
  1411. QMessageBox::Ok,
  1412. this);
  1413. m_exportTempFile.clear();
  1414. return;
  1415. }
  1416. emit m_object->statusMessage(tr("Exporting graph"));
  1417. QString filePath(m_exportTempFile->fileName());
  1418. QByteArray out;
  1419. if (p_lang == "puml") {
  1420. out = VPlantUMLHelper::process(p_format,
  1421. VEditUtils::removeCodeBlockFence(p_text));
  1422. } else if (p_lang == "dot") {
  1423. out = VGraphvizHelper::process(p_format,
  1424. VEditUtils::removeCodeBlockFence(p_text));
  1425. }
  1426. if (out.isEmpty() || m_exportTempFile->write(out) == -1) {
  1427. m_exportTempFile->close();
  1428. VUtils::showMessage(QMessageBox::Warning,
  1429. tr("Warning"),
  1430. tr("Fail to export graph."),
  1431. "",
  1432. QMessageBox::Ok,
  1433. QMessageBox::Ok,
  1434. this);
  1435. } else {
  1436. m_exportTempFile->close();
  1437. QClipboard *clipboard = QApplication::clipboard();
  1438. clipboard->clear();
  1439. QImage img;
  1440. img.loadFromData(out, p_format.toLocal8Bit().data());
  1441. if (!img.isNull()) {
  1442. VClipboardUtils::setImageAndLinkToClipboard(clipboard,
  1443. img,
  1444. filePath,
  1445. QClipboard::Clipboard);
  1446. emit m_object->statusMessage(tr("Graph exported and copied"));
  1447. } else {
  1448. emit m_object->statusMessage(tr("Fail to read exported image: %1").arg(filePath));
  1449. }
  1450. }
  1451. }
  1452. void VMdEditor::parseAndPaste()
  1453. {
  1454. if (!m_editTab
  1455. || !m_editTab->isEditMode()
  1456. || isReadOnly()) {
  1457. return;
  1458. }
  1459. QClipboard *clipboard = QApplication::clipboard();
  1460. const QMimeData *mimeData = clipboard->mimeData();
  1461. QString html(mimeData->html());
  1462. if (!html.isEmpty()) {
  1463. ++m_copyTimeStamp;
  1464. emit requestHtmlToText(html, 0, m_copyTimeStamp);
  1465. }
  1466. }
  1467. bool VMdEditor::processHtmlFromMimeData(const QMimeData *p_source)
  1468. {
  1469. if (!p_source->hasHtml()) {
  1470. return false;
  1471. }
  1472. // Handle <img>.
  1473. QRegExp reg("<img ([^>]*)src=\"([^\"]+)\"([^>]*)>");
  1474. QString html(p_source->html());
  1475. if (reg.indexIn(html) != -1 && VUtils::onlyHasImgInHtml(html)) {
  1476. if (p_source->hasImage()) {
  1477. // Both image data and URL are embedded.
  1478. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  1479. dialog.addSelection(tr("Insert From URL"), 0);
  1480. dialog.addSelection(tr("Insert From Image Data"), 1);
  1481. dialog.addSelection(tr("Insert As Image Link"), 2);
  1482. if (dialog.exec() == QDialog::Accepted) {
  1483. int selection = dialog.getSelection();
  1484. if (selection == 1) {
  1485. // Insert from image data.
  1486. m_editOps->insertImageFromMimeData(p_source);
  1487. return true;
  1488. } else if (selection == 2) {
  1489. // Insert as link.
  1490. insertImageLink("", reg.cap(2));
  1491. return true;
  1492. }
  1493. } else {
  1494. return true;
  1495. }
  1496. }
  1497. m_editOps->insertImageFromURL(QUrl(reg.cap(2)));
  1498. return true;
  1499. }
  1500. return false;
  1501. }
  1502. bool VMdEditor::processImageFromMimeData(const QMimeData *p_source)
  1503. {
  1504. if (!p_source->hasImage()) {
  1505. return false;
  1506. }
  1507. // Image data in the clipboard
  1508. if (p_source->hasText()) {
  1509. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  1510. dialog.addSelection(tr("Insert As Image"), 0);
  1511. dialog.addSelection(tr("Insert As Text"), 1);
  1512. dialog.addSelection(tr("Insert As Image Link"), 2);
  1513. if (dialog.exec() == QDialog::Accepted) {
  1514. int selection = dialog.getSelection();
  1515. if (selection == 1) {
  1516. // Insert as text.
  1517. Q_ASSERT(p_source->hasText() && p_source->hasImage());
  1518. VTextEdit::insertFromMimeData(p_source);
  1519. return true;
  1520. } else if (selection == 2) {
  1521. // Insert as link.
  1522. insertImageLink("", p_source->text());
  1523. return true;
  1524. }
  1525. } else {
  1526. return true;
  1527. }
  1528. }
  1529. m_editOps->insertImageFromMimeData(p_source);
  1530. return true;
  1531. }
  1532. bool VMdEditor::processUrlFromMimeData(const QMimeData *p_source)
  1533. {
  1534. QUrl url;
  1535. if (p_source->hasUrls()) {
  1536. QList<QUrl> urls = p_source->urls();
  1537. if (urls.size() == 1) {
  1538. url = urls[0];
  1539. }
  1540. } else if (p_source->hasText()) {
  1541. // Try to get URL from text.
  1542. QString text = p_source->text();
  1543. if (QFileInfo::exists(text)) {
  1544. url = QUrl::fromLocalFile(text);
  1545. } else {
  1546. url = QUrl(text);
  1547. if (url.scheme() != "https" && url.scheme() != "http") {
  1548. url.clear();
  1549. }
  1550. }
  1551. }
  1552. if (!url.isValid()) {
  1553. return false;
  1554. }
  1555. bool isImage = VUtils::isImageURL(url);
  1556. bool isLocalFile = url.isLocalFile()
  1557. && QFileInfo::exists(url.toLocalFile());
  1558. QString localTextFilePath;
  1559. if (!isImage && isLocalFile) {
  1560. localTextFilePath = url.toLocalFile();
  1561. QMimeDatabase mimeDatabase;
  1562. const QMimeType mimeType = mimeDatabase.mimeTypeForFile(localTextFilePath);
  1563. if (mimeType.isValid() && !mimeType.inherits(QStringLiteral("text/plain"))) {
  1564. localTextFilePath.clear();
  1565. }
  1566. }
  1567. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  1568. if (isImage) {
  1569. dialog.addSelection(tr("Insert As Image"), 0);
  1570. dialog.addSelection(tr("Insert As Image Link"), 1);
  1571. }
  1572. dialog.addSelection(tr("Insert As Link"), 2);
  1573. if (isLocalFile) {
  1574. dialog.addSelection(tr("Insert As Relative Link"), 3);
  1575. // Attach as attachment.
  1576. if (m_file->getType() == FileType::Note) {
  1577. VNoteFile *note = static_cast<VNoteFile *>((VFile *)m_file);
  1578. if (-1 == note->findAttachmentByPath(url.toLocalFile(), false)) {
  1579. dialog.addSelection(tr("Attach And Insert Link"), 6);
  1580. }
  1581. }
  1582. }
  1583. dialog.addSelection(tr("Insert As Text"), 4);
  1584. if (!localTextFilePath.isEmpty()) {
  1585. dialog.addSelection(tr("Insert File Content"), 5);
  1586. }
  1587. // FIXME: After calling dialog.exec(), p_source->hasUrl() returns false.
  1588. if (dialog.exec() == QDialog::Accepted) {
  1589. bool relativeLink = false;
  1590. switch (dialog.getSelection()) {
  1591. case 0:
  1592. {
  1593. // Insert As Image.
  1594. m_editOps->insertImageFromURL(url);
  1595. return true;
  1596. }
  1597. case 1:
  1598. {
  1599. // Insert As Image Link.
  1600. insertImageLink("", url.isLocalFile() ? url.toString(QUrl::EncodeSpaces)
  1601. : url.toString());
  1602. return true;
  1603. }
  1604. case 6:
  1605. {
  1606. // Attach And Insert Link.
  1607. QString file = url.toLocalFile();
  1608. Q_ASSERT(m_file->getType() == FileType::Note);
  1609. VNoteFile *note = static_cast<VNoteFile *>((VFile *)m_file);
  1610. QString destFile;
  1611. if (!note->addAttachment(file, &destFile)) {
  1612. VUtils::showMessage(QMessageBox::Warning,
  1613. tr("Warning"),
  1614. tr("Fail to add attachment %1 for note <span style=\"%2\">%3</span>.")
  1615. .arg(file)
  1616. .arg(g_config->c_dataTextStyle)
  1617. .arg(note->getName()),
  1618. "",
  1619. QMessageBox::Ok,
  1620. QMessageBox::Ok,
  1621. this);
  1622. return true;
  1623. }
  1624. emit m_object->statusMessage(tr("1 file added as attachment"));
  1625. // Update url to point to the attachment file.
  1626. Q_ASSERT(!destFile.isEmpty());
  1627. url = QUrl::fromLocalFile(destFile);
  1628. V_FALLTHROUGH;
  1629. }
  1630. case 3:
  1631. // Insert As Relative link.
  1632. relativeLink = true;
  1633. V_FALLTHROUGH;
  1634. case 2:
  1635. {
  1636. // Insert As Link.
  1637. QString initLinkText;
  1638. if (isLocalFile) {
  1639. initLinkText = QFileInfo(url.toLocalFile()).fileName();
  1640. }
  1641. QString ut;
  1642. if (relativeLink) {
  1643. QDir dir(m_file->fetchBasePath());
  1644. ut = dir.relativeFilePath(url.toLocalFile());
  1645. ut = QUrl(ut).toString(QUrl::EncodeSpaces);
  1646. } else {
  1647. ut = url.isLocalFile() ? url.toString(QUrl::EncodeSpaces)
  1648. : url.toString();
  1649. }
  1650. VInsertLinkDialog ld(QObject::tr("Insert Link"),
  1651. "",
  1652. "",
  1653. initLinkText,
  1654. ut,
  1655. false,
  1656. this);
  1657. if (ld.exec() == QDialog::Accepted) {
  1658. QString linkText = ld.getLinkText();
  1659. QString linkUrl = ld.getLinkUrl();
  1660. Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty());
  1661. m_editOps->insertLink(linkText, linkUrl);
  1662. }
  1663. return true;
  1664. }
  1665. case 4:
  1666. {
  1667. // Insert As Text.
  1668. if (p_source->hasText()) {
  1669. m_editOps->insertText(p_source->text());
  1670. } else {
  1671. m_editOps->insertText(url.toString());
  1672. }
  1673. return true;
  1674. }
  1675. case 5:
  1676. {
  1677. // Insert File Content.
  1678. Q_ASSERT(!localTextFilePath.isEmpty());
  1679. m_editOps->insertText(VUtils::readFileFromDisk(localTextFilePath));
  1680. return true;
  1681. }
  1682. default:
  1683. Q_ASSERT(false);
  1684. break;
  1685. }
  1686. }
  1687. return true;
  1688. }
  1689. void VMdEditor::replaceTextWithLocalImages(QString &p_text)
  1690. {
  1691. QVector<VElementRegion> regs = VUtils::fetchImageRegionsUsingParser(p_text);
  1692. if (regs.isEmpty()) {
  1693. return;
  1694. }
  1695. // Sort it in ascending order.
  1696. std::sort(regs.begin(), regs.end());
  1697. QProgressDialog proDlg(tr("Fetching images to local folder..."),
  1698. tr("Abort"),
  1699. 0,
  1700. regs.size(),
  1701. this);
  1702. proDlg.setWindowModality(Qt::WindowModal);
  1703. proDlg.setWindowTitle(tr("Fetching Images To Local Folder"));
  1704. QRegExp zhihuRegExp("^https?://www\\.zhihu\\.com/equation\\?tex=(.+)$");
  1705. QRegExp regExp(VUtils::c_imageLinkRegExp);
  1706. for (int i = regs.size() - 1; i >= 0; --i) {
  1707. proDlg.setValue(regs.size() - 1 - i);
  1708. if (proDlg.wasCanceled()) {
  1709. break;
  1710. }
  1711. const VElementRegion &reg = regs[i];
  1712. QString linkText = p_text.mid(reg.m_startPos, reg.m_endPos - reg.m_startPos);
  1713. if (regExp.indexIn(linkText) == -1) {
  1714. continue;
  1715. }
  1716. QString imageTitle = VUtils::purifyImageTitle(regExp.cap(1).trimmed());
  1717. QString imageUrl = regExp.cap(2).trimmed();
  1718. const int maxUrlLength = 100;
  1719. QString urlToDisplay(imageUrl);
  1720. if (urlToDisplay.size() > maxUrlLength) {
  1721. urlToDisplay = urlToDisplay.left(maxUrlLength) + "...";
  1722. }
  1723. proDlg.setLabelText(tr("Fetching image: %1").arg(urlToDisplay));
  1724. // Handle equation from zhihu.com like http://www.zhihu.com/equation?tex=P.
  1725. if (zhihuRegExp.indexIn(imageUrl) != -1) {
  1726. QString tex = zhihuRegExp.cap(1).trimmed();
  1727. // Remove the +.
  1728. tex.replace(QChar('+'), " ");
  1729. tex = QUrl::fromPercentEncoding(tex.toUtf8());
  1730. if (tex.isEmpty()) {
  1731. continue;
  1732. }
  1733. tex = "$" + tex + "$";
  1734. p_text.replace(reg.m_startPos,
  1735. reg.m_endPos - reg.m_startPos,
  1736. tex);
  1737. continue;
  1738. }
  1739. QString destImagePath, urlInLink;
  1740. // Only handle absolute file path or network path.
  1741. QString srcImagePath;
  1742. QFileInfo info(VUtils::purifyUrl(imageUrl));
  1743. // For network image.
  1744. QScopedPointer<QTemporaryFile> tmpFile;
  1745. if (info.exists()) {
  1746. if (info.isAbsolute()) {
  1747. // Absolute local path.
  1748. srcImagePath = info.absoluteFilePath();
  1749. }
  1750. } else {
  1751. // Network path.
  1752. QByteArray data = VDownloader::downloadSync(QUrl(imageUrl));
  1753. if (!data.isEmpty()) {
  1754. tmpFile.reset(VUtils::createTemporaryFile(info.suffix()));
  1755. if (tmpFile->open() && tmpFile->write(data) > -1) {
  1756. srcImagePath = tmpFile->fileName();
  1757. }
  1758. // Need to close it explicitly to flush cache of small file.
  1759. tmpFile->close();
  1760. }
  1761. }
  1762. if (srcImagePath.isEmpty()) {
  1763. continue;
  1764. }
  1765. // Insert image without inserting text.
  1766. auto ops = static_cast<VMdEditOperations *>(m_editOps);
  1767. ops->insertImageFromPath(imageTitle,
  1768. m_file->fetchImageFolderPath(),
  1769. m_file->getImageFolderInLink(),
  1770. srcImagePath,
  1771. false,
  1772. destImagePath,
  1773. urlInLink);
  1774. if (urlInLink.isEmpty()) {
  1775. continue;
  1776. }
  1777. // Replace URL in link.
  1778. QString newLink = QString("![%1](%2%3%4)")
  1779. .arg(imageTitle)
  1780. .arg(urlInLink)
  1781. .arg(regExp.cap(3))
  1782. .arg(regExp.cap(6));
  1783. p_text.replace(reg.m_startPos,
  1784. reg.m_endPos - reg.m_startPos,
  1785. newLink);
  1786. }
  1787. proDlg.setValue(regs.size());
  1788. }
  1789. void VMdEditor::initAttachmentMenu(QMenu *p_menu)
  1790. {
  1791. if (m_file->getType() != FileType::Note) {
  1792. return;
  1793. }
  1794. const VNoteFile *note = static_cast<const VNoteFile *>((VFile *)m_file);
  1795. const QVector<VAttachment> &attas = note->getAttachments();
  1796. if (attas.isEmpty()) {
  1797. return;
  1798. }
  1799. QMenu *subMenu = new QMenu(tr("Link To Attachment"), p_menu);
  1800. for (auto const & att : attas) {
  1801. QAction *act = new QAction(att.m_name, subMenu);
  1802. act->setData(att.m_name);
  1803. subMenu->addAction(act);
  1804. }
  1805. connect(subMenu, &QMenu::triggered,
  1806. this, &VMdEditor::handleLinkToAttachmentAction);
  1807. p_menu->addSeparator();
  1808. p_menu->addMenu(subMenu);
  1809. }
  1810. void VMdEditor::handleLinkToAttachmentAction(QAction *p_act)
  1811. {
  1812. Q_ASSERT(m_file->getType() == FileType::Note);
  1813. VNoteFile *note = static_cast<VNoteFile *>((VFile *)m_file);
  1814. QString name = p_act->data().toString();
  1815. QString folderPath = note->fetchAttachmentFolderPath();
  1816. QString filePath = QDir(folderPath).filePath(name);
  1817. QDir dir(note->fetchBasePath());
  1818. QString ut = dir.relativeFilePath(filePath);
  1819. ut = QUrl(ut).toString(QUrl::EncodeSpaces);
  1820. VInsertLinkDialog ld(QObject::tr("Insert Link"),
  1821. "",
  1822. "",
  1823. name,
  1824. ut,
  1825. false,
  1826. this);
  1827. if (ld.exec() == QDialog::Accepted) {
  1828. QString linkText = ld.getLinkText();
  1829. QString linkUrl = ld.getLinkUrl();
  1830. Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty());
  1831. m_editOps->insertLink(linkText, linkUrl);
  1832. }
  1833. }