vmdeditor.cpp 56 KB

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