forked from gnachman/iTerm2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LineBuffer.m
964 lines (885 loc) · 32.4 KB
/
LineBuffer.m
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
// -*- mode:objc -*-
// $Id: $
/*
** LineBuffer.h
**
** Copyright (c) 2002, 2003
**
** Author: George Nachman
**
** Project: iTerm
**
** Description: Implements a buffer of lines. It can hold a large number
** of lines and can quickly format them to a fixed width.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#import "LineBuffer.h"
#import "BackgroundThread.h"
#import "LineBlock.h"
#import "RegexKitLite/RegexKitLite.h"
@implementation LineBuffer
// Append a block
- (LineBlock*) _addBlockOfSize: (int) size
{
LineBlock* block = [[LineBlock alloc] initWithRawBufferSize: size];
block.mayHaveDoubleWidthCharacter = self.mayHaveDoubleWidthCharacter;
[blocks addObject:block];
[block release];
return block;
}
// The designated initializer. We prefer not to explose the notion of block sizes to
// clients, so this is internal.
- (LineBuffer*)initWithBlockSize:(int)bs
{
self = [super init];
if (self) {
block_size = bs;
blocks = [[NSMutableArray alloc] initWithCapacity: 1];
[self _addBlockOfSize: block_size];
max_lines = -1;
num_wrapped_lines_width = -1;
num_dropped_blocks = 0;
}
return self;
}
- (void)dealloc
{
// This causes the blocks to be released in a background thread.
// When a LineBuffer is really gigantic, it can take
// quite a bit of time to release all the blocks.
[blocks performSelector:@selector(removeAllObjects)
onThread:[BackgroundThread backgroundThread]
withObject:nil
waitUntilDone:NO];
[blocks release];
[super dealloc];
}
- (void)setMayHaveDoubleWidthCharacter:(BOOL)mayHaveDoubleWidthCharacter {
if (!_mayHaveDoubleWidthCharacter) {
_mayHaveDoubleWidthCharacter = mayHaveDoubleWidthCharacter;
for (LineBlock *block in blocks) {
block.mayHaveDoubleWidthCharacter = YES;
}
}
}
// This is called a lot so it's a C function to avoid obj_msgSend
static int RawNumLines(LineBuffer* buffer, int width) {
if (buffer->num_wrapped_lines_width == width) {
return buffer->num_wrapped_lines_cache;
}
int count = 0;
int i;
const int numBlocks = [buffer->blocks count];
for (i = 0; i < numBlocks; ++i) {
LineBlock* block = [buffer->blocks objectAtIndex: i];
count += [block getNumLinesWithWrapWidth: width];
}
buffer->num_wrapped_lines_width = width;
buffer->num_wrapped_lines_cache = count;
return count;
}
- (void) setMaxLines: (int) maxLines
{
max_lines = maxLines;
num_wrapped_lines_width = -1;
}
- (int)dropExcessLinesWithWidth: (int) width
{
int nl = RawNumLines(self, width);
int totalDropped = 0;
if (max_lines != -1 && nl > max_lines) {
LineBlock *block = blocks[0];
int total_lines = nl;
while (total_lines > max_lines) {
int extra_lines = total_lines - max_lines;
int block_lines = [block getNumLinesWithWrapWidth: width];
#if ITERM_DEBUG
NSAssert(block_lines > 0, @"Empty leading block");
#endif
int toDrop = block_lines;
if (toDrop > extra_lines) {
toDrop = extra_lines;
}
int charsDropped;
int dropped = [block dropLines:toDrop withWidth:width chars:&charsDropped];
totalDropped += dropped;
droppedChars += charsDropped;
if ([block isEmpty]) {
[blocks removeObjectAtIndex:0];
++num_dropped_blocks;
if ([blocks count] > 0) {
block = blocks[0];
}
}
total_lines -= dropped;
}
num_wrapped_lines_cache = total_lines;
}
#if ITERM_DEBUG
assert(totalDropped == (nl - RawNumLines(self, width)));
#endif
return totalDropped;
}
- (NSString *)debugString {
NSMutableString *s = [NSMutableString string];
for (int i = 0; i < [blocks count]; i++) {
LineBlock *block = [blocks objectAtIndex:i];
[block appendToDebugString:s];
}
return [s length] ? [s substringToIndex:s.length - 1] : @""; // strip trailing newline
}
- (void) dump
{
int i;
int rawOffset = 0;
for (i = 0; i < [blocks count]; ++i) {
NSLog(@"Block %d:\n", i);
[[blocks objectAtIndex: i] dump:rawOffset];
rawOffset += [[blocks objectAtIndex:i] rawSpaceUsed];
}
}
- (NSString *)compactLineDumpWithWidth:(int)width {
NSMutableString *s = [NSMutableString string];
int n = [self numLinesWithWidth:width];
for (int i = 0; i < n; i++) {
ScreenCharArray *line = [self wrappedLineAtIndex:i width:width];
[s appendFormat:@"%@", ScreenCharArrayToStringDebug(line.line, line.length)];
for (int j = line.length; j < width; j++) {
[s appendString:@"."];
}
if (i < n - 1) {
[s appendString:@"\n"];
}
}
return s;
}
- (void)dumpWrappedToWidth:(int)width
{
NSLog(@"%@", [self compactLineDumpWithWidth:width]);
}
- (LineBuffer*)init
{
// I picked 8k because it's a multiple of the page size and should hold about 100-200 lines
// on average. Very small blocks make finding a wrapped line expensive because caching the
// number of wrapped lines is spread out over more blocks. Very large blocks are expensive
// because of the linear search through a block for the start of a wrapped line. This is
// in the middle. Ideally, the number of blocks would equal the number of wrapped lines per
// block, and this should be in that neighborhood for typical uses.
const int BLOCK_SIZE = 1024 * 8;
return [self initWithBlockSize:BLOCK_SIZE];
}
- (void)appendLine:(screen_char_t*)buffer
length:(int)length
partial:(BOOL)partial
width:(int)width
timestamp:(NSTimeInterval)timestamp
{
#ifdef LOG_MUTATIONS
{
char a[1000];
int i;
for (i = 0; i < length; i++) {
a[i] = (buffer[i].code && !buffer[i].complex) ? buffer[i].code : '.';
}
a[i] = '\0';
NSLog(@"Append: %s\n", a);
}
#endif
if ([blocks count] == 0) {
[self _addBlockOfSize: block_size];
}
LineBlock* block = [blocks objectAtIndex: ([blocks count] - 1)];
int beforeLines = [block getNumLinesWithWrapWidth:width];
if (![block appendLine:buffer length:length partial:partial width:width timestamp:timestamp]) {
// It's going to be complicated. Invalidate the number of wrapped lines
// cache.
num_wrapped_lines_width = -1;
int prefix_len = 0;
NSTimeInterval prefixTimestamp = 0;
screen_char_t* prefix = NULL;
if ([block hasPartial]) {
// There is a line that's too long for the current block to hold.
// Remove its prefix from the current block and later add the
// concatenation of prefix + buffer to a larger block.
screen_char_t* temp;
BOOL ok = [block popLastLineInto:&temp
withLength:&prefix_len
upToWidth:[block rawBufferSize]+1
timestamp:&prefixTimestamp];
assert(ok);
prefix = (screen_char_t*) malloc(MAX(1, prefix_len) * sizeof(screen_char_t));
memcpy(prefix, temp, prefix_len * sizeof(screen_char_t));
NSAssert(ok, @"hasPartial but pop failed.");
}
if ([block isEmpty]) {
// The buffer is empty but it's not large enough to hold a whole line. It must be grown.
if (partial) {
// The line is partial so we know there's more coming. Allocate enough space to hold the current line
// plus the usual block size (this is the case when the line is freaking huge).
// We could double the size to ensure better asymptotic runtime but you'd run out of memory
// faster with huge lines.
[block changeBufferSize: length + prefix_len + block_size];
} else {
// Allocate exactly enough space to hold this one line.
[block changeBufferSize: length + prefix_len];
}
} else {
// The existing buffer can't hold this line, but it has preceding line(s). Shrink it and
// allocate a new buffer that is large enough to hold this line.
[block shrinkToFit];
if (length + prefix_len > block_size) {
block = [self _addBlockOfSize: length + prefix_len];
} else {
block = [self _addBlockOfSize: block_size];
}
}
// Append the prefix if there is one (the prefix was a partial line that we're
// moving out of the last block into the new block)
if (prefix) {
BOOL ok = [block appendLine:prefix length:prefix_len partial:YES width:width timestamp:prefixTimestamp];
NSAssert(ok, @"append can't fail here");
free(prefix);
}
// Finally, append this line to the new block. We know it'll fit because we made
// enough room for it.
BOOL ok = [block appendLine:buffer length:length partial:partial width:width timestamp:timestamp];
NSAssert(ok, @"append can't fail here");
} else if (num_wrapped_lines_width == width) {
// Straightforward addition of a line to an existing block. Update the
// wrapped lines cache.
int afterLines = [block getNumLinesWithWrapWidth:width];
num_wrapped_lines_cache += (afterLines - beforeLines);
} else {
// Width change. Invalidate the wrapped lines cache.
num_wrapped_lines_width = -1;
}
}
- (NSTimeInterval)timestampForLineNumber:(int)lineNum width:(int)width
{
int line = lineNum;
int i;
for (i = 0; i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
NSAssert(block, @"Null block");
// getNumLinesWithWrapWidth caches its result for the last-used width so
// this is usually faster than calling getWrappedLineWithWrapWidth since
// most calls to the latter will just decrement line and return NULL.
int block_lines = [block getNumLinesWithWrapWidth:width];
if (block_lines < line) {
line -= block_lines;
continue;
}
return [block timestampForLineNumber:line width:width];
}
return 0;
}
// Copy a line into the buffer. If the line is shorter than 'width' then only
// the first 'width' characters will be modified.
// 0 <= lineNum < numLinesWithWidth:width
- (int) copyLineToBuffer: (screen_char_t*) buffer width: (int) width lineNum: (int) lineNum
{
int line = lineNum;
int i;
for (i = 0; i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex: i];
NSAssert(block, @"Null block");
// getNumLinesWithWrapWidth caches its result for the last-used width so
// this is usually faster than calling getWrappedLineWithWrapWidth since
// most calls to the latter will just decrement line and return NULL.
int block_lines = [block getNumLinesWithWrapWidth:width];
if (block_lines < line) {
line -= block_lines;
continue;
}
int length;
int eol;
screen_char_t* p = [block getWrappedLineWithWrapWidth: width
lineNum: &line
lineLength: &length
includesEndOfLine: &eol];
if (p) {
NSAssert(length <= width, @"Length too long");
memcpy((char*) buffer, (char*) p, length * sizeof(screen_char_t));
return eol;
}
}
NSLog(@"Couldn't find line %d", lineNum);
NSAssert(NO, @"Tried to get non-existant line");
return NO;
}
- (ScreenCharArray *)wrappedLineAtIndex:(int)lineNum width:(int)width
{
int line = lineNum;
int i;
ScreenCharArray *result = [[[ScreenCharArray alloc] init] autorelease];
for (i = 0; i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
// getNumLinesWithWrapWidth caches its result for the last-used width so
// this is usually faster than calling getWrappedLineWithWrapWidth since
// most calls to the latter will just decrement line and return NULL.
int block_lines = [block getNumLinesWithWrapWidth:width];
if (block_lines < line) {
line -= block_lines;
continue;
}
int length, eol;
result.line = [block getWrappedLineWithWrapWidth:width
lineNum:&line
lineLength:&length
includesEndOfLine:&eol];
if (result.line) {
result.length = length;
result.eol = eol;
NSAssert(result.length <= width, @"Length too long");
return result;
}
}
NSLog(@"Couldn't find line %d", lineNum);
NSAssert(NO, @"Tried to get non-existant line");
return nil;
}
- (int) numLinesWithWidth: (int) width
{
return RawNumLines(self, width);
}
- (BOOL)popAndCopyLastLineInto:(screen_char_t*)ptr
width:(int)width
includesEndOfLine:(int*)includesEndOfLine
timestamp:(NSTimeInterval *)timestampPtr
{
if ([self numLinesWithWidth: width] == 0) {
return NO;
}
num_wrapped_lines_width = -1;
LineBlock* block = [blocks lastObject];
// If the line is partial the client will want to add a continuation marker so
// tell him there's no EOL in that case.
*includesEndOfLine = [block hasPartial] ? EOL_SOFT : EOL_HARD;
// Pop the last up-to-width chars off the last line.
int length;
screen_char_t* temp;
BOOL ok = [block popLastLineInto:&temp
withLength:&length
upToWidth:width
timestamp:timestampPtr];
NSAssert(ok, @"Unexpected empty block");
NSAssert(length <= width, @"Length too large");
NSAssert(length >= 0, @"Negative length");
// Copy into the provided buffer.
memcpy(ptr, temp, sizeof(screen_char_t) * length);
// Clean up the block if the whole thing is empty, otherwise another call
// to this function would not work correctly.
if ([block isEmpty]) {
[blocks removeLastObject];
}
#ifdef LOG_MUTATIONS
{
char a[1000];
int i;
for (i = 0; i < width; i++) {
a[i] = (ptr[i].code && !ptr[i].complexChar) ? ptr[i].code : '.';
}
a[i] = '\0';
NSLog(@"Pop: %s\n", a);
}
#endif
return YES;
}
- (void) setCursor: (int) x
{
LineBlock* block = [blocks lastObject];
if ([block hasPartial]) {
int last_line_length = [block getRawLineLength: [block numEntries]-1];
cursor_x = x + last_line_length;
cursor_rawline = -1;
} else {
cursor_x = x;
cursor_rawline = 0;
}
int i;
for (i = 0; i < [blocks count]; ++i) {
cursor_rawline += [[blocks objectAtIndex: i] numRawLines];
}
}
- (BOOL) getCursorInLastLineWithWidth: (int) width atX: (int*) x
{
int total_raw_lines = 0;
int i;
for (i = 0; i < [blocks count]; ++i) {
total_raw_lines += [[blocks objectAtIndex:i] numRawLines];
}
if (cursor_rawline == total_raw_lines-1) {
// The cursor is on the last line in the buffer.
LineBlock* block = [blocks lastObject];
int last_line_length = [block getRawLineLength: ([block numEntries]-1)];
screen_char_t* lastRawLine = [block rawLine: ([block numEntries]-1)];
int num_overflow_lines = NumberOfFullLines(lastRawLine,
last_line_length,
width,
_mayHaveDoubleWidthCharacter);
int min_x = OffsetOfWrappedLine(lastRawLine,
num_overflow_lines,
last_line_length,
width);
//int num_overflow_lines = (last_line_length-1) / width;
//int min_x = num_overflow_lines * width;
int max_x = min_x + width; // inclusive because the cursor wraps to the next line on the last line in the buffer
if (cursor_x >= min_x && cursor_x <= max_x) {
*x = cursor_x - min_x;
return YES;
}
}
return NO;
}
- (BOOL)_findPosition:(LineBufferPosition *)start inBlock:(int*)block_num inOffset:(int*)offset
{
int i;
int position = start.absolutePosition - droppedChars;
for (i = 0; position >= 0 && i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
int used = [block rawSpaceUsed];
if (position >= used) {
position -= used;
} else {
*block_num = i;
*offset = position;
return YES;
}
}
return NO;
}
- (int) _blockPosition: (int) block_num
{
int i;
int position = 0;
for (i = 0; i < block_num; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
position += [block rawSpaceUsed];
}
return position;
}
- (void)prepareToSearchFor:(NSString*)substring
startingAt:(LineBufferPosition *)start
options:(int)options
withContext:(FindContext*)context
{
context.substring = substring;
context.options = options;
if (options & FindOptBackwards) {
context.dir = -1;
} else {
context.dir = 1;
}
int offset = context.offset;
int absBlockNum = context.absBlockNum;
if ([self _findPosition:start inBlock:&absBlockNum inOffset:&offset]) {
context.offset = offset;
context.absBlockNum = absBlockNum + num_dropped_blocks;
context.status = Searching;
} else {
context.status = NotFound;
}
context.results = [NSMutableArray array];
}
- (void)findSubstring:(FindContext*)context stopAt:(int)stopAt
{
if (context.dir > 0) {
// Search forwards
if (context.absBlockNum < num_dropped_blocks) {
// The next block to search was dropped. Skip ahead to the first block.
// NSLog(@"Next to search was dropped. Skip to start");
context.absBlockNum = num_dropped_blocks;
}
if (context.absBlockNum - num_dropped_blocks >= [blocks count]) {
// Got to bottom
// NSLog(@"Got to bottom");
context.status = NotFound;
return;
}
} else {
// Search backwards
if (context.absBlockNum < num_dropped_blocks) {
// Got to top
// NSLog(@"Got to top");
context.status = NotFound;
return;
}
}
NSAssert(context.absBlockNum - num_dropped_blocks >= 0, @"bounds check");
NSAssert(context.absBlockNum - num_dropped_blocks < [blocks count], @"bounds check");
LineBlock* block = [blocks objectAtIndex:context.absBlockNum - num_dropped_blocks];
if (context.absBlockNum - num_dropped_blocks == 0 &&
context.offset != -1 &&
context.offset < [block startOffset]) {
if (context.dir > 0) {
// Part of the first block has been dropped. Skip ahead to its
// current beginning.
context.offset = [block startOffset];
} else {
// This block has scrolled off.
// NSLog(@"offset=%d, block's startOffset=%d. give up", context.offset, [block startOffset]);
context.status = NotFound;
return;
}
}
// NSLog(@"search block %d starting at offset %d", context.absBlockNum - num_dropped_blocks, context.offset);
[block findSubstring:context.substring
options:context.options
atOffset:context.offset
results:context.results
multipleResults:((context.options & FindMultipleResults) != 0)];
NSMutableArray* filtered = [NSMutableArray arrayWithCapacity:[context.results count]];
BOOL haveOutOfRangeResults = NO;
int blockPosition = [self _blockPosition:context.absBlockNum - num_dropped_blocks];
for (ResultRange* range in context.results) {
range->position += blockPosition;
if (context.dir * (range->position - stopAt) > 0 ||
context.dir * (range->position + context.matchLength - stopAt) > 0) {
// result was outside the range to be searched
haveOutOfRangeResults = YES;
} else {
// Found a good result.
context.status = Matched;
[filtered addObject:range];
}
}
context.results = filtered;
if ([filtered count] == 0 && haveOutOfRangeResults) {
context.status = NotFound;
}
// Prepare to continue searching next block.
if (context.dir < 0) {
context.offset = -1;
} else {
context.offset = 0;
}
context.absBlockNum = context.absBlockNum + context.dir;
}
// Returns an array of XRange values
- (NSArray*)convertPositions:(NSArray*)resultRanges withWidth:(int)width
{
// Create sorted array of all positions to convert.
NSMutableArray* unsortedPositions = [NSMutableArray arrayWithCapacity:[resultRanges count] * 2];
for (ResultRange* rr in resultRanges) {
[unsortedPositions addObject:[NSNumber numberWithInt:rr->position]];
[unsortedPositions addObject:[NSNumber numberWithInt:rr->position + rr->length - 1]];
}
// Walk blocks and positions in parallel, converting each position in order. Store in
// intermediate dict, mapping position->NSPoint(x,y)
NSArray *positionsArray = [unsortedPositions sortedArrayUsingSelector:@selector(compare:)];
int i = 0;
int yoffset = 0;
int numBlocks = [blocks count];
int passed = 0;
LineBlock *block = [blocks objectAtIndex:0];
int used = [block rawSpaceUsed];
NSMutableDictionary* intermediate = [NSMutableDictionary dictionaryWithCapacity:[resultRanges count] * 2];
int prev = -1;
for (NSNumber* positionNum in positionsArray) {
int position = [positionNum intValue];
if (position == prev) {
continue;
}
prev = position;
// Advance block until it includes this position
while (position >= passed + used && i < numBlocks) {
passed += used;
yoffset += [block getNumLinesWithWrapWidth:width];
i++;
if (i < numBlocks) {
block = [blocks objectAtIndex:i];
used = [block rawSpaceUsed];
}
}
if (i < numBlocks) {
int x, y;
assert(position >= passed);
assert(position < passed + used);
assert(used == [block rawSpaceUsed]);
BOOL isOk = [block convertPosition:position - passed
withWidth:width
toX:&x
toY:&y];
assert(x < 2000);
if (isOk) {
y += yoffset;
[intermediate setObject:[NSValue valueWithPoint:NSMakePoint(x, y)]
forKey:positionNum];
} else {
assert(false);
}
}
}
// Walk the positions array and populate results by looking up points in intermediate dict.
NSMutableArray* result = [NSMutableArray arrayWithCapacity:[resultRanges count]];
for (ResultRange* rr in resultRanges) {
NSValue *start = [intermediate objectForKey:[NSNumber numberWithInt:rr->position]];
NSValue *end = [intermediate objectForKey:[NSNumber numberWithInt:rr->position + rr->length - 1]];
if (start && end) {
XYRange *xyrange = [[[XYRange alloc] init] autorelease];
NSPoint startPoint = [start pointValue];
NSPoint endPoint = [end pointValue];
xyrange->xStart = startPoint.x;
xyrange->yStart = startPoint.y;
xyrange->xEnd = endPoint.x;
xyrange->yEnd = endPoint.y;
[result addObject:xyrange];
} else {
assert(false);
[result addObject:[NSNull null]];
}
}
return result;
}
// Returns YES if the position is valid.
- (BOOL)convertPosition:(int)position
withWidth:(int)width
toX:(int*)x
toY:(int*)y
{
BOOL ok;
LineBufferPosition *lbp = [LineBufferPosition position];
lbp.absolutePosition = position + droppedChars;
lbp.yOffset = 0;
lbp.extendsToEndOfLine = NO;
VT100GridCoord coord = [self coordinateForPosition:lbp width:width ok:&ok];
*x = coord.x;
*y = coord.y;
return ok;
}
- (LineBufferPosition *)positionForCoordinate:(VT100GridCoord)coord
width:(int)width
offset:(int)offset
{
int x = coord.x;
int y = coord.y;
long long absolutePosition = droppedChars;
int line = y;
int i;
for (i = 0; i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex: i];
NSAssert(block, @"Null block");
// getNumLinesWithWrapWidth caches its result for the last-used width so
// this is usually faster than calling getWrappedLineWithWrapWidth since
// most calls to the latter will just decrement line and return NULL.
int block_lines = [block getNumLinesWithWrapWidth:width];
if (block_lines <= line) {
line -= block_lines;
absolutePosition += [block rawSpaceUsed];
continue;
}
int pos;
int yOffset = 0;
BOOL extends = NO;
pos = [block getPositionOfLine:&line
atX:x
withWidth:width
yOffset:&yOffset
extends:&extends];
if (pos >= 0) {
absolutePosition += pos + offset;
LineBufferPosition *result = [LineBufferPosition position];
result.absolutePosition = absolutePosition;
result.yOffset = yOffset;
result.extendsToEndOfLine = extends;
// Make sure position is valid (might not be because of offset).
BOOL ok;
[self coordinateForPosition:result width:width ok:&ok];
if (ok) {
return result;
} else {
return nil;
}
}
}
return nil;
}
- (VT100GridCoord)coordinateForPosition:(LineBufferPosition *)position
width:(int)width
ok:(BOOL *)ok
{
if (position.absolutePosition == [self lastPos] + droppedChars) {
VT100GridCoord result;
result.y = [self numLinesWithWidth:width] - 1;
ScreenCharArray *lastLine = [self wrappedLineAtIndex:result.y width:width];
result.x = lastLine.length;
if (position.yOffset > 0) {
result.x = 0;
result.y += position.yOffset;
} else {
result.x = lastLine.length;
}
if (position.extendsToEndOfLine) {
result.x = width - 1;
}
if (ok) {
*ok = YES;
}
return result;
}
int i;
int yoffset = 0;
int p = position.absolutePosition - droppedChars;
for (i = 0; p >= 0 && i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
int used = [block rawSpaceUsed];
if (p >= used) {
p -= used;
yoffset += [block getNumLinesWithWrapWidth:width];
} else {
int y;
int x;
BOOL positionIsValid = [block convertPosition:p
withWidth:width
toX:&x
toY:&y];
if (ok) {
*ok = positionIsValid;
}
if (position.yOffset > 0) {
x = 0;
y += position.yOffset;
}
if (position.extendsToEndOfLine) {
x = width - 1;
}
return VT100GridCoordMake(x, y + yoffset);
}
}
if (ok) {
*ok = NO;
}
return VT100GridCoordMake(0, 0);
}
- (int) firstPos
{
int i;
int position = 0;
for (i = 0; i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
if (![block isEmpty]) {
position += [block startOffset];
break;
} else {
position += [block rawSpaceUsed];
}
}
return position;
}
- (int) lastPos
{
int i;
int position = 0;
for (i = 0; i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
if (![block isEmpty]) {
position += [block rawSpaceUsed];
} else {
position += [block rawSpaceUsed];
}
}
return position;
}
- (LineBufferPosition *)firstPosition {
LineBufferPosition *position = [LineBufferPosition position];
position.absolutePosition = droppedChars;
return position;
}
- (LineBufferPosition *)lastPosition {
LineBufferPosition *position = [LineBufferPosition position];
position.absolutePosition = droppedChars;
for (int i = 0; i < [blocks count]; ++i) {
LineBlock* block = [blocks objectAtIndex:i];
position.absolutePosition = position.absolutePosition + [block rawSpaceUsed];
}
return position;
}
- (long long)absPositionOfFindContext:(FindContext *)findContext
{
long long offset = droppedChars + findContext.offset;
int numBlocks = findContext.absBlockNum - num_dropped_blocks;
for (LineBlock *block in blocks) {
if (!numBlocks) {
break;
}
--numBlocks;
offset += [block rawSpaceUsed];
}
return offset;
}
- (int)positionForAbsPosition:(long long)absPosition
{
absPosition -= droppedChars;
if (absPosition < 0) {
return [[blocks objectAtIndex:0] startOffset];
}
if (absPosition > INT_MAX) {
absPosition = INT_MAX;
}
return (int)absPosition;
}
- (long long)absPositionForPosition:(int)pos
{
long long absPos = pos;
return absPos + droppedChars;
}
- (int)absBlockNumberOfAbsPos:(long long)absPos
{
int absBlock = num_dropped_blocks;
long long cumPos = droppedChars;
for (LineBlock *block in blocks) {
cumPos += [block rawSpaceUsed];
if (cumPos >= absPos) {
return absBlock;
}
++absBlock;
}
return absBlock;
}
- (long long)absPositionOfAbsBlock:(int)absBlockNum
{
long long cumPos = droppedChars;
for (int i = 0; i < blocks.count && i + num_dropped_blocks < absBlockNum; i++) {
cumPos += [[blocks objectAtIndex:i] rawSpaceUsed];
}
return cumPos;
}
- (void)storeLocationOfAbsPos:(long long)absPos
inContext:(FindContext *)context
{
context.absBlockNum = [self absBlockNumberOfAbsPos:absPos];
long long absOffset = [self absPositionOfAbsBlock:context.absBlockNum];
context.offset = MAX(0, absPos - absOffset);
}
- (LineBuffer *)newAppendOnlyCopy {
LineBuffer *theCopy = [[LineBuffer alloc] init];
theCopy->blocks = [[NSMutableArray alloc] initWithArray:blocks];
LineBlock *lastBlock = [blocks lastObject];
if (lastBlock) {
[theCopy->blocks removeLastObject];
[theCopy->blocks addObject:[[lastBlock copy] autorelease]];
}
theCopy->block_size = block_size;
theCopy->cursor_x = cursor_x;
theCopy->cursor_rawline = cursor_rawline;
theCopy->max_lines = max_lines;
theCopy->num_dropped_blocks = num_dropped_blocks;
theCopy->num_wrapped_lines_cache = num_wrapped_lines_cache;
theCopy->num_wrapped_lines_width = num_wrapped_lines_width;
theCopy->droppedChars = droppedChars;
return theCopy;
}
@end