texteditoroverlay.cpp 13.1 KB
Newer Older
mae's avatar
mae committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

30
31
32
33
34
35
36
37
38
39
40
41
42
#include <QtGui/QPainter>
#include "texteditoroverlay.h"
#include <QDebug>

using namespace TextEditor;
using namespace TextEditor::Internal;



TextEditorOverlay::TextEditorOverlay(BaseTextEditor *editor)
    :QObject(editor) {
    m_visible = false;
    m_borderWidth = 1;
mae's avatar
mae committed
43
    m_dropShadowWidth = 2;
44
    m_editor = editor;
45
    m_alpha = true;
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    m_viewport = editor->viewport();
}

void TextEditorOverlay::update()
{
    if (m_visible)
        m_viewport->update();
}


void TextEditorOverlay::setVisible(bool b)
{
    if (m_visible == b)
        return;
    m_visible = b;
    update();
}

void TextEditorOverlay::clear()
{
mae's avatar
mae committed
66
67
    if (m_selections.isEmpty())
        return;
68
69
70
71
    m_selections.clear();
    update();
}

72
void TextEditorOverlay::addOverlaySelection(int begin, int end,
73
74
75
                                            const QColor &fg, const QColor &bg,
                                            bool lockSize,
                                            bool dropShadow)
76
{
mae's avatar
mae committed
77
    if (end < begin)
78
79
80
81
82
        return;

    QTextDocument *document = m_editor->document();

    OverlaySelection selection;
83
84
    selection.m_fg = fg;
    selection.m_bg = bg;
85

mae's avatar
mae committed
86
87
    selection.m_cursor_begin = QTextCursor(document->docHandle(), begin);
    selection.m_cursor_end = QTextCursor(document->docHandle(), end);
88

mae's avatar
mae committed
89
90
91
    if (lockSize)
        selection.m_fixedLength = (end - begin);

92
93
    selection.m_dropShadow = dropShadow;

mae's avatar
mae committed
94
95
96
97
    if (dropShadow)
        m_selections.append(selection);
    else
        m_selections.prepend(selection);
98
99
100
101
    update();
}


102
103
void TextEditorOverlay::addOverlaySelection(const QTextCursor &cursor,
                                            const QColor &fg, const QColor &bg, bool lockSize)
104
{
105
    addOverlaySelection(cursor.selectionStart(), cursor.selectionEnd(), fg, bg, lockSize);
106
107
108
109
110
111
112
}

QRect TextEditorOverlay::rect() const
{
    return m_viewport->rect();
}

113
114
QPainterPath TextEditorOverlay::createSelectionPath(const QTextCursor &begin, const QTextCursor &end,
                                                    const QRect &clip)
115
116
{
    if (begin.isNull() || end.isNull() || begin.position() > end.position())
117
        return QPainterPath();
118
119
120
121
122

    QPointF offset = m_editor->contentOffset();
    QRect viewportRect = rect();
    QTextDocument *document = m_editor->document();

123
124
    if (m_editor->blockBoundingGeometry(begin.block()).translated(offset).top() > clip.bottom() + 10
        || m_editor->blockBoundingGeometry(end.block()).translated(offset).bottom() < clip.top() - 10
125
        )
126
        return QPainterPath(); // nothing of the selection is visible
127
128
129
130
131
132
133

    QTextBlock block = begin.block();

    bool inSelection = false;

    QVector<QRectF> selection;

134
135
    if (begin.position() == end.position()) {
        // special case empty selections
136
137
        const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
        QTextLayout *blockLayout = block.layout();
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        int pos = begin.position() - begin.block().position();
        QTextLine line = blockLayout->lineForTextPosition(pos);
        QRectF lineRect = line.naturalTextRect();
        int x = line.cursorToX(pos);
        lineRect.setLeft(x - m_borderWidth);
        lineRect.setRight(x + m_borderWidth);
        selection += lineRect.translated(blockGeometry.topLeft());
    } else {
        for (; block.isValid() && block.blockNumber() <= end.blockNumber(); block = block.next()) {
            if (! block.isVisible())
                continue;

            const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
            QTextLayout *blockLayout = block.layout();

            QTextLine line = blockLayout->lineAt(0);

            int beginChar = 0;
            if (!inSelection) {
                beginChar = begin.position() - begin.block().position();
                line = blockLayout->lineForTextPosition(beginChar);
                inSelection = true;
            } else {
                while (beginChar < block.length() && document->characterAt(block.position() + beginChar).isSpace())
                    ++beginChar;
                if (beginChar == block.length())
                    beginChar = 0;
            }
166

167
168
169
170
171
172
173
174
175
176
177
            int lastLine = blockLayout->lineCount()-1;
            int endChar = -1;
            if (block == end.block()) {
                endChar = end.position()  - end.block().position();
                lastLine = blockLayout->lineForTextPosition(endChar).lineNumber();
                inSelection = false;
            } else {
                endChar = block.length();
                while (endChar > beginChar && document->characterAt(block.position() + endChar - 1).isSpace())
                    --endChar;
            }
178

179
180
181
182
            QRectF lineRect = line.naturalTextRect();
            if (beginChar < endChar) {
                lineRect.setLeft(line.cursorToX(beginChar));
                if (line.lineNumber() == lastLine)
183
184
                    lineRect.setRight(line.cursorToX(endChar));
                selection += lineRect.translated(blockGeometry.topLeft());
185
186
187
188
189
190
191
192
193
194
195
196
197

                for (int lineIndex = line.lineNumber()+1; lineIndex <= lastLine; ++lineIndex) {
                    line = blockLayout->lineAt(lineIndex);
                    lineRect = line.naturalTextRect();
                    if (lineIndex == lastLine)
                        lineRect.setRight(line.cursorToX(endChar));
                    selection += lineRect.translated(blockGeometry.topLeft());
                }
            } else { // empty lines
                if (!selection.isEmpty())
                    lineRect.setLeft(selection.last().left());
                lineRect.setRight(lineRect.left() + 16);
                selection += lineRect.translated(blockGeometry.topLeft());
198
199
            }

200
201
            if (!inSelection)
                break;
202

203
204
205
            if (blockGeometry.translated(offset).y() > 2*viewportRect.height())
                break;
        }
206
207
208
209
    }


    if (selection.isEmpty())
210
        return QPainterPath();
211
212
213
214

    QVector<QPointF> points;

    const int margin = m_borderWidth/2;
215
    const int extra = 0;
216
217
218
219
220
221
222
223
224
225
226
227
228
229

    points += (selection.at(0).topLeft() + selection.at(0).topRight()) / 2 + QPointF(0, -margin);
    points += selection.at(0).topRight() + QPointF(margin+1, -margin);
    points += selection.at(0).bottomRight() + QPointF(margin+1, 0);


    for(int i = 1; i < selection.count()-1; ++i) {

#define MAX3(a,b,c) qMax(a, qMax(b,c))
        qreal x = MAX3(selection.at(i-1).right(),
                       selection.at(i).right(),
                       selection.at(i+1).right()) + margin;

        points += QPointF(x+1, selection.at(i).top());
mae's avatar
mae committed
230
        points += QPointF(x+1, selection.at(i).bottom());
231
232
233
234

    }

    points += selection.at(selection.count()-1).topRight() + QPointF(margin+1, 0);
235
236
    points += selection.at(selection.count()-1).bottomRight() + QPointF(margin+1, margin+extra);
    points += selection.at(selection.count()-1).bottomLeft() + QPointF(-margin, margin+extra);
237
238
239
240
241
242
243
244
    points += selection.at(selection.count()-1).topLeft() + QPointF(-margin, 0);

    for(int i = selection.count()-2; i > 0; --i) {
#define MIN3(a,b,c) qMin(a, qMin(b,c))
        qreal x = MIN3(selection.at(i-1).left(),
                       selection.at(i).left(),
                       selection.at(i+1).left()) - margin;

245
        points += QPointF(x, selection.at(i).bottom()+extra);
246
247
248
        points += QPointF(x, selection.at(i).top());
    }

249
    points += selection.at(0).bottomLeft() + QPointF(-margin, extra);
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    points += selection.at(0).topLeft() + QPointF(-margin, -margin);


    QPainterPath path;
    const int corner = 4;
    path.moveTo(points.at(0));
    points += points.at(0);
    QPointF previous = points.at(0);
    for (int i = 1; i < points.size(); ++i) {
        QPointF point = points.at(i);
        if (point.y() == previous.y() && qAbs(point.x() - previous.x()) > 2*corner) {
            QPointF tmp = QPointF(previous.x() + corner * ((point.x() > previous.x())?1:-1), previous.y());
            path.quadTo(previous, tmp);
            previous = tmp;
            i--;
            continue;
        } else if (point.x() == previous.x() && qAbs(point.y() - previous.y()) > 2*corner) {
            QPointF tmp = QPointF(previous.x(), previous.y() + corner * ((point.y() > previous.y())?1:-1));
            path.quadTo(previous, tmp);
            previous = tmp;
            i--;
            continue;
        }


        QPointF target = (previous + point) / 2;
        path.quadTo(previous, target);
        previous = points.at(i);
    }
    path.closeSubpath();
280
281
282
283
    path.translate(offset);
    return path;
}

284
285
void TextEditorOverlay::paintSelection(QPainter *painter,
                                       const OverlaySelection &selection)
286
{
287
288
289
290
291
292
293

    const QTextCursor &begin = selection.m_cursor_begin;
    const QTextCursor &end= selection.m_cursor_end;
    const QColor &fg = selection.m_fg;
    const QColor &bg = selection.m_bg;


294
295
296
297
    if (begin.isNull() || end.isNull() || begin.position() > end.position())
        return;

    QPainterPath path = createSelectionPath(begin, end, m_editor->viewport()->rect());
298
299

    painter->save();
300
    QColor penColor = fg;
301
302
    if (m_alpha)
        penColor.setAlpha(220);
303
    QPen pen(penColor, m_borderWidth);
304
    painter->translate(-.5, -.5);
305
306
307

    QRectF pathRect = path.controlPointRect();

308
    if (bg.isValid()) {
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        if (!m_alpha || begin.blockNumber() != end.blockNumber()) {
            // gradients are too slow for larger selections :(
            QColor col = bg;
            if (m_alpha)
                col.setAlpha(50);
            painter->setBrush(col);
        } else {
            QLinearGradient linearGrad(pathRect.topLeft(), pathRect.bottomLeft());
            QColor col1 = fg.lighter(150);
            col1.setAlpha(20);
            QColor col2 = fg;
            col2.setAlpha(80);
            linearGrad.setColorAt(0, col1);
            linearGrad.setColorAt(1, col2);
            painter->setBrush(QBrush(linearGrad));
        }
325
326
327
    } else {
        painter->setBrush(QBrush());
    }
328

329
    painter->setRenderHint(QPainter::Antialiasing);
330
331
332

    if (selection.m_dropShadow) {
        painter->save();
333
334
        QPainterPath shadow = path;
        shadow.translate(m_dropShadowWidth, m_dropShadowWidth);
Roberto Raggi's avatar
Roberto Raggi committed
335
336
337
        QPainterPath clip;
        clip.addRect(m_editor->viewport()->rect());
        painter->setClipPath(clip - path);
338
        painter->fillPath(shadow, QColor(0, 0, 0, 100));
339
340
341
        painter->restore();
    }

342
343
344
345
346
347
    pen.setJoinStyle(Qt::RoundJoin);
    painter->setPen(pen);
    painter->drawPath(path);
    painter->restore();
}

348
349
350
void TextEditorOverlay::fillSelection(QPainter *painter,
                                      const OverlaySelection &selection,
                                      const QColor &color)
351
{
352
353
    const QTextCursor &begin = selection.m_cursor_begin;
    const QTextCursor &end= selection.m_cursor_end;
354
355
356
357
358
359
360
361
362
363
364
    if (begin.isNull() || end.isNull() || begin.position() > end.position())
        return;

    QPainterPath path = createSelectionPath(begin, end, m_editor->viewport()->rect());

    painter->save();
    painter->translate(-.5, -.5);
    painter->setRenderHint(QPainter::Antialiasing);
    painter->fillPath(path, color);
    painter->restore();
}
365
366
367
368
369
370

void TextEditorOverlay::paint(QPainter *painter, const QRect &clip)
{
    Q_UNUSED(clip);
    for (int i = 0; i < m_selections.size(); ++i) {
        const OverlaySelection &selection = m_selections.at(i);
mae's avatar
mae committed
371
372
373
374
375
        if (selection.m_fixedLength >= 0
            && selection.m_cursor_end.position() - selection.m_cursor_begin.position()
            != selection.m_fixedLength)
            continue;

376
        paintSelection(painter, selection);
377
378
379
380
381
382
383
384
385
386
387
388
389
    }
}

void TextEditorOverlay::fill(QPainter *painter, const QColor &color, const QRect &clip)
{
    Q_UNUSED(clip);
    for (int i = 0; i < m_selections.size(); ++i) {
        const OverlaySelection &selection = m_selections.at(i);
        if (selection.m_fixedLength >= 0
            && selection.m_cursor_end.position() - selection.m_cursor_begin.position()
            != selection.m_fixedLength)
            continue;

390
        fillSelection(painter, selection, color);
391
392
393
    }
}