Browse Source

replace VPlainTextEdit with VTextEdit

Le Tan 8 years ago
parent
commit
9de40e4d78

+ 8 - 2
src/src.pro

@@ -88,7 +88,10 @@ SOURCES += main.cpp\
     veditor.cpp \
     vmdeditor.cpp \
     veditconfig.cpp \
-    vpreviewmanager.cpp
+    vpreviewmanager.cpp \
+    vimageresourcemanager2.cpp \
+    vtextdocumentlayout.cpp \
+    vtextedit.cpp
 
 HEADERS  += vmainwindow.h \
     vdirectorytree.h \
@@ -164,7 +167,10 @@ HEADERS  += vmainwindow.h \
     veditor.h \
     vmdeditor.h \
     veditconfig.h \
-    vpreviewmanager.h
+    vpreviewmanager.h \
+    vimageresourcemanager2.h \
+    vtextdocumentlayout.h \
+    vtextedit.h
 
 RESOURCES += \
     vnote.qrc \

+ 88 - 0
src/vimageresourcemanager2.cpp

@@ -0,0 +1,88 @@
+#include "vimageresourcemanager2.h"
+
+#include <QDebug>
+
+#include "vtextedit.h"
+
+
+VImageResourceManager2::VImageResourceManager2()
+{
+}
+
+void VImageResourceManager2::addImage(const QString &p_name,
+                                      const QPixmap &p_image)
+{
+    m_images.insert(p_name, p_image);
+}
+
+bool VImageResourceManager2::contains(const QString &p_name) const
+{
+    return m_images.contains(p_name);
+}
+
+QSet<int> VImageResourceManager2::updateBlockInfos(const QVector<VBlockImageInfo2> &p_blocksInfo)
+{
+    QSet<QString> usedImages;
+    QHash<int, VBlockImageInfo2> newBlocksInfo;
+
+    for (auto const & info : p_blocksInfo) {
+        auto it = newBlocksInfo.insert(info.m_blockNumber, info);
+        VBlockImageInfo2 &newInfo = it.value();
+        if (newInfo.m_padding < 0) {
+            newInfo.m_padding = 0;
+        }
+
+        auto imageIt = m_images.find(newInfo.m_imageName);
+        if (imageIt != m_images.end()) {
+            // Fill the width and height.
+            newInfo.m_imageSize = imageIt.value().size();
+            usedImages.insert(newInfo.m_imageName);
+        }
+    }
+
+    QSet<int> affectedBlocks;
+    if (m_blocksInfo != newBlocksInfo) {
+        affectedBlocks = QSet<int>::fromList(m_blocksInfo.keys());
+        affectedBlocks.unite(QSet<int>::fromList(newBlocksInfo.keys()));
+
+        m_blocksInfo = newBlocksInfo;
+
+        // Clear unused images.
+        for (auto it = m_images.begin(); it != m_images.end();) {
+            if (!usedImages.contains(it.key())) {
+                // Remove the image.
+                it = m_images.erase(it);
+            } else {
+                ++it;
+            }
+        }
+    }
+
+    return affectedBlocks;
+}
+
+const VBlockImageInfo2 *VImageResourceManager2::findImageInfoByBlock(int p_blockNumber) const
+{
+    auto it = m_blocksInfo.find(p_blockNumber);
+    if (it != m_blocksInfo.end()) {
+        return &it.value();
+    }
+
+    return NULL;
+}
+
+const QPixmap *VImageResourceManager2::findImage(const QString &p_name) const
+{
+    auto it = m_images.find(p_name);
+    if (it != m_images.end()) {
+        return &it.value();
+    }
+
+    return NULL;
+}
+
+void VImageResourceManager2::clear()
+{
+    m_blocksInfo.clear();
+    m_images.clear();
+}

+ 45 - 0
src/vimageresourcemanager2.h

@@ -0,0 +1,45 @@
+#ifndef VIMAGERESOURCEMANAGER2_H
+#define VIMAGERESOURCEMANAGER2_H
+
+#include <QHash>
+#include <QString>
+#include <QPixmap>
+#include <QTextBlock>
+#include <QVector>
+#include <QSet>
+
+struct VBlockImageInfo2;
+
+
+class VImageResourceManager2
+{
+public:
+    VImageResourceManager2();
+
+    // Add an image to the resource with @p_name as the key.
+    // If @p_name already exists in the resources, it will update it.
+    void addImage(const QString &p_name, const QPixmap &p_image);
+
+    // Whether the resources contains image with name @p_name.
+    bool contains(const QString &p_name) const;
+
+    // Update the block-image info for all blocks.
+    // @p_maximumWidth: maximum width of the images plus the margin.
+    // Return changed blocks' block number.
+    QSet<int> updateBlockInfos(const QVector<VBlockImageInfo2> &p_blocksInfo);
+
+    const VBlockImageInfo2 *findImageInfoByBlock(int p_blockNumber) const;
+
+    const QPixmap *findImage(const QString &p_name) const;
+
+    void clear();
+
+private:
+    // All the images resources.
+    QHash<QString, QPixmap> m_images;
+
+    // Image info of all the blocks with image.
+    QHash<int, VBlockImageInfo2> m_blocksInfo;
+};
+
+#endif // VIMAGERESOURCEMANAGER2_H

+ 2 - 0
src/vmainwindow.cpp

@@ -2276,6 +2276,8 @@ void VMainWindow::enableCodeBlockHighlight(bool p_checked)
 void VMainWindow::enableImagePreview(bool p_checked)
 {
     g_config->setEnablePreviewImages(p_checked);
+
+    emit editorConfigUpdated();
 }
 
 void VMainWindow::enableImagePreviewConstraint(bool p_checked)

+ 40 - 32
src/vmdeditor.cpp

@@ -25,7 +25,7 @@ VMdEditor::VMdEditor(VFile *p_file,
                      VDocument *p_doc,
                      MarkdownConverterType p_type,
                      QWidget *p_parent)
-    : VPlainTextEdit(p_parent),
+    : VTextEdit(p_parent),
       VEditor(p_file, this),
       m_mdHighlighter(NULL),
       m_freshEdit(true)
@@ -35,12 +35,12 @@ VMdEditor::VMdEditor(VFile *p_file,
     VEditor::init();
 
     // Hook functions from VEditor.
-    connect(this, &VPlainTextEdit::cursorPositionChanged,
+    connect(this, &VTextEdit::cursorPositionChanged,
             this, [this]() {
                 highlightOnCursorPositionChanged();
             });
 
-    connect(this, &VPlainTextEdit::selectionChanged,
+    connect(this, &VTextEdit::selectionChanged,
             this, [this]() {
                 highlightSelectedWord();
             });
@@ -77,7 +77,7 @@ VMdEditor::VMdEditor(VFile *p_file,
     connect(m_editOps, &VEditOperations::vimStatusUpdated,
             m_object, &VEditorObject::vimStatusUpdated);
 
-    connect(this, &VPlainTextEdit::cursorPositionChanged,
+    connect(this, &VTextEdit::cursorPositionChanged,
             this, &VMdEditor::updateCurrentHeader);
 
     updateFontAndPalette();
@@ -152,7 +152,7 @@ bool VMdEditor::scrollToBlock(int p_blockNumber)
 }
 
 // Get the visual offset of a block.
-#define GETVISUALOFFSETY ((int)(contentOffset().y() + rect.y()))
+#define GETVISUALOFFSETY (contentOffsetY() + (int)rect.y())
 
 void VMdEditor::makeBlockVisible(const QTextBlock &p_block)
 {
@@ -174,32 +174,37 @@ void VMdEditor::makeBlockVisible(const QTextBlock &p_block)
 
     bool moved = false;
 
-    QRectF rect = blockBoundingGeometry(p_block);
+    QAbstractTextDocumentLayout *layout = document()->documentLayout();
+    QRectF rect = layout->blockBoundingRect(p_block);
     int y = GETVISUALOFFSETY;
     int rectHeight = (int)rect.height();
 
     // Handle the case rectHeight >= height.
     if (rectHeight >= height) {
-        if (y <= 0) {
-            if (y + rectHeight < height) {
-                // Need to scroll up.
-                while (y + rectHeight < height && vbar->value() > vbar->minimum()) {
-                    moved = true;
-                    vbar->setValue(vbar->value() - vbar->singleStep());
-                    rect = blockBoundingGeometry(p_block);
-                    rectHeight = (int)rect.height();
-                    y = GETVISUALOFFSETY;
-                }
+        if (y < 0) {
+            // Need to scroll up.
+            while (y + rectHeight < height && vbar->value() > vbar->minimum()) {
+                moved = true;
+                vbar->setValue(vbar->value() - vbar->singleStep());
+                rect = layout->blockBoundingRect(p_block);
+                rectHeight = (int)rect.height();
+                y = GETVISUALOFFSETY;
             }
-        } else {
+        } else if (y > 0) {
             // Need to scroll down.
             while (y > 0 && vbar->value() < vbar->maximum()) {
                 moved = true;
                 vbar->setValue(vbar->value() + vbar->singleStep());
-                rect = blockBoundingGeometry(p_block);
+                rect = layout->blockBoundingRect(p_block);
                 rectHeight = (int)rect.height();
                 y = GETVISUALOFFSETY;
             }
+
+            if (y < 0) {
+                // One step back.
+                moved = true;
+                vbar->setValue(vbar->value() - vbar->singleStep());
+            }
         }
 
         if (moved) {
@@ -213,7 +218,7 @@ void VMdEditor::makeBlockVisible(const QTextBlock &p_block)
         qDebug() << y << vbar->value() << vbar->minimum() << rectHeight;
         moved = true;
         vbar->setValue(vbar->value() - vbar->singleStep());
-        rect = blockBoundingGeometry(p_block);
+        rect = layout->blockBoundingRect(p_block);
         rectHeight = (int)rect.height();
         y = GETVISUALOFFSETY;
     }
@@ -226,7 +231,7 @@ void VMdEditor::makeBlockVisible(const QTextBlock &p_block)
     while (y + rectHeight > height && vbar->value() < vbar->maximum()) {
         moved = true;
         vbar->setValue(vbar->value() + vbar->singleStep());
-        rect = blockBoundingGeometry(p_block);
+        rect = layout->blockBoundingRect(p_block);
         rectHeight = (int)rect.height();
         y = GETVISUALOFFSETY;
     }
@@ -283,7 +288,7 @@ void VMdEditor::mousePressEvent(QMouseEvent *p_event)
         return;
     }
 
-    VPlainTextEdit::mousePressEvent(p_event);
+    VTextEdit::mousePressEvent(p_event);
 
     emit m_object->selectionChangedByMouse(textCursor().hasSelection());
 }
@@ -294,7 +299,7 @@ void VMdEditor::mouseReleaseEvent(QMouseEvent *p_event)
         return;
     }
 
-    VPlainTextEdit::mousePressEvent(p_event);
+    VTextEdit::mousePressEvent(p_event);
 }
 
 void VMdEditor::mouseMoveEvent(QMouseEvent *p_event)
@@ -303,7 +308,7 @@ void VMdEditor::mouseMoveEvent(QMouseEvent *p_event)
         return;
     }
 
-    VPlainTextEdit::mouseMoveEvent(p_event);
+    VTextEdit::mouseMoveEvent(p_event);
 
     emit m_object->selectionChangedByMouse(textCursor().hasSelection());
 }
@@ -315,7 +320,7 @@ QVariant VMdEditor::inputMethodQuery(Qt::InputMethodQuery p_query) const
         return ret;
     }
 
-    return VPlainTextEdit::inputMethodQuery(p_query);
+    return VTextEdit::inputMethodQuery(p_query);
 }
 
 bool VMdEditor::isBlockVisible(const QTextBlock &p_block)
@@ -336,7 +341,8 @@ bool VMdEditor::isBlockVisible(const QTextBlock &p_block)
         height -= hbar->height();
     }
 
-    QRectF rect = blockBoundingGeometry(p_block);
+    QAbstractTextDocumentLayout *layout = document()->documentLayout();
+    QRectF rect = layout->blockBoundingRect(p_block);
     int y = GETVISUALOFFSETY;
     int rectHeight = (int)rect.height();
 
@@ -630,14 +636,14 @@ void VMdEditor::keyPressEvent(QKeyEvent *p_event)
         return;
     }
 
-    VPlainTextEdit::keyPressEvent(p_event);
+    VTextEdit::keyPressEvent(p_event);
 }
 
 bool VMdEditor::canInsertFromMimeData(const QMimeData *p_source) const
 {
     return p_source->hasImage()
            || p_source->hasUrls()
-           || VPlainTextEdit::canInsertFromMimeData(p_source);
+           || VTextEdit::canInsertFromMimeData(p_source);
 }
 
 void VMdEditor::insertFromMimeData(const QMimeData *p_source)
@@ -653,7 +659,7 @@ void VMdEditor::insertFromMimeData(const QMimeData *p_source)
                 if (dialog.getSelection() == 1) {
                     // Insert as text.
                     Q_ASSERT(p_source->hasText() && p_source->hasImage());
-                    VPlainTextEdit::insertFromMimeData(p_source);
+                    VTextEdit::insertFromMimeData(p_source);
                     return;
                 }
             } else {
@@ -676,7 +682,7 @@ void VMdEditor::insertFromMimeData(const QMimeData *p_source)
 
                 QMimeData newSource;
                 newSource.setUrls(urls);
-                VPlainTextEdit::insertFromMimeData(&newSource);
+                VTextEdit::insertFromMimeData(&newSource);
                 return;
             } else {
                 return;
@@ -703,7 +709,7 @@ void VMdEditor::insertFromMimeData(const QMimeData *p_source)
         Q_ASSERT(p_source->hasText());
     }
 
-    VPlainTextEdit::insertFromMimeData(p_source);
+    VTextEdit::insertFromMimeData(p_source);
 }
 
 void VMdEditor::imageInserted(const QString &p_path)
@@ -838,13 +844,15 @@ void VMdEditor::scrollBlockInPage(int p_blockNum, int p_dest)
     VEditUtils::scrollBlockInPage(this, p_blockNum, p_dest);
 }
 
-void VMdEditor::updatePlainTextEditConfig()
+void VMdEditor::updateTextEditConfig()
 {
     m_previewMgr->setPreviewEnabled(g_config->getEnablePreviewImages());
     setBlockImageEnabled(g_config->getEnablePreviewImages());
 
     setImageWidthConstrainted(g_config->getEnablePreviewImageConstraint());
 
+    setLineLeading(m_config.m_lineDistanceHeight);
+
     int lineNumber = g_config->getEditorLineNumber();
     if (lineNumber < (int)LineNumberType::None || lineNumber >= (int)LineNumberType::Invalid) {
         lineNumber = (int)LineNumberType::None;
@@ -857,6 +865,6 @@ void VMdEditor::updatePlainTextEditConfig()
 
 void VMdEditor::updateConfig()
 {
-    updatePlainTextEditConfig();
     updateEditConfig();
+    updateTextEditConfig();
 }

+ 4 - 4
src/vmdeditor.h

@@ -6,7 +6,7 @@
 #include <QClipboard>
 #include <QImage>
 
-#include "vplaintextedit.h"
+#include "vtextedit.h"
 #include "veditor.h"
 #include "vconfigmanager.h"
 #include "vtableofcontent.h"
@@ -19,7 +19,7 @@ class VCodeBlockHighlightHelper;
 class VDocument;
 class VPreviewManager;
 
-class VMdEditor : public VPlainTextEdit, public VEditor
+class VMdEditor : public VTextEdit, public VEditor
 {
     Q_OBJECT
 public:
@@ -177,8 +177,8 @@ private slots:
     void updateCurrentHeader();
 
 private:
-    // Update the config of VPlainTextEdit according to global configurations.
-    void updatePlainTextEditConfig();
+    // Update the config of VTextEdit according to global configurations.
+    void updateTextEditConfig();
 
     // Get the initial images from file before edit.
     void initInitImages();

+ 7 - 2
src/vpreviewmanager.cpp

@@ -132,6 +132,7 @@ void VPreviewManager::fetchImageLinksFromRegions(QVector<ImageLinkInfo> &p_image
         Q_ASSERT(reg.m_endPos <= blockEnd);
         ImageLinkInfo info(reg.m_startPos,
                            reg.m_endPos,
+                           blockStart,
                            block.blockNumber(),
                            calculateBlockMargin(block));
         if ((reg.m_startPos == blockStart
@@ -219,7 +220,7 @@ QString VPreviewManager::fetchImagePathToPreview(const QString &p_text, QString
 
 void VPreviewManager::updateBlockImageInfo(const QVector<ImageLinkInfo> &p_imageLinks)
 {
-    QVector<VBlockImageInfo> &blockInfos = m_blockImageInfo[PreviewSource::ImageLink];
+    QVector<VBlockImageInfo2> &blockInfos = m_blockImageInfo[PreviewSource::ImageLink];
     blockInfos.clear();
 
     for (int i = 0; i < p_imageLinks.size(); ++i) {
@@ -235,7 +236,11 @@ void VPreviewManager::updateBlockImageInfo(const QVector<ImageLinkInfo> &p_image
             continue;
         }
 
-        VBlockImageInfo info(link.m_blockNumber, name, link.m_margin);
+        VBlockImageInfo2 info(link.m_blockNumber,
+                              name,
+                              link.m_startPos - link.m_blockPos,
+                              link.m_endPos - link.m_blockPos,
+                              link.m_padding);
         blockInfos.push_back(info);
     }
 }

+ 12 - 6
src/vpreviewmanager.h

@@ -48,20 +48,23 @@ private:
         ImageLinkInfo()
             : m_startPos(-1),
               m_endPos(-1),
+              m_blockPos(-1),
               m_blockNumber(-1),
-              m_margin(0),
+              m_padding(0),
               m_isBlock(false)
         {
         }
 
         ImageLinkInfo(int p_startPos,
                       int p_endPos,
+                      int p_blockPos,
                       int p_blockNumber,
-                      int p_margin)
+                      int p_padding)
             : m_startPos(p_startPos),
               m_endPos(p_endPos),
+              m_blockPos(p_blockPos),
               m_blockNumber(p_blockNumber),
-              m_margin(p_margin),
+              m_padding(p_padding),
               m_isBlock(false)
         {
         }
@@ -70,10 +73,13 @@ private:
 
         int m_endPos;
 
+        // Position of this block.
+        int m_blockPos;
+
         int m_blockNumber;
 
-        // Left margin of this block in pixels.
-        int m_margin;
+        // Left padding of this block in pixels.
+        int m_padding;
 
         // Short URL within the () of ![]().
         // Used as the ID of the image.
@@ -125,7 +131,7 @@ private:
 
     // All preview images and information.
     // Each preview source corresponds to one vector.
-    QVector<QVector<VBlockImageInfo>> m_blockImageInfo;
+    QVector<QVector<VBlockImageInfo2>> m_blockImageInfo;
 
     // Map from URL to name in the resource manager.
     // Used for downloading images.

+ 804 - 0
src/vtextdocumentlayout.cpp

@@ -0,0 +1,804 @@
+#include "vtextdocumentlayout.h"
+
+#include <QTextDocument>
+#include <QTextBlock>
+#include <QTextFrame>
+#include <QTextLayout>
+#include <QPointF>
+#include <QFontMetrics>
+#include <QFont>
+#include <QPainter>
+#include <QDebug>
+
+#include "vimageresourcemanager2.h"
+#include "vtextedit.h"
+
+
+VTextDocumentLayout::VTextDocumentLayout(QTextDocument *p_doc,
+                                         VImageResourceManager2 *p_imageMgr)
+    : QAbstractTextDocumentLayout(p_doc),
+      m_margin(p_doc->documentMargin()),
+      m_width(0),
+      m_maximumWidthBlockNumber(-1),
+      m_height(0),
+      m_lineLeading(0),
+      m_blockCount(0),
+      m_cursorWidth(1),
+      m_cursorMargin(4),
+      m_imageMgr(p_imageMgr),
+      m_blockImageEnabled(false),
+      m_imageWidthConstrainted(false)
+{
+}
+
+static void fillBackground(QPainter *p_painter,
+                           const QRectF &p_rect,
+                           QBrush p_brush,
+                           QRectF p_gradientRect = QRectF())
+{
+    p_painter->save();
+    if (p_brush.style() >= Qt::LinearGradientPattern
+        && p_brush.style() <= Qt::ConicalGradientPattern) {
+        if (!p_gradientRect.isNull()) {
+            QTransform m = QTransform::fromTranslate(p_gradientRect.left(),
+                                                     p_gradientRect.top());
+            m.scale(p_gradientRect.width(), p_gradientRect.height());
+            p_brush.setTransform(m);
+            const_cast<QGradient *>(p_brush.gradient())->setCoordinateMode(QGradient::LogicalMode);
+        }
+    } else {
+        p_painter->setBrushOrigin(p_rect.topLeft());
+    }
+
+    p_painter->fillRect(p_rect, p_brush);
+    p_painter->restore();
+}
+
+void VTextDocumentLayout::blockRangeFromRect(const QRectF &p_rect,
+                                             int &p_first,
+                                             int &p_last) const
+{
+    if (p_rect.isNull()) {
+        p_first = 0;
+        p_last = m_blocks.size() - 1;
+        return;
+    }
+
+    p_first = -1;
+    p_last = m_blocks.size() - 1;
+    int y = p_rect.y();
+    Q_ASSERT(document()->blockCount() == m_blocks.size());
+    QTextBlock block = document()->firstBlock();
+    while (block.isValid()) {
+        const BlockInfo &info = m_blocks[block.blockNumber()];
+        Q_ASSERT(info.hasOffset());
+
+        if (info.top() == y
+            || (info.top() < y && info.bottom() >= y)) {
+            p_first = block.blockNumber();
+            break;
+        }
+
+        block = block.next();
+    }
+
+    if (p_first == -1) {
+        p_last = -1;
+        return;
+    }
+
+    y += p_rect.height();
+    while (block.isValid()) {
+        const BlockInfo &info = m_blocks[block.blockNumber()];
+        Q_ASSERT(info.hasOffset());
+
+        if (info.bottom() > y) {
+            p_last = block.blockNumber();
+            break;
+        }
+
+        block = block.next();
+    }
+}
+
+void VTextDocumentLayout::blockRangeFromRectBS(const QRectF &p_rect,
+                                               int &p_first,
+                                               int &p_last) const
+{
+    if (p_rect.isNull()) {
+        p_first = 0;
+        p_last = m_blocks.size() - 1;
+        return;
+    }
+
+    Q_ASSERT(document()->blockCount() == m_blocks.size());
+
+    p_first = findBlockByPosition(p_rect.topLeft());
+
+    if (p_first == -1) {
+        p_last = -1;
+        return;
+    }
+
+    int y = p_rect.bottom();
+    QTextBlock block = document()->findBlockByNumber(p_first);
+
+    if (m_blocks[p_first].top() == p_rect.top()
+        && p_first > 0) {
+        --p_first;
+    }
+
+    p_last = m_blocks.size() - 1;
+    while (block.isValid()) {
+        const BlockInfo &info = m_blocks[block.blockNumber()];
+        Q_ASSERT(info.hasOffset());
+
+        if (info.bottom() > y) {
+            p_last = block.blockNumber();
+            break;
+        }
+
+        block = block.next();
+    }
+}
+
+int VTextDocumentLayout::findBlockByPosition(const QPointF &p_point) const
+{
+    int first = 0, last = m_blocks.size() - 1;
+    int y = p_point.y();
+    while (first <= last) {
+        int mid = (first + last) / 2;
+        const BlockInfo &info = m_blocks[mid];
+        Q_ASSERT(info.hasOffset());
+        if (info.top() <= y && info.bottom() > y) {
+            // Found it.
+            return mid;
+        } else if (info.top() > y) {
+            last = mid - 1;
+        } else {
+            first = mid + 1;
+        }
+    }
+
+    int idx = previousValidBlockNumber(m_blocks.size());
+    if (y >= m_blocks[idx].bottom()) {
+        return idx;
+    }
+
+    idx = nextValidBlockNumber(-1);
+    if (y < m_blocks[idx].top()) {
+        return idx;
+    }
+
+    Q_ASSERT(false);
+    return -1;
+}
+
+void VTextDocumentLayout::draw(QPainter *p_painter, const PaintContext &p_context)
+{
+    // Find out the blocks.
+    int first, last;
+    blockRangeFromRectBS(p_context.clip, first, last);
+    if (first == -1) {
+        return;
+    }
+
+    QTextDocument *doc = document();
+    Q_ASSERT(doc->blockCount() == m_blocks.size());
+    QPointF offset(m_margin, m_blocks[first].top());
+    QTextBlock block = doc->findBlockByNumber(first);
+    QTextBlock lastBlock = doc->findBlockByNumber(last);
+
+    QPen oldPen = p_painter->pen();
+    p_painter->setPen(p_context.palette.color(QPalette::Text));
+
+    while (block.isValid()) {
+        const BlockInfo &info = m_blocks[block.blockNumber()];
+        Q_ASSERT(info.hasOffset());
+
+        const QRectF &rect = info.m_rect;
+        QTextLayout *layout = block.layout();
+
+        if (!block.isVisible()) {
+            offset.ry() += rect.height();
+            if (block == lastBlock) {
+                break;
+            }
+
+            block = block.next();
+            continue;
+        }
+
+        QTextBlockFormat blockFormat = block.blockFormat();
+        QBrush bg = blockFormat.background();
+        if (bg != Qt::NoBrush) {
+            fillBackground(p_painter, rect, bg);
+        }
+
+        auto selections = formatRangeFromSelection(block, p_context.selections);
+
+        layout->draw(p_painter,
+                     offset,
+                     selections,
+                     p_context.clip.isValid() ? p_context.clip : QRectF());
+
+        drawBlockImage(p_painter, block, offset);
+
+        // Draw the cursor.
+        int blpos = block.position();
+        int bllen = block.length();
+        bool drawCursor = p_context.cursorPosition >= blpos
+                          && p_context.cursorPosition < blpos + bllen;
+        if (drawCursor
+            || (p_context.cursorPosition < -1
+                && !layout->preeditAreaText().isEmpty())) {
+            int cpos = p_context.cursorPosition;
+            if (cpos < -1) {
+                cpos = layout->preeditAreaPosition() - (cpos + 2);
+            } else {
+                cpos -= blpos;
+            }
+
+            layout->drawCursor(p_painter, offset, cpos, m_cursorWidth);
+        }
+
+        offset.ry() += rect.height();
+        if (block == lastBlock) {
+            break;
+        }
+
+        block = block.next();
+    }
+
+    p_painter->setPen(oldPen);
+}
+
+QVector<QTextLayout::FormatRange> VTextDocumentLayout::formatRangeFromSelection(const QTextBlock &p_block,
+                                                                                const QVector<Selection> &p_selections) const
+{
+    QVector<QTextLayout::FormatRange> ret;
+
+    int blpos = p_block.position();
+    int bllen = p_block.length();
+    for (int i = 0; i < p_selections.size(); ++i) {
+        const QAbstractTextDocumentLayout::Selection &range = p_selections.at(i);
+        const int selStart = range.cursor.selectionStart() - blpos;
+        const int selEnd = range.cursor.selectionEnd() - blpos;
+        if (selStart < bllen
+            && selEnd > 0
+            && selEnd > selStart) {
+            QTextLayout::FormatRange o;
+            o.start = selStart;
+            o.length = selEnd - selStart;
+            o.format = range.format;
+            ret.append(o);
+        } else if (!range.cursor.hasSelection()
+                   && range.format.hasProperty(QTextFormat::FullWidthSelection)
+                   && p_block.contains(range.cursor.position())) {
+            // For full width selections we don't require an actual selection, just
+            // a position to specify the line. that's more convenience in usage.
+            QTextLayout::FormatRange o;
+            QTextLine l = p_block.layout()->lineForTextPosition(range.cursor.position() - blpos);
+            o.start = l.textStart();
+            o.length = l.textLength();
+            if (o.start + o.length == bllen - 1) {
+                ++o.length; // include newline
+            }
+
+            o.format = range.format;
+            ret.append(o);
+        }
+    }
+
+    return ret;
+}
+
+int VTextDocumentLayout::hitTest(const QPointF &p_point, Qt::HitTestAccuracy p_accuracy) const
+{
+    Q_UNUSED(p_accuracy);
+    int bn = findBlockByPosition(p_point);
+    if (bn == -1) {
+        return -1;
+    }
+
+    QTextBlock block = document()->findBlockByNumber(bn);
+    Q_ASSERT(block.isValid());
+    QTextLayout *layout = block.layout();
+    int off = 0;
+    QPointF pos = p_point - QPointF(m_margin, m_blocks[bn].top());
+    for (int i = 0; i < layout->lineCount(); ++i) {
+        QTextLine line = layout->lineAt(i);
+        const QRectF lr = line.naturalTextRect();
+        if (lr.top() > pos.y()) {
+            off = qMin(off, line.textStart());
+        } else if (lr.bottom() <= pos.y()) {
+            off = qMax(off, line.textStart() + line.textLength());
+        } else {
+            off = line.xToCursor(pos.x(), QTextLine::CursorBetweenCharacters);
+            break;
+        }
+    }
+
+    return block.position() + off;
+}
+
+int VTextDocumentLayout::pageCount() const
+{
+    return 1;
+}
+
+QSizeF VTextDocumentLayout::documentSize() const
+{
+    return QSizeF(m_width, m_height);
+}
+
+QRectF VTextDocumentLayout::frameBoundingRect(QTextFrame *p_frame) const
+{
+    Q_UNUSED(p_frame);
+    return QRectF(0, 0,
+                  qMax(document()->pageSize().width(), m_width), qreal(INT_MAX));
+}
+
+QRectF VTextDocumentLayout::blockBoundingRect(const QTextBlock &p_block) const
+{
+    // Sometimes blockBoundingRect() maybe called before documentChanged().
+    if (!p_block.isValid() || p_block.blockNumber() >= m_blocks.size()) {
+        return QRectF();
+    }
+
+    const BlockInfo &info = m_blocks[p_block.blockNumber()];
+    QRectF geo = info.m_rect.adjusted(0, info.m_offset, 0, info.m_offset);
+    Q_ASSERT(info.hasOffset());
+
+    return geo;
+}
+
+void VTextDocumentLayout::documentChanged(int p_from, int p_charsRemoved, int p_charsAdded)
+{
+    QTextDocument *doc = document();
+    int newBlockCount = doc->blockCount();
+
+    // Update the margin.
+    m_margin = doc->documentMargin();
+
+    int charsChanged = p_charsRemoved + p_charsAdded;
+
+    QTextBlock changeStartBlock = doc->findBlock(p_from);
+    // May be an invalid block.
+    QTextBlock changeEndBlock = doc->findBlock(qMax(0, p_from + charsChanged));
+
+    bool needRelayout = false;
+    if (changeStartBlock == changeEndBlock
+        && newBlockCount == m_blockCount) {
+        // Change single block internal only.
+        QTextBlock block = changeStartBlock;
+        if (block.isValid() && block.length()) {
+            QRectF oldBr = blockBoundingRect(block);
+            clearBlockLayout(block);
+            layoutBlock(block);
+            QRectF newBr = blockBoundingRect(block);
+            // Only one block is affected.
+            if (newBr.height() == oldBr.height()) {
+                // Update document size.
+                updateDocumentSizeWithOneBlockChanged(block.blockNumber());
+
+                emit updateBlock(block);
+                return;
+            }
+        }
+    } else {
+        // Clear layout of all affected blocks.
+        QTextBlock block = changeStartBlock;
+        do {
+            clearBlockLayout(block);
+            if (block == changeEndBlock) {
+                break;
+            }
+
+            block = block.next();
+        } while(block.isValid());
+
+        needRelayout = true;
+    }
+
+    updateBlockCount(newBlockCount, changeStartBlock.blockNumber());
+
+    if (needRelayout) {
+        // Relayout all affected blocks.
+        QTextBlock block = changeStartBlock;
+        do {
+            layoutBlock(block);
+            if (block == changeEndBlock) {
+                break;
+            }
+
+            block = block.next();
+        } while(block.isValid());
+    }
+
+    updateDocumentSize();
+
+    // TODO: Update the view of all the blocks after changeStartBlock.
+    const BlockInfo &firstInfo = m_blocks[changeStartBlock.blockNumber()];
+    emit update(QRectF(0., firstInfo.m_offset, 1000000000., 1000000000.));
+}
+
+void VTextDocumentLayout::clearBlockLayout(QTextBlock &p_block)
+{
+    p_block.clearLayout();
+    int num = p_block.blockNumber();
+    if (num < m_blocks.size()) {
+        m_blocks[num].reset();
+        clearOffsetFrom(num + 1);
+    }
+}
+
+void VTextDocumentLayout::clearOffsetFrom(int p_blockNumber)
+{
+    for (int i = p_blockNumber; i < m_blocks.size(); ++i) {
+        if (!m_blocks[i].hasOffset()) {
+            Q_ASSERT(validateBlocks());
+            break;
+        }
+
+        m_blocks[i].m_offset = -1;
+    }
+}
+
+void VTextDocumentLayout::fillOffsetFrom(int p_blockNumber)
+{
+    qreal offset = m_blocks[p_blockNumber].bottom();
+    for (int i = p_blockNumber + 1; i < m_blocks.size(); ++i) {
+        BlockInfo &info = m_blocks[i];
+        if (!info.m_rect.isNull()) {
+            info.m_offset = offset;
+            offset += info.m_rect.height();
+        } else {
+            break;
+        }
+    }
+}
+
+bool VTextDocumentLayout::validateBlocks() const
+{
+    bool valid = true;
+    for (int i = 0; i < m_blocks.size(); ++i) {
+        const BlockInfo &info = m_blocks[i];
+        if (!info.hasOffset()) {
+            valid = false;
+        } else if (!valid) {
+            return false;
+        }
+    }
+
+    return true;
+}
+
+void VTextDocumentLayout::updateBlockCount(int p_count, int p_changeStartBlock)
+{
+    if (m_blockCount != p_count) {
+        m_blockCount = p_count;
+        m_blocks.resize(m_blockCount);
+
+        // Fix m_blocks.
+        QTextBlock block = document()->findBlockByNumber(p_changeStartBlock);
+        while (block.isValid()) {
+            BlockInfo &info = m_blocks[block.blockNumber()];
+            info.reset();
+
+            QRectF br = blockRectFromTextLayout(block);
+            if (!br.isNull()) {
+                info.m_rect = br;
+            }
+
+            block = block.next();
+        }
+    }
+}
+
+void VTextDocumentLayout::layoutBlock(const QTextBlock &p_block)
+{
+    QTextDocument *doc = document();
+    Q_ASSERT(m_margin == doc->documentMargin());
+
+    // The height (y) of the next line.
+    qreal height = 0;
+    QTextLayout *tl = p_block.layout();
+    QTextOption option = doc->defaultTextOption();
+    tl->setTextOption(option);
+
+    int extraMargin = 0;
+    if (option.flags() & QTextOption::AddSpaceForLineAndParagraphSeparators) {
+        QFontMetrics fm(p_block.charFormat().font());
+        extraMargin += fm.width(QChar(0x21B5));
+    }
+
+    qreal availableWidth = doc->pageSize().width();
+    if (availableWidth <= 0) {
+        availableWidth = qreal(INT_MAX);
+    }
+
+    availableWidth -= (2 * m_margin + extraMargin + m_cursorMargin);
+
+    tl->beginLayout();
+
+    while (true) {
+        QTextLine line = tl->createLine();
+        if (!line.isValid()) {
+            break;
+        }
+
+        line.setLeadingIncluded(true);
+        line.setLineWidth(availableWidth);
+        height += m_lineLeading;
+        line.setPosition(QPointF(m_margin, height));
+        height += line.height();
+    }
+
+    tl->endLayout();
+
+    // Set this block's line count to its layout's line count.
+    // That is one block may occupy multiple visual lines.
+    const_cast<QTextBlock&>(p_block).setLineCount(p_block.isVisible() ? tl->lineCount() : 0);
+
+    // Update the info about this block.
+    finishBlockLayout(p_block);
+}
+
+void VTextDocumentLayout::finishBlockLayout(const QTextBlock &p_block)
+{
+    // Update rect and offset.
+    Q_ASSERT(p_block.isValid());
+    int num = p_block.blockNumber();
+    Q_ASSERT(m_blocks.size() > num);
+    BlockInfo &info = m_blocks[num];
+    info.reset();
+    info.m_rect = blockRectFromTextLayout(p_block);
+    Q_ASSERT(!info.m_rect.isNull());
+    int pre = previousValidBlockNumber(num);
+    if (pre == -1) {
+        info.m_offset = 0;
+    } else if (m_blocks[pre].hasOffset()) {
+        info.m_offset = m_blocks[pre].bottom();
+    }
+
+    if (info.hasOffset()) {
+        fillOffsetFrom(num);
+    }
+}
+
+int VTextDocumentLayout::previousValidBlockNumber(int p_number) const
+{
+    return p_number >= 0 ? p_number - 1 : -1;
+}
+
+int VTextDocumentLayout::nextValidBlockNumber(int p_number) const
+{
+    if (p_number <= -1) {
+        return 0;
+    } else if (p_number >= m_blocks.size() - 1) {
+        return -1;
+    } else {
+        return p_number + 1;
+    }
+}
+
+void VTextDocumentLayout::updateDocumentSize()
+{
+    // The last valid block.
+    int idx = previousValidBlockNumber(m_blocks.size());
+    Q_ASSERT(idx > -1);
+    if (m_blocks[idx].hasOffset()) {
+        int oldHeight = m_height;
+        int oldWidth = m_width;
+
+        m_height = m_blocks[idx].bottom();
+
+        m_width = 0;
+        for (int i = 0; i < m_blocks.size(); ++i) {
+            const BlockInfo &info = m_blocks[i];
+            Q_ASSERT(info.hasOffset());
+            if (m_width < info.m_rect.width()) {
+                m_width = info.m_rect.width();
+                m_maximumWidthBlockNumber = i;
+            }
+        }
+
+        if (oldHeight != m_height
+            || oldWidth != m_width) {
+            emit documentSizeChanged(documentSize());
+        }
+    }
+}
+
+void VTextDocumentLayout::setCursorWidth(int p_width)
+{
+    m_cursorWidth = p_width;
+}
+
+int VTextDocumentLayout::cursorWidth() const
+{
+    return m_cursorWidth;
+}
+
+QRectF VTextDocumentLayout::blockRectFromTextLayout(const QTextBlock &p_block)
+{
+    QTextLayout *tl = p_block.layout();
+    if (tl->lineCount() < 1) {
+        return QRectF();
+    }
+
+    QRectF tlRect = tl->boundingRect();
+    QRectF br(QPointF(0, 0), tlRect.bottomRight());
+
+    // Do not know why. Copied from QPlainTextDocumentLayout.
+    if (tl->lineCount() == 1) {
+        br.setWidth(qMax(br.width(), tl->lineAt(0).naturalTextWidth()));
+    }
+
+    // Handle block image.
+    if (m_blockImageEnabled) {
+        const VBlockImageInfo2 *info = m_imageMgr->findImageInfoByBlock(p_block.blockNumber());
+        if (info && !info->m_imageSize.isNull()) {
+            int maximumWidth = tlRect.width();
+            int padding;
+            QSize size;
+            adjustImagePaddingAndSize(info, maximumWidth, padding, size);
+            int dw = padding + size.width() + m_margin - br.width();
+            int dh = size.height() + m_lineLeading;
+            br.adjust(0, 0, dw > 0 ? dw : 0, dh);
+        }
+    }
+
+    br.adjust(0, 0, m_margin + m_cursorMargin, 0);
+
+    // Add bottom margin.
+    if (!p_block.next().isValid()) {
+        br.adjust(0, 0, 0, m_margin);
+    }
+
+    return br;
+}
+
+void VTextDocumentLayout::updateDocumentSizeWithOneBlockChanged(int p_blockNumber)
+{
+    const BlockInfo &info = m_blocks[p_blockNumber];
+    qreal width = info.m_rect.width();
+    if (width > m_width) {
+        m_width = width;
+        m_maximumWidthBlockNumber = p_blockNumber;
+        emit documentSizeChanged(documentSize());
+    } else if (width < m_width && p_blockNumber == m_maximumWidthBlockNumber) {
+        // Shrink the longest block.
+        updateDocumentSize();
+    }
+}
+
+void VTextDocumentLayout::setLineLeading(qreal p_leading)
+{
+    if (p_leading >= 0) {
+        m_lineLeading = p_leading;
+    }
+}
+
+void VTextDocumentLayout::setImageWidthConstrainted(bool p_enabled)
+{
+    if (m_imageWidthConstrainted == p_enabled) {
+        return;
+    }
+
+    m_imageWidthConstrainted = p_enabled;
+    relayout();
+}
+
+void VTextDocumentLayout::setBlockImageEnabled(bool p_enabled)
+{
+    if (m_blockImageEnabled == p_enabled) {
+        return;
+    }
+
+    m_blockImageEnabled = p_enabled;
+    relayout();
+}
+
+void VTextDocumentLayout::adjustImagePaddingAndSize(const VBlockImageInfo2 *p_info,
+                                                    int p_maximumWidth,
+                                                    int &p_padding,
+                                                    QSize &p_size) const
+{
+    const int minimumImageWidth = 400;
+
+    p_padding = p_info->m_padding;
+    p_size = p_info->m_imageSize;
+
+    if (!m_imageWidthConstrainted) {
+        return;
+    }
+
+    int availableWidth = p_maximumWidth - p_info->m_padding;
+    if (availableWidth < p_info->m_imageSize.width()) {
+        // Need to resize the width.
+        if (availableWidth >= minimumImageWidth) {
+            p_size.scale(availableWidth, p_size.height(), Qt::KeepAspectRatio);
+        } else {
+            // Omit the padding.
+            p_padding = 0;
+            p_size.scale(p_maximumWidth, p_size.height(), Qt::KeepAspectRatio);
+        }
+    }
+}
+
+void VTextDocumentLayout::drawBlockImage(QPainter *p_painter,
+                                         const QTextBlock &p_block,
+                                         const QPointF &p_offset)
+{
+    if (!m_blockImageEnabled) {
+        return;
+    }
+
+    const VBlockImageInfo2 *info = m_imageMgr->findImageInfoByBlock(p_block.blockNumber());
+    if (!info || info->m_imageSize.isNull()) {
+        return;
+    }
+
+    const QPixmap *image = m_imageMgr->findImage(info->m_imageName);
+    Q_ASSERT(image);
+
+    // Draw block image.
+    QTextLayout *tl = p_block.layout();
+    QRectF tlRect = tl->boundingRect();
+    int maximumWidth = tlRect.width();
+    int padding;
+    QSize size;
+    adjustImagePaddingAndSize(info, maximumWidth, padding, size);
+    QRect targetRect(p_offset.x() + padding,
+                     p_offset.y() + tlRect.height() + m_lineLeading,
+                     size.width(),
+                     size.height());
+
+    p_painter->drawPixmap(targetRect, *image);
+}
+
+void VTextDocumentLayout::relayout()
+{
+    QTextDocument *doc = document();
+
+    // Update the margin.
+    m_margin = doc->documentMargin();
+
+    QTextBlock block = doc->lastBlock();
+    while (block.isValid()) {
+        clearBlockLayout(block);
+        block = block.previous();
+    }
+
+    block = doc->firstBlock();
+    while (block.isValid()) {
+        layoutBlock(block);
+        block = block.next();
+    }
+
+    updateDocumentSize();
+
+    emit update(QRectF(0., 0., 1000000000., 1000000000.));
+}
+
+void VTextDocumentLayout::relayout(const QSet<int> &p_blocks)
+{
+    if (p_blocks.isEmpty()) {
+        return;
+    }
+
+    QTextDocument *doc = document();
+
+    for (auto bn : p_blocks) {
+        QTextBlock block = doc->findBlockByNumber(bn);
+        if (block.isValid()) {
+            clearBlockLayout(block);
+            layoutBlock(block);
+            emit updateBlock(block);
+        }
+    }
+
+    updateDocumentSize();
+}

+ 194 - 0
src/vtextdocumentlayout.h

@@ -0,0 +1,194 @@
+#ifndef VTEXTDOCUMENTLAYOUT_H
+#define VTEXTDOCUMENTLAYOUT_H
+
+#include <QAbstractTextDocumentLayout>
+#include <QVector>
+#include <QSize>
+#include <QSet>
+
+class VImageResourceManager2;
+struct VBlockImageInfo2;
+
+
+class VTextDocumentLayout : public QAbstractTextDocumentLayout
+{
+    Q_OBJECT
+public:
+    VTextDocumentLayout(QTextDocument *p_doc,
+                        VImageResourceManager2 *p_imageMgr);
+
+    void draw(QPainter *p_painter, const PaintContext &p_context) Q_DECL_OVERRIDE;
+
+    int hitTest(const QPointF &p_point, Qt::HitTestAccuracy p_accuracy) const Q_DECL_OVERRIDE;
+
+    int pageCount() const Q_DECL_OVERRIDE;
+
+    QSizeF documentSize() const Q_DECL_OVERRIDE;
+
+    QRectF frameBoundingRect(QTextFrame *p_frame) const Q_DECL_OVERRIDE;
+
+    QRectF blockBoundingRect(const QTextBlock &p_block) const Q_DECL_OVERRIDE;
+
+    void setCursorWidth(int p_width);
+
+    int cursorWidth() const;
+
+    void setLineLeading(qreal p_leading);
+
+    qreal getLineLeading() const;
+
+    // Return the block number which contains point @p_point.
+    // If @p_point is at the border, returns the block below.
+    int findBlockByPosition(const QPointF &p_point) const;
+
+    void setImageWidthConstrainted(bool p_enabled);
+
+    void setBlockImageEnabled(bool p_enabled);
+
+    // Relayout all the blocks.
+    void relayout();
+
+    // Relayout @p_blocks.
+    void relayout(const QSet<int> &p_blocks);
+
+protected:
+    void documentChanged(int p_from, int p_charsRemoved, int p_charsAdded) Q_DECL_OVERRIDE;
+
+private:
+    struct BlockInfo
+    {
+        BlockInfo()
+        {
+            reset();
+        }
+
+        void reset()
+        {
+            m_offset = -1;
+            m_rect = QRectF();
+        }
+
+        bool hasOffset() const
+        {
+            return m_offset > -1 && !m_rect.isNull();
+        }
+
+        qreal top() const
+        {
+            Q_ASSERT(hasOffset());
+            return m_offset;
+        }
+
+        qreal bottom() const
+        {
+            Q_ASSERT(hasOffset());
+            return m_offset + m_rect.height();
+        }
+
+        // Y offset of this block.
+        // -1 for invalid.
+        qreal m_offset;
+
+        // The bounding rect of this block, including the margins.
+        // Null for invalid.
+        QRectF m_rect;
+    };
+
+    void layoutBlock(const QTextBlock &p_block);
+
+    // Clear the layout of @p_block.
+    // Also clear all the offset behind this block.
+    void clearBlockLayout(QTextBlock &p_block);
+
+    // Clear the offset of all the blocks from @p_blockNumber.
+    void clearOffsetFrom(int p_blockNumber);
+
+    // Fill the offset filed from @p_blockNumber + 1.
+    void fillOffsetFrom(int p_blockNumber);
+
+    // Update block count to @p_count due to document change.
+    // Maintain m_blocks.
+    // @p_changeStartBlock is the block number of the start block in this change.
+    void updateBlockCount(int p_count, int p_changeStartBlock);
+
+    bool validateBlocks() const;
+
+    void finishBlockLayout(const QTextBlock &p_block);
+
+    int previousValidBlockNumber(int p_number) const;
+
+    int nextValidBlockNumber(int p_number) const;
+
+    // Update block count and m_blocks size.
+    void updateDocumentSize();
+
+    QVector<QTextLayout::FormatRange> formatRangeFromSelection(const QTextBlock &p_block,
+                                                               const QVector<Selection> &p_selections) const;
+
+    // Get the block range [first, last] by rect @p_rect.
+    // @p_rect: a clip region in document coordinates. If null, returns all the blocks.
+    // Return [-1, -1] if no valid block range found.
+    void blockRangeFromRect(const QRectF &p_rect, int &p_first, int &p_last) const;
+
+    // Binary search to get the block range [first, last] by @p_rect.
+    void blockRangeFromRectBS(const QRectF &p_rect, int &p_first, int &p_last) const;
+
+    // Return a rect from the layout.
+    // Return a null rect if @p_block has not been layouted.
+    QRectF blockRectFromTextLayout(const QTextBlock &p_block);
+
+    // Update document size when only block @p_blockNumber is changed and the height
+    // remain the same.
+    void updateDocumentSizeWithOneBlockChanged(int p_blockNumber);
+
+    void adjustImagePaddingAndSize(const VBlockImageInfo2 *p_info,
+                                   int p_maximumWidth,
+                                   int &p_padding,
+                                   QSize &p_size) const;
+
+    // Draw images of block @p_block.
+    // @p_offset: the offset for the drawing of the block.
+    void drawBlockImage(QPainter *p_painter,
+                        const QTextBlock &p_block,
+                        const QPointF &p_offset);
+
+    // Document margin on left/right/bottom.
+    qreal m_margin;
+
+    // Maximum width of the contents.
+    qreal m_width;
+
+    // The block number of the block which contains the m_width.
+    int m_maximumWidthBlockNumber;
+
+    // Height of all the document (all the blocks).
+    qreal m_height;
+
+    // Set the leading space of a line.
+    qreal m_lineLeading;
+
+    // Block count of the document.
+    int m_blockCount;
+
+    // Width of the cursor.
+    int m_cursorWidth;
+
+    // Right margin for cursor.
+    qreal m_cursorMargin;
+
+    QVector<BlockInfo> m_blocks;
+
+    VImageResourceManager2 *m_imageMgr;
+
+    bool m_blockImageEnabled;
+
+    // Whether constraint the width of image to the width of the page.
+    bool m_imageWidthConstrainted;
+};
+
+inline qreal VTextDocumentLayout::getLineLeading() const
+{
+    return m_lineLeading;
+}
+
+#endif // VTEXTDOCUMENTLAYOUT_H

+ 315 - 0
src/vtextedit.cpp

@@ -0,0 +1,315 @@
+#include "vtextedit.h"
+
+#include <QDebug>
+#include <QScrollBar>
+#include <QPainter>
+#include <QResizeEvent>
+
+#include "vtextdocumentlayout.h"
+#include "vimageresourcemanager2.h"
+
+
+enum class BlockState
+{
+    Normal = 0,
+    CodeBlockStart,
+    CodeBlock,
+    CodeBlockEnd,
+    Comment
+};
+
+
+VTextEdit::VTextEdit(QWidget *p_parent)
+    : QTextEdit(p_parent),
+      m_imageMgr(nullptr)
+{
+    init();
+}
+
+VTextEdit::VTextEdit(const QString &p_text, QWidget *p_parent)
+    : QTextEdit(p_text, p_parent),
+      m_imageMgr(nullptr)
+{
+    init();
+}
+
+VTextEdit::~VTextEdit()
+{
+    if (m_imageMgr) {
+        delete m_imageMgr;
+    }
+}
+
+void VTextEdit::init()
+{
+    m_lineNumberType = LineNumberType::None;
+
+    m_blockImageEnabled = false;
+
+    m_imageMgr = new VImageResourceManager2();
+
+    QTextDocument *doc = document();
+    VTextDocumentLayout *docLayout = new VTextDocumentLayout(doc, m_imageMgr);
+    docLayout->setBlockImageEnabled(m_blockImageEnabled);
+    doc->setDocumentLayout(docLayout);
+
+    m_lineNumberArea = new VLineNumberArea(this,
+                                           document(),
+                                           fontMetrics().width(QLatin1Char('8')),
+                                           fontMetrics().height(),
+                                           this);
+    connect(doc, &QTextDocument::blockCountChanged,
+            this, &VTextEdit::updateLineNumberAreaMargin);
+    connect(this, &QTextEdit::textChanged,
+            this, &VTextEdit::updateLineNumberArea);
+    connect(verticalScrollBar(), &QScrollBar::valueChanged,
+            this, &VTextEdit::updateLineNumberArea);
+    connect(this, &QTextEdit::cursorPositionChanged,
+            this, &VTextEdit::updateLineNumberArea);
+}
+
+VTextDocumentLayout *VTextEdit::getLayout() const
+{
+    return qobject_cast<VTextDocumentLayout *>(document()->documentLayout());
+}
+
+void VTextEdit::setLineLeading(qreal p_leading)
+{
+    getLayout()->setLineLeading(p_leading);
+}
+
+void VTextEdit::resizeEvent(QResizeEvent *p_event)
+{
+    QTextEdit::resizeEvent(p_event);
+
+    if (m_lineNumberType != LineNumberType::None) {
+        QRect rect = contentsRect();
+        m_lineNumberArea->setGeometry(QRect(rect.left(),
+                                            rect.top(),
+                                            m_lineNumberArea->calculateWidth(),
+                                            rect.height()));
+    }
+}
+
+void VTextEdit::paintLineNumberArea(QPaintEvent *p_event)
+{
+    if (m_lineNumberType == LineNumberType::None) {
+        updateLineNumberAreaMargin();
+        m_lineNumberArea->hide();
+        return;
+    }
+
+    QPainter painter(m_lineNumberArea);
+    painter.fillRect(p_event->rect(), m_lineNumberArea->getBackgroundColor());
+
+    QTextBlock block = firstVisibleBlock();
+    if (!block.isValid()) {
+        return;
+    }
+
+    VTextDocumentLayout *layout = getLayout();
+    Q_ASSERT(layout);
+
+    int blockNumber = block.blockNumber();
+    QRectF rect = layout->blockBoundingRect(block);
+    int top = contentOffsetY() + (int)rect.y();
+    int bottom = top + (int)rect.height();
+    int eventTop = p_event->rect().top();
+    int eventBtm = p_event->rect().bottom();
+    const int digitHeight = m_lineNumberArea->getDigitHeight();
+    const int curBlockNumber = textCursor().block().blockNumber();
+    painter.setPen(m_lineNumberArea->getForegroundColor());
+    const int leading = (int)layout->getLineLeading();
+
+    // Display line number only in code block.
+    if (m_lineNumberType == LineNumberType::CodeBlock) {
+        int number = 0;
+        while (block.isValid() && top <= eventBtm) {
+            int blockState = block.userState();
+            switch (blockState) {
+            case (int)BlockState::CodeBlockStart:
+                Q_ASSERT(number == 0);
+                number = 1;
+                break;
+
+            case (int)BlockState::CodeBlockEnd:
+                number = 0;
+                break;
+
+            case (int)BlockState::CodeBlock:
+                if (number == 0) {
+                    // Need to find current line number in code block.
+                    QTextBlock startBlock = block.previous();
+                    while (startBlock.isValid()) {
+                        if (startBlock.userState() == (int)BlockState::CodeBlockStart) {
+                            number = block.blockNumber() - startBlock.blockNumber();
+                            break;
+                        }
+
+                        startBlock = startBlock.previous();
+                    }
+                }
+
+                break;
+
+            default:
+                break;
+            }
+
+            if (blockState == (int)BlockState::CodeBlock) {
+                if (block.isVisible() && bottom >= eventTop) {
+                    QString numberStr = QString::number(number);
+                    painter.drawText(0,
+                                     top + leading,
+                                     m_lineNumberArea->width(),
+                                     digitHeight,
+                                     Qt::AlignRight,
+                                     numberStr);
+                }
+
+                ++number;
+            }
+
+            block = block.next();
+            top = bottom;
+            bottom = top + (int)layout->blockBoundingRect(block).height();
+        }
+
+        return;
+    }
+
+    // Handle m_lineNumberType 1 and 2.
+    Q_ASSERT(m_lineNumberType == LineNumberType::Absolute
+             || m_lineNumberType == LineNumberType::Relative);
+    while (block.isValid() && top <= eventBtm) {
+        if (block.isVisible() && bottom >= eventTop) {
+            bool currentLine = false;
+            int number = blockNumber + 1;
+            if (m_lineNumberType == LineNumberType::Relative) {
+                number = blockNumber - curBlockNumber;
+                if (number == 0) {
+                    currentLine = true;
+                    number = blockNumber + 1;
+                } else if (number < 0) {
+                    number = -number;
+                }
+            } else if (blockNumber == curBlockNumber) {
+                currentLine = true;
+            }
+
+            QString numberStr = QString::number(number);
+
+            if (currentLine) {
+                QFont font = painter.font();
+                font.setBold(true);
+                painter.setFont(font);
+            }
+
+            painter.drawText(0,
+                             top + leading,
+                             m_lineNumberArea->width(),
+                             digitHeight,
+                             Qt::AlignRight,
+                             numberStr);
+
+            if (currentLine) {
+                QFont font = painter.font();
+                font.setBold(false);
+                painter.setFont(font);
+            }
+        }
+
+        block = block.next();
+        top = bottom;
+        bottom = top + (int)layout->blockBoundingRect(block).height();
+        ++blockNumber;
+    }
+}
+
+void VTextEdit::updateLineNumberAreaMargin()
+{
+    int width = 0;
+    if (m_lineNumberType != LineNumberType::None) {
+        width = m_lineNumberArea->calculateWidth();
+    }
+
+    if (width != viewportMargins().left()) {
+        setViewportMargins(width, 0, 0, 0);
+    }
+}
+
+void VTextEdit::updateLineNumberArea()
+{
+    if (m_lineNumberType != LineNumberType::None) {
+        if (!m_lineNumberArea->isVisible()) {
+            updateLineNumberAreaMargin();
+            m_lineNumberArea->show();
+        }
+
+        m_lineNumberArea->update();
+    } else if (m_lineNumberArea->isVisible()) {
+        updateLineNumberAreaMargin();
+        m_lineNumberArea->hide();
+    }
+}
+
+QTextBlock VTextEdit::firstVisibleBlock() const
+{
+    VTextDocumentLayout *layout = getLayout();
+    Q_ASSERT(layout);
+    int blockNumber = layout->findBlockByPosition(QPointF(0, -contentOffsetY()));
+    return document()->findBlockByNumber(blockNumber);
+}
+
+int VTextEdit::contentOffsetY() const
+{
+    QScrollBar *sb = verticalScrollBar();
+    return -(sb->value());
+}
+
+void VTextEdit::updateBlockImages(const QVector<VBlockImageInfo2> &p_blocksInfo)
+{
+    if (m_blockImageEnabled) {
+        auto blocks = m_imageMgr->updateBlockInfos(p_blocksInfo);
+        getLayout()->relayout(blocks);
+    }
+}
+
+void VTextEdit::clearBlockImages()
+{
+    m_imageMgr->clear();
+
+    getLayout()->relayout();
+}
+
+bool VTextEdit::containsImage(const QString &p_imageName) const
+{
+    return m_imageMgr->contains(p_imageName);
+}
+
+void VTextEdit::addImage(const QString &p_imageName, const QPixmap &p_image)
+{
+    if (m_blockImageEnabled) {
+        m_imageMgr->addImage(p_imageName, p_image);
+    }
+}
+
+void VTextEdit::setBlockImageEnabled(bool p_enabled)
+{
+    if (m_blockImageEnabled == p_enabled) {
+        return;
+    }
+
+    m_blockImageEnabled = p_enabled;
+
+    getLayout()->setBlockImageEnabled(m_blockImageEnabled);
+
+    if (!m_blockImageEnabled) {
+        clearBlockImages();
+    }
+}
+
+void VTextEdit::setImageWidthConstrainted(bool p_enabled)
+{
+    getLayout()->setImageWidthConstrainted(p_enabled);
+}

+ 174 - 0
src/vtextedit.h

@@ -0,0 +1,174 @@
+#ifndef VTEXTEDIT_H
+#define VTEXTEDIT_H
+
+#include <QTextEdit>
+#include <QTextBlock>
+
+#include "vlinenumberarea.h"
+
+class VTextDocumentLayout;
+class QPainter;
+class QResizeEvent;
+class VImageResourceManager2;
+
+
+struct VBlockImageInfo2
+{
+public:
+    VBlockImageInfo2()
+        : m_blockNumber(-1),
+          m_startPos(-1),
+          m_endPos(-1),
+          m_padding(0),
+          m_inlineImage(false)
+    {
+    }
+
+    VBlockImageInfo2(int p_blockNumber,
+                     const QString &p_imageName,
+                     int p_startPos = -1,
+                     int p_endPos = -1,
+                     int p_padding = 0,
+                     bool p_inlineImage = false)
+        : m_blockNumber(p_blockNumber),
+          m_startPos(p_startPos),
+          m_endPos(p_endPos),
+          m_padding(p_padding),
+          m_inlineImage(p_inlineImage),
+          m_imageName(p_imageName)
+    {
+    }
+
+    bool operator==(const VBlockImageInfo2 &p_other) const
+    {
+        return m_blockNumber == p_other.m_blockNumber
+               && m_startPos == p_other.m_startPos
+               && m_endPos == p_other.m_endPos
+               && m_padding == p_other.m_padding
+               && m_inlineImage == p_other.m_inlineImage
+               && m_imageName == p_other.m_imageName
+               && m_imageSize == p_other.m_imageSize;
+    }
+
+    QString toString() const
+    {
+        return QString("VBlockImageInfo2 block %1 start %2 end %3 padding %4 "
+                       "inline %5 image %6 size [%7,%8]")
+                      .arg(m_blockNumber)
+                      .arg(m_startPos)
+                      .arg(m_endPos)
+                      .arg(m_padding)
+                      .arg(m_inlineImage)
+                      .arg(m_imageName)
+                      .arg(m_imageSize.width())
+                      .arg(m_imageSize.height());
+    }
+
+    // Block number.
+    int m_blockNumber;
+
+    // Start position of the image link in block.
+    int m_startPos;
+
+    // End position of the image link in block.
+    int m_endPos;
+
+    // Padding of the image.
+    int m_padding;
+
+    // Whether it is inline image or block image.
+    bool m_inlineImage;
+
+    // The name of the image corresponding to this block.
+    QString m_imageName;
+
+private:
+    // For cache only.
+    QSize m_imageSize;
+
+    friend class VImageResourceManager2;
+    friend class VTextDocumentLayout;
+};
+
+
+class VTextEdit : public QTextEdit, public VTextEditWithLineNumber
+{
+    Q_OBJECT
+public:
+    explicit VTextEdit(QWidget *p_parent = nullptr);
+
+    explicit VTextEdit(const QString &p_text, QWidget *p_parent = nullptr);
+
+    virtual ~VTextEdit();
+
+    void init();
+
+    void setLineLeading(qreal p_leading);
+
+    void paintLineNumberArea(QPaintEvent *p_event) Q_DECL_OVERRIDE;
+
+    void setLineNumberType(LineNumberType p_type);
+
+    void setLineNumberColor(const QColor &p_foreground, const QColor &p_background);
+
+    QTextBlock firstVisibleBlock() const;
+
+    // Update images of these given blocks.
+    // Images of blocks not given here will be clear.
+    void updateBlockImages(const QVector<VBlockImageInfo2> &p_blocksInfo);
+
+    void clearBlockImages();
+
+    // Whether the resoruce manager contains image of name @p_imageName.
+    bool containsImage(const QString &p_imageName) const;
+
+    // Add an image to the resources.
+    void addImage(const QString &p_imageName, const QPixmap &p_image);
+
+    void setBlockImageEnabled(bool p_enabled);
+
+    void setImageWidthConstrainted(bool p_enabled);
+
+protected:
+    void resizeEvent(QResizeEvent *p_event) Q_DECL_OVERRIDE;
+
+    // Return the Y offset of the content via the scrollbar.
+    int contentOffsetY() const;
+
+private slots:
+    // Update viewport margin to hold the line number area.
+    void updateLineNumberAreaMargin();
+
+    void updateLineNumberArea();
+
+private:
+    VTextDocumentLayout *getLayout() const;
+
+    VLineNumberArea *m_lineNumberArea;
+
+    LineNumberType m_lineNumberType;
+
+    VImageResourceManager2 *m_imageMgr;
+
+    bool m_blockImageEnabled;
+};
+
+inline void VTextEdit::setLineNumberType(LineNumberType p_type)
+{
+    if (p_type == m_lineNumberType) {
+        return;
+    }
+
+    m_lineNumberType = p_type;
+
+    updateLineNumberArea();
+}
+
+inline void VTextEdit::setLineNumberColor(const QColor &p_foreground,
+                                          const QColor &p_background)
+{
+    m_lineNumberArea->setForegroundColor(p_foreground);
+    m_lineNumberArea->setBackgroundColor(p_background);
+}
+
+#endif // VTEXTEDIT_H