vmdeditor.cpp 67 KB

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