vmdeditor.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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 "hgmarkdownhighlighter.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. extern VWebUtils *g_webUtils;
  26. extern VConfigManager *g_config;
  27. VMdEditor::VMdEditor(VFile *p_file,
  28. VDocument *p_doc,
  29. MarkdownConverterType p_type,
  30. QWidget *p_parent)
  31. : VTextEdit(p_parent),
  32. VEditor(p_file, this),
  33. m_mdHighlighter(NULL),
  34. m_freshEdit(true),
  35. m_textToHtmlDialog(NULL),
  36. m_zoomDelta(0)
  37. {
  38. Q_ASSERT(p_file->getDocType() == DocType::Markdown);
  39. VEditor::init();
  40. // Hook functions from VEditor.
  41. connect(this, &VTextEdit::cursorPositionChanged,
  42. this, [this]() {
  43. highlightOnCursorPositionChanged();
  44. });
  45. connect(this, &VTextEdit::selectionChanged,
  46. this, [this]() {
  47. highlightSelectedWord();
  48. });
  49. // End.
  50. setReadOnly(true);
  51. m_mdHighlighter = new HGMarkdownHighlighter(g_config->getMdHighlightingStyles(),
  52. g_config->getCodeBlockStyles(),
  53. g_config->getMarkdownHighlightInterval(),
  54. document());
  55. connect(m_mdHighlighter, &HGMarkdownHighlighter::headersUpdated,
  56. this, &VMdEditor::updateHeaders);
  57. // After highlight, the cursor may trun into non-visible. We should make it visible
  58. // in this case.
  59. connect(m_mdHighlighter, &HGMarkdownHighlighter::highlightCompleted,
  60. this, [this]() {
  61. makeBlockVisible(textCursor().block());
  62. if (m_freshEdit) {
  63. m_freshEdit = false;
  64. emit m_object->ready();
  65. }
  66. });
  67. m_cbHighlighter = new VCodeBlockHighlightHelper(m_mdHighlighter,
  68. p_doc,
  69. p_type);
  70. m_previewMgr = new VPreviewManager(this, m_mdHighlighter);
  71. connect(m_mdHighlighter, &HGMarkdownHighlighter::imageLinksUpdated,
  72. m_previewMgr, &VPreviewManager::imageLinksUpdated);
  73. connect(m_previewMgr, &VPreviewManager::requestUpdateImageLinks,
  74. m_mdHighlighter, &HGMarkdownHighlighter::updateHighlight);
  75. m_editOps = new VMdEditOperations(this, m_file);
  76. connect(m_editOps, &VEditOperations::statusMessage,
  77. m_object, &VEditorObject::statusMessage);
  78. connect(m_editOps, &VEditOperations::vimStatusUpdated,
  79. m_object, &VEditorObject::vimStatusUpdated);
  80. connect(this, &VTextEdit::cursorPositionChanged,
  81. this, &VMdEditor::updateCurrentHeader);
  82. setDisplayScaleFactor(VUtils::calculateScaleFactor());
  83. updateFontAndPalette();
  84. updateConfig();
  85. }
  86. void VMdEditor::updateFontAndPalette()
  87. {
  88. setFont(g_config->getMdEditFont());
  89. setPalette(g_config->getMdEditPalette());
  90. // setPalette() won't change the foreground.
  91. setTextColor(g_config->getMdEditPalette().color(QPalette::Text));
  92. }
  93. void VMdEditor::beginEdit()
  94. {
  95. updateConfig();
  96. initInitImages();
  97. setModified(false);
  98. setReadOnlyAndHighlightCurrentLine(false);
  99. emit statusChanged();
  100. if (m_freshEdit) {
  101. m_mdHighlighter->updateHighlight();
  102. relayout();
  103. } else {
  104. updateHeaders(m_mdHighlighter->getHeaderRegions());
  105. }
  106. }
  107. void VMdEditor::endEdit()
  108. {
  109. setReadOnlyAndHighlightCurrentLine(true);
  110. clearUnusedImages();
  111. }
  112. void VMdEditor::saveFile()
  113. {
  114. Q_ASSERT(m_file->isModifiable());
  115. if (!document()->isModified()) {
  116. return;
  117. }
  118. m_file->setContent(toPlainText());
  119. setModified(false);
  120. clearUnusedImages();
  121. initInitImages();
  122. }
  123. void VMdEditor::reloadFile()
  124. {
  125. bool readonly = isReadOnly();
  126. setReadOnly(true);
  127. const QString &content = m_file->getContent();
  128. setPlainText(content);
  129. setModified(false);
  130. m_mdHighlighter->updateHighlightFast();
  131. m_freshEdit = true;
  132. setReadOnly(readonly);
  133. }
  134. bool VMdEditor::scrollToBlock(int p_blockNumber)
  135. {
  136. QTextBlock block = document()->findBlockByNumber(p_blockNumber);
  137. if (block.isValid()) {
  138. VEditUtils::scrollBlockInPage(this, block.blockNumber(), 0);
  139. moveCursor(QTextCursor::EndOfBlock);
  140. return true;
  141. }
  142. return false;
  143. }
  144. // Get the visual offset of a block.
  145. #define GETVISUALOFFSETY (contentOffsetY() + (int)rect.y())
  146. void VMdEditor::makeBlockVisible(const QTextBlock &p_block)
  147. {
  148. if (!p_block.isValid() || !p_block.isVisible()) {
  149. return;
  150. }
  151. QScrollBar *vbar = verticalScrollBar();
  152. if (!vbar || (vbar->minimum() == vbar->maximum())) {
  153. // No vertical scrollbar. No need to scroll.
  154. return;
  155. }
  156. int height = rect().height();
  157. QScrollBar *hbar = horizontalScrollBar();
  158. if (hbar && (hbar->minimum() != hbar->maximum())) {
  159. height -= hbar->height();
  160. }
  161. bool moved = false;
  162. QAbstractTextDocumentLayout *layout = document()->documentLayout();
  163. QRectF rect = layout->blockBoundingRect(p_block);
  164. int y = GETVISUALOFFSETY;
  165. int rectHeight = (int)rect.height();
  166. // Handle the case rectHeight >= height.
  167. if (rectHeight >= height) {
  168. if (y < 0) {
  169. // Need to scroll up.
  170. while (y + rectHeight < height && vbar->value() > vbar->minimum()) {
  171. moved = true;
  172. vbar->setValue(vbar->value() - vbar->singleStep());
  173. rect = layout->blockBoundingRect(p_block);
  174. rectHeight = (int)rect.height();
  175. y = GETVISUALOFFSETY;
  176. }
  177. } else if (y > 0) {
  178. // Need to scroll down.
  179. while (y > 0 && vbar->value() < vbar->maximum()) {
  180. moved = true;
  181. vbar->setValue(vbar->value() + vbar->singleStep());
  182. rect = layout->blockBoundingRect(p_block);
  183. rectHeight = (int)rect.height();
  184. y = GETVISUALOFFSETY;
  185. }
  186. if (y < 0) {
  187. // One step back.
  188. moved = true;
  189. vbar->setValue(vbar->value() - vbar->singleStep());
  190. }
  191. }
  192. if (moved) {
  193. qDebug() << "scroll to make huge block visible";
  194. }
  195. return;
  196. }
  197. while (y < 0 && vbar->value() > vbar->minimum()) {
  198. moved = true;
  199. vbar->setValue(vbar->value() - vbar->singleStep());
  200. rect = layout->blockBoundingRect(p_block);
  201. rectHeight = (int)rect.height();
  202. y = GETVISUALOFFSETY;
  203. }
  204. if (moved) {
  205. qDebug() << "scroll page down to make block visible";
  206. return;
  207. }
  208. while (y + rectHeight > height && vbar->value() < vbar->maximum()) {
  209. moved = true;
  210. vbar->setValue(vbar->value() + vbar->singleStep());
  211. rect = layout->blockBoundingRect(p_block);
  212. rectHeight = (int)rect.height();
  213. y = GETVISUALOFFSETY;
  214. }
  215. if (moved) {
  216. qDebug() << "scroll page up to make block visible";
  217. }
  218. }
  219. void VMdEditor::contextMenuEvent(QContextMenuEvent *p_event)
  220. {
  221. QScopedPointer<QMenu> menu(createStandardContextMenu());
  222. menu->setToolTipsVisible(true);
  223. VEditTab *editTab = dynamic_cast<VEditTab *>(parent());
  224. Q_ASSERT(editTab);
  225. if (editTab->isEditMode()) {
  226. const QList<QAction *> actions = menu->actions();
  227. if (textCursor().hasSelection()) {
  228. initCopyAsMenu(actions.isEmpty() ? NULL : actions.last(), menu.data());
  229. } else {
  230. QAction *saveExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/save_exit.svg"),
  231. tr("&Save Changes And Read"),
  232. menu.data());
  233. saveExitAct->setToolTip(tr("Save changes and exit edit mode"));
  234. connect(saveExitAct, &QAction::triggered,
  235. this, [this]() {
  236. emit m_object->saveAndRead();
  237. });
  238. QAction *discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"),
  239. tr("&Discard Changes And Read"),
  240. menu.data());
  241. discardExitAct->setToolTip(tr("Discard changes and exit edit mode"));
  242. connect(discardExitAct, &QAction::triggered,
  243. this, [this]() {
  244. emit m_object->discardAndRead();
  245. });
  246. menu->insertAction(actions.isEmpty() ? NULL : actions[0], discardExitAct);
  247. menu->insertAction(discardExitAct, saveExitAct);
  248. if (!actions.isEmpty()) {
  249. menu->insertSeparator(actions[0]);
  250. }
  251. }
  252. QClipboard *clipboard = QApplication::clipboard();
  253. const QMimeData *mimeData = clipboard->mimeData();
  254. if (mimeData->hasText()) {
  255. initPasteAsBlockQuoteMenu(menu.data());
  256. }
  257. }
  258. menu->exec(p_event->globalPos());
  259. }
  260. void VMdEditor::mousePressEvent(QMouseEvent *p_event)
  261. {
  262. if (handleMousePressEvent(p_event)) {
  263. return;
  264. }
  265. VTextEdit::mousePressEvent(p_event);
  266. emit m_object->mousePressed(p_event);
  267. }
  268. void VMdEditor::mouseReleaseEvent(QMouseEvent *p_event)
  269. {
  270. if (handleMouseReleaseEvent(p_event)) {
  271. return;
  272. }
  273. VTextEdit::mouseReleaseEvent(p_event);
  274. emit m_object->mouseReleased(p_event);
  275. }
  276. void VMdEditor::mouseMoveEvent(QMouseEvent *p_event)
  277. {
  278. if (handleMouseMoveEvent(p_event)) {
  279. return;
  280. }
  281. VTextEdit::mouseMoveEvent(p_event);
  282. emit m_object->mouseMoved(p_event);
  283. }
  284. QVariant VMdEditor::inputMethodQuery(Qt::InputMethodQuery p_query) const
  285. {
  286. QVariant ret;
  287. if (handleInputMethodQuery(p_query, ret)) {
  288. return ret;
  289. }
  290. return VTextEdit::inputMethodQuery(p_query);
  291. }
  292. bool VMdEditor::isBlockVisible(const QTextBlock &p_block)
  293. {
  294. if (!p_block.isValid() || !p_block.isVisible()) {
  295. return false;
  296. }
  297. QScrollBar *vbar = verticalScrollBar();
  298. if (!vbar || !vbar->isVisible()) {
  299. // No vertical scrollbar.
  300. return true;
  301. }
  302. int height = rect().height();
  303. QScrollBar *hbar = horizontalScrollBar();
  304. if (hbar && hbar->isVisible()) {
  305. height -= hbar->height();
  306. }
  307. QAbstractTextDocumentLayout *layout = document()->documentLayout();
  308. QRectF rect = layout->blockBoundingRect(p_block);
  309. int y = GETVISUALOFFSETY;
  310. int rectHeight = (int)rect.height();
  311. return (y >= 0 && y < height) || (y < 0 && y + rectHeight > 0);
  312. }
  313. static void addHeaderSequence(QVector<int> &p_sequence, int p_level, int p_baseLevel)
  314. {
  315. Q_ASSERT(p_level >= 1 && p_level < p_sequence.size());
  316. if (p_level < p_baseLevel) {
  317. p_sequence.fill(0);
  318. return;
  319. }
  320. ++p_sequence[p_level];
  321. for (int i = p_level + 1; i < p_sequence.size(); ++i) {
  322. p_sequence[i] = 0;
  323. }
  324. }
  325. static QString headerSequenceStr(const QVector<int> &p_sequence)
  326. {
  327. QString res;
  328. for (int i = 1; i < p_sequence.size(); ++i) {
  329. if (p_sequence[i] != 0) {
  330. res = res + QString::number(p_sequence[i]) + '.';
  331. } else if (res.isEmpty()) {
  332. continue;
  333. } else {
  334. break;
  335. }
  336. }
  337. return res;
  338. }
  339. static void insertSequenceToHeader(QTextBlock p_block,
  340. QRegExp &p_reg,
  341. QRegExp &p_preReg,
  342. const QString &p_seq)
  343. {
  344. if (!p_block.isValid()) {
  345. return;
  346. }
  347. QString text = p_block.text();
  348. bool matched = p_reg.exactMatch(text);
  349. Q_ASSERT(matched);
  350. matched = p_preReg.exactMatch(text);
  351. Q_ASSERT(matched);
  352. int start = p_reg.cap(1).length() + 1;
  353. int end = p_preReg.cap(1).length();
  354. Q_ASSERT(start <= end);
  355. QTextCursor cursor(p_block);
  356. cursor.setPosition(p_block.position() + start);
  357. if (start != end) {
  358. cursor.setPosition(p_block.position() + end, QTextCursor::KeepAnchor);
  359. }
  360. if (p_seq.isEmpty()) {
  361. cursor.removeSelectedText();
  362. } else {
  363. cursor.insertText(p_seq + ' ');
  364. }
  365. }
  366. void VMdEditor::updateHeaders(const QVector<VElementRegion> &p_headerRegions)
  367. {
  368. QTextDocument *doc = document();
  369. QVector<VTableOfContentItem> headers;
  370. QVector<int> headerBlockNumbers;
  371. QVector<QString> headerSequences;
  372. if (!p_headerRegions.isEmpty()) {
  373. headers.reserve(p_headerRegions.size());
  374. headerBlockNumbers.reserve(p_headerRegions.size());
  375. headerSequences.reserve(p_headerRegions.size());
  376. }
  377. // Assume that each block contains only one line
  378. // Only support # syntax for now
  379. QRegExp headerReg(VUtils::c_headerRegExp);
  380. int baseLevel = -1;
  381. for (auto const & reg : p_headerRegions) {
  382. QTextBlock block = doc->findBlock(reg.m_startPos);
  383. if (!block.isValid()) {
  384. continue;
  385. }
  386. if (!block.contains(reg.m_endPos - 1)) {
  387. qWarning() << "header accross multiple blocks, starting from block"
  388. << block.blockNumber()
  389. << block.text();
  390. }
  391. if ((block.userState() == HighlightBlockState::Normal)
  392. && headerReg.exactMatch(block.text())) {
  393. int level = headerReg.cap(1).length();
  394. VTableOfContentItem header(headerReg.cap(2).trimmed(),
  395. level,
  396. block.blockNumber(),
  397. headers.size());
  398. headers.append(header);
  399. headerBlockNumbers.append(block.blockNumber());
  400. headerSequences.append(headerReg.cap(3));
  401. if (baseLevel == -1) {
  402. baseLevel = level;
  403. } else if (baseLevel > level) {
  404. baseLevel = level;
  405. }
  406. }
  407. }
  408. m_headers.clear();
  409. bool autoSequence = m_config.m_enableHeadingSequence
  410. && !isReadOnly()
  411. && m_file->isModifiable();
  412. int headingSequenceBaseLevel = g_config->getHeadingSequenceBaseLevel();
  413. if (headingSequenceBaseLevel < 1 || headingSequenceBaseLevel > 6) {
  414. headingSequenceBaseLevel = 1;
  415. }
  416. QVector<int> seqs(7, 0);
  417. QRegExp preReg(VUtils::c_headerPrefixRegExp);
  418. int curLevel = baseLevel - 1;
  419. for (int i = 0; i < headers.size(); ++i) {
  420. VTableOfContentItem &item = headers[i];
  421. while (item.m_level > curLevel + 1) {
  422. curLevel += 1;
  423. // Insert empty level which is an invalid header.
  424. m_headers.append(VTableOfContentItem(c_emptyHeaderName,
  425. curLevel,
  426. -1,
  427. m_headers.size()));
  428. if (autoSequence) {
  429. addHeaderSequence(seqs, curLevel, headingSequenceBaseLevel);
  430. }
  431. }
  432. item.m_index = m_headers.size();
  433. m_headers.append(item);
  434. curLevel = item.m_level;
  435. if (autoSequence) {
  436. addHeaderSequence(seqs, item.m_level, headingSequenceBaseLevel);
  437. QString seqStr = headerSequenceStr(seqs);
  438. if (headerSequences[i] != seqStr) {
  439. // Insert correct sequence.
  440. insertSequenceToHeader(doc->findBlockByNumber(headerBlockNumbers[i]),
  441. headerReg,
  442. preReg,
  443. seqStr);
  444. }
  445. }
  446. }
  447. emit headersChanged(m_headers);
  448. updateCurrentHeader();
  449. }
  450. void VMdEditor::updateCurrentHeader()
  451. {
  452. emit currentHeaderChanged(textCursor().block().blockNumber());
  453. }
  454. void VMdEditor::initInitImages()
  455. {
  456. m_initImages = VUtils::fetchImagesFromMarkdownFile(m_file,
  457. ImageLink::LocalRelativeInternal);
  458. }
  459. void VMdEditor::clearUnusedImages()
  460. {
  461. QVector<ImageLink> images = VUtils::fetchImagesFromMarkdownFile(m_file,
  462. ImageLink::LocalRelativeInternal);
  463. QSet<QString> unusedImages;
  464. if (!m_insertedImages.isEmpty()) {
  465. for (int i = 0; i < m_insertedImages.size(); ++i) {
  466. const ImageLink &link = m_insertedImages[i];
  467. if (link.m_type != ImageLink::LocalRelativeInternal) {
  468. continue;
  469. }
  470. int j;
  471. for (j = 0; j < images.size(); ++j) {
  472. if (VUtils::equalPath(link.m_path, images[j].m_path)) {
  473. break;
  474. }
  475. }
  476. // This inserted image is no longer in the file.
  477. if (j == images.size()) {
  478. unusedImages.insert(link.m_path);
  479. }
  480. }
  481. m_insertedImages.clear();
  482. }
  483. for (int i = 0; i < m_initImages.size(); ++i) {
  484. const ImageLink &link = m_initImages[i];
  485. V_ASSERT(link.m_type == ImageLink::LocalRelativeInternal);
  486. int j;
  487. for (j = 0; j < images.size(); ++j) {
  488. if (VUtils::equalPath(link.m_path, images[j].m_path)) {
  489. break;
  490. }
  491. }
  492. // Original local relative image is no longer in the file.
  493. if (j == images.size()) {
  494. unusedImages.insert(link.m_path);
  495. }
  496. }
  497. if (!unusedImages.isEmpty()) {
  498. if (g_config->getConfirmImagesCleanUp()) {
  499. QVector<ConfirmItemInfo> items;
  500. for (auto const & img : unusedImages) {
  501. items.push_back(ConfirmItemInfo(img,
  502. img,
  503. img,
  504. NULL));
  505. }
  506. QString text = tr("Following images seems not to be used in this note anymore. "
  507. "Please confirm the deletion of these images.");
  508. QString info = tr("Deleted files could be found in the recycle "
  509. "bin of this note.<br>"
  510. "Click \"Cancel\" to leave them untouched.");
  511. VConfirmDeletionDialog dialog(tr("Confirm Cleaning Up Unused Images"),
  512. text,
  513. info,
  514. items,
  515. true,
  516. true,
  517. true,
  518. this);
  519. unusedImages.clear();
  520. if (dialog.exec()) {
  521. items = dialog.getConfirmedItems();
  522. g_config->setConfirmImagesCleanUp(dialog.getAskAgainEnabled());
  523. for (auto const & item : items) {
  524. unusedImages.insert(item.m_name);
  525. }
  526. }
  527. }
  528. for (auto const & item : unusedImages) {
  529. bool ret = false;
  530. if (m_file->getType() == FileType::Note) {
  531. const VNoteFile *tmpFile = dynamic_cast<const VNoteFile *>((VFile *)m_file);
  532. ret = VUtils::deleteFile(tmpFile->getNotebook(), item, false);
  533. } else if (m_file->getType() == FileType::Orphan) {
  534. const VOrphanFile *tmpFile = dynamic_cast<const VOrphanFile *>((VFile *)m_file);
  535. ret = VUtils::deleteFile(tmpFile, item, false);
  536. } else {
  537. Q_ASSERT(false);
  538. }
  539. if (!ret) {
  540. qWarning() << "fail to delete unused original image" << item;
  541. } else {
  542. qDebug() << "delete unused image" << item;
  543. }
  544. }
  545. }
  546. m_initImages.clear();
  547. }
  548. void VMdEditor::keyPressEvent(QKeyEvent *p_event)
  549. {
  550. int key = p_event->key();
  551. int modifiers = p_event->modifiers();
  552. switch (key) {
  553. case Qt::Key_Minus:
  554. case Qt::Key_Underscore:
  555. // Zoom out.
  556. if (modifiers & Qt::ControlModifier) {
  557. zoomPage(false);
  558. return;
  559. }
  560. break;
  561. case Qt::Key_Plus:
  562. case Qt::Key_Equal:
  563. // Zoom in.
  564. if (modifiers & Qt::ControlModifier) {
  565. zoomPage(true);
  566. return;
  567. }
  568. break;
  569. case Qt::Key_0:
  570. // Restore zoom.
  571. if (modifiers & Qt::ControlModifier) {
  572. if (m_zoomDelta > 0) {
  573. zoomPage(false, m_zoomDelta);
  574. } else if (m_zoomDelta < 0) {
  575. zoomPage(true, -m_zoomDelta);
  576. }
  577. return;
  578. }
  579. break;
  580. default:
  581. break;
  582. }
  583. if (m_editOps && m_editOps->handleKeyPressEvent(p_event)) {
  584. return;
  585. }
  586. // Esc to exit edit mode when Vim is disabled.
  587. if (key == Qt::Key_Escape) {
  588. emit m_object->discardAndRead();
  589. return;
  590. }
  591. VTextEdit::keyPressEvent(p_event);
  592. }
  593. bool VMdEditor::canInsertFromMimeData(const QMimeData *p_source) const
  594. {
  595. return p_source->hasImage()
  596. || p_source->hasUrls()
  597. || VTextEdit::canInsertFromMimeData(p_source);
  598. }
  599. void VMdEditor::insertFromMimeData(const QMimeData *p_source)
  600. {
  601. if (p_source->hasHtml()) {
  602. // Handle <img>.
  603. QRegExp reg("<img ([^>]*)src=\"([^\"]+)\"([^>]*)>");
  604. if (reg.indexIn(p_source->html()) != -1) {
  605. if (p_source->hasImage()) {
  606. // Both image data and URL are embedded.
  607. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  608. dialog.addSelection(tr("Insert From URL"), 0);
  609. dialog.addSelection(tr("Insert From Image Data"), 1);
  610. dialog.addSelection(tr("Insert As Image Link"), 2);
  611. if (dialog.exec() == QDialog::Accepted) {
  612. int selection = dialog.getSelection();
  613. if (selection == 1) {
  614. // Insert from image data.
  615. m_editOps->insertImageFromMimeData(p_source);
  616. return;
  617. } else if (selection == 2) {
  618. // Insert as link.
  619. insertImageLink("", reg.cap(2));
  620. return;
  621. }
  622. } else {
  623. return;
  624. }
  625. }
  626. m_editOps->insertImageFromURL(QUrl(reg.cap(2)));
  627. return;
  628. }
  629. }
  630. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  631. dialog.addSelection(tr("Insert As Image"), 0);
  632. dialog.addSelection(tr("Insert As Text"), 1);
  633. dialog.addSelection(tr("Insert As Image Link"), 2);
  634. if (p_source->hasImage()) {
  635. // Image data in the clipboard
  636. if (p_source->hasText()) {
  637. if (dialog.exec() == QDialog::Accepted) {
  638. int selection = dialog.getSelection();
  639. if (selection == 1) {
  640. // Insert as text.
  641. Q_ASSERT(p_source->hasText() && p_source->hasImage());
  642. VTextEdit::insertFromMimeData(p_source);
  643. return;
  644. } else if (selection == 2) {
  645. // Insert as link.
  646. insertImageLink("", p_source->text());
  647. return;
  648. }
  649. } else {
  650. return;
  651. }
  652. }
  653. m_editOps->insertImageFromMimeData(p_source);
  654. return;
  655. }
  656. if (p_source->hasUrls()) {
  657. QList<QUrl> urls = p_source->urls();
  658. if (urls.size() == 1 && VUtils::isImageURL(urls[0])) {
  659. if (dialog.exec() == QDialog::Accepted) {
  660. // FIXME: After calling dialog.exec(), p_source->hasUrl() returns false.
  661. int selection = dialog.getSelection();
  662. if (selection == 0) {
  663. // Insert as image.
  664. m_editOps->insertImageFromURL(urls[0]);
  665. return;
  666. } else if (selection == 2) {
  667. // Insert as link.
  668. insertImageLink("", urls[0].toString(QUrl::FullyEncoded));
  669. return;
  670. }
  671. QMimeData newSource;
  672. newSource.setUrls(urls);
  673. VTextEdit::insertFromMimeData(&newSource);
  674. return;
  675. } else {
  676. return;
  677. }
  678. }
  679. }
  680. if (p_source->hasText()) {
  681. QString text = p_source->text();
  682. if (VUtils::isImageURLText(text)) {
  683. // The text is a URL to an image.
  684. if (dialog.exec() == QDialog::Accepted) {
  685. int selection = dialog.getSelection();
  686. if (selection == 0) {
  687. // Insert as image.
  688. QUrl url(text);
  689. if (url.isValid()) {
  690. m_editOps->insertImageFromURL(QUrl(text));
  691. }
  692. return;
  693. } else if (selection == 2) {
  694. // Insert as link.
  695. insertImageLink("", text);
  696. return;
  697. }
  698. } else {
  699. return;
  700. }
  701. }
  702. Q_ASSERT(p_source->hasText());
  703. }
  704. VTextEdit::insertFromMimeData(p_source);
  705. }
  706. void VMdEditor::imageInserted(const QString &p_path, const QString &p_url)
  707. {
  708. ImageLink link;
  709. link.m_path = p_path;
  710. link.m_url = p_url;
  711. if (m_file->useRelativeImageFolder()) {
  712. link.m_type = ImageLink::LocalRelativeInternal;
  713. } else {
  714. link.m_type = ImageLink::LocalAbsolute;
  715. }
  716. m_insertedImages.append(link);
  717. }
  718. bool VMdEditor::scrollToHeader(int p_blockNumber)
  719. {
  720. if (p_blockNumber < 0) {
  721. return false;
  722. }
  723. return scrollToBlock(p_blockNumber);
  724. }
  725. int VMdEditor::indexOfCurrentHeader() const
  726. {
  727. if (m_headers.isEmpty()) {
  728. return -1;
  729. }
  730. int blockNumber = textCursor().block().blockNumber();
  731. for (int i = m_headers.size() - 1; i >= 0; --i) {
  732. if (!m_headers[i].isEmpty()
  733. && m_headers[i].m_blockNumber <= blockNumber) {
  734. return i;
  735. }
  736. }
  737. return -1;
  738. }
  739. bool VMdEditor::jumpTitle(bool p_forward, int p_relativeLevel, int p_repeat)
  740. {
  741. if (m_headers.isEmpty()) {
  742. return false;
  743. }
  744. QTextCursor cursor = textCursor();
  745. int cursorLine = cursor.block().blockNumber();
  746. int targetIdx = -1;
  747. // -1: skip level check.
  748. int targetLevel = 0;
  749. int idx = indexOfCurrentHeader();
  750. if (idx == -1) {
  751. // Cursor locates at the beginning, before any headers.
  752. if (p_relativeLevel < 0 || !p_forward) {
  753. return false;
  754. }
  755. }
  756. int delta = 1;
  757. if (!p_forward) {
  758. delta = -1;
  759. }
  760. bool firstHeader = true;
  761. for (targetIdx = idx == -1 ? 0 : idx;
  762. targetIdx >= 0 && targetIdx < m_headers.size();
  763. targetIdx += delta) {
  764. const VTableOfContentItem &header = m_headers[targetIdx];
  765. if (header.isEmpty()) {
  766. continue;
  767. }
  768. if (targetLevel == 0) {
  769. // The target level has not been init yet.
  770. Q_ASSERT(firstHeader);
  771. targetLevel = header.m_level;
  772. if (p_relativeLevel < 0) {
  773. targetLevel += p_relativeLevel;
  774. if (targetLevel < 1) {
  775. // Invalid level.
  776. return false;
  777. }
  778. } else if (p_relativeLevel > 0) {
  779. targetLevel = -1;
  780. }
  781. }
  782. if (targetLevel == -1 || header.m_level == targetLevel) {
  783. if (firstHeader
  784. && (cursorLine == header.m_blockNumber
  785. || p_forward)
  786. && idx != -1) {
  787. // This header is not counted for the repeat.
  788. firstHeader = false;
  789. continue;
  790. }
  791. if (--p_repeat == 0) {
  792. // Found.
  793. break;
  794. }
  795. } else if (header.m_level < targetLevel) {
  796. // Stop by higher level.
  797. return false;
  798. }
  799. firstHeader = false;
  800. }
  801. if (targetIdx < 0 || targetIdx >= m_headers.size()) {
  802. return false;
  803. }
  804. // Jump to target header.
  805. int line = m_headers[targetIdx].m_blockNumber;
  806. if (line > -1) {
  807. QTextBlock block = document()->findBlockByNumber(line);
  808. if (block.isValid()) {
  809. cursor.setPosition(block.position());
  810. setTextCursor(cursor);
  811. return true;
  812. }
  813. }
  814. return false;
  815. }
  816. void VMdEditor::scrollBlockInPage(int p_blockNum, int p_dest)
  817. {
  818. VEditUtils::scrollBlockInPage(this, p_blockNum, p_dest);
  819. }
  820. void VMdEditor::updateTextEditConfig()
  821. {
  822. setBlockImageEnabled(g_config->getEnablePreviewImages());
  823. setImageWidthConstrainted(g_config->getEnablePreviewImageConstraint());
  824. setLineLeading(m_config.m_lineDistanceHeight);
  825. setImageLineColor(g_config->getEditorPreviewImageLineFg());
  826. int lineNumber = g_config->getEditorLineNumber();
  827. if (lineNumber < (int)LineNumberType::None || lineNumber >= (int)LineNumberType::Invalid) {
  828. lineNumber = (int)LineNumberType::None;
  829. }
  830. setLineNumberType((LineNumberType)lineNumber);
  831. setLineNumberColor(g_config->getEditorLineNumberFg(),
  832. g_config->getEditorLineNumberBg());
  833. m_previewMgr->setPreviewEnabled(g_config->getEnablePreviewImages());
  834. }
  835. void VMdEditor::updateConfig()
  836. {
  837. updateEditConfig();
  838. updateTextEditConfig();
  839. }
  840. QString VMdEditor::getContent() const
  841. {
  842. return toPlainText();
  843. }
  844. void VMdEditor::setContent(const QString &p_content, bool p_modified)
  845. {
  846. if (p_modified) {
  847. QTextCursor cursor = textCursor();
  848. cursor.select(QTextCursor::Document);
  849. cursor.insertText(p_content);
  850. setTextCursor(cursor);
  851. } else {
  852. setPlainText(p_content);
  853. }
  854. }
  855. void VMdEditor::refreshPreview()
  856. {
  857. m_previewMgr->refreshPreview();
  858. }
  859. void VMdEditor::updateInitAndInsertedImages(bool p_fileChanged, UpdateAction p_act)
  860. {
  861. if (p_fileChanged && p_act == UpdateAction::InfoChanged) {
  862. return;
  863. }
  864. if (!isModified()) {
  865. Q_ASSERT(m_insertedImages.isEmpty());
  866. m_insertedImages.clear();
  867. if (!m_initImages.isEmpty()) {
  868. // Re-generate init images.
  869. initInitImages();
  870. }
  871. return;
  872. }
  873. // Update init images.
  874. QVector<ImageLink> tmp = m_initImages;
  875. initInitImages();
  876. Q_ASSERT(tmp.size() == m_initImages.size());
  877. QDir dir(m_file->fetchBasePath());
  878. // File has been moved.
  879. if (p_fileChanged) {
  880. // Since we clear unused images once user save the note, all images
  881. // in m_initImages now are moved already.
  882. // Update inserted images.
  883. // Inserted images should be moved manually here. Then update all the
  884. // paths.
  885. for (auto & link : m_insertedImages) {
  886. if (link.m_type == ImageLink::LocalAbsolute) {
  887. continue;
  888. }
  889. QString newPath = QDir::cleanPath(dir.absoluteFilePath(link.m_url));
  890. if (VUtils::equalPath(link.m_path, newPath)) {
  891. continue;
  892. }
  893. if (!VUtils::copyFile(link.m_path, newPath, true)) {
  894. VUtils::showMessage(QMessageBox::Warning,
  895. tr("Warning"),
  896. tr("Fail to move unsaved inserted image %1 to %2.")
  897. .arg(link.m_path)
  898. .arg(newPath),
  899. tr("Please check it manually to avoid image loss."),
  900. QMessageBox::Ok,
  901. QMessageBox::Ok,
  902. this);
  903. continue;
  904. }
  905. link.m_path = newPath;
  906. }
  907. } else {
  908. // Directory changed.
  909. // Update inserted images.
  910. for (auto & link : m_insertedImages) {
  911. if (link.m_type == ImageLink::LocalAbsolute) {
  912. continue;
  913. }
  914. QString newPath = QDir::cleanPath(dir.absoluteFilePath(link.m_url));
  915. link.m_path = newPath;
  916. }
  917. }
  918. }
  919. void VMdEditor::handleCopyAsAction(QAction *p_act)
  920. {
  921. QTextCursor cursor = textCursor();
  922. Q_ASSERT(cursor.hasSelection());
  923. QString text = VEditUtils::selectedText(cursor);
  924. Q_ASSERT(!text.isEmpty());
  925. Q_ASSERT(!m_textToHtmlDialog);
  926. m_textToHtmlDialog = new VCopyTextAsHtmlDialog(text, p_act->data().toString(), this);
  927. // For Hoedown, we use marked.js to convert the text to have a general interface.
  928. emit requestTextToHtml(text);
  929. m_textToHtmlDialog->exec();
  930. delete m_textToHtmlDialog;
  931. m_textToHtmlDialog = NULL;
  932. }
  933. void VMdEditor::textToHtmlFinished(const QString &p_text,
  934. const QUrl &p_baseUrl,
  935. const QString &p_html)
  936. {
  937. if (m_textToHtmlDialog && m_textToHtmlDialog->getText() == p_text) {
  938. m_textToHtmlDialog->setConvertedHtml(p_baseUrl, p_html);
  939. }
  940. }
  941. void VMdEditor::wheelEvent(QWheelEvent *p_event)
  942. {
  943. if (handleWheelEvent(p_event)) {
  944. return;
  945. }
  946. VTextEdit::wheelEvent(p_event);
  947. }
  948. void VMdEditor::zoomPage(bool p_zoomIn, int p_range)
  949. {
  950. int delta;
  951. const int minSize = 2;
  952. if (p_zoomIn) {
  953. delta = p_range;
  954. zoomIn(p_range);
  955. } else {
  956. delta = -p_range;
  957. zoomOut(p_range);
  958. }
  959. m_zoomDelta += delta;
  960. QVector<HighlightingStyle> &styles = m_mdHighlighter->getHighlightingStyles();
  961. for (auto & it : styles) {
  962. int size = it.format.fontPointSize();
  963. if (size == 0) {
  964. // It contains no font size format.
  965. continue;
  966. }
  967. size += delta;
  968. if (size < minSize) {
  969. size = minSize;
  970. }
  971. it.format.setFontPointSize(size);
  972. }
  973. QHash<QString, QTextCharFormat> &cbStyles = m_mdHighlighter->getCodeBlockStyles();
  974. for (auto it = cbStyles.begin(); it != cbStyles.end(); ++it) {
  975. int size = it.value().fontPointSize();
  976. if (size == 0) {
  977. // It contains no font size format.
  978. continue;
  979. }
  980. size += delta;
  981. if (size < minSize) {
  982. size = minSize;
  983. }
  984. it.value().setFontPointSize(size);
  985. }
  986. m_mdHighlighter->rehighlight();
  987. }
  988. void VMdEditor::initCopyAsMenu(QAction *p_before, QMenu *p_menu)
  989. {
  990. QStringList targets = g_webUtils->getCopyTargetsName();
  991. if (targets.isEmpty()) {
  992. return;
  993. }
  994. QMenu *subMenu = new QMenu(tr("Copy HTML As"), p_menu);
  995. subMenu->setToolTipsVisible(true);
  996. for (auto const & target : targets) {
  997. QAction *act = new QAction(target, subMenu);
  998. act->setData(target);
  999. act->setToolTip(tr("Copy selected content as HTML using rules specified by target %1").arg(target));
  1000. subMenu->addAction(act);
  1001. }
  1002. connect(subMenu, &QMenu::triggered,
  1003. this, &VMdEditor::handleCopyAsAction);
  1004. QAction *menuAct = p_menu->insertMenu(p_before, subMenu);
  1005. if (p_before) {
  1006. p_menu->removeAction(p_before);
  1007. p_menu->insertAction(menuAct, p_before);
  1008. p_menu->insertSeparator(menuAct);
  1009. }
  1010. }
  1011. void VMdEditor::initPasteAsBlockQuoteMenu(QMenu *p_menu)
  1012. {
  1013. QAction *pbqAct = new QAction(tr("Paste As Block &Quote"), p_menu);
  1014. pbqAct->setToolTip(tr("Paste text from clipboard as block quote"));
  1015. connect(pbqAct, &QAction::triggered,
  1016. this, [this]() {
  1017. QClipboard *clipboard = QApplication::clipboard();
  1018. const QMimeData *mimeData = clipboard->mimeData();
  1019. QString text = mimeData->text();
  1020. QTextCursor cursor = textCursor();
  1021. cursor.removeSelectedText();
  1022. QTextBlock block = cursor.block();
  1023. QString indent = VEditUtils::fetchIndentSpaces(block);
  1024. // Insert '> ' in front of each line.
  1025. VEditUtils::insertBeforeEachLine(text, indent + QStringLiteral("> "));
  1026. if (VEditUtils::isSpaceBlock(block)) {
  1027. if (!indent.isEmpty()) {
  1028. // Remove the indent.
  1029. cursor.movePosition(QTextCursor::StartOfBlock);
  1030. cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
  1031. cursor.removeSelectedText();
  1032. }
  1033. } else {
  1034. // Insert a new block.
  1035. VEditUtils::insertBlock(cursor, false);
  1036. }
  1037. cursor.insertText(text);
  1038. setTextCursor(cursor);
  1039. });
  1040. p_menu->addSeparator();
  1041. p_menu->addAction(pbqAct);
  1042. }
  1043. void VMdEditor::insertImageLink(const QString &p_text, const QString &p_url)
  1044. {
  1045. VInsertLinkDialog dialog(tr("Insert Image Link"),
  1046. "",
  1047. "",
  1048. p_text,
  1049. p_url,
  1050. true,
  1051. this);
  1052. if (dialog.exec() == QDialog::Accepted) {
  1053. QString linkText = dialog.getLinkText();
  1054. QString linkUrl = dialog.getLinkUrl();
  1055. static_cast<VMdEditOperations *>(m_editOps)->insertImageLink(linkText, linkUrl);
  1056. }
  1057. }
  1058. VWordCountInfo VMdEditor::fetchWordCountInfo() const
  1059. {
  1060. VWordCountInfo info;
  1061. QTextDocument *doc = document();
  1062. // Char without spaces.
  1063. int cns = 0;
  1064. int wc = 0;
  1065. // Remove th ending new line.
  1066. int cc = doc->characterCount() - 1;
  1067. // 0 - not in word;
  1068. // 1 - in English word;
  1069. // 2 - in non-English word;
  1070. int state = 0;
  1071. for (int i = 0; i < cc; ++i) {
  1072. QChar ch = doc->characterAt(i);
  1073. if (ch.isSpace()) {
  1074. if (state) {
  1075. state = 0;
  1076. }
  1077. continue;
  1078. } else if (ch.unicode() < 128) {
  1079. if (state != 1) {
  1080. state = 1;
  1081. ++wc;
  1082. }
  1083. } else {
  1084. state = 2;
  1085. ++wc;
  1086. }
  1087. ++cns;
  1088. }
  1089. info.m_mode = VWordCountInfo::Edit;
  1090. info.m_wordCount = wc;
  1091. info.m_charWithoutSpacesCount = cns;
  1092. info.m_charWithSpacesCount = cc;
  1093. return info;
  1094. }