vtextdocumentlayout.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. #include "vtextdocumentlayout.h"
  2. #include <QTextDocument>
  3. #include <QTextBlock>
  4. #include <QTextFrame>
  5. #include <QTextLayout>
  6. #include <QPointF>
  7. #include <QFontMetrics>
  8. #include <QFont>
  9. #include <QPainter>
  10. #include <QDebug>
  11. #include "vimageresourcemanager2.h"
  12. #include "vtextedit.h"
  13. #include "vtextblockdata.h"
  14. #define MARKER_THICKNESS 2
  15. #define MAX_INLINE_IMAGE_HEIGHT 400
  16. VTextDocumentLayout::VTextDocumentLayout(QTextDocument *p_doc,
  17. VImageResourceManager2 *p_imageMgr)
  18. : QAbstractTextDocumentLayout(p_doc),
  19. m_margin(p_doc->documentMargin()),
  20. m_width(0),
  21. m_maximumWidthBlockNumber(-1),
  22. m_height(0),
  23. m_lineLeading(0),
  24. m_blockCount(0),
  25. m_cursorWidth(1),
  26. m_cursorMargin(4),
  27. m_imageMgr(p_imageMgr),
  28. m_blockImageEnabled(false),
  29. m_imageWidthConstrainted(false),
  30. m_imageLineColor("#9575CD"),
  31. m_cursorBlockMode(CursorBlock::None),
  32. m_virtualCursorBlockWidth(8),
  33. m_cursorBlockFg("#EEEEEE"),
  34. m_cursorBlockBg("#222222"),
  35. m_lastCursorBlockWidth(-1)
  36. {
  37. }
  38. static void fillBackground(QPainter *p_painter,
  39. const QRectF &p_rect,
  40. QBrush p_brush,
  41. QRectF p_gradientRect = QRectF())
  42. {
  43. p_painter->save();
  44. if (p_brush.style() >= Qt::LinearGradientPattern
  45. && p_brush.style() <= Qt::ConicalGradientPattern) {
  46. if (!p_gradientRect.isNull()) {
  47. QTransform m = QTransform::fromTranslate(p_gradientRect.left(),
  48. p_gradientRect.top());
  49. m.scale(p_gradientRect.width(), p_gradientRect.height());
  50. p_brush.setTransform(m);
  51. const_cast<QGradient *>(p_brush.gradient())->setCoordinateMode(QGradient::LogicalMode);
  52. }
  53. } else {
  54. p_painter->setBrushOrigin(p_rect.topLeft());
  55. }
  56. p_painter->fillRect(p_rect, p_brush);
  57. p_painter->restore();
  58. }
  59. void VTextDocumentLayout::blockRangeFromRect(const QRectF &p_rect,
  60. int &p_first,
  61. int &p_last) const
  62. {
  63. if (p_rect.isNull()) {
  64. p_first = 0;
  65. p_last = m_blocks.size() - 1;
  66. return;
  67. }
  68. p_first = -1;
  69. p_last = m_blocks.size() - 1;
  70. int y = p_rect.y();
  71. Q_ASSERT(document()->blockCount() == m_blocks.size());
  72. QTextBlock block = document()->firstBlock();
  73. while (block.isValid()) {
  74. const BlockInfo &info = m_blocks[block.blockNumber()];
  75. Q_ASSERT(info.hasOffset());
  76. if (info.top() == y
  77. || (info.top() < y && info.bottom() >= y)) {
  78. p_first = block.blockNumber();
  79. break;
  80. }
  81. block = block.next();
  82. }
  83. if (p_first == -1) {
  84. p_last = -1;
  85. return;
  86. }
  87. y += p_rect.height();
  88. while (block.isValid()) {
  89. const BlockInfo &info = m_blocks[block.blockNumber()];
  90. Q_ASSERT(info.hasOffset());
  91. if (info.bottom() > y) {
  92. p_last = block.blockNumber();
  93. break;
  94. }
  95. block = block.next();
  96. }
  97. }
  98. void VTextDocumentLayout::blockRangeFromRectBS(const QRectF &p_rect,
  99. int &p_first,
  100. int &p_last) const
  101. {
  102. if (p_rect.isNull()) {
  103. p_first = 0;
  104. p_last = m_blocks.size() - 1;
  105. return;
  106. }
  107. Q_ASSERT(document()->blockCount() == m_blocks.size());
  108. p_first = findBlockByPosition(p_rect.topLeft());
  109. if (p_first == -1) {
  110. p_last = -1;
  111. return;
  112. }
  113. int y = p_rect.bottom();
  114. QTextBlock block = document()->findBlockByNumber(p_first);
  115. if (m_blocks[p_first].top() == p_rect.top()
  116. && p_first > 0) {
  117. --p_first;
  118. }
  119. p_last = m_blocks.size() - 1;
  120. while (block.isValid()) {
  121. const BlockInfo &info = m_blocks[block.blockNumber()];
  122. Q_ASSERT(info.hasOffset());
  123. if (info.bottom() > y) {
  124. p_last = block.blockNumber();
  125. break;
  126. }
  127. block = block.next();
  128. }
  129. }
  130. int VTextDocumentLayout::findBlockByPosition(const QPointF &p_point) const
  131. {
  132. int first = 0, last = m_blocks.size() - 1;
  133. int y = p_point.y();
  134. while (first <= last) {
  135. int mid = (first + last) / 2;
  136. const BlockInfo &info = m_blocks[mid];
  137. Q_ASSERT(info.hasOffset());
  138. if (info.top() <= y && info.bottom() > y) {
  139. // Found it.
  140. return mid;
  141. } else if (info.top() > y) {
  142. last = mid - 1;
  143. } else {
  144. first = mid + 1;
  145. }
  146. }
  147. int idx = previousValidBlockNumber(m_blocks.size());
  148. if (y >= m_blocks[idx].bottom()) {
  149. return idx;
  150. }
  151. idx = nextValidBlockNumber(-1);
  152. if (y < m_blocks[idx].top()) {
  153. return idx;
  154. }
  155. Q_ASSERT(false);
  156. return -1;
  157. }
  158. void VTextDocumentLayout::draw(QPainter *p_painter, const PaintContext &p_context)
  159. {
  160. // Find out the blocks.
  161. int first, last;
  162. blockRangeFromRectBS(p_context.clip, first, last);
  163. if (first == -1) {
  164. return;
  165. }
  166. QTextDocument *doc = document();
  167. Q_ASSERT(doc->blockCount() == m_blocks.size());
  168. QPointF offset(m_margin, m_blocks[first].top());
  169. QTextBlock block = doc->findBlockByNumber(first);
  170. QTextBlock lastBlock = doc->findBlockByNumber(last);
  171. QPen oldPen = p_painter->pen();
  172. p_painter->setPen(p_context.palette.color(QPalette::Text));
  173. while (block.isValid()) {
  174. const BlockInfo &info = m_blocks[block.blockNumber()];
  175. Q_ASSERT(info.hasOffset());
  176. const QRectF &rect = info.m_rect;
  177. QTextLayout *layout = block.layout();
  178. if (!block.isVisible()) {
  179. offset.ry() += rect.height();
  180. if (block == lastBlock) {
  181. break;
  182. }
  183. block = block.next();
  184. continue;
  185. }
  186. QTextBlockFormat blockFormat = block.blockFormat();
  187. QBrush bg = blockFormat.background();
  188. if (bg != Qt::NoBrush) {
  189. fillBackground(p_painter, rect, bg);
  190. }
  191. auto selections = formatRangeFromSelection(block, p_context.selections);
  192. // Draw the cursor.
  193. int blpos = block.position();
  194. int bllen = block.length();
  195. bool drawCursor = p_context.cursorPosition >= blpos
  196. && p_context.cursorPosition < blpos + bllen;
  197. int cursorWidth = m_cursorWidth;
  198. int cursorPosition = p_context.cursorPosition - blpos;
  199. if (drawCursor && m_cursorBlockMode != CursorBlock::None) {
  200. if (cursorPosition > 0 && m_cursorBlockMode == CursorBlock::LeftSide) {
  201. --cursorPosition;
  202. }
  203. if (cursorPosition == bllen - 1) {
  204. cursorWidth = m_virtualCursorBlockWidth;
  205. } else {
  206. // Get the width of the selection to update cursor width.
  207. cursorWidth = getTextWidthWithinTextLine(layout, cursorPosition, 1);
  208. if (cursorWidth < m_cursorWidth) {
  209. cursorWidth = m_cursorWidth;
  210. }
  211. }
  212. if (cursorWidth != m_lastCursorBlockWidth) {
  213. m_lastCursorBlockWidth = cursorWidth;
  214. emit cursorBlockWidthUpdated(m_lastCursorBlockWidth);
  215. }
  216. }
  217. layout->draw(p_painter,
  218. offset,
  219. selections,
  220. p_context.clip.isValid() ? p_context.clip : QRectF());
  221. drawImages(p_painter, block, offset);
  222. drawMarkers(p_painter, block, offset);
  223. if (drawCursor
  224. || (p_context.cursorPosition < -1
  225. && !layout->preeditAreaText().isEmpty())) {
  226. if (p_context.cursorPosition < -1) {
  227. cursorPosition = layout->preeditAreaPosition()
  228. - (p_context.cursorPosition + 2);
  229. }
  230. layout->drawCursor(p_painter,
  231. offset,
  232. cursorPosition,
  233. cursorWidth);
  234. }
  235. offset.ry() += rect.height();
  236. if (block == lastBlock) {
  237. break;
  238. }
  239. block = block.next();
  240. }
  241. p_painter->setPen(oldPen);
  242. }
  243. QVector<QTextLayout::FormatRange> VTextDocumentLayout::formatRangeFromSelection(const QTextBlock &p_block,
  244. const QVector<Selection> &p_selections) const
  245. {
  246. QVector<QTextLayout::FormatRange> ret;
  247. int blpos = p_block.position();
  248. int bllen = p_block.length();
  249. for (int i = 0; i < p_selections.size(); ++i) {
  250. const QAbstractTextDocumentLayout::Selection &range = p_selections.at(i);
  251. const int selStart = range.cursor.selectionStart() - blpos;
  252. const int selEnd = range.cursor.selectionEnd() - blpos;
  253. if (selStart < bllen
  254. && selEnd > 0
  255. && selEnd > selStart) {
  256. QTextLayout::FormatRange o;
  257. o.start = selStart;
  258. o.length = selEnd - selStart;
  259. o.format = range.format;
  260. ret.append(o);
  261. } else if (!range.cursor.hasSelection()
  262. && range.format.hasProperty(QTextFormat::FullWidthSelection)
  263. && p_block.contains(range.cursor.position())) {
  264. // For full width selections we don't require an actual selection, just
  265. // a position to specify the line. that's more convenience in usage.
  266. QTextLayout::FormatRange o;
  267. QTextLine l = p_block.layout()->lineForTextPosition(range.cursor.position() - blpos);
  268. Q_ASSERT(l.isValid());
  269. o.start = l.textStart();
  270. o.length = l.textLength();
  271. if (o.start + o.length == bllen - 1) {
  272. ++o.length; // include newline
  273. }
  274. o.format = range.format;
  275. ret.append(o);
  276. }
  277. }
  278. return ret;
  279. }
  280. int VTextDocumentLayout::hitTest(const QPointF &p_point, Qt::HitTestAccuracy p_accuracy) const
  281. {
  282. Q_UNUSED(p_accuracy);
  283. int bn = findBlockByPosition(p_point);
  284. if (bn == -1) {
  285. return -1;
  286. }
  287. QTextBlock block = document()->findBlockByNumber(bn);
  288. Q_ASSERT(block.isValid());
  289. QTextLayout *layout = block.layout();
  290. int off = 0;
  291. QPointF pos = p_point - QPointF(m_margin, m_blocks[bn].top());
  292. for (int i = 0; i < layout->lineCount(); ++i) {
  293. QTextLine line = layout->lineAt(i);
  294. const QRectF lr = line.naturalTextRect();
  295. if (lr.top() > pos.y()) {
  296. off = qMin(off, line.textStart());
  297. } else if (lr.bottom() <= pos.y()) {
  298. off = qMax(off, line.textStart() + line.textLength());
  299. } else {
  300. off = line.xToCursor(pos.x(), QTextLine::CursorBetweenCharacters);
  301. break;
  302. }
  303. }
  304. return block.position() + off;
  305. }
  306. int VTextDocumentLayout::pageCount() const
  307. {
  308. return 1;
  309. }
  310. QSizeF VTextDocumentLayout::documentSize() const
  311. {
  312. return QSizeF(m_width, m_height);
  313. }
  314. QRectF VTextDocumentLayout::frameBoundingRect(QTextFrame *p_frame) const
  315. {
  316. Q_UNUSED(p_frame);
  317. return QRectF(0, 0,
  318. qMax(document()->pageSize().width(), m_width), qreal(INT_MAX));
  319. }
  320. QRectF VTextDocumentLayout::blockBoundingRect(const QTextBlock &p_block) const
  321. {
  322. // Sometimes blockBoundingRect() maybe called before documentChanged().
  323. if (!p_block.isValid() || p_block.blockNumber() >= m_blocks.size()) {
  324. return QRectF();
  325. }
  326. const BlockInfo &info = m_blocks[p_block.blockNumber()];
  327. QRectF geo = info.m_rect.adjusted(0, info.m_offset, 0, info.m_offset);
  328. Q_ASSERT(info.hasOffset());
  329. return geo;
  330. }
  331. void VTextDocumentLayout::documentChanged(int p_from, int p_charsRemoved, int p_charsAdded)
  332. {
  333. QTextDocument *doc = document();
  334. int newBlockCount = doc->blockCount();
  335. // Update the margin.
  336. m_margin = doc->documentMargin();
  337. int charsChanged = p_charsRemoved + p_charsAdded;
  338. QTextBlock changeStartBlock = doc->findBlock(p_from);
  339. // May be an invalid block.
  340. QTextBlock changeEndBlock = doc->findBlock(qMax(0, p_from + charsChanged));
  341. bool needRelayout = false;
  342. if (changeStartBlock == changeEndBlock
  343. && newBlockCount == m_blockCount) {
  344. // Change single block internal only.
  345. QTextBlock block = changeStartBlock;
  346. if (block.isValid() && block.length()) {
  347. QRectF oldBr = blockBoundingRect(block);
  348. clearBlockLayout(block);
  349. layoutBlock(block);
  350. QRectF newBr = blockBoundingRect(block);
  351. // Only one block is affected.
  352. if (newBr.height() == oldBr.height()) {
  353. // Update document size.
  354. updateDocumentSizeWithOneBlockChanged(block.blockNumber());
  355. emit updateBlock(block);
  356. return;
  357. }
  358. }
  359. } else {
  360. // Clear layout of all affected blocks.
  361. QTextBlock block = changeStartBlock;
  362. do {
  363. clearBlockLayout(block);
  364. if (block == changeEndBlock) {
  365. break;
  366. }
  367. block = block.next();
  368. } while(block.isValid());
  369. needRelayout = true;
  370. }
  371. updateBlockCount(newBlockCount, changeStartBlock.blockNumber());
  372. if (needRelayout) {
  373. // Relayout all affected blocks.
  374. QTextBlock block = changeStartBlock;
  375. do {
  376. layoutBlock(block);
  377. if (block == changeEndBlock) {
  378. break;
  379. }
  380. block = block.next();
  381. } while(block.isValid());
  382. }
  383. updateDocumentSize();
  384. // TODO: Update the view of all the blocks after changeStartBlock.
  385. const BlockInfo &firstInfo = m_blocks[changeStartBlock.blockNumber()];
  386. emit update(QRectF(0., firstInfo.m_offset, 1000000000., 1000000000.));
  387. }
  388. void VTextDocumentLayout::clearBlockLayout(QTextBlock &p_block)
  389. {
  390. p_block.clearLayout();
  391. int num = p_block.blockNumber();
  392. if (num < m_blocks.size()) {
  393. m_blocks[num].reset();
  394. clearOffsetFrom(num + 1);
  395. }
  396. }
  397. void VTextDocumentLayout::clearOffsetFrom(int p_blockNumber)
  398. {
  399. for (int i = p_blockNumber; i < m_blocks.size(); ++i) {
  400. if (!m_blocks[i].hasOffset()) {
  401. Q_ASSERT(validateBlocks());
  402. break;
  403. }
  404. m_blocks[i].m_offset = -1;
  405. }
  406. }
  407. void VTextDocumentLayout::fillOffsetFrom(int p_blockNumber)
  408. {
  409. qreal offset = m_blocks[p_blockNumber].bottom();
  410. for (int i = p_blockNumber + 1; i < m_blocks.size(); ++i) {
  411. BlockInfo &info = m_blocks[i];
  412. if (!info.m_rect.isNull()) {
  413. info.m_offset = offset;
  414. offset += info.m_rect.height();
  415. } else {
  416. break;
  417. }
  418. }
  419. }
  420. bool VTextDocumentLayout::validateBlocks() const
  421. {
  422. bool valid = true;
  423. for (int i = 0; i < m_blocks.size(); ++i) {
  424. const BlockInfo &info = m_blocks[i];
  425. if (!info.hasOffset()) {
  426. valid = false;
  427. } else if (!valid) {
  428. return false;
  429. }
  430. }
  431. return true;
  432. }
  433. void VTextDocumentLayout::updateBlockCount(int p_count, int p_changeStartBlock)
  434. {
  435. if (m_blockCount != p_count) {
  436. m_blockCount = p_count;
  437. m_blocks.resize(m_blockCount);
  438. // Fix m_blocks.
  439. QTextBlock block = document()->findBlockByNumber(p_changeStartBlock);
  440. while (block.isValid()) {
  441. BlockInfo &info = m_blocks[block.blockNumber()];
  442. info.reset();
  443. QRectF br = blockRectFromTextLayout(block);
  444. if (!br.isNull()) {
  445. info.m_rect = br;
  446. }
  447. block = block.next();
  448. }
  449. }
  450. }
  451. void VTextDocumentLayout::layoutBlock(const QTextBlock &p_block)
  452. {
  453. QTextDocument *doc = document();
  454. Q_ASSERT(m_margin == doc->documentMargin());
  455. QTextLayout *tl = p_block.layout();
  456. QTextOption option = doc->defaultTextOption();
  457. tl->setTextOption(option);
  458. int extraMargin = 0;
  459. if (option.flags() & QTextOption::AddSpaceForLineAndParagraphSeparators) {
  460. QFontMetrics fm(p_block.charFormat().font());
  461. extraMargin += fm.width(QChar(0x21B5));
  462. }
  463. qreal availableWidth = doc->pageSize().width();
  464. if (availableWidth <= 0) {
  465. availableWidth = qreal(INT_MAX);
  466. }
  467. availableWidth -= (2 * m_margin + extraMargin + m_cursorMargin + m_cursorWidth);
  468. QVector<Marker> markers;
  469. QVector<ImagePaintInfo> images;
  470. layoutLines(p_block, tl, markers, images, availableWidth, 0);
  471. // Set this block's line count to its layout's line count.
  472. // That is one block may occupy multiple visual lines.
  473. const_cast<QTextBlock&>(p_block).setLineCount(p_block.isVisible() ? tl->lineCount() : 0);
  474. // Update the info about this block.
  475. finishBlockLayout(p_block, markers, images);
  476. }
  477. qreal VTextDocumentLayout::layoutLines(const QTextBlock &p_block,
  478. QTextLayout *p_tl,
  479. QVector<Marker> &p_markers,
  480. QVector<ImagePaintInfo> &p_images,
  481. qreal p_availableWidth,
  482. qreal p_height)
  483. {
  484. // Handle block inline image.
  485. bool hasInlineImages = false;
  486. const QVector<VPreviewInfo *> *info = NULL;
  487. if (m_blockImageEnabled) {
  488. VTextBlockData *blockData = dynamic_cast<VTextBlockData *>(p_block.userData());
  489. if (blockData) {
  490. info = &(blockData->getPreviews());
  491. if (!info->isEmpty()
  492. && info->first()->m_imageInfo.m_inline) {
  493. hasInlineImages = true;
  494. }
  495. }
  496. }
  497. p_tl->beginLayout();
  498. int imgIdx = 0;
  499. while (true) {
  500. QTextLine line = p_tl->createLine();
  501. if (!line.isValid()) {
  502. break;
  503. }
  504. line.setLeadingIncluded(true);
  505. line.setLineWidth(p_availableWidth);
  506. p_height += m_lineLeading;
  507. if (hasInlineImages) {
  508. QVector<const VPreviewedImageInfo *> images;
  509. QVector<QPair<qreal, qreal>> imageRange;
  510. qreal imgHeight = fetchInlineImagesForOneLine(*info,
  511. &line,
  512. m_margin,
  513. imgIdx,
  514. images,
  515. imageRange);
  516. for (int i = 0; i < images.size(); ++i) {
  517. layoutInlineImage(images[i],
  518. p_height,
  519. imgHeight,
  520. imageRange[i].first,
  521. imageRange[i].second,
  522. p_markers,
  523. p_images);
  524. }
  525. if (!images.isEmpty()) {
  526. p_height += imgHeight + MARKER_THICKNESS + MARKER_THICKNESS;
  527. }
  528. }
  529. line.setPosition(QPointF(m_margin, p_height));
  530. p_height += line.height();
  531. }
  532. p_tl->endLayout();
  533. return p_height;
  534. }
  535. void VTextDocumentLayout::layoutInlineImage(const VPreviewedImageInfo *p_info,
  536. qreal p_heightInBlock,
  537. qreal p_imageSpaceHeight,
  538. qreal p_xStart,
  539. qreal p_xEnd,
  540. QVector<Marker> &p_markers,
  541. QVector<ImagePaintInfo> &p_images)
  542. {
  543. Marker mk;
  544. qreal mky = p_imageSpaceHeight + p_heightInBlock + MARKER_THICKNESS;
  545. mk.m_start = QPointF(p_xStart, mky);
  546. mk.m_end = QPointF(p_xEnd, mky);
  547. p_markers.append(mk);
  548. if (p_info) {
  549. QSize size = p_info->m_imageSize;
  550. scaleSize(size, p_xEnd - p_xStart, p_imageSpaceHeight);
  551. ImagePaintInfo ipi;
  552. ipi.m_name = p_info->m_imageName;
  553. ipi.m_rect = QRectF(QPointF(p_xStart,
  554. p_heightInBlock + p_imageSpaceHeight - size.height()),
  555. size);
  556. p_images.append(ipi);
  557. }
  558. }
  559. void VTextDocumentLayout::finishBlockLayout(const QTextBlock &p_block,
  560. const QVector<Marker> &p_markers,
  561. const QVector<ImagePaintInfo> &p_images)
  562. {
  563. // Update rect and offset.
  564. Q_ASSERT(p_block.isValid());
  565. int num = p_block.blockNumber();
  566. Q_ASSERT(m_blocks.size() > num);
  567. ImagePaintInfo ipi;
  568. BlockInfo &info = m_blocks[num];
  569. info.reset();
  570. info.m_rect = blockRectFromTextLayout(p_block, &ipi);
  571. Q_ASSERT(!info.m_rect.isNull());
  572. int pre = previousValidBlockNumber(num);
  573. if (pre == -1) {
  574. info.m_offset = 0;
  575. } else if (m_blocks[pre].hasOffset()) {
  576. info.m_offset = m_blocks[pre].bottom();
  577. }
  578. bool hasImage = false;
  579. if (ipi.isValid()) {
  580. Q_ASSERT(p_markers.isEmpty());
  581. Q_ASSERT(p_images.isEmpty());
  582. info.m_images.append(ipi);
  583. hasImage = true;
  584. } else if (!p_markers.isEmpty()) {
  585. // Q_ASSERT(!p_images.isEmpty());
  586. info.m_markers = p_markers;
  587. info.m_images = p_images;
  588. hasImage = true;
  589. }
  590. // Add vertical marker.
  591. if (hasImage) {
  592. // Fill the marker.
  593. // Will be adjusted using offset.
  594. Marker mk;
  595. mk.m_start = QPointF(-1, 0);
  596. mk.m_end = QPointF(-1, info.m_rect.height());
  597. info.m_markers.append(mk);
  598. }
  599. if (info.hasOffset()) {
  600. fillOffsetFrom(num);
  601. }
  602. }
  603. int VTextDocumentLayout::previousValidBlockNumber(int p_number) const
  604. {
  605. return p_number >= 0 ? p_number - 1 : -1;
  606. }
  607. int VTextDocumentLayout::nextValidBlockNumber(int p_number) const
  608. {
  609. if (p_number <= -1) {
  610. return 0;
  611. } else if (p_number >= m_blocks.size() - 1) {
  612. return -1;
  613. } else {
  614. return p_number + 1;
  615. }
  616. }
  617. void VTextDocumentLayout::updateDocumentSize()
  618. {
  619. // The last valid block.
  620. int idx = previousValidBlockNumber(m_blocks.size());
  621. Q_ASSERT(idx > -1);
  622. if (m_blocks[idx].hasOffset()) {
  623. int oldHeight = m_height;
  624. int oldWidth = m_width;
  625. m_height = m_blocks[idx].bottom();
  626. m_width = 0;
  627. for (int i = 0; i < m_blocks.size(); ++i) {
  628. const BlockInfo &info = m_blocks[i];
  629. Q_ASSERT(info.hasOffset());
  630. if (m_width < info.m_rect.width()) {
  631. m_width = info.m_rect.width();
  632. m_maximumWidthBlockNumber = i;
  633. }
  634. }
  635. if (oldHeight != m_height
  636. || oldWidth != m_width) {
  637. emit documentSizeChanged(documentSize());
  638. }
  639. }
  640. }
  641. void VTextDocumentLayout::setCursorWidth(int p_width)
  642. {
  643. m_cursorWidth = p_width;
  644. }
  645. int VTextDocumentLayout::cursorWidth() const
  646. {
  647. return m_cursorWidth;
  648. }
  649. QRectF VTextDocumentLayout::blockRectFromTextLayout(const QTextBlock &p_block,
  650. ImagePaintInfo *p_image)
  651. {
  652. if (p_image) {
  653. *p_image = ImagePaintInfo();
  654. }
  655. QTextLayout *tl = p_block.layout();
  656. if (tl->lineCount() < 1) {
  657. return QRectF();
  658. }
  659. QRectF tlRect = tl->boundingRect();
  660. QRectF br(QPointF(0, 0), tlRect.bottomRight());
  661. // Do not know why. Copied from QPlainTextDocumentLayout.
  662. if (tl->lineCount() == 1) {
  663. br.setWidth(qMax(br.width(), tl->lineAt(0).naturalTextWidth()));
  664. }
  665. // Handle block non-inline image.
  666. if (m_blockImageEnabled) {
  667. VTextBlockData *blockData = dynamic_cast<VTextBlockData *>(p_block.userData());
  668. if (blockData) {
  669. const QVector<VPreviewInfo *> &info = blockData->getPreviews();
  670. if (info.size() == 1) {
  671. const VPreviewedImageInfo& img = info.first()->m_imageInfo;
  672. if (!img.m_inline) {
  673. int maximumWidth = tlRect.width();
  674. int padding;
  675. QSize size;
  676. adjustImagePaddingAndSize(&img, maximumWidth, padding, size);
  677. if (p_image) {
  678. p_image->m_name = img.m_imageName;
  679. p_image->m_rect = QRectF(padding + m_margin,
  680. br.height() + m_lineLeading,
  681. size.width(),
  682. size.height());
  683. }
  684. int dw = padding + size.width() + m_margin - br.width();
  685. int dh = size.height() + m_lineLeading;
  686. br.adjust(0, 0, dw > 0 ? dw : 0, dh);
  687. }
  688. }
  689. }
  690. }
  691. br.adjust(0, 0, m_margin + m_cursorWidth, 0);
  692. // Add bottom margin.
  693. if (!p_block.next().isValid()) {
  694. br.adjust(0, 0, 0, m_margin);
  695. }
  696. return br;
  697. }
  698. void VTextDocumentLayout::updateDocumentSizeWithOneBlockChanged(int p_blockNumber)
  699. {
  700. const BlockInfo &info = m_blocks[p_blockNumber];
  701. qreal width = info.m_rect.width();
  702. if (width > m_width) {
  703. m_width = width;
  704. m_maximumWidthBlockNumber = p_blockNumber;
  705. emit documentSizeChanged(documentSize());
  706. } else if (width < m_width && p_blockNumber == m_maximumWidthBlockNumber) {
  707. // Shrink the longest block.
  708. updateDocumentSize();
  709. }
  710. }
  711. void VTextDocumentLayout::setLineLeading(qreal p_leading)
  712. {
  713. if (p_leading >= 0) {
  714. m_lineLeading = p_leading;
  715. }
  716. }
  717. void VTextDocumentLayout::setImageWidthConstrainted(bool p_enabled)
  718. {
  719. if (m_imageWidthConstrainted == p_enabled) {
  720. return;
  721. }
  722. m_imageWidthConstrainted = p_enabled;
  723. relayout();
  724. }
  725. void VTextDocumentLayout::setBlockImageEnabled(bool p_enabled)
  726. {
  727. if (m_blockImageEnabled == p_enabled) {
  728. return;
  729. }
  730. m_blockImageEnabled = p_enabled;
  731. relayout();
  732. }
  733. void VTextDocumentLayout::adjustImagePaddingAndSize(const VPreviewedImageInfo *p_info,
  734. int p_maximumWidth,
  735. int &p_padding,
  736. QSize &p_size) const
  737. {
  738. const int minimumImageWidth = 400;
  739. p_padding = p_info->m_padding;
  740. p_size = p_info->m_imageSize;
  741. if (!m_imageWidthConstrainted) {
  742. return;
  743. }
  744. int availableWidth = p_maximumWidth - p_info->m_padding;
  745. if (availableWidth < p_info->m_imageSize.width()) {
  746. // Need to resize the width.
  747. if (availableWidth >= minimumImageWidth) {
  748. p_size.scale(availableWidth, p_size.height(), Qt::KeepAspectRatio);
  749. } else {
  750. // Omit the padding.
  751. p_padding = 0;
  752. p_size.scale(p_maximumWidth, p_size.height(), Qt::KeepAspectRatio);
  753. }
  754. }
  755. }
  756. void VTextDocumentLayout::drawImages(QPainter *p_painter,
  757. const QTextBlock &p_block,
  758. const QPointF &p_offset)
  759. {
  760. if (m_blocks.size() <= p_block.blockNumber()) {
  761. return;
  762. }
  763. const QVector<ImagePaintInfo> &images = m_blocks[p_block.blockNumber()].m_images;
  764. if (images.isEmpty()) {
  765. return;
  766. }
  767. for (auto const & img : images) {
  768. const QPixmap *image = m_imageMgr->findImage(img.m_name);
  769. if (!image) {
  770. continue;
  771. }
  772. QRect targetRect = img.m_rect.adjusted(p_offset.x(),
  773. p_offset.y(),
  774. p_offset.x(),
  775. p_offset.y()).toRect();
  776. p_painter->drawPixmap(targetRect, *image);
  777. }
  778. }
  779. void VTextDocumentLayout::drawMarkers(QPainter *p_painter,
  780. const QTextBlock &p_block,
  781. const QPointF &p_offset)
  782. {
  783. if (m_blocks.size() <= p_block.blockNumber()) {
  784. return;
  785. }
  786. const QVector<Marker> &markers = m_blocks[p_block.blockNumber()].m_markers;
  787. if (markers.isEmpty()) {
  788. return;
  789. }
  790. QPen oldPen = p_painter->pen();
  791. QPen newPen(m_imageLineColor, MARKER_THICKNESS, Qt::DashLine);
  792. p_painter->setPen(newPen);
  793. for (auto const & mk : markers) {
  794. p_painter->drawLine(mk.m_start + p_offset, mk.m_end + p_offset);
  795. }
  796. p_painter->setPen(oldPen);
  797. }
  798. void VTextDocumentLayout::relayout()
  799. {
  800. QTextDocument *doc = document();
  801. // Update the margin.
  802. m_margin = doc->documentMargin();
  803. QTextBlock block = doc->lastBlock();
  804. while (block.isValid()) {
  805. clearBlockLayout(block);
  806. block = block.previous();
  807. }
  808. block = doc->firstBlock();
  809. while (block.isValid()) {
  810. layoutBlock(block);
  811. block = block.next();
  812. }
  813. updateDocumentSize();
  814. emit update(QRectF(0., 0., 1000000000., 1000000000.));
  815. }
  816. void VTextDocumentLayout::relayout(const QSet<int> &p_blocks)
  817. {
  818. if (p_blocks.isEmpty()) {
  819. return;
  820. }
  821. QTextDocument *doc = document();
  822. for (auto bn : p_blocks) {
  823. QTextBlock block = doc->findBlockByNumber(bn);
  824. if (block.isValid()) {
  825. clearBlockLayout(block);
  826. layoutBlock(block);
  827. emit updateBlock(block);
  828. }
  829. }
  830. updateDocumentSize();
  831. }
  832. qreal VTextDocumentLayout::fetchInlineImagesForOneLine(const QVector<VPreviewInfo *> &p_info,
  833. const QTextLine *p_line,
  834. qreal p_margin,
  835. int &p_index,
  836. QVector<const VPreviewedImageInfo *> &p_images,
  837. QVector<QPair<qreal, qreal>> &p_imageRange)
  838. {
  839. qreal maxHeight = 0;
  840. int start = p_line->textStart();
  841. int end = p_line->textLength() + start;
  842. for (int i = 0; i < p_info.size(); ++i) {
  843. const VPreviewedImageInfo &img = p_info[i]->m_imageInfo;
  844. Q_ASSERT(img.m_inline);
  845. if (img.m_startPos >= start && img.m_startPos < end) {
  846. // Start of a new image.
  847. qreal startX = p_line->cursorToX(img.m_startPos) + p_margin;
  848. qreal endX;
  849. if (img.m_endPos <= end) {
  850. // End an image.
  851. endX = p_line->cursorToX(img.m_endPos) + p_margin;
  852. p_images.append(&img);
  853. p_imageRange.append(QPair<qreal, qreal>(startX, endX));
  854. QSize size = img.m_imageSize;
  855. scaleSize(size, endX - startX, MAX_INLINE_IMAGE_HEIGHT);
  856. if (size.height() > maxHeight) {
  857. maxHeight = size.height();
  858. }
  859. // Image i has been drawn.
  860. p_index = i + 1;
  861. } else {
  862. // This image cross the line.
  863. endX = p_line->x() + p_line->width() + p_margin;
  864. if (end - img.m_startPos >= ((img.m_endPos - img.m_startPos) >> 1)) {
  865. // Put image at this side.
  866. p_images.append(&img);
  867. p_imageRange.append(QPair<qreal, qreal>(startX, endX));
  868. QSize size = img.m_imageSize;
  869. scaleSize(size, endX - startX, MAX_INLINE_IMAGE_HEIGHT);
  870. if (size.height() > maxHeight) {
  871. maxHeight = size.height();
  872. }
  873. // Image i has been drawn.
  874. p_index = i + 1;
  875. } else {
  876. // Just put a marker here.
  877. p_images.append(NULL);
  878. p_imageRange.append(QPair<qreal, qreal>(startX, endX));
  879. }
  880. break;
  881. }
  882. } else if (img.m_endPos > start && img.m_startPos < start) {
  883. qreal startX = p_line->x() + p_margin;
  884. qreal endX = img.m_endPos > end ? p_line->x() + p_line->width()
  885. : p_line->cursorToX(img.m_endPos);
  886. if (p_index <= i) {
  887. // Image i has not been drawn. Draw it here.
  888. p_images.append(&img);
  889. p_imageRange.append(QPair<qreal, qreal>(startX, endX));
  890. QSize size = img.m_imageSize;
  891. scaleSize(size, endX - startX, MAX_INLINE_IMAGE_HEIGHT);
  892. if (size.height() > maxHeight) {
  893. maxHeight = size.height();
  894. }
  895. // Image i has been drawn.
  896. p_index = i + 1;
  897. } else {
  898. // Image i has been drawn. Just put a marker here.
  899. p_images.append(NULL);
  900. p_imageRange.append(QPair<qreal, qreal>(startX, endX));
  901. }
  902. if (img.m_endPos >= end) {
  903. break;
  904. }
  905. } else if (img.m_endPos <= start) {
  906. continue;
  907. } else {
  908. break;
  909. }
  910. }
  911. return maxHeight;
  912. }
  913. int VTextDocumentLayout::getTextWidthWithinTextLine(const QTextLayout *p_layout,
  914. int p_pos,
  915. int p_length)
  916. {
  917. QTextLine line = p_layout->lineForTextPosition(p_pos);
  918. Q_ASSERT(line.isValid());
  919. Q_ASSERT(p_pos + p_length <= line.textStart() + line.textLength());
  920. return line.cursorToX(p_pos + p_length) - line.cursorToX(p_pos);
  921. }