vmdeditor.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. #include "vmdeditor.h"
  2. #include <QtWidgets>
  3. #include <QMenu>
  4. #include <QDebug>
  5. #include "vdocument.h"
  6. #include "utils/veditutils.h"
  7. #include "vedittab.h"
  8. #include "hgmarkdownhighlighter.h"
  9. #include "vcodeblockhighlighthelper.h"
  10. #include "vmdeditoperations.h"
  11. #include "vtableofcontent.h"
  12. #include "utils/veditutils.h"
  13. #include "dialog/vselectdialog.h"
  14. #include "dialog/vconfirmdeletiondialog.h"
  15. #include "vtextblockdata.h"
  16. #include "vorphanfile.h"
  17. #include "vnotefile.h"
  18. #include "vpreviewmanager.h"
  19. #include "utils/viconutils.h"
  20. #include "dialog/vcopytextashtmldialog.h"
  21. extern VConfigManager *g_config;
  22. VMdEditor::VMdEditor(VFile *p_file,
  23. VDocument *p_doc,
  24. MarkdownConverterType p_type,
  25. QWidget *p_parent)
  26. : VTextEdit(p_parent),
  27. VEditor(p_file, this),
  28. m_mdHighlighter(NULL),
  29. m_freshEdit(true),
  30. m_textToHtmlDialog(NULL)
  31. {
  32. Q_ASSERT(p_file->getDocType() == DocType::Markdown);
  33. VEditor::init();
  34. // Hook functions from VEditor.
  35. connect(this, &VTextEdit::cursorPositionChanged,
  36. this, [this]() {
  37. highlightOnCursorPositionChanged();
  38. });
  39. connect(this, &VTextEdit::selectionChanged,
  40. this, [this]() {
  41. highlightSelectedWord();
  42. });
  43. // End.
  44. setReadOnly(true);
  45. m_mdHighlighter = new HGMarkdownHighlighter(g_config->getMdHighlightingStyles(),
  46. g_config->getCodeBlockStyles(),
  47. g_config->getMarkdownHighlightInterval(),
  48. document());
  49. connect(m_mdHighlighter, &HGMarkdownHighlighter::headersUpdated,
  50. this, &VMdEditor::updateHeaders);
  51. // After highlight, the cursor may trun into non-visible. We should make it visible
  52. // in this case.
  53. connect(m_mdHighlighter, &HGMarkdownHighlighter::highlightCompleted,
  54. this, [this]() {
  55. makeBlockVisible(textCursor().block());
  56. if (m_freshEdit) {
  57. m_freshEdit = false;
  58. emit m_object->ready();
  59. }
  60. });
  61. m_cbHighlighter = new VCodeBlockHighlightHelper(m_mdHighlighter,
  62. p_doc,
  63. p_type);
  64. m_previewMgr = new VPreviewManager(this, m_mdHighlighter);
  65. connect(m_mdHighlighter, &HGMarkdownHighlighter::imageLinksUpdated,
  66. m_previewMgr, &VPreviewManager::imageLinksUpdated);
  67. connect(m_previewMgr, &VPreviewManager::requestUpdateImageLinks,
  68. m_mdHighlighter, &HGMarkdownHighlighter::updateHighlight);
  69. m_editOps = new VMdEditOperations(this, m_file);
  70. connect(m_editOps, &VEditOperations::statusMessage,
  71. m_object, &VEditorObject::statusMessage);
  72. connect(m_editOps, &VEditOperations::vimStatusUpdated,
  73. m_object, &VEditorObject::vimStatusUpdated);
  74. connect(this, &VTextEdit::cursorPositionChanged,
  75. this, &VMdEditor::updateCurrentHeader);
  76. updateFontAndPalette();
  77. updateConfig();
  78. }
  79. void VMdEditor::updateFontAndPalette()
  80. {
  81. setFont(g_config->getMdEditFont());
  82. setPalette(g_config->getMdEditPalette());
  83. // setPalette() won't change the foreground.
  84. setTextColor(g_config->getMdEditPalette().color(QPalette::Text));
  85. }
  86. void VMdEditor::beginEdit()
  87. {
  88. updateConfig();
  89. initInitImages();
  90. setModified(false);
  91. setReadOnlyAndHighlightCurrentLine(false);
  92. emit statusChanged();
  93. if (m_freshEdit) {
  94. m_mdHighlighter->updateHighlight();
  95. relayout();
  96. } else {
  97. updateHeaders(m_mdHighlighter->getHeaderRegions());
  98. }
  99. }
  100. void VMdEditor::endEdit()
  101. {
  102. setReadOnlyAndHighlightCurrentLine(true);
  103. clearUnusedImages();
  104. }
  105. void VMdEditor::saveFile()
  106. {
  107. Q_ASSERT(m_file->isModifiable());
  108. if (!document()->isModified()) {
  109. return;
  110. }
  111. m_file->setContent(toPlainText());
  112. setModified(false);
  113. clearUnusedImages();
  114. initInitImages();
  115. }
  116. void VMdEditor::reloadFile()
  117. {
  118. bool readonly = isReadOnly();
  119. setReadOnly(true);
  120. const QString &content = m_file->getContent();
  121. setPlainText(content);
  122. setModified(false);
  123. m_mdHighlighter->updateHighlightFast();
  124. m_freshEdit = true;
  125. setReadOnly(readonly);
  126. }
  127. bool VMdEditor::scrollToBlock(int p_blockNumber)
  128. {
  129. QTextBlock block = document()->findBlockByNumber(p_blockNumber);
  130. if (block.isValid()) {
  131. VEditUtils::scrollBlockInPage(this, block.blockNumber(), 0);
  132. moveCursor(QTextCursor::EndOfBlock);
  133. return true;
  134. }
  135. return false;
  136. }
  137. // Get the visual offset of a block.
  138. #define GETVISUALOFFSETY (contentOffsetY() + (int)rect.y())
  139. void VMdEditor::makeBlockVisible(const QTextBlock &p_block)
  140. {
  141. if (!p_block.isValid() || !p_block.isVisible()) {
  142. return;
  143. }
  144. QScrollBar *vbar = verticalScrollBar();
  145. if (!vbar || (vbar->minimum() == vbar->maximum())) {
  146. // No vertical scrollbar. No need to scroll.
  147. return;
  148. }
  149. int height = rect().height();
  150. QScrollBar *hbar = horizontalScrollBar();
  151. if (hbar && (hbar->minimum() != hbar->maximum())) {
  152. height -= hbar->height();
  153. }
  154. bool moved = false;
  155. QAbstractTextDocumentLayout *layout = document()->documentLayout();
  156. QRectF rect = layout->blockBoundingRect(p_block);
  157. int y = GETVISUALOFFSETY;
  158. int rectHeight = (int)rect.height();
  159. // Handle the case rectHeight >= height.
  160. if (rectHeight >= height) {
  161. if (y < 0) {
  162. // Need to scroll up.
  163. while (y + rectHeight < height && vbar->value() > vbar->minimum()) {
  164. moved = true;
  165. vbar->setValue(vbar->value() - vbar->singleStep());
  166. rect = layout->blockBoundingRect(p_block);
  167. rectHeight = (int)rect.height();
  168. y = GETVISUALOFFSETY;
  169. }
  170. } else if (y > 0) {
  171. // Need to scroll down.
  172. while (y > 0 && vbar->value() < vbar->maximum()) {
  173. moved = true;
  174. vbar->setValue(vbar->value() + vbar->singleStep());
  175. rect = layout->blockBoundingRect(p_block);
  176. rectHeight = (int)rect.height();
  177. y = GETVISUALOFFSETY;
  178. }
  179. if (y < 0) {
  180. // One step back.
  181. moved = true;
  182. vbar->setValue(vbar->value() - vbar->singleStep());
  183. }
  184. }
  185. if (moved) {
  186. qDebug() << "scroll to make huge block visible";
  187. }
  188. return;
  189. }
  190. while (y < 0 && vbar->value() > vbar->minimum()) {
  191. moved = true;
  192. vbar->setValue(vbar->value() - vbar->singleStep());
  193. rect = layout->blockBoundingRect(p_block);
  194. rectHeight = (int)rect.height();
  195. y = GETVISUALOFFSETY;
  196. }
  197. if (moved) {
  198. qDebug() << "scroll page down to make block visible";
  199. return;
  200. }
  201. while (y + rectHeight > height && vbar->value() < vbar->maximum()) {
  202. moved = true;
  203. vbar->setValue(vbar->value() + vbar->singleStep());
  204. rect = layout->blockBoundingRect(p_block);
  205. rectHeight = (int)rect.height();
  206. y = GETVISUALOFFSETY;
  207. }
  208. if (moved) {
  209. qDebug() << "scroll page up to make block visible";
  210. }
  211. }
  212. void VMdEditor::contextMenuEvent(QContextMenuEvent *p_event)
  213. {
  214. QMenu *menu = createStandardContextMenu();
  215. menu->setToolTipsVisible(true);
  216. VEditTab *editTab = dynamic_cast<VEditTab *>(parent());
  217. Q_ASSERT(editTab);
  218. if (editTab->isEditMode()) {
  219. const QList<QAction *> actions = menu->actions();
  220. if (textCursor().hasSelection()) {
  221. QAction *copyAsHtmlAct = new QAction(tr("Copy As &HTML without Background"), menu);
  222. copyAsHtmlAct->setToolTip(tr("Copy selected contents as HTML without background styles"));
  223. connect(copyAsHtmlAct, &QAction::triggered,
  224. this, &VMdEditor::handleCopyAsHtmlAction);
  225. menu->insertAction(actions.isEmpty() ? NULL : actions[0], copyAsHtmlAct);
  226. } else {
  227. QAction *saveExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/save_exit.svg"),
  228. tr("&Save Changes And Read"),
  229. menu);
  230. saveExitAct->setToolTip(tr("Save changes and exit edit mode"));
  231. connect(saveExitAct, &QAction::triggered,
  232. this, [this]() {
  233. emit m_object->saveAndRead();
  234. });
  235. QAction *discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"),
  236. tr("&Discard Changes And Read"),
  237. menu);
  238. discardExitAct->setToolTip(tr("Discard changes and exit edit mode"));
  239. connect(discardExitAct, &QAction::triggered,
  240. this, [this]() {
  241. emit m_object->discardAndRead();
  242. });
  243. menu->insertAction(actions.isEmpty() ? NULL : actions[0], discardExitAct);
  244. menu->insertAction(discardExitAct, saveExitAct);
  245. }
  246. if (!actions.isEmpty()) {
  247. menu->insertSeparator(actions[0]);
  248. }
  249. }
  250. menu->exec(p_event->globalPos());
  251. delete menu;
  252. }
  253. void VMdEditor::mousePressEvent(QMouseEvent *p_event)
  254. {
  255. if (handleMousePressEvent(p_event)) {
  256. return;
  257. }
  258. VTextEdit::mousePressEvent(p_event);
  259. emit m_object->mousePressed(p_event);
  260. }
  261. void VMdEditor::mouseReleaseEvent(QMouseEvent *p_event)
  262. {
  263. if (handleMouseReleaseEvent(p_event)) {
  264. return;
  265. }
  266. VTextEdit::mouseReleaseEvent(p_event);
  267. emit m_object->mouseReleased(p_event);
  268. }
  269. void VMdEditor::mouseMoveEvent(QMouseEvent *p_event)
  270. {
  271. if (handleMouseMoveEvent(p_event)) {
  272. return;
  273. }
  274. VTextEdit::mouseMoveEvent(p_event);
  275. emit m_object->mouseMoved(p_event);
  276. }
  277. QVariant VMdEditor::inputMethodQuery(Qt::InputMethodQuery p_query) const
  278. {
  279. QVariant ret;
  280. if (handleInputMethodQuery(p_query, ret)) {
  281. return ret;
  282. }
  283. return VTextEdit::inputMethodQuery(p_query);
  284. }
  285. bool VMdEditor::isBlockVisible(const QTextBlock &p_block)
  286. {
  287. if (!p_block.isValid() || !p_block.isVisible()) {
  288. return false;
  289. }
  290. QScrollBar *vbar = verticalScrollBar();
  291. if (!vbar || !vbar->isVisible()) {
  292. // No vertical scrollbar.
  293. return true;
  294. }
  295. int height = rect().height();
  296. QScrollBar *hbar = horizontalScrollBar();
  297. if (hbar && hbar->isVisible()) {
  298. height -= hbar->height();
  299. }
  300. QAbstractTextDocumentLayout *layout = document()->documentLayout();
  301. QRectF rect = layout->blockBoundingRect(p_block);
  302. int y = GETVISUALOFFSETY;
  303. int rectHeight = (int)rect.height();
  304. return (y >= 0 && y < height) || (y < 0 && y + rectHeight > 0);
  305. }
  306. static void addHeaderSequence(QVector<int> &p_sequence, int p_level, int p_baseLevel)
  307. {
  308. Q_ASSERT(p_level >= 1 && p_level < p_sequence.size());
  309. if (p_level < p_baseLevel) {
  310. p_sequence.fill(0);
  311. return;
  312. }
  313. ++p_sequence[p_level];
  314. for (int i = p_level + 1; i < p_sequence.size(); ++i) {
  315. p_sequence[i] = 0;
  316. }
  317. }
  318. static QString headerSequenceStr(const QVector<int> &p_sequence)
  319. {
  320. QString res;
  321. for (int i = 1; i < p_sequence.size(); ++i) {
  322. if (p_sequence[i] != 0) {
  323. res = res + QString::number(p_sequence[i]) + '.';
  324. } else if (res.isEmpty()) {
  325. continue;
  326. } else {
  327. break;
  328. }
  329. }
  330. return res;
  331. }
  332. static void insertSequenceToHeader(QTextBlock p_block,
  333. QRegExp &p_reg,
  334. QRegExp &p_preReg,
  335. const QString &p_seq)
  336. {
  337. if (!p_block.isValid()) {
  338. return;
  339. }
  340. QString text = p_block.text();
  341. bool matched = p_reg.exactMatch(text);
  342. Q_ASSERT(matched);
  343. matched = p_preReg.exactMatch(text);
  344. Q_ASSERT(matched);
  345. int start = p_reg.cap(1).length() + 1;
  346. int end = p_preReg.cap(1).length();
  347. Q_ASSERT(start <= end);
  348. QTextCursor cursor(p_block);
  349. cursor.setPosition(p_block.position() + start);
  350. if (start != end) {
  351. cursor.setPosition(p_block.position() + end, QTextCursor::KeepAnchor);
  352. }
  353. if (p_seq.isEmpty()) {
  354. cursor.removeSelectedText();
  355. } else {
  356. cursor.insertText(p_seq + ' ');
  357. }
  358. }
  359. void VMdEditor::updateHeaders(const QVector<VElementRegion> &p_headerRegions)
  360. {
  361. QTextDocument *doc = document();
  362. QVector<VTableOfContentItem> headers;
  363. QVector<int> headerBlockNumbers;
  364. QVector<QString> headerSequences;
  365. if (!p_headerRegions.isEmpty()) {
  366. headers.reserve(p_headerRegions.size());
  367. headerBlockNumbers.reserve(p_headerRegions.size());
  368. headerSequences.reserve(p_headerRegions.size());
  369. }
  370. // Assume that each block contains only one line
  371. // Only support # syntax for now
  372. QRegExp headerReg(VUtils::c_headerRegExp);
  373. int baseLevel = -1;
  374. for (auto const & reg : p_headerRegions) {
  375. QTextBlock block = doc->findBlock(reg.m_startPos);
  376. if (!block.isValid()) {
  377. continue;
  378. }
  379. if (!block.contains(reg.m_endPos - 1)) {
  380. qWarning() << "header accross multiple blocks, starting from block"
  381. << block.blockNumber()
  382. << block.text();
  383. }
  384. if ((block.userState() == HighlightBlockState::Normal)
  385. && headerReg.exactMatch(block.text())) {
  386. int level = headerReg.cap(1).length();
  387. VTableOfContentItem header(headerReg.cap(2).trimmed(),
  388. level,
  389. block.blockNumber(),
  390. headers.size());
  391. headers.append(header);
  392. headerBlockNumbers.append(block.blockNumber());
  393. headerSequences.append(headerReg.cap(3));
  394. if (baseLevel == -1) {
  395. baseLevel = level;
  396. } else if (baseLevel > level) {
  397. baseLevel = level;
  398. }
  399. }
  400. }
  401. m_headers.clear();
  402. bool autoSequence = m_config.m_enableHeadingSequence
  403. && !isReadOnly()
  404. && m_file->isModifiable();
  405. int headingSequenceBaseLevel = g_config->getHeadingSequenceBaseLevel();
  406. if (headingSequenceBaseLevel < 1 || headingSequenceBaseLevel > 6) {
  407. headingSequenceBaseLevel = 1;
  408. }
  409. QVector<int> seqs(7, 0);
  410. QRegExp preReg(VUtils::c_headerPrefixRegExp);
  411. int curLevel = baseLevel - 1;
  412. for (int i = 0; i < headers.size(); ++i) {
  413. VTableOfContentItem &item = headers[i];
  414. while (item.m_level > curLevel + 1) {
  415. curLevel += 1;
  416. // Insert empty level which is an invalid header.
  417. m_headers.append(VTableOfContentItem(c_emptyHeaderName,
  418. curLevel,
  419. -1,
  420. m_headers.size()));
  421. if (autoSequence) {
  422. addHeaderSequence(seqs, curLevel, headingSequenceBaseLevel);
  423. }
  424. }
  425. item.m_index = m_headers.size();
  426. m_headers.append(item);
  427. curLevel = item.m_level;
  428. if (autoSequence) {
  429. addHeaderSequence(seqs, item.m_level, headingSequenceBaseLevel);
  430. QString seqStr = headerSequenceStr(seqs);
  431. if (headerSequences[i] != seqStr) {
  432. // Insert correct sequence.
  433. insertSequenceToHeader(doc->findBlockByNumber(headerBlockNumbers[i]),
  434. headerReg,
  435. preReg,
  436. seqStr);
  437. }
  438. }
  439. }
  440. emit headersChanged(m_headers);
  441. updateCurrentHeader();
  442. }
  443. void VMdEditor::updateCurrentHeader()
  444. {
  445. emit currentHeaderChanged(textCursor().block().blockNumber());
  446. }
  447. void VMdEditor::initInitImages()
  448. {
  449. m_initImages = VUtils::fetchImagesFromMarkdownFile(m_file,
  450. ImageLink::LocalRelativeInternal);
  451. }
  452. void VMdEditor::clearUnusedImages()
  453. {
  454. QVector<ImageLink> images = VUtils::fetchImagesFromMarkdownFile(m_file,
  455. ImageLink::LocalRelativeInternal);
  456. QSet<QString> unusedImages;
  457. if (!m_insertedImages.isEmpty()) {
  458. for (int i = 0; i < m_insertedImages.size(); ++i) {
  459. const ImageLink &link = m_insertedImages[i];
  460. if (link.m_type != ImageLink::LocalRelativeInternal) {
  461. continue;
  462. }
  463. int j;
  464. for (j = 0; j < images.size(); ++j) {
  465. if (VUtils::equalPath(link.m_path, images[j].m_path)) {
  466. break;
  467. }
  468. }
  469. // This inserted image is no longer in the file.
  470. if (j == images.size()) {
  471. unusedImages.insert(link.m_path);
  472. }
  473. }
  474. m_insertedImages.clear();
  475. }
  476. for (int i = 0; i < m_initImages.size(); ++i) {
  477. const ImageLink &link = m_initImages[i];
  478. V_ASSERT(link.m_type == ImageLink::LocalRelativeInternal);
  479. int j;
  480. for (j = 0; j < images.size(); ++j) {
  481. if (VUtils::equalPath(link.m_path, images[j].m_path)) {
  482. break;
  483. }
  484. }
  485. // Original local relative image is no longer in the file.
  486. if (j == images.size()) {
  487. unusedImages.insert(link.m_path);
  488. }
  489. }
  490. if (!unusedImages.isEmpty()) {
  491. if (g_config->getConfirmImagesCleanUp()) {
  492. QVector<ConfirmItemInfo> items;
  493. for (auto const & img : unusedImages) {
  494. items.push_back(ConfirmItemInfo(img,
  495. img,
  496. img,
  497. NULL));
  498. }
  499. QString text = tr("Following images seems not to be used in this note anymore. "
  500. "Please confirm the deletion of these images.");
  501. QString info = tr("Deleted files could be found in the recycle "
  502. "bin of this note.<br>"
  503. "Click \"Cancel\" to leave them untouched.");
  504. VConfirmDeletionDialog dialog(tr("Confirm Cleaning Up Unused Images"),
  505. text,
  506. info,
  507. items,
  508. true,
  509. true,
  510. true,
  511. this);
  512. unusedImages.clear();
  513. if (dialog.exec()) {
  514. items = dialog.getConfirmedItems();
  515. g_config->setConfirmImagesCleanUp(dialog.getAskAgainEnabled());
  516. for (auto const & item : items) {
  517. unusedImages.insert(item.m_name);
  518. }
  519. }
  520. }
  521. for (auto const & item : unusedImages) {
  522. bool ret = false;
  523. if (m_file->getType() == FileType::Note) {
  524. const VNoteFile *tmpFile = dynamic_cast<const VNoteFile *>((VFile *)m_file);
  525. ret = VUtils::deleteFile(tmpFile->getNotebook(), item, false);
  526. } else if (m_file->getType() == FileType::Orphan) {
  527. const VOrphanFile *tmpFile = dynamic_cast<const VOrphanFile *>((VFile *)m_file);
  528. ret = VUtils::deleteFile(tmpFile, item, false);
  529. } else {
  530. Q_ASSERT(false);
  531. }
  532. if (!ret) {
  533. qWarning() << "fail to delete unused original image" << item;
  534. } else {
  535. qDebug() << "delete unused image" << item;
  536. }
  537. }
  538. }
  539. m_initImages.clear();
  540. }
  541. void VMdEditor::keyPressEvent(QKeyEvent *p_event)
  542. {
  543. if (m_editOps && m_editOps->handleKeyPressEvent(p_event)) {
  544. return;
  545. }
  546. VTextEdit::keyPressEvent(p_event);
  547. }
  548. bool VMdEditor::canInsertFromMimeData(const QMimeData *p_source) const
  549. {
  550. return p_source->hasImage()
  551. || p_source->hasUrls()
  552. || VTextEdit::canInsertFromMimeData(p_source);
  553. }
  554. void VMdEditor::insertFromMimeData(const QMimeData *p_source)
  555. {
  556. VSelectDialog dialog(tr("Insert From Clipboard"), this);
  557. dialog.addSelection(tr("Insert As Image"), 0);
  558. dialog.addSelection(tr("Insert As Text"), 1);
  559. if (p_source->hasImage()) {
  560. // Image data in the clipboard
  561. if (p_source->hasText()) {
  562. if (dialog.exec() == QDialog::Accepted) {
  563. if (dialog.getSelection() == 1) {
  564. // Insert as text.
  565. Q_ASSERT(p_source->hasText() && p_source->hasImage());
  566. VTextEdit::insertFromMimeData(p_source);
  567. return;
  568. }
  569. } else {
  570. return;
  571. }
  572. }
  573. m_editOps->insertImageFromMimeData(p_source);
  574. return;
  575. } else if (p_source->hasUrls()) {
  576. QList<QUrl> urls = p_source->urls();
  577. if (urls.size() == 1 && VUtils::isImageURL(urls[0])) {
  578. if (dialog.exec() == QDialog::Accepted) {
  579. // FIXME: After calling dialog.exec(), p_source->hasUrl() returns false.
  580. if (dialog.getSelection() == 0) {
  581. // Insert as image.
  582. m_editOps->insertImageFromURL(urls[0]);
  583. return;
  584. }
  585. QMimeData newSource;
  586. newSource.setUrls(urls);
  587. VTextEdit::insertFromMimeData(&newSource);
  588. return;
  589. } else {
  590. return;
  591. }
  592. }
  593. } else if (p_source->hasText()) {
  594. QString text = p_source->text();
  595. if (VUtils::isImageURLText(text)) {
  596. // The text is a URL to an image.
  597. if (dialog.exec() == QDialog::Accepted) {
  598. if (dialog.getSelection() == 0) {
  599. // Insert as image.
  600. QUrl url(text);
  601. if (url.isValid()) {
  602. m_editOps->insertImageFromURL(QUrl(text));
  603. }
  604. return;
  605. }
  606. } else {
  607. return;
  608. }
  609. }
  610. Q_ASSERT(p_source->hasText());
  611. }
  612. VTextEdit::insertFromMimeData(p_source);
  613. }
  614. void VMdEditor::imageInserted(const QString &p_path, const QString &p_url)
  615. {
  616. ImageLink link;
  617. link.m_path = p_path;
  618. link.m_url = p_url;
  619. if (m_file->useRelativeImageFolder()) {
  620. link.m_type = ImageLink::LocalRelativeInternal;
  621. } else {
  622. link.m_type = ImageLink::LocalAbsolute;
  623. }
  624. m_insertedImages.append(link);
  625. }
  626. bool VMdEditor::scrollToHeader(int p_blockNumber)
  627. {
  628. if (p_blockNumber < 0) {
  629. return false;
  630. }
  631. return scrollToBlock(p_blockNumber);
  632. }
  633. int VMdEditor::indexOfCurrentHeader() const
  634. {
  635. if (m_headers.isEmpty()) {
  636. return -1;
  637. }
  638. int blockNumber = textCursor().block().blockNumber();
  639. for (int i = m_headers.size() - 1; i >= 0; --i) {
  640. if (!m_headers[i].isEmpty()
  641. && m_headers[i].m_blockNumber <= blockNumber) {
  642. return i;
  643. }
  644. }
  645. return -1;
  646. }
  647. bool VMdEditor::jumpTitle(bool p_forward, int p_relativeLevel, int p_repeat)
  648. {
  649. if (m_headers.isEmpty()) {
  650. return false;
  651. }
  652. QTextCursor cursor = textCursor();
  653. int cursorLine = cursor.block().blockNumber();
  654. int targetIdx = -1;
  655. // -1: skip level check.
  656. int targetLevel = 0;
  657. int idx = indexOfCurrentHeader();
  658. if (idx == -1) {
  659. // Cursor locates at the beginning, before any headers.
  660. if (p_relativeLevel < 0 || !p_forward) {
  661. return false;
  662. }
  663. }
  664. int delta = 1;
  665. if (!p_forward) {
  666. delta = -1;
  667. }
  668. bool firstHeader = true;
  669. for (targetIdx = idx == -1 ? 0 : idx;
  670. targetIdx >= 0 && targetIdx < m_headers.size();
  671. targetIdx += delta) {
  672. const VTableOfContentItem &header = m_headers[targetIdx];
  673. if (header.isEmpty()) {
  674. continue;
  675. }
  676. if (targetLevel == 0) {
  677. // The target level has not been init yet.
  678. Q_ASSERT(firstHeader);
  679. targetLevel = header.m_level;
  680. if (p_relativeLevel < 0) {
  681. targetLevel += p_relativeLevel;
  682. if (targetLevel < 1) {
  683. // Invalid level.
  684. return false;
  685. }
  686. } else if (p_relativeLevel > 0) {
  687. targetLevel = -1;
  688. }
  689. }
  690. if (targetLevel == -1 || header.m_level == targetLevel) {
  691. if (firstHeader
  692. && (cursorLine == header.m_blockNumber
  693. || p_forward)
  694. && idx != -1) {
  695. // This header is not counted for the repeat.
  696. firstHeader = false;
  697. continue;
  698. }
  699. if (--p_repeat == 0) {
  700. // Found.
  701. break;
  702. }
  703. } else if (header.m_level < targetLevel) {
  704. // Stop by higher level.
  705. return false;
  706. }
  707. firstHeader = false;
  708. }
  709. if (targetIdx < 0 || targetIdx >= m_headers.size()) {
  710. return false;
  711. }
  712. // Jump to target header.
  713. int line = m_headers[targetIdx].m_blockNumber;
  714. if (line > -1) {
  715. QTextBlock block = document()->findBlockByNumber(line);
  716. if (block.isValid()) {
  717. cursor.setPosition(block.position());
  718. setTextCursor(cursor);
  719. return true;
  720. }
  721. }
  722. return false;
  723. }
  724. void VMdEditor::scrollBlockInPage(int p_blockNum, int p_dest)
  725. {
  726. VEditUtils::scrollBlockInPage(this, p_blockNum, p_dest);
  727. }
  728. void VMdEditor::updateTextEditConfig()
  729. {
  730. setBlockImageEnabled(g_config->getEnablePreviewImages());
  731. setImageWidthConstrainted(g_config->getEnablePreviewImageConstraint());
  732. setLineLeading(m_config.m_lineDistanceHeight);
  733. setImageLineColor(g_config->getEditorPreviewImageLineFg());
  734. int lineNumber = g_config->getEditorLineNumber();
  735. if (lineNumber < (int)LineNumberType::None || lineNumber >= (int)LineNumberType::Invalid) {
  736. lineNumber = (int)LineNumberType::None;
  737. }
  738. setLineNumberType((LineNumberType)lineNumber);
  739. setLineNumberColor(g_config->getEditorLineNumberFg(),
  740. g_config->getEditorLineNumberBg());
  741. m_previewMgr->setPreviewEnabled(g_config->getEnablePreviewImages());
  742. }
  743. void VMdEditor::updateConfig()
  744. {
  745. updateEditConfig();
  746. updateTextEditConfig();
  747. }
  748. QString VMdEditor::getContent() const
  749. {
  750. return toPlainText();
  751. }
  752. void VMdEditor::setContent(const QString &p_content, bool p_modified)
  753. {
  754. if (p_modified) {
  755. QTextCursor cursor = textCursor();
  756. cursor.select(QTextCursor::Document);
  757. cursor.insertText(p_content);
  758. setTextCursor(cursor);
  759. } else {
  760. setPlainText(p_content);
  761. }
  762. }
  763. void VMdEditor::refreshPreview()
  764. {
  765. m_previewMgr->refreshPreview();
  766. }
  767. void VMdEditor::updateInitAndInsertedImages(bool p_fileChanged, UpdateAction p_act)
  768. {
  769. if (p_fileChanged && p_act == UpdateAction::InfoChanged) {
  770. return;
  771. }
  772. if (!isModified()) {
  773. Q_ASSERT(m_insertedImages.isEmpty());
  774. m_insertedImages.clear();
  775. if (!m_initImages.isEmpty()) {
  776. // Re-generate init images.
  777. initInitImages();
  778. }
  779. return;
  780. }
  781. // Update init images.
  782. QVector<ImageLink> tmp = m_initImages;
  783. initInitImages();
  784. Q_ASSERT(tmp.size() == m_initImages.size());
  785. QDir dir(m_file->fetchBasePath());
  786. // File has been moved.
  787. if (p_fileChanged) {
  788. // Since we clear unused images once user save the note, all images
  789. // in m_initImages now are moved already.
  790. // Update inserted images.
  791. // Inserted images should be moved manually here. Then update all the
  792. // paths.
  793. for (auto & link : m_insertedImages) {
  794. if (link.m_type == ImageLink::LocalAbsolute) {
  795. continue;
  796. }
  797. QString newPath = QDir::cleanPath(dir.absoluteFilePath(link.m_url));
  798. if (VUtils::equalPath(link.m_path, newPath)) {
  799. continue;
  800. }
  801. if (!VUtils::copyFile(link.m_path, newPath, true)) {
  802. VUtils::showMessage(QMessageBox::Warning,
  803. tr("Warning"),
  804. tr("Fail to move unsaved inserted image %1 to %2.")
  805. .arg(link.m_path)
  806. .arg(newPath),
  807. tr("Please check it manually to avoid image loss."),
  808. QMessageBox::Ok,
  809. QMessageBox::Ok,
  810. this);
  811. continue;
  812. }
  813. link.m_path = newPath;
  814. }
  815. } else {
  816. // Directory changed.
  817. // Update inserted images.
  818. for (auto & link : m_insertedImages) {
  819. if (link.m_type == ImageLink::LocalAbsolute) {
  820. continue;
  821. }
  822. QString newPath = QDir::cleanPath(dir.absoluteFilePath(link.m_url));
  823. link.m_path = newPath;
  824. }
  825. }
  826. }
  827. void VMdEditor::handleCopyAsHtmlAction()
  828. {
  829. QTextCursor cursor = textCursor();
  830. Q_ASSERT(cursor.hasSelection());
  831. QString text = VEditUtils::selectedText(cursor);
  832. Q_ASSERT(!text.isEmpty());
  833. Q_ASSERT(!m_textToHtmlDialog);
  834. m_textToHtmlDialog = new VCopyTextAsHtmlDialog(text, this);
  835. // For Hoedown, we use marked.js to convert the text to have a general interface.
  836. emit requestTextToHtml(text);
  837. m_textToHtmlDialog->exec();
  838. delete m_textToHtmlDialog;
  839. m_textToHtmlDialog = NULL;
  840. }
  841. void VMdEditor::textToHtmlFinished(const QString &p_text,
  842. const QUrl &p_baseUrl,
  843. const QString &p_html)
  844. {
  845. if (m_textToHtmlDialog && m_textToHtmlDialog->getText() == p_text) {
  846. m_textToHtmlDialog->setConvertedHtml(p_baseUrl, p_html);
  847. }
  848. }