basetextdocumentlayout.cpp 27.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
hjk's avatar
hjk committed
3
4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29
30

#include "basetextdocumentlayout.h"
31
#include <utils/qtcassert.h>
32
#include <QDebug>
33
34
35

using namespace TextEditor;

36
namespace TextEditor {
37
38
39
40
41
42
43
44
45
46
47
48
namespace Internal {

class DocumentMarker : public ITextMarkable
{
    Q_OBJECT
public:
    DocumentMarker(QTextDocument *);
    ~DocumentMarker();

    TextMarks marks() const { return m_marksCache; }

    // ITextMarkable
49
    bool addMark(ITextMark *mark);
50
51
52
53
    TextMarks marksAt(int line) const;
    void removeMark(ITextMark *mark);
    void updateMark(ITextMark *mark);

54
    void removeMarkFromMarksCache(TextEditor::ITextMark *mark);
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
private:
    TextMarks m_marksCache; // not owned
    QTextDocument *document;
};

DocumentMarker::DocumentMarker(QTextDocument *doc)
  : ITextMarkable(doc), document(doc)
{
}

DocumentMarker::~DocumentMarker()
{

}

70
bool DocumentMarker::addMark(TextEditor::ITextMark *mark)
71
{
72
73
    if (mark->markableInterface())
        return false;
74
75
    QTC_ASSERT(mark->lineNumber() >= 1, return false);
    int blockNumber = mark->lineNumber() - 1;
76
77
78
79
80
81
82
83
84
85
    BaseTextDocumentLayout *documentLayout =
        qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
    QTC_ASSERT(documentLayout, return false);
    QTextBlock block = document->findBlockByNumber(blockNumber);

    if (block.isValid()) {
        TextBlockUserData *userData = BaseTextDocumentLayout::userData(block);
        userData->addMark(mark);
        m_marksCache.append(mark);
        mark->updateLineNumber(blockNumber + 1);
86
        QTC_CHECK(mark->lineNumber() == blockNumber + 1); // Checks that the base class is called
87
        mark->updateBlock(block);
88
        mark->setMarkableInterface(this);
89
        if (!mark->isVisible())
90
91
92
93
            return true;
        // Update document layout
        double newMaxWidthFactor = qMax(mark->widthFactor(), documentLayout->maxMarkWidthFactor);
        bool fullUpdate =  newMaxWidthFactor > documentLayout->maxMarkWidthFactor || !documentLayout->hasMarks;
94
        documentLayout->hasMarks = true;
95
96
97
98
99
        documentLayout->maxMarkWidthFactor = newMaxWidthFactor;
        if (fullUpdate)
            documentLayout->requestUpdate();
        else
            documentLayout->requestExtraAreaUpdate();
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        return true;
    }
    return false;
}

TextEditor::TextMarks DocumentMarker::marksAt(int line) const
{
    QTC_ASSERT(line >= 1, return TextMarks());
    int blockNumber = line - 1;
    QTextBlock block = document->findBlockByNumber(blockNumber);

    if (block.isValid()) {
        if (TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(block))
            return userData->marks();
    }
    return TextMarks();
}

118
119
120
121
void DocumentMarker::removeMarkFromMarksCache(TextEditor::ITextMark *mark)
{
    BaseTextDocumentLayout *documentLayout =
        qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
122
    QTC_ASSERT(documentLayout, return);
123
124
    m_marksCache.removeAll(mark);

125
126
    if (m_marksCache.isEmpty()) {
        documentLayout->hasMarks = false;
127
128
129
        documentLayout->maxMarkWidthFactor = 1.0;
        documentLayout->requestUpdate();
        return;
130
131
    }

132
    if (!mark->isVisible())
133
134
135
136
137
138
139
140
141
142
        return;

    if (documentLayout->maxMarkWidthFactor == 1.0
            || mark->widthFactor() == 1.0
            || mark->widthFactor() < documentLayout->maxMarkWidthFactor) {
        // No change in width possible
        documentLayout->requestExtraAreaUpdate();
    } else {
        double maxWidthFactor = 1.0;
        foreach (const ITextMark *mark, marks()) {
143
            if (!mark->isVisible())
144
145
146
147
148
149
150
151
152
153
154
155
                continue;
            maxWidthFactor = qMax(mark->widthFactor(), maxWidthFactor);
            if (maxWidthFactor == documentLayout->maxMarkWidthFactor)
                break; // Still a mark with the maxMarkWidthFactor
        }

        if (maxWidthFactor != documentLayout->maxMarkWidthFactor) {
            documentLayout->maxMarkWidthFactor = maxWidthFactor;
            documentLayout->requestUpdate();
        } else {
            documentLayout->requestExtraAreaUpdate();
        }
156
157
158
    }
}

159
160
void DocumentMarker::removeMark(TextEditor::ITextMark *mark)
{
161
162
163
164
    QTextBlock block = document->findBlockByNumber(mark->lineNumber() - 1);
    if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
        if (!data->removeMark(mark))
            qDebug() << "Could not find mark" << mark << "on line" << mark->lineNumber();
165
    }
166

167
168
    removeMarkFromMarksCache(mark);
    mark->setMarkableInterface(0);
169
170
171
172
173
174
175
176
177
178
179
180
}

void DocumentMarker::updateMark(ITextMark *mark)
{
    Q_UNUSED(mark)
    BaseTextDocumentLayout *documentLayout =
        qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
    QTC_ASSERT(documentLayout, return);
    documentLayout->requestUpdate();
}

} // namespace Internal
181
} // namespace TextEditor
182

183
184
185
186
CodeFormatterData::~CodeFormatterData()
{
}

187
188
TextBlockUserData::~TextBlockUserData()
{
189
    foreach (ITextMark *mrk, m_marks) {
190
191
192
193
        TextEditor::Internal::DocumentMarker *documentMarker
                = static_cast<TextEditor::Internal::DocumentMarker *>(mrk->markableInterface());
        documentMarker->removeMarkFromMarksCache(mrk);
        mrk->setMarkableInterface(0);
194
195
        mrk->removedFromEditor();
    }
196
197
198

    if (m_codeFormatterData)
        delete m_codeFormatterData;
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
}

int TextBlockUserData::braceDepthDelta() const
{
    int delta = 0;
    for (int i = 0; i < m_parentheses.size(); ++i) {
        switch (m_parentheses.at(i).chr.unicode()) {
        case '{': case '+': case '[': ++delta; break;
        case '}': case '-': case ']': --delta; break;
        default: break;
        }
    }
    return delta;
}

TextBlockUserData::MatchType TextBlockUserData::checkOpenParenthesis(QTextCursor *cursor, QChar c)
{
    QTextBlock block = cursor->block();
217
    if (!BaseTextDocumentLayout::hasParentheses(block) || BaseTextDocumentLayout::ifdefedOut(block))
218
219
        return NoMatch;

220
    Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    Parenthesis openParen, closedParen;
    QTextBlock closedParenParag = block;

    const int cursorPos = cursor->position() - closedParenParag.position();
    int i = 0;
    int ignore = 0;
    bool foundOpen = false;
    for (;;) {
        if (!foundOpen) {
            if (i >= parenList.count())
                return NoMatch;
            openParen = parenList.at(i);
            if (openParen.pos != cursorPos) {
                ++i;
                continue;
            } else {
                foundOpen = true;
                ++i;
            }
        }

        if (i >= parenList.count()) {
            for (;;) {
                closedParenParag = closedParenParag.next();
                if (!closedParenParag.isValid())
                    return NoMatch;
247
248
249
                if (BaseTextDocumentLayout::hasParentheses(closedParenParag)
                    && !BaseTextDocumentLayout::ifdefedOut(closedParenParag)) {
                    parenList = BaseTextDocumentLayout::parentheses(closedParenParag);
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
280
281
282
283
284
285
                    break;
                }
            }
            i = 0;
        }

        closedParen = parenList.at(i);
        if (closedParen.type == Parenthesis::Opened) {
            ignore++;
            ++i;
            continue;
        } else {
            if (ignore > 0) {
                ignore--;
                ++i;
                continue;
            }

            cursor->clearSelection();
            cursor->setPosition(closedParenParag.position() + closedParen.pos + 1, QTextCursor::KeepAnchor);

            if ((c == QLatin1Char('{') && closedParen.chr != QLatin1Char('}'))
                || (c == QLatin1Char('(') && closedParen.chr != QLatin1Char(')'))
                || (c == QLatin1Char('[') && closedParen.chr != QLatin1Char(']'))
                || (c == QLatin1Char('+') && closedParen.chr != QLatin1Char('-'))
               )
                return Mismatch;

            return Match;
        }
    }
}

TextBlockUserData::MatchType TextBlockUserData::checkClosedParenthesis(QTextCursor *cursor, QChar c)
{
    QTextBlock block = cursor->block();
286
    if (!BaseTextDocumentLayout::hasParentheses(block) || BaseTextDocumentLayout::ifdefedOut(block))
287
288
        return NoMatch;

289
    Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
    Parenthesis openParen, closedParen;
    QTextBlock openParenParag = block;

    const int cursorPos = cursor->position() - openParenParag.position();
    int i = parenList.count() - 1;
    int ignore = 0;
    bool foundClosed = false;
    for (;;) {
        if (!foundClosed) {
            if (i < 0)
                return NoMatch;
            closedParen = parenList.at(i);
            if (closedParen.pos != cursorPos - 1) {
                --i;
                continue;
            } else {
                foundClosed = true;
                --i;
            }
        }

        if (i < 0) {
            for (;;) {
                openParenParag = openParenParag.previous();
                if (!openParenParag.isValid())
                    return NoMatch;

317
318
319
                if (BaseTextDocumentLayout::hasParentheses(openParenParag)
                    && !BaseTextDocumentLayout::ifdefedOut(openParenParag)) {
                    parenList = BaseTextDocumentLayout::parentheses(openParenParag);
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
                    break;
                }
            }
            i = parenList.count() - 1;
        }

        openParen = parenList.at(i);
        if (openParen.type == Parenthesis::Closed) {
            ignore++;
            --i;
            continue;
        } else {
            if (ignore > 0) {
                ignore--;
                --i;
                continue;
            }

            cursor->clearSelection();
            cursor->setPosition(openParenParag.position() + openParen.pos, QTextCursor::KeepAnchor);

341
342
343
344
            if ((c == QLatin1Char('}') && openParen.chr != QLatin1Char('{'))    ||
                 (c == QLatin1Char(')') && openParen.chr != QLatin1Char('('))   ||
                 (c == QLatin1Char(']') && openParen.chr != QLatin1Char('['))   ||
                 (c == QLatin1Char('-') && openParen.chr != QLatin1Char('+')))
345
346
347
348
349
350
351
                return Mismatch;

            return Match;
        }
    }
}

352
bool TextBlockUserData::findPreviousOpenParenthesis(QTextCursor *cursor, bool select, bool onlyInCurrentBlock)
353
354
355
356
357
{
    QTextBlock block = cursor->block();
    int position = cursor->position();
    int ignore = 0;
    while (block.isValid()) {
358
359
        Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
        if (!parenList.isEmpty() && !BaseTextDocumentLayout::ifdefedOut(block)) {
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
            for (int i = parenList.count()-1; i >= 0; --i) {
                Parenthesis paren = parenList.at(i);
                if (block == cursor->block() &&
                    (position - block.position() <= paren.pos + (paren.type == Parenthesis::Closed ? 1 : 0)))
                        continue;
                if (paren.type == Parenthesis::Closed) {
                    ++ignore;
                } else if (ignore > 0) {
                    --ignore;
                } else {
                    cursor->setPosition(block.position() + paren.pos, select ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
                    return true;
                }
            }
        }
375
376
        if (onlyInCurrentBlock)
            return false;
377
378
379
380
381
382
383
384
385
386
387
        block = block.previous();
    }
    return false;
}

bool TextBlockUserData::findPreviousBlockOpenParenthesis(QTextCursor *cursor, bool checkStartPosition)
{
    QTextBlock block = cursor->block();
    int position = cursor->position();
    int ignore = 0;
    while (block.isValid()) {
388
389
        Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
        if (!parenList.isEmpty() && !BaseTextDocumentLayout::ifdefedOut(block)) {
390
391
392
            for (int i = parenList.count()-1; i >= 0; --i) {
                Parenthesis paren = parenList.at(i);
                if (paren.chr != QLatin1Char('{') && paren.chr != QLatin1Char('}')
393
                    && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-'))
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
                    continue;
                if (block == cursor->block()) {
                    if (position - block.position() <= paren.pos + (paren.type == Parenthesis::Closed ? 1 : 0))
                        continue;
                    if (checkStartPosition && paren.type == Parenthesis::Opened && paren.pos== cursor->position()) {
                        return true;
                    }
                }
                if (paren.type == Parenthesis::Closed) {
                    ++ignore;
                } else if (ignore > 0) {
                    --ignore;
                } else {
                    cursor->setPosition(block.position() + paren.pos);
                    return true;
                }
            }
        }
        block = block.previous();
    }
    return false;
}

bool TextBlockUserData::findNextClosingParenthesis(QTextCursor *cursor, bool select)
{
    QTextBlock block = cursor->block();
    int position = cursor->position();
    int ignore = 0;
    while (block.isValid()) {
423
424
        Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
        if (!parenList.isEmpty() && !BaseTextDocumentLayout::ifdefedOut(block)) {
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
            for (int i = 0; i < parenList.count(); ++i) {
                Parenthesis paren = parenList.at(i);
                if (block == cursor->block() &&
                    (position - block.position() > paren.pos - (paren.type == Parenthesis::Opened ? 1 : 0)))
                    continue;
                if (paren.type == Parenthesis::Opened) {
                    ++ignore;
                } else if (ignore > 0) {
                    --ignore;
                } else {
                    cursor->setPosition(block.position() + paren.pos+1, select ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
                    return true;
                }
            }
        }
        block = block.next();
    }
    return false;
}

bool TextBlockUserData::findNextBlockClosingParenthesis(QTextCursor *cursor)
{
    QTextBlock block = cursor->block();
    int position = cursor->position();
    int ignore = 0;
    while (block.isValid()) {
451
452
        Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
        if (!parenList.isEmpty() && !BaseTextDocumentLayout::ifdefedOut(block)) {
453
454
455
            for (int i = 0; i < parenList.count(); ++i) {
                Parenthesis paren = parenList.at(i);
                if (paren.chr != QLatin1Char('{') && paren.chr != QLatin1Char('}')
456
                    && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-'))
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
                    continue;
                if (block == cursor->block() &&
                    (position - block.position() > paren.pos - (paren.type == Parenthesis::Opened ? 1 : 0)))
                    continue;
                if (paren.type == Parenthesis::Opened) {
                    ++ignore;
                } else if (ignore > 0) {
                    --ignore;
                } else {
                    cursor->setPosition(block.position() + paren.pos+1);
                    return true;
                }
            }
        }
        block = block.next();
    }
    return false;
}

TextBlockUserData::MatchType TextBlockUserData::matchCursorBackward(QTextCursor *cursor)
{
    cursor->clearSelection();
    const QTextBlock block = cursor->block();

481
    if (!BaseTextDocumentLayout::hasParentheses(block) || BaseTextDocumentLayout::ifdefedOut(block))
482
483
484
485
        return NoMatch;

    const int relPos = cursor->position() - block.position();

486
    Parentheses parentheses = BaseTextDocumentLayout::parentheses(block);
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    const Parentheses::const_iterator cend = parentheses.constEnd();
    for (Parentheses::const_iterator it = parentheses.constBegin();it != cend; ++it) {
        const Parenthesis &paren = *it;
        if (paren.pos == relPos - 1
            && paren.type == Parenthesis::Closed) {
            return checkClosedParenthesis(cursor, paren.chr);
        }
    }
    return NoMatch;
}

TextBlockUserData::MatchType TextBlockUserData::matchCursorForward(QTextCursor *cursor)
{
    cursor->clearSelection();
    const QTextBlock block = cursor->block();

503
    if (!BaseTextDocumentLayout::hasParentheses(block) || BaseTextDocumentLayout::ifdefedOut(block))
504
505
506
507
        return NoMatch;

    const int relPos = cursor->position() - block.position();

508
    Parentheses parentheses = BaseTextDocumentLayout::parentheses(block);
509
510
511
512
513
514
515
516
517
518
519
    const Parentheses::const_iterator cend = parentheses.constEnd();
    for (Parentheses::const_iterator it = parentheses.constBegin();it != cend; ++it) {
        const Parenthesis &paren = *it;
        if (paren.pos == relPos
            && paren.type == Parenthesis::Opened) {
            return checkOpenParenthesis(cursor, paren.chr);
        }
    }
    return NoMatch;
}

520
521
522
523
524
525
526
void TextBlockUserData::setCodeFormatterData(CodeFormatterData *data)
{
    if (m_codeFormatterData)
        delete m_codeFormatterData;

    m_codeFormatterData = data;
}
527

528
529
530
531
532
533
534
535
536
537
538
void TextBlockUserData::addMark(ITextMark *mark)
{
    int i = 0;
    for ( ; i < m_marks.size(); ++i) {
        if (mark->priority() < m_marks.at(i)->priority())
            break;
    }
    m_marks.insert(i, mark);
}


539
BaseTextDocumentLayout::BaseTextDocumentLayout(QTextDocument *doc)
540
541
542
543
544
545
546
547
    : QPlainTextDocumentLayout(doc),
      lastSaveRevision(0),
      hasMarks(false),
      maxMarkWidthFactor(1.0),
      m_requiredWidth(0),
      m_documentMarker(new Internal::DocumentMarker(doc))
{

548
549
}

550
BaseTextDocumentLayout::~BaseTextDocumentLayout()
551
{
552
    documentClosing();
553
554
}

555
void BaseTextDocumentLayout::setParentheses(const QTextBlock &block, const Parentheses &parentheses)
556
557
558
559
560
561
562
563
564
{
    if (parentheses.isEmpty()) {
        if (TextBlockUserData *userData = testUserData(block))
            userData->clearParentheses();
    } else {
        userData(block)->setParentheses(parentheses);
    }
}

565
Parentheses BaseTextDocumentLayout::parentheses(const QTextBlock &block)
566
567
568
569
570
571
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->parentheses();
    return Parentheses();
}

572
bool BaseTextDocumentLayout::hasParentheses(const QTextBlock &block)
573
574
575
576
577
578
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->hasParentheses();
    return false;
}

579
bool BaseTextDocumentLayout::setIfdefedOut(const QTextBlock &block)
580
581
582
583
{
    return userData(block)->setIfdefedOut();
}

584
bool BaseTextDocumentLayout::clearIfdefedOut(const QTextBlock &block)
585
586
587
588
589
590
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->clearIfdefedOut();
    return false;
}

591
bool BaseTextDocumentLayout::ifdefedOut(const QTextBlock &block)
592
593
594
595
596
597
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->ifdefedOut();
    return false;
}

598
int BaseTextDocumentLayout::braceDepthDelta(const QTextBlock &block)
599
600
601
602
603
604
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->braceDepthDelta();
    return 0;
}

605
int BaseTextDocumentLayout::braceDepth(const QTextBlock &block)
606
607
608
609
610
611
612
{
    int state = block.userState();
    if (state == -1)
        return 0;
    return state >> 8;
}

613
void BaseTextDocumentLayout::setBraceDepth(QTextBlock &block, int depth)
614
615
616
617
618
619
620
621
{
    int state = block.userState();
    if (state == -1)
        state = 0;
    state = state & 0xff;
    block.setUserState((depth << 8) | state);
}

622
void BaseTextDocumentLayout::changeBraceDepth(QTextBlock &block, int delta)
623
624
625
626
{
    if (delta)
        setBraceDepth(block, braceDepth(block) + delta);
}
mae's avatar
mae committed
627

mae's avatar
mae committed
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
void BaseTextDocumentLayout::setLexerState(const QTextBlock &block, int state)
{
    if (state == 0) {
        if (TextBlockUserData *userData = testUserData(block))
            userData->setLexerState(0);
    } else {
        userData(block)->setLexerState(qMax(0,state));
    }
}

int BaseTextDocumentLayout::lexerState(const QTextBlock &block)
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->lexerState();
    return 0;
}

mae's avatar
mae committed
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
void BaseTextDocumentLayout::setFoldingIndent(const QTextBlock &block, int indent)
{
    if (indent == 0) {
        if (TextBlockUserData *userData = testUserData(block))
            userData->setFoldingIndent(0);
    } else {
        userData(block)->setFoldingIndent(qMax(0,indent));
    }
}

int BaseTextDocumentLayout::foldingIndent(const QTextBlock &block)
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->foldingIndent();
    return 0;
}

void BaseTextDocumentLayout::changeFoldingIndent(QTextBlock &block, int delta)
{
    if (delta)
        setFoldingIndent(block, foldingIndent(block) + delta);
}

bool BaseTextDocumentLayout::canFold(const QTextBlock &block)
{
    return (block.next().isValid() && foldingIndent(block.next()) > foldingIndent(block));
}

bool BaseTextDocumentLayout::isFolded(const QTextBlock &block)
{
    if (TextBlockUserData *userData = testUserData(block))
        return userData->folded();
    return false;
}

void BaseTextDocumentLayout::setFolded(const QTextBlock &block, bool folded)
{
    if (folded)
        userData(block)->setFolded(true);
    else {
        if (TextBlockUserData *userData = testUserData(block))
            return userData->setFolded(false);
    }
}

690
691
692
693
694
void BaseTextDocumentLayout::requestExtraAreaUpdate()
{
    emit updateExtraArea();
}

695
696
697
698
699
ITextMarkable *BaseTextDocumentLayout::markableInterface()
{
    return m_documentMarker;
}

mae's avatar
mae committed
700
701
702
703
704
705
706
void BaseTextDocumentLayout::doFoldOrUnfold(const QTextBlock& block, bool unfold)
{
    if (!canFold(block))
        return;
    QTextBlock b = block.next();

    int indent = foldingIndent(block);
mae's avatar
mae committed
707
    while (b.isValid() && foldingIndent(b) > indent && (unfold || b.next().isValid())) {
mae's avatar
mae committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
        b.setVisible(unfold);
        b.setLineCount(unfold? qMax(1, b.layout()->lineCount()) : 0);
        if (unfold) { // do not unfold folded sub-blocks
            if (isFolded(b) && b.next().isValid()) {
                int jndent = foldingIndent(b);
                b = b.next();
                while (b.isValid() && foldingIndent(b) > jndent)
                    b = b.next();
                continue;
            }
        }
        b = b.next();
    }
    setFolded(block, !unfold);
}

724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
void BaseTextDocumentLayout::setRequiredWidth(int width)
{
    int oldw = m_requiredWidth;
    m_requiredWidth = width;
    int dw = QPlainTextDocumentLayout::documentSize().width();
    if (oldw > dw || width > dw)
        emitDocumentSizeChanged();
}


QSizeF BaseTextDocumentLayout::documentSize() const
{
    QSizeF size = QPlainTextDocumentLayout::documentSize();
    size.setWidth(qMax((qreal)m_requiredWidth, size.width()));
    return size;
}
740

741
TextMarks BaseTextDocumentLayout::documentClosing()
742
{
743
    TextMarks marks;
744
745
746
    QTextBlock block = document()->begin();
    while (block.isValid()) {
        if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData()))
747
            marks.append(data->documentClosing());
748
749
        block = block.next();
    }
750
    return marks;
751
752
}

753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
void BaseTextDocumentLayout::documentReloaded(TextMarks marks)
{
    foreach (ITextMark *mark, marks) {
        int blockNumber = mark->lineNumber() - 1;
        QTextBlock block = document()->findBlockByNumber(blockNumber);
        if (block.isValid()) {
            TextBlockUserData *userData = BaseTextDocumentLayout::userData(block);
            userData->addMark(mark);
            mark->setMarkableInterface(m_documentMarker);
            mark->updateBlock(block);
        } else {
            TextEditor::Internal::DocumentMarker *documentMarker
                    = static_cast<TextEditor::Internal::DocumentMarker *>(m_documentMarker);
            documentMarker->removeMarkFromMarksCache(mark);
            mark->removedFromEditor();
768
            mark->setMarkableInterface(0);
769
770
771
772
        }
    }
    requestUpdate();
}
773

774
775
void BaseTextDocumentLayout::updateMarksLineNumber()
{
776
777
    // Note: the breakpointmanger deletes breakpoint marks and readds them
    // if it doesn't agree with our updating
778
779
780
781
    QTextBlock block = document()->begin();
    int blockNumber = 0;
    while (block.isValid()) {
        if (const TextBlockUserData *userData = testUserData(block))
782
            foreach (ITextMark *mrk, userData->marks())
783
784
785
786
787
788
789
790
791
792
793
794
795
                mrk->updateLineNumber(blockNumber + 1);
        block = block.next();
        ++blockNumber;
    }
}

void BaseTextDocumentLayout::updateMarksBlock(const QTextBlock &block)
{
    if (const TextBlockUserData *userData = testUserData(block))
        foreach (ITextMark *mrk, userData->marks())
            mrk->updateBlock(block);
}

796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
BaseTextDocumentLayout::FoldValidator::FoldValidator()
    : m_layout(0)
    , m_requestDocUpdate(false)
    , m_insideFold(0)
{}

void BaseTextDocumentLayout::FoldValidator::setup(BaseTextDocumentLayout *layout)
{
    m_layout = layout;
}

void BaseTextDocumentLayout::FoldValidator::reset()
{
    m_insideFold = 0;
    m_requestDocUpdate = false;
}

void BaseTextDocumentLayout::FoldValidator::process(QTextBlock block)
{
    if (!m_layout)
        return;

    const QTextBlock &previous = block.previous();
    if (!previous.isValid())
        return;

    if ((BaseTextDocumentLayout::isFolded(previous)
            && !BaseTextDocumentLayout::canFold(previous))
            || (!BaseTextDocumentLayout::isFolded(previous)
                && BaseTextDocumentLayout::canFold(previous)
                && !block.isVisible())) {
        BaseTextDocumentLayout::setFolded(previous, !BaseTextDocumentLayout::isFolded(previous));
    }

    if (BaseTextDocumentLayout::isFolded(previous) && !m_insideFold)
        m_insideFold = BaseTextDocumentLayout::foldingIndent(block);

    bool toggleVisibility = false;
    if (m_insideFold) {
        if (BaseTextDocumentLayout::foldingIndent(block) >= m_insideFold) {
            if (block.isVisible())
                toggleVisibility = true;
        } else {
            m_insideFold = 0;
            if (!block.isVisible())
                toggleVisibility = true;
        }
    } else if (!block.isVisible()) {
        toggleVisibility = true;
    }

    if (toggleVisibility) {
        block.setVisible(!block.isVisible());
        block.setLineCount(block.isVisible() ? qMax(1, block.layout()->lineCount()) : 0);
        m_requestDocUpdate = true;
    }
}

void BaseTextDocumentLayout::FoldValidator::finalize()
{
    if (m_requestDocUpdate && m_layout) {
        m_layout->requestUpdate();
        m_layout->emitDocumentSizeChanged();
    }
}
861
862

#include "basetextdocumentlayout.moc"