-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtextdocument.cpp
1895 lines (1731 loc) · 57.7 KB
/
textdocument.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
247
248
249
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
286
287
288
289
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
423
424
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "textdocument.h"
#include "textcursor.h"
#include "textcursor_p.h"
#include "textdocument_p.h"
#include <QBuffer>
#include <QIODevice>
#include <QObject>
#include <QString>
#include <QString>
#include <QFile>
#include <QFileInfo>
#include <QList>
#include <QTextCharFormat>
#include <QVariant>
#include <QDesktopServices>
#include <qalgorithms.h>
// #define DEBUG_CACHE_HITS
#ifndef TEXTDOCUMENT_FIND_INTERVAL_PERCENTAGE
#define TEXTDOCUMENT_FIND_INTERVAL_PERCENTAGE 1000
#endif
#ifndef TEXTDOCUMENT_MAX_INTERVAL
#define TEXTDOCUMENT_MAX_INTERVAL 1000
#endif
#ifdef TEXTDOCUMENT_FIND_SLEEP
static void findSleep(const TextDocument *document)
{
Q_ASSERT(document);
const int duration = document->property("TEXTDOCUMENT_FIND_SLEEP").toInt();
if (duration > 0) {
usleep(duration * 1000);
}
}
#endif
TextDocument::TextDocument(QObject *parent)
: QObject(parent), d(new TextDocumentPrivate(this))
{
}
TextDocument::~TextDocument()
{
{
QWriteLocker locker(d->readWriteLock);
foreach(TextCursorSharedPrivate *cursor, d->textCursors) {
cursor->document = 0;
}
Chunk *c = d->first;
while (c) {
if (!(d->options & KeepTemporaryFiles) && !c->swap.isEmpty())
QFile::remove(c->swap);
Chunk *tmp = c;
c = c->next;
delete tmp;
}
foreach(TextSection *section, d->sections) {
section->d.document = 0;
section->d.textEdit = 0;
delete section;
}
if (d->ownDevice)
delete d->device.data();
}
delete d->readWriteLock;
delete d;
}
bool TextDocument::load(QIODevice *device, DeviceMode mode, QTextCodec *codec)
{
QWriteLocker locker(d->readWriteLock);
Q_ASSERT(device);
if (!device->isReadable())
return false;
Options options = d->options;
if (options & ConvertCarriageReturns && mode == Sparse) {
qWarning("TextDocument::load() ConvertCarriageReturns is incompatible with Sparse");
options &= ~ConvertCarriageReturns;
}
if ((options & (AutoDetectCarriageReturns|ConvertCarriageReturns)) == (AutoDetectCarriageReturns|ConvertCarriageReturns))
options &= ~AutoDetectCarriageReturns;
foreach(TextSection *section, d->sections) {
emit sectionRemoved(section);
section->d.document = 0;
delete section;
}
d->sections.clear();
if (d->documentSize > 0) {
emit charactersRemoved(0, d->documentSize);
}
Chunk *c = d->first;
while (c) {
Chunk *tmp = c;
c = c->next;
delete tmp;
}
d->textCodec = codec;
d->documentSize = device->size();
if (d->documentSize <= d->chunkSize && mode == Sparse && !(options & NoImplicitLoadAll))
mode = LoadAll;
#if 0
if (codec && mode == Sparse) {
qWarning("Sparse mode doesn't really work with unicode data yet. I am working on it.\n--\nAnders");
}
#endif
d->first = d->last = 0;
if (d->device) {
if (d->ownDevice && d->device.data() != device) // this is done when saving to the same file
delete d->device.data();
}
d->ownDevice = false;
d->device = device;
d->deviceMode = mode;
#ifndef NO_TEXTDOCUMENT_CHUNK_CACHE
d->cachedChunk = 0;
d->cachedChunkPos = -1;
d->cachedChunkData.clear();
#endif
#ifndef NO_TEXTDOCUMENT_READ_CACHE
d->cachePos = -1;
d->cache.clear();
#endif
switch (d->deviceMode) {
case LoadAll: {
device->seek(0);
QTextStream ts(device);
if (d->textCodec)
ts.setCodec(d->textCodec);
Chunk *current = 0;
d->documentSize = 0; // in case of unicode
do {
Chunk *c = new Chunk;
c->data = ts.read(d->chunkSize);
if (options & AutoDetectCarriageReturns) {
if (c->data.contains(QLatin1Char('\n'))) {
options |= ConvertCarriageReturns;
}
options &= ~AutoDetectCarriageReturns;
}
if (options & ConvertCarriageReturns)
c->data.remove(QLatin1Char('\r'));
d->documentSize += c->data.size();
if (current) {
current->next = c;
c->previous = current;
} else {
d->first = c;
}
current = c;
} while (!ts.atEnd());
d->last = current;
break; }
case Sparse: {
int index = 0;
Chunk *current = 0;
do {
Chunk *chunk = new Chunk;
chunk->from = index;
chunk->length = qMin<int>(d->documentSize - index, d->chunkSize);
if (!current) {
d->first = chunk;
} else {
chunk->previous = current;
current->next = chunk;
}
current = chunk;
index += chunk->length;
} while (index < d->documentSize);
d->last = current;
break; }
}
// if (d->first)
// d->first->firstLineIndex = 0;
emit charactersAdded(0, d->documentSize);
emit documentSizeChanged(d->documentSize);
emit textChanged();
setModified(false);
return true;
}
bool TextDocument::load(const QString &fileName, DeviceMode mode, QTextCodec *codec)
{
if (mode == LoadAll) {
QFile from(fileName);
return from.open(QIODevice::ReadOnly) && load(&from, mode, codec);
} else {
QFile *file = new QFile(fileName);
if (file->open(QIODevice::ReadOnly) && load(file, mode, codec)) {
d->ownDevice = true;
return true;
} else {
delete file;
d->ownDevice = false;
return false;
}
}
}
void TextDocument::clear()
{
setText(QString());
}
QString TextDocument::read(int pos, int size) const
{
QReadLocker locker(d->readWriteLock);
Q_ASSERT(size >= 0);
if (size == 0 || pos == d->documentSize) {
return QString();
}
Q_ASSERT(pos < d->documentSize);
#ifndef NO_TEXTDOCUMENT_READ_CACHE
#ifdef DEBUG_CACHE_HITS
static int hits = 0;
static int misses = 0;
#endif
if (d->cachePos != -1 && pos >= d->cachePos && d->cache.size() - (pos - d->cachePos) >= size) {
#ifdef DEBUG_CACHE_HITS
qWarning() << "read hits" << ++hits << "misses" << misses;
#endif
return d->cache.mid(pos - d->cachePos, size);
}
#ifdef DEBUG_CACHE_HITS
qWarning() << "read hits" << hits << "misses" << ++misses;
#endif
#endif
QString ret(size, '\0');
int written = 0;
int offset;
Chunk *c = d->chunkAt(pos, &offset);
Q_ASSERT(c);
int chunkPos = pos - offset;
while (written < size && c) {
const int max = qMin(size - written, c->size() - offset);
const QString data = d->chunkData(c, chunkPos);
chunkPos += data.size();
ret.replace(written, max, data.constData() + offset, max);
written += max;
offset = 0;
c = c->next;
}
if (written < size) {
ret.truncate(written);
}
Q_ASSERT(!c || written == size);
#ifndef NO_TEXTDOCUMENT_READ_CACHE
d->cachePos = pos;
d->cache = ret;
#endif
return ret;
}
QStringRef TextDocument::readRef(int pos, int size) const
{
QReadLocker locker(d->readWriteLock);
int offset;
Chunk *c = d->chunkAt(pos, &offset);
if (c && pos + offset + size <= c->size()) {
const QString string = d->chunkData(c, pos - offset);
return string.midRef(offset, size);
}
return QStringRef();
}
bool TextDocument::save(const QString &file)
{
QFile from(file);
return from.open(QIODevice::WriteOnly) && save(&from);
}
bool TextDocument::save()
{
return d->device && save(d->device.data());
}
static bool isSameFile(const QIODevice *left, const QIODevice *right)
{
if (left == right)
return true;
if (const QFile *lf = qobject_cast<const QFile *>(left)) {
if (const QFile *rf = qobject_cast<const QFile *>(right)) {
return QFileInfo(*lf) == QFileInfo(*rf);
}
}
return false;
}
bool TextDocument::save(QIODevice *device)
{
QReadLocker locker(d->readWriteLock);
Q_ASSERT(device);
if (::isSameFile(d->device.data(), device)) {
QTemporaryFile tmp(0);
if (!tmp.open())
return false;
if (save(&tmp)) {
Q_ASSERT(qobject_cast<QFile*>(device));
Q_ASSERT(qobject_cast<QFile*>(d->device));
d->device.data()->close();
d->device.data()->open(QIODevice::WriteOnly);
tmp.seek(0);
const int chunkSize = 128; //1024 * 16;
char chunk[chunkSize];
forever {
const qint64 read = tmp.read(chunk, chunkSize);
switch (read) {
case -1: return false;
case 0: return true;
default:
if (d->device.data()->write(chunk, read) != read) {
return false;
}
break;
}
}
d->device.data()->close();
d->device.data()->open(QIODevice::ReadOnly);
if (d->deviceMode == Sparse) {
qDeleteAll(d->undoRedoStack);
d->undoRedoStack.clear();
d->undoRedoStackCurrent = 0;
#ifndef NO_TEXTDOCUMENT_CHUNK_CACHE
d->cachedChunkPos = -1;
d->cachedChunk = 0;
d->cachedChunkData.clear();
#endif
Chunk *c = d->first;
int pos = 0;
while (c) {
Q_ASSERT((c->from == -1) == (c->length == -1));
if (c->from == -1) { // unload chunks from memory
c->from = pos;
c->length = c->data.size();
c->data.clear();
}
pos += c->length;
c = c->next;
}
}
return true;
// return load(d->device, d->deviceMode);
}
return false;
}
Q_ASSERT(device);
if (!device->isWritable() || !d->first) {
return false;
}
d->saveState = TextDocumentPrivate::Saving;
const Chunk *c = d->first;
emit saveProgress(0.0);
int written = 0;
QTextStream ts(device);
if (d->textCodec)
ts.setCodec(d->textCodec);
while (c) {
ts << d->chunkData(c, written);
written += c->size();
if (c != d->last) {
const double part = qreal(written) / double(d->documentSize);
emit saveProgress(part * 100.0);
}
if (d->saveState == TextDocumentPrivate::AbortSave) {
d->saveState = TextDocumentPrivate::NotSaving;
return false;
}
c = c->next;
}
d->saveState = TextDocumentPrivate::NotSaving;
emit saveProgress(100.0);
return true;
}
int TextDocument::documentSize() const
{
QReadLocker locker(d->readWriteLock);
return d->documentSize;
}
int TextDocument::chunkCount() const
{
QReadLocker locker(d->readWriteLock);
Chunk *c = d->first;
int count = 0;
while (c) {
++count;
c = c->next;
}
return count;
}
int TextDocument::instantiatedChunkCount() const
{
QReadLocker locker(d->readWriteLock);
Chunk *c = d->first;
int count = 0;
while (c) {
if (!c->data.isEmpty())
++count;
c = c->next;
}
return count;
}
int TextDocument::swappedChunkCount() const
{
QReadLocker locker(d->readWriteLock);
Chunk *c = d->first;
int count = 0;
while (c) {
if (!c->swap.isEmpty())
++count;
c = c->next;
}
return count;
}
TextDocument::DeviceMode TextDocument::deviceMode() const
{
QReadLocker locker(d->readWriteLock);
return d->deviceMode;
}
QTextCodec * TextDocument::textCodec() const
{
QReadLocker locker(d->readWriteLock);
return d->textCodec;
}
class FindScope
{
public:
FindScope(TextDocumentPrivate::FindState *s) : state(s) { if (state) *state = TextDocumentPrivate::Finding; }
~FindScope() { if (state) *state = TextDocumentPrivate::NotFinding; }
TextDocumentPrivate::FindState *state;
};
static void initFind(const TextCursor &cursor, bool reverse, int *start, int *limit)
{
if (cursor.hasSelection()) {
*start = cursor.selectionStart();
*limit = cursor.selectionEnd();
if (reverse) {
qSwap(*start, *limit);
}
} else {
*start = cursor.position();
*limit = (reverse ? 0 : cursor.document()->documentSize());
}
}
TextCursor TextDocument::find(const QRegExp ®exp, const TextCursor &cursor, FindMode flags) const
{
QReadLocker locker(d->readWriteLock);
if (flags & FindWholeWords) {
qWarning("FindWholeWords doesn't work with regexps. Instead use an actual RegExp for this");
}
if (flags & FindCaseSensitively) {
qWarning("FindCaseSensitively doesn't work with regexps. Instead use an QRegExp::caseSensitivity for this");
}
if (flags & FindWrap && cursor.hasSelection()) {
qWarning("It makes no sense to pass FindWrap and set a selection for the cursor. The entire selection will be searched");
flags &= ~FindWrap;
}
const bool reverse = flags & FindBackward;
int pos;
int limit;
::initFind(cursor, reverse, &pos, &limit);
if (pos == d->documentSize) {
if (reverse) {
--pos;
} else if (!(flags & FindWrap)) {
return TextCursor();
}
}
const TextDocumentIterator::Direction direction = (reverse
? TextDocumentIterator::Left
: TextDocumentIterator::Right);
TextDocumentIterator it(d, pos);
if (reverse) {
it.setMinBoundary(limit);
} else {
it.setMaxBoundary(limit);
}
const QLatin1Char newline('\n');
int last = pos;
bool ok = true;
int progressInterval = 0;
int lastProgress = pos;
const int initialPos = pos;
int maxFindLength = 0;
const FindScope scope(flags & FindAllowInterrupt ? &d->findState : 0);
QTime lastProgressTime;
if (flags & FindAllowInterrupt) {
progressInterval = qMax<int>(1, (reverse
? (static_cast<qreal>(pos) / static_cast<qreal>(TEXTDOCUMENT_FIND_INTERVAL_PERCENTAGE))
: (static_cast<qreal>(d->documentSize) - static_cast<qreal>(pos)) / 100.0));
maxFindLength = (reverse ? pos : d->documentSize - pos);
lastProgressTime.start();
}
do {
#ifdef TEXTDOCUMENT_FIND_SLEEP
findSleep(this);
#endif
while ((it.nextPrev(direction, ok) != newline) && ok) ;
int from = qMin(it.position(), last);
int to = qMax(it.position(), last);
if (!ok) {
if (direction == TextDocumentIterator::Right)
++to;
} else if (direction == TextDocumentIterator::Left) {
++from;
++to;
}
const QString line = read(from, to - from);
last = it.position() + 1;
int lineIndex = reverse ? line.size() : 0;
bool done;
do {
done = true;
const int index = (reverse ? regexp.lastIndexIn(line, lineIndex) : regexp.indexIn(line, lineIndex));
if (index != -1) {
if (!reverse && from + index + regexp.matchedLength() > limit) {
ok = false;
break;
}
const TextCursor ret(this, from + index + regexp.matchedLength(), from + index);
Q_ASSERT(ret.selectedText() == regexp.capturedTexts().first());
if (flags & FindAll) {
emit entryFound(ret);
if (reverse) {
lineIndex = index;
} else {
lineIndex = index + regexp.matchedLength();
}
done = false;
if (d->findState == TextDocumentPrivate::AbortFind)
return TextCursor();
} else {
return ret;
}
}
} while (!done);
if (progressInterval != 0) {
const int progress = qAbs(it.position() - lastProgress);
if (progress >= progressInterval
|| (lastProgressTime.elapsed() >= TEXTDOCUMENT_MAX_INTERVAL)) {
const qreal progress = qAbs<int>(static_cast<qreal>(it.position() - initialPos)) / static_cast<qreal>(maxFindLength);
emit findProgress(progress * 100.0, it.position());
if (d->findState == TextDocumentPrivate::AbortFind) {
return TextCursor();
}
lastProgress = it.position();
lastProgressTime.restart();
}
}
} while (ok);
if (flags & FindWrap) {
Q_ASSERT(!cursor.hasSelection());
if (reverse) {
if (cursor.position() + 1 < d->documentSize) {
return find(regexp, TextCursor(this, cursor.position(), d->documentSize), flags & ~FindWrap);
}
} else if (cursor.position() > 0) {
return find(regexp, TextCursor(this, 0, cursor.position()), flags & ~FindWrap);
}
}
return TextCursor();
}
TextCursor TextDocument::find(const QString &in, const TextCursor &cursor, FindMode flags) const
{
if (in.isEmpty()) {
return TextCursor();
} else if (in.size() == 1) {
return find(in.at(0), cursor, flags);
}
QReadLocker locker(d->readWriteLock);
const bool reverse = flags & FindBackward;
const bool caseSensitive = flags & FindCaseSensitively;
const bool wholeWords = flags & FindWholeWords;
if (flags & FindWrap && cursor.hasSelection()) {
qWarning("It makes no sense to pass FindWrap and set a selection for the cursor. The entire selection will be searched");
flags &= ~FindWrap;
}
int pos;
int limit;
::initFind(cursor, reverse, &pos, &limit);
if (pos == d->documentSize) {
if (reverse) {
--pos;
} else if (!(flags & FindWrap)) {
return TextCursor();
}
}
// ### what if one searches for a string with non-word characters in it and FindWholeWords?
const TextDocumentIterator::Direction direction = (reverse ? TextDocumentIterator::Left : TextDocumentIterator::Right);
QString word = caseSensitive ? in : in.toLower();
if (reverse) {
QChar *data = word.data();
const int size = word.size();
for (int i=0; i<size / 2; ++i) {
qSwap(data[i], data[size - 1 - i]);
}
}
TextDocumentIterator it(d, pos);
if (reverse) {
it.setMinBoundary(limit);
} else {
it.setMaxBoundary(limit);
}
if (!caseSensitive)
it.setConvertToLowerCase(true);
bool ok = true;
QChar ch = it.current();
int wordIndex = 0;
int progressInterval = 0;
int lastProgress = pos;
const int initialPos = pos;
int maxFindLength = 0;
const FindScope scope(flags & FindAllowInterrupt ? &d->findState : 0);
QTime lastProgressTime;
if (flags & FindAllowInterrupt) {
progressInterval = qMax<int>(1, (reverse
? (static_cast<qreal>(pos) / static_cast<qreal>(TEXTDOCUMENT_FIND_INTERVAL_PERCENTAGE))
: (static_cast<qreal>(d->documentSize) - static_cast<qreal>(pos)) / 100.0));
maxFindLength = (reverse ? pos : d->documentSize - pos);
lastProgressTime.start();
}
do {
#ifdef TEXTDOCUMENT_FIND_SLEEP
findSleep(this);
#endif
if (progressInterval != 0) {
const int progress = qAbs(it.position() - lastProgress);
if (progress >= progressInterval
|| (progress % 10 == 0 && lastProgressTime.elapsed() >= TEXTDOCUMENT_MAX_INTERVAL)) {
const qreal progress = qAbs<int>(static_cast<qreal>(it.position() - initialPos)) / static_cast<qreal>(maxFindLength);
emit findProgress(progress * 100.0, it.position());
if (d->findState == TextDocumentPrivate::AbortFind) {
return TextCursor();
}
lastProgress = it.position();
lastProgressTime.restart();
}
}
bool found = ch == word.at(wordIndex);
if (found && wholeWords && (wordIndex == 0 || wordIndex == word.size() - 1)) {
Q_ASSERT(word.size() > 1);
const uint requiredBounds = ((wordIndex == 0) != reverse)
? TextDocumentIterator::Left
: TextDocumentIterator::Right;
const uint bounds = d->wordBoundariesAt(it.position());
if (requiredBounds & ~bounds) {
found = false;
}
}
if (found) {
if (++wordIndex == word.size()) {
const int pos = it.position() - (reverse ? 0 : word.size() - 1);
// the iterator reads one past the last matched character so we have to account for that here
const TextCursor ret(this, pos + wordIndex, pos);
if (flags & FindAll) {
emit entryFound(ret);
if (d->findState == TextDocumentPrivate::AbortFind)
return TextCursor();
wordIndex = 0;
} else {
return ret;
}
}
} else if (wordIndex != 0) {
wordIndex = 0;
continue;
}
ch = it.nextPrev(direction, ok);
} while (ok);
if (flags & FindWrap) {
Q_ASSERT(!cursor.hasSelection());
if (reverse) {
if (cursor.position() + 1 < d->documentSize) {
return find(in, TextCursor(this, cursor.position(), d->documentSize), flags & ~FindWrap);
}
} else if (cursor.position() > 0) {
return find(in, TextCursor(this, 0, cursor.position()), flags & ~FindWrap);
}
}
return TextCursor();
}
TextCursor TextDocument::find(const QChar &chIn, const TextCursor &cursor, FindMode flags) const
{
QReadLocker locker(d->readWriteLock);
if (flags & FindWrap && cursor.hasSelection()) {
qWarning("It makes no sense to pass FindWrap and set a selection for the cursor. The entire selection will be searched");
flags &= ~FindWrap;
}
const bool reverse = flags & FindBackward;
int pos;
int limit;
::initFind(cursor, reverse, &pos, &limit);
if (pos == d->documentSize) {
if (reverse) {
--pos;
} else if (!(flags & FindWrap)) {
return TextCursor();
}
}
Q_ASSERT(pos >= 0 && pos <= d->documentSize);
const bool caseSensitive = flags & FindCaseSensitively;
const bool wholeWords = flags & FindWholeWords;
const QChar ch = (caseSensitive ? chIn : chIn.toLower());
TextDocumentIterator it(d, pos);
if (reverse) {
it.setMinBoundary(limit);
} else {
it.setMaxBoundary(limit);
}
const TextDocumentIterator::Direction dir = (reverse
? TextDocumentIterator::Left
: TextDocumentIterator::Right);
int lastProgress = pos;
const int initialPos = pos;
int maxFindLength = 0;
int progressInterval = 0;
const FindScope scope(flags & FindAllowInterrupt ? &d->findState : 0);
QTime lastProgressTime;
if (flags & FindAllowInterrupt) {
progressInterval = qMax<int>(1, (reverse
? (static_cast<qreal>(pos) / static_cast<qreal>(TEXTDOCUMENT_FIND_INTERVAL_PERCENTAGE))
: (static_cast<qreal>(d->documentSize) - static_cast<qreal>(pos)) / 100.0));
maxFindLength = (reverse ? pos : d->documentSize - pos);
lastProgressTime.start();
}
QChar c = it.current();
bool ok = true;
do {
#ifdef TEXTDOCUMENT_FIND_SLEEP
findSleep(this);
#endif
if (((caseSensitive ? c : c.toLower()) == ch)
&& (!wholeWords || (d->wordBoundariesAt(it.position()) == TextDocumentIterator::Both))) {
const TextCursor ret(this, it.position() + 1, it.position());
if (flags & FindAll) {
emit entryFound(ret);
if (d->findState == TextDocumentPrivate::AbortFind)
return TextCursor();
} else {
return ret;
}
}
c = it.nextPrev(dir, ok);
// qDebug() << "progressInterval" << progressInterval << qAbs(it.position() - lastProgress)
// << lastProgressTime.elapsed() << TEXTDOCUMENT_MAX_INTERVAL;
if (progressInterval != 0) {
const int progress = qAbs(it.position() - lastProgress);
if (progress >= progressInterval
|| (progress % 10 == 0 && lastProgressTime.elapsed() >= TEXTDOCUMENT_MAX_INTERVAL)) {
const qreal progress = qAbs<int>(static_cast<qreal>(it.position() - initialPos)) / static_cast<qreal>(maxFindLength);
emit findProgress(progress * 100.0, it.position());
if (d->findState == TextDocumentPrivate::AbortFind) {
return TextCursor();
}
lastProgress = it.position();
lastProgressTime.restart();
}
}
} while (ok);
if (flags & FindWrap) {
Q_ASSERT(!cursor.hasSelection());
if (reverse) {
if (cursor.position() + 1 < d->documentSize) {
return find(ch, TextCursor(this, cursor.position(), d->documentSize), flags & ~FindWrap);
}
} else if (cursor.position() > 0) {
return find(ch, TextCursor(this, 0, cursor.position()), flags & ~FindWrap);
}
}
return TextCursor();
}
bool TextDocument::insert(int pos, const QString &string)
{
QWriteLocker locker(d->readWriteLock);
#ifdef QT_DEBUG
Q_ASSERT(d->iterators.isEmpty());
#endif
Q_ASSERT(pos >= 0 && pos <= d->documentSize);
if (string.isEmpty())
return false;
const bool undoAvailable = isUndoAvailable();
DocumentCommand *cmd = 0;
if (!d->ignoreUndoRedo && d->undoRedoEnabled && d->cursorCommand) { // can only undo commands from
d->clearRedo();
if (d->collapseInsertUndo
&& !d->undoRedoStack.isEmpty()
&& d->undoRedoStack.last()->type == DocumentCommand::Inserted
&& d->undoRedoStack.last()->position + d->undoRedoStack.last()->text.size() == pos) {
d->undoRedoStack.last()->text += string;
} else {
cmd = new DocumentCommand(DocumentCommand::Inserted, pos, string);
if (!d->modified)
d->modifiedIndex = d->undoRedoStackCurrent;
emit d->undoRedoCommandInserted(cmd);
d->undoRedoStack.append(cmd);
++d->undoRedoStackCurrent;
Q_ASSERT(d->undoRedoStackCurrent == d->undoRedoStack.size());
}
}
d->modified = true;
Chunk *c;
int offset;
c = d->chunkAt(pos, &offset);
// qDebug() << c << (c == d->last) << (c == d->first) << offset << c->size() << d->chunkSize;
if (c == d->last && offset == c->size() && c->size() >= d->chunkSize) {
Chunk *chunk = new Chunk;
c->next = chunk;
chunk->previous = c;
d->last = chunk;
offset = 0;
chunk->data = string;
d->documentSize += string.size();
if (d->options & SwapChunks) {
if (c->previous) {
d->swapOutChunk(c->previous);
}
}
c = chunk;
} else {
d->instantiateChunk(c);
#ifndef NO_TEXTDOCUMENT_CHUNK_CACHE
if (c == d->cachedChunk) {
d->cachedChunkData.clear(); // avoid detach when inserting
}
#endif
c->data.insert(offset, string);
#ifndef NO_TEXTDOCUMENT_CHUNK_CACHE
if (c == d->cachedChunk) {
d->cachedChunkData = c->data;
} else if (pos <= d->cachedChunkPos) {
Q_ASSERT(d->cachedChunk);
d->cachedChunkPos += string.size();
}
#endif
#ifndef NO_TEXTDOCUMENT_READ_CACHE
if (pos <= d->cachePos) {
d->cachePos += string.size();
} else if (pos < d->cachePos + d->cache.size()) {
d->cachePos = -1;
d->cache.clear();
}
#endif
TextSection *s = d->sectionAt(pos, 0);
if (s && s->position() != pos) {
s->d.size += string.size();
}
d->documentSize += string.size();
foreach(TextCursorSharedPrivate *cursor, d->textCursors) {
if (cursor->position >= pos)
cursor->position += string.size();
if (cursor->anchor >= pos)
cursor->anchor += string.size();
}
foreach(TextSection *section, d->getSections(pos, -1, 0, 0)) {
section->d.position += string.size();
}
if (d->hasChunksWithLineNumbers && c->firstLineIndex != -1) {
const int extraLines = string.count(QLatin1Char('\n'));
if (extraLines != 0) {
#ifdef TEXTDOCUMENT_LINENUMBER_CACHE
c->lineNumbers.clear();
// ### could be optimized
#else
Q_ASSERT(c->lines != -1);
c->lines += extraLines;
#endif
c = c->next;
while (c) {
if (c->firstLineIndex != -1) {
// qDebug() << "changing chunk number" << d->chunkIndex(c)
// << "starting with" << d->chunkData(c, -1).left(5)
// << "from" << c->firstLineIndex << "to" << (c->firstLineIndex + extraLines);
c->firstLineIndex += extraLines;
}
c = c->next;
}
}
}
}
emit charactersAdded(pos, string.size());
emit documentSizeChanged(d->documentSize);
if (isUndoAvailable() != undoAvailable) {
emit undoAvailableChanged(!undoAvailable);
}
if (cmd)
emit d->undoRedoCommandFinished(cmd);
emit textChanged();
return true;
}
static inline int count(const QString &string, int from, int size, const QChar &ch)
{
Q_ASSERT(from + size <= string.size());
const ushort needle = ch.unicode();
const ushort *haystack = string.utf16() + from;
int num = 0;
for (int i=0; i<size; ++i) {
if (*haystack++ == needle)
++num;
}
// Q_ASSERT(string.mid(from, size).count(ch) == num);
return num;
}
void TextDocument::remove(int pos, int size)
{
QWriteLocker locker(d->readWriteLock);
#ifdef QT_DEBUG
Q_ASSERT(d->iterators.isEmpty());
#endif
Q_ASSERT(pos >= 0 && pos + size <= d->documentSize);
Q_ASSERT(size >= 0);
if (size == 0)
return;
DocumentCommand *cmd = 0;
const bool undoAvailable = isUndoAvailable();
if (!d->ignoreUndoRedo && d->undoRedoEnabled && d->cursorCommand) {
d->clearRedo();
if (!d->undoRedoStack.isEmpty()
&& d->undoRedoStack.last()->type == DocumentCommand::Removed
&& d->undoRedoStack.last()->position == pos + size) {
d->undoRedoStack.last()->text.prepend(read(pos, size));
d->undoRedoStack.last()->position -= size;
} else {
cmd = new DocumentCommand(DocumentCommand::Removed, pos, read(pos, size));
if (!d->modified)
d->modifiedIndex = d->undoRedoStackCurrent;
emit d->undoRedoCommandInserted(cmd);
d->undoRedoStack.append(cmd);
++d->undoRedoStackCurrent;
Q_ASSERT(d->undoRedoStackCurrent == d->undoRedoStack.size());
}
}
d->modified = true;
int toRemove = size;
int newLinesRemoved = 0;