vmdeditor.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172
  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(VUtils::createTemporaryFile(p_format));
  1397. if (!m_exportTempFile->open()) {
  1398. VUtils::showMessage(QMessageBox::Warning,
  1399. tr("Warning"),
  1400. tr("Fail to open a temporary file for export."),
  1401. "",
  1402. QMessageBox::Ok,
  1403. QMessageBox::Ok,
  1404. this);
  1405. m_exportTempFile.clear();
  1406. return;
  1407. }
  1408. emit m_object->statusMessage(tr("Exporting graph"));
  1409. QString filePath(m_exportTempFile->fileName());
  1410. QByteArray out;
  1411. if (p_lang == "puml") {
  1412. out = VPlantUMLHelper::process(p_format,
  1413. VEditUtils::removeCodeBlockFence(p_text));
  1414. } else if (p_lang == "dot") {
  1415. out = VGraphvizHelper::process(p_format,
  1416. VEditUtils::removeCodeBlockFence(p_text));
  1417. }
  1418. if (out.isEmpty() || m_exportTempFile->write(out) == -1) {
  1419. m_exportTempFile->close();
  1420. VUtils::showMessage(QMessageBox::Warning,
  1421. tr("Warning"),
  1422. tr("Fail to export graph."),
  1423. "",
  1424. QMessageBox::Ok,
  1425. QMessageBox::Ok,
  1426. this);
  1427. } else {
  1428. m_exportTempFile->close();
  1429. QClipboard *clipboard = QApplication::clipboard();
  1430. clipboard->clear();
  1431. QImage img;
  1432. img.loadFromData(out, p_format.toLocal8Bit().data());
  1433. if (!img.isNull()) {
  1434. VClipboardUtils::setImageAndLinkToClipboard(clipboard,
  1435. img,
  1436. filePath,
  1437. QClipboard::Clipboard);
  1438. emit m_object->statusMessage(tr("Graph exported and copied"));
  1439. } else {
  1440. emit m_object->statusMessage(tr("Fail to read exported image: %1").arg(filePath));
  1441. }
  1442. }
  1443. }
  1444. void VMdEditor::parseAndPaste()
  1445. {
  1446. if (!m_editTab
  1447. || !m_editTab->isEditMode()
  1448. || isReadOnly()) {
  1449. return;
  1450. }
  1451. QClipboard *clipboard = QApplication::clipboard();
  1452. const QMimeData *mimeData = clipboard->mimeData();
  1453. QString html(mimeData->html());
  1454. if (!html.isEmpty()) {
  1455. ++m_copyTimeStamp;
  1456. emit requestHtmlToText(html, 0, m_copyTimeStamp);
  1457. }
  1458. }
  1459. bool VMdEditor::processHtmlFromMimeData(const QMimeData *p_source)
  1460. {
  1461. if (!p_source->hasHtml()) {
  1462. return false;
  1463. }
  1464. // Handle <img>.
  1465. QRegExp reg("<img ([^>]*)src=\"([^\"]+)\"([^>]*)>");
  1466. QString html(p_source->html());
  1467. if (reg.indexIn(html) != -1 && VUtils::onlyHasImgInHtml(html)) {
  1468. if (p_source->hasImage()) {
  1469. // Both image data and URL are embedded.
  1470. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  1471. dialog.addSelection(tr("Insert From URL"), 0);
  1472. dialog.addSelection(tr("Insert From Image Data"), 1);
  1473. dialog.addSelection(tr("Insert As Image Link"), 2);
  1474. if (dialog.exec() == QDialog::Accepted) {
  1475. int selection = dialog.getSelection();
  1476. if (selection == 1) {
  1477. // Insert from image data.
  1478. m_editOps->insertImageFromMimeData(p_source);
  1479. return true;
  1480. } else if (selection == 2) {
  1481. // Insert as link.
  1482. insertImageLink("", reg.cap(2));
  1483. return true;
  1484. }
  1485. } else {
  1486. return true;
  1487. }
  1488. }
  1489. m_editOps->insertImageFromURL(QUrl(reg.cap(2)));
  1490. return true;
  1491. }
  1492. return false;
  1493. }
  1494. bool VMdEditor::processImageFromMimeData(const QMimeData *p_source)
  1495. {
  1496. if (!p_source->hasImage()) {
  1497. return false;
  1498. }
  1499. // Image data in the clipboard
  1500. if (p_source->hasText()) {
  1501. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  1502. dialog.addSelection(tr("Insert As Image"), 0);
  1503. dialog.addSelection(tr("Insert As Text"), 1);
  1504. dialog.addSelection(tr("Insert As Image Link"), 2);
  1505. if (dialog.exec() == QDialog::Accepted) {
  1506. int selection = dialog.getSelection();
  1507. if (selection == 1) {
  1508. // Insert as text.
  1509. Q_ASSERT(p_source->hasText() && p_source->hasImage());
  1510. VTextEdit::insertFromMimeData(p_source);
  1511. return true;
  1512. } else if (selection == 2) {
  1513. // Insert as link.
  1514. insertImageLink("", p_source->text());
  1515. return true;
  1516. }
  1517. } else {
  1518. return true;
  1519. }
  1520. }
  1521. m_editOps->insertImageFromMimeData(p_source);
  1522. return true;
  1523. }
  1524. bool VMdEditor::processUrlFromMimeData(const QMimeData *p_source)
  1525. {
  1526. QUrl url;
  1527. if (p_source->hasUrls()) {
  1528. QList<QUrl> urls = p_source->urls();
  1529. if (urls.size() == 1) {
  1530. url = urls[0];
  1531. }
  1532. } else if (p_source->hasText()) {
  1533. // Try to get URL from text.
  1534. QString text = p_source->text();
  1535. if (QFileInfo::exists(text)) {
  1536. url = QUrl::fromLocalFile(text);
  1537. } else {
  1538. url = QUrl(text);
  1539. if (url.scheme() != "https" && url.scheme() != "http") {
  1540. url.clear();
  1541. }
  1542. }
  1543. }
  1544. if (!url.isValid()) {
  1545. return false;
  1546. }
  1547. bool isImage = VUtils::isImageURL(url);
  1548. bool isLocalFile = url.isLocalFile()
  1549. && QFileInfo::exists(url.toLocalFile());
  1550. QString localTextFilePath;
  1551. if (!isImage && isLocalFile) {
  1552. localTextFilePath = url.toLocalFile();
  1553. QMimeDatabase mimeDatabase;
  1554. const QMimeType mimeType = mimeDatabase.mimeTypeForFile(localTextFilePath);
  1555. if (mimeType.isValid() && !mimeType.inherits(QStringLiteral("text/plain"))) {
  1556. localTextFilePath.clear();
  1557. }
  1558. }
  1559. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  1560. if (isImage) {
  1561. dialog.addSelection(tr("Insert As Image"), 0);
  1562. dialog.addSelection(tr("Insert As Image Link"), 1);
  1563. }
  1564. dialog.addSelection(tr("Insert As Link"), 2);
  1565. if (isLocalFile) {
  1566. dialog.addSelection(tr("Insert As Relative Link"), 3);
  1567. // Attach as attachment.
  1568. if (m_file->getType() == FileType::Note) {
  1569. VNoteFile *note = static_cast<VNoteFile *>((VFile *)m_file);
  1570. if (-1 == note->findAttachmentByPath(url.toLocalFile(), false)) {
  1571. dialog.addSelection(tr("Attach And Insert Link"), 6);
  1572. }
  1573. }
  1574. }
  1575. dialog.addSelection(tr("Insert As Text"), 4);
  1576. if (!localTextFilePath.isEmpty()) {
  1577. dialog.addSelection(tr("Insert File Content"), 5);
  1578. }
  1579. // FIXME: After calling dialog.exec(), p_source->hasUrl() returns false.
  1580. if (dialog.exec() == QDialog::Accepted) {
  1581. bool relativeLink = false;
  1582. switch (dialog.getSelection()) {
  1583. case 0:
  1584. {
  1585. // Insert As Image.
  1586. m_editOps->insertImageFromURL(url);
  1587. return true;
  1588. }
  1589. case 1:
  1590. {
  1591. // Insert As Image Link.
  1592. insertImageLink("", url.isLocalFile() ? url.toString(QUrl::EncodeSpaces)
  1593. : url.toString());
  1594. return true;
  1595. }
  1596. case 6:
  1597. {
  1598. // Attach And Insert Link.
  1599. QString file = url.toLocalFile();
  1600. Q_ASSERT(m_file->getType() == FileType::Note);
  1601. VNoteFile *note = static_cast<VNoteFile *>((VFile *)m_file);
  1602. QString destFile;
  1603. if (!note->addAttachment(file, &destFile)) {
  1604. VUtils::showMessage(QMessageBox::Warning,
  1605. tr("Warning"),
  1606. tr("Fail to add attachment %1 for note <span style=\"%2\">%3</span>.")
  1607. .arg(file)
  1608. .arg(g_config->c_dataTextStyle)
  1609. .arg(note->getName()),
  1610. "",
  1611. QMessageBox::Ok,
  1612. QMessageBox::Ok,
  1613. this);
  1614. return true;
  1615. }
  1616. emit m_object->statusMessage(tr("1 file added as attachment"));
  1617. // Update url to point to the attachment file.
  1618. Q_ASSERT(!destFile.isEmpty());
  1619. url = QUrl::fromLocalFile(destFile);
  1620. V_FALLTHROUGH;
  1621. }
  1622. case 3:
  1623. // Insert As Relative link.
  1624. relativeLink = true;
  1625. V_FALLTHROUGH;
  1626. case 2:
  1627. {
  1628. // Insert As Link.
  1629. QString initLinkText;
  1630. if (isLocalFile) {
  1631. initLinkText = QFileInfo(url.toLocalFile()).fileName();
  1632. }
  1633. QString ut;
  1634. if (relativeLink) {
  1635. QDir dir(m_file->fetchBasePath());
  1636. ut = dir.relativeFilePath(url.toLocalFile());
  1637. ut = QUrl(ut).toString(QUrl::EncodeSpaces);
  1638. } else {
  1639. ut = url.isLocalFile() ? url.toString(QUrl::EncodeSpaces)
  1640. : url.toString();
  1641. }
  1642. VInsertLinkDialog ld(QObject::tr("Insert Link"),
  1643. "",
  1644. "",
  1645. initLinkText,
  1646. ut,
  1647. false,
  1648. this);
  1649. if (ld.exec() == QDialog::Accepted) {
  1650. QString linkText = ld.getLinkText();
  1651. QString linkUrl = ld.getLinkUrl();
  1652. Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty());
  1653. m_editOps->insertLink(linkText, linkUrl);
  1654. }
  1655. return true;
  1656. }
  1657. case 4:
  1658. {
  1659. // Insert As Text.
  1660. if (p_source->hasText()) {
  1661. m_editOps->insertText(p_source->text());
  1662. } else {
  1663. m_editOps->insertText(url.toString());
  1664. }
  1665. return true;
  1666. }
  1667. case 5:
  1668. {
  1669. // Insert File Content.
  1670. Q_ASSERT(!localTextFilePath.isEmpty());
  1671. m_editOps->insertText(VUtils::readFileFromDisk(localTextFilePath));
  1672. return true;
  1673. }
  1674. default:
  1675. Q_ASSERT(false);
  1676. break;
  1677. }
  1678. }
  1679. return true;
  1680. }
  1681. void VMdEditor::replaceTextWithLocalImages(QString &p_text)
  1682. {
  1683. QVector<VElementRegion> regs = VUtils::fetchImageRegionsUsingParser(p_text);
  1684. if (regs.isEmpty()) {
  1685. return;
  1686. }
  1687. // Sort it in ascending order.
  1688. std::sort(regs.begin(), regs.end());
  1689. QProgressDialog proDlg(tr("Fetching images to local folder..."),
  1690. tr("Abort"),
  1691. 0,
  1692. regs.size(),
  1693. this);
  1694. proDlg.setWindowModality(Qt::WindowModal);
  1695. proDlg.setWindowTitle(tr("Fetching Images To Local Folder"));
  1696. QRegExp regExp(VUtils::c_imageLinkRegExp);
  1697. for (int i = regs.size() - 1; i >= 0; --i) {
  1698. proDlg.setValue(regs.size() - 1 - i);
  1699. if (proDlg.wasCanceled()) {
  1700. break;
  1701. }
  1702. const VElementRegion &reg = regs[i];
  1703. QString linkText = p_text.mid(reg.m_startPos, reg.m_endPos - reg.m_startPos);
  1704. if (regExp.indexIn(linkText) == -1) {
  1705. continue;
  1706. }
  1707. QString imageTitle = regExp.cap(1).trimmed();
  1708. QString imageUrl = regExp.cap(2).trimmed();
  1709. const int maxUrlLength = 100;
  1710. QString urlToDisplay(imageUrl);
  1711. if (urlToDisplay.size() > maxUrlLength) {
  1712. urlToDisplay = urlToDisplay.left(maxUrlLength) + "...";
  1713. }
  1714. proDlg.setLabelText(tr("Fetching image: %1").arg(urlToDisplay));
  1715. QString destImagePath, urlInLink;
  1716. // Only handle absolute file path or network path.
  1717. QString srcImagePath;
  1718. QFileInfo info(VUtils::purifyUrl(imageUrl));
  1719. // For network image.
  1720. QScopedPointer<QTemporaryFile> tmpFile;
  1721. if (info.exists()) {
  1722. if (info.isAbsolute()) {
  1723. // Absolute local path.
  1724. srcImagePath = info.absoluteFilePath();
  1725. }
  1726. } else {
  1727. // Network path.
  1728. QByteArray data = VDownloader::downloadSync(QUrl(imageUrl));
  1729. if (!data.isEmpty()) {
  1730. tmpFile.reset(VUtils::createTemporaryFile(info.suffix()));
  1731. if (tmpFile->open() && tmpFile->write(data) > -1) {
  1732. srcImagePath = tmpFile->fileName();
  1733. }
  1734. // Need to close it explicitly to flush cache of small file.
  1735. tmpFile->close();
  1736. }
  1737. }
  1738. if (srcImagePath.isEmpty()) {
  1739. continue;
  1740. }
  1741. // Insert image without inserting text.
  1742. auto ops = static_cast<VMdEditOperations *>(m_editOps);
  1743. ops->insertImageFromPath(imageTitle,
  1744. m_file->fetchImageFolderPath(),
  1745. m_file->getImageFolderInLink(),
  1746. srcImagePath,
  1747. false,
  1748. destImagePath,
  1749. urlInLink);
  1750. if (urlInLink.isEmpty()) {
  1751. continue;
  1752. }
  1753. // Replace URL in link.
  1754. QString newLink = QString("![%1](%2%3%4)")
  1755. .arg(imageTitle)
  1756. .arg(urlInLink)
  1757. .arg(regExp.cap(3))
  1758. .arg(regExp.cap(6));
  1759. p_text.replace(reg.m_startPos,
  1760. reg.m_endPos - reg.m_startPos,
  1761. newLink);
  1762. qDebug() << "replace link" << linkText << "to" << newLink;
  1763. }
  1764. proDlg.setValue(regs.size());
  1765. }
  1766. void VMdEditor::initAttachmentMenu(QMenu *p_menu)
  1767. {
  1768. if (m_file->getType() != FileType::Note) {
  1769. return;
  1770. }
  1771. const VNoteFile *note = static_cast<const VNoteFile *>((VFile *)m_file);
  1772. const QVector<VAttachment> &attas = note->getAttachments();
  1773. if (attas.isEmpty()) {
  1774. return;
  1775. }
  1776. QMenu *subMenu = new QMenu(tr("Link To Attachment"), p_menu);
  1777. for (auto const & att : attas) {
  1778. QAction *act = new QAction(att.m_name, subMenu);
  1779. act->setData(att.m_name);
  1780. subMenu->addAction(act);
  1781. }
  1782. connect(subMenu, &QMenu::triggered,
  1783. this, &VMdEditor::handleLinkToAttachmentAction);
  1784. p_menu->addSeparator();
  1785. p_menu->addMenu(subMenu);
  1786. }
  1787. void VMdEditor::handleLinkToAttachmentAction(QAction *p_act)
  1788. {
  1789. Q_ASSERT(m_file->getType() == FileType::Note);
  1790. VNoteFile *note = static_cast<VNoteFile *>((VFile *)m_file);
  1791. QString name = p_act->data().toString();
  1792. QString folderPath = note->fetchAttachmentFolderPath();
  1793. QString filePath = QDir(folderPath).filePath(name);
  1794. QDir dir(note->fetchBasePath());
  1795. QString ut = dir.relativeFilePath(filePath);
  1796. ut = QUrl(ut).toString(QUrl::EncodeSpaces);
  1797. VInsertLinkDialog ld(QObject::tr("Insert Link"),
  1798. "",
  1799. "",
  1800. name,
  1801. ut,
  1802. false,
  1803. this);
  1804. if (ld.exec() == QDialog::Accepted) {
  1805. QString linkText = ld.getLinkText();
  1806. QString linkUrl = ld.getLinkUrl();
  1807. Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty());
  1808. m_editOps->insertLink(linkText, linkUrl);
  1809. }
  1810. }