vmdeditor.cpp 66 KB

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