vmdeditor.cpp 41 KB

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