forked from LIJI32/SameBoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHFLineCountingView.m
689 lines (601 loc) · 28.6 KB
/
HFLineCountingView.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
//
// HFLineCountingView.m
// HexFiend_2
//
// Copyright 2007 ridiculous_fish. All rights reserved.
//
#import <HexFiend/HFLineCountingView.h>
#import <HexFiend/HFLineCountingRepresenter.h>
#import <HexFiend/HFFunctions.h>
#define TIME_LINE_NUMBERS 0
#define HEX_LINE_NUMBERS_HAVE_0X_PREFIX 0
#define INVALID_LINE_COUNT NSUIntegerMax
#if TIME_LINE_NUMBERS
@interface HFTimingTextView : NSTextView
@end
@implementation HFTimingTextView
- (void)drawRect:(NSRect)rect {
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
[super drawRect:rect];
CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent();
NSLog(@"TextView line number time: %f", endTime - startTime);
}
@end
#endif
@implementation HFLineCountingView
- (void)_sharedInitLineCountingView {
layoutManager = [[NSLayoutManager alloc] init];
textStorage = [[NSTextStorage alloc] init];
[textStorage addLayoutManager:layoutManager];
textContainer = [[NSTextContainer alloc] init];
[textContainer setLineFragmentPadding:(CGFloat)5];
[textContainer setContainerSize:NSMakeSize(self.bounds.size.width, [textContainer containerSize].height)];
[layoutManager addTextContainer:textContainer];
}
- (instancetype)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self _sharedInitLineCountingView];
}
return self;
}
- (void)dealloc {
HFUnregisterViewForWindowAppearanceChanges(self, registeredForAppNotifications);
[_font release];
[layoutManager release];
[textContainer release];
[textStorage release];
[textAttributes release];
[super dealloc];
}
- (void)encodeWithCoder:(NSCoder *)coder {
HFASSERT([coder allowsKeyedCoding]);
[super encodeWithCoder:coder];
[coder encodeObject:_font forKey:@"HFFont"];
[coder encodeDouble:_lineHeight forKey:@"HFLineHeight"];
[coder encodeObject:_representer forKey:@"HFRepresenter"];
[coder encodeInt64:_bytesPerLine forKey:@"HFBytesPerLine"];
[coder encodeInt64:_lineNumberFormat forKey:@"HFLineNumberFormat"];
[coder encodeBool:useStringDrawingPath forKey:@"HFUseStringDrawingPath"];
}
- (instancetype)initWithCoder:(NSCoder *)coder {
HFASSERT([coder allowsKeyedCoding]);
self = [super initWithCoder:coder];
[self _sharedInitLineCountingView];
_font = [[coder decodeObjectForKey:@"HFFont"] retain];
_lineHeight = (CGFloat)[coder decodeDoubleForKey:@"HFLineHeight"];
_representer = [coder decodeObjectForKey:@"HFRepresenter"];
_bytesPerLine = (NSUInteger)[coder decodeInt64ForKey:@"HFBytesPerLine"];
_lineNumberFormat = (NSUInteger)[coder decodeInt64ForKey:@"HFLineNumberFormat"];
useStringDrawingPath = [coder decodeBoolForKey:@"HFUseStringDrawingPath"];
return self;
}
- (BOOL)isFlipped { return YES; }
- (void)getLineNumberFormatString:(char *)outString length:(NSUInteger)length {
HFLineNumberFormat format = self.lineNumberFormat;
if (format == HFLineNumberFormatDecimal) {
strlcpy(outString, "%llu", length);
}
else if (format == HFLineNumberFormatHexadecimal) {
#if HEX_LINE_NUMBERS_HAVE_0X_PREFIX
// we want a format string like 0x%08llX
snprintf(outString, length, "0x%%0%lullX", (unsigned long)self.representer.digitCount - 2);
#else
// we want a format string like %08llX
snprintf(outString, length, "%%0%lullX", (unsigned long)self.representer.digitCount);
#endif
}
else {
strlcpy(outString, "", length);
}
}
- (void)windowDidChangeKeyStatus:(NSNotification *)note {
USE(note);
[self setNeedsDisplay:YES];
}
- (void)viewDidMoveToWindow {
HFRegisterViewForWindowAppearanceChanges(self, @selector(windowDidChangeKeyStatus:), !registeredForAppNotifications);
registeredForAppNotifications = YES;
[super viewDidMoveToWindow];
}
- (void)viewWillMoveToWindow:(NSWindow *)newWindow {
HFUnregisterViewForWindowAppearanceChanges(self, NO);
[super viewWillMoveToWindow:newWindow];
}
- (void)drawGradientWithClip:(NSRect)clip {
[_representer.backgroundColor set];
NSRectFill(clip);
NSInteger shadowEdge = _representer.interiorShadowEdge;
if (shadowEdge >= 0) {
const CGFloat shadowWidth = 6;
NSWindow *window = self.window;
BOOL drawActive = (window == nil || [window isKeyWindow] || [window isMainWindow]);
HFDrawShadow([[NSGraphicsContext currentContext] graphicsPort], self.bounds, shadowWidth, shadowEdge, drawActive, clip);
}
}
- (void)drawDividerWithClip:(NSRect)clipRect {
USE(clipRect);
#if 1
NSInteger edges = _representer.borderedEdges;
NSRect bounds = self.bounds;
// -1 means to draw no edges
if (edges == -1) {
edges = 0;
}
[_representer.borderColor set];
if ((edges & (1 << NSMinXEdge)) > 0) {
NSRect lineRect = bounds;
lineRect.size.width = 1;
lineRect.origin.x = 0;
if (NSIntersectsRect(lineRect, clipRect)) {
NSRectFill(lineRect);
}
}
if ((edges & (1 << NSMaxXEdge)) > 0) {
NSRect lineRect = bounds;
lineRect.size.width = 1;
lineRect.origin.x = NSMaxX(bounds) - lineRect.size.width;
if (NSIntersectsRect(lineRect, clipRect)) {
NSRectFill(lineRect);
}
}
if ((edges & (1 << NSMinYEdge)) > 0) {
NSRect lineRect = bounds;
lineRect.size.height = 1;
lineRect.origin.y = 0;
if (NSIntersectsRect(lineRect, clipRect)) {
NSRectFill(lineRect);
}
}
if ((edges & (1 << NSMaxYEdge)) > 0) {
NSRect lineRect = bounds;
lineRect.size.height = 1;
lineRect.origin.y = NSMaxY(bounds) - lineRect.size.height;
if (NSIntersectsRect(lineRect, clipRect)) {
NSRectFill(lineRect);
}
}
// Backwards compatibility to always draw a border on the edge with the interior shadow
NSRect lineRect = bounds;
lineRect.size.width = 1;
NSInteger shadowEdge = _representer.interiorShadowEdge;
if (shadowEdge == NSMaxXEdge) {
lineRect.origin.x = NSMaxX(bounds) - lineRect.size.width;
} else if (shadowEdge == NSMinXEdge) {
lineRect.origin.x = NSMinX(bounds);
} else {
lineRect = NSZeroRect;
}
if (NSIntersectsRect(lineRect, clipRect)) {
NSRectFill(lineRect);
}
#else
if (NSIntersectsRect(lineRect, clipRect)) {
// this looks better when we have no shadow
[[NSColor lightGrayColor] set];
NSRect bounds = self.bounds;
NSRect lineRect = bounds;
lineRect.origin.x += lineRect.size.width - 2;
lineRect.size.width = 1;
NSRectFill(NSIntersectionRect(lineRect, clipRect));
[[NSColor whiteColor] set];
lineRect.origin.x += 1;
NSRectFill(NSIntersectionRect(lineRect, clipRect));
}
#endif
}
static inline int common_prefix_length(const char *a, const char *b) {
int i;
for (i=0; ; i++) {
char ac = a[i];
char bc = b[i];
if (ac != bc || ac == 0 || bc == 0) break;
}
return i;
}
/* Drawing with NSLayoutManager is necessary because the 10_2 typesetting behavior used by the old string drawing does the wrong thing for fonts like Bitstream Vera Sans Mono. Also it's an optimization for drawing the shadow. */
- (void)drawLineNumbersWithClipLayoutManagerPerLine:(NSRect)clipRect {
#if TIME_LINE_NUMBERS
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
#endif
NSUInteger previousTextStorageCharacterCount = [textStorage length];
CGFloat verticalOffset = ld2f(_lineRangeToDraw.location - floorl(_lineRangeToDraw.location));
NSRect textRect = self.bounds;
textRect.size.height = _lineHeight;
textRect.origin.y -= verticalOffset * _lineHeight;
unsigned long long lineIndex = HFFPToUL(floorl(_lineRangeToDraw.location));
unsigned long long lineValue = lineIndex * _bytesPerLine;
NSUInteger linesRemaining = ll2l(HFFPToUL(ceill(_lineRangeToDraw.length + _lineRangeToDraw.location) - floorl(_lineRangeToDraw.location)));
char previousBuff[256];
int previousStringLength = (int)previousTextStorageCharacterCount;
BOOL conversionResult = [[textStorage string] getCString:previousBuff maxLength:sizeof previousBuff encoding:NSASCIIStringEncoding];
HFASSERT(conversionResult);
while (linesRemaining--) {
char formatString[64];
[self getLineNumberFormatString:formatString length:sizeof formatString];
if (NSIntersectsRect(textRect, clipRect)) {
NSString *replacementCharacters = nil;
NSRange replacementRange;
char buff[256];
int newStringLength = snprintf(buff, sizeof buff, formatString, lineValue);
HFASSERT(newStringLength > 0);
int prefixLength = common_prefix_length(previousBuff, buff);
HFASSERT(prefixLength <= newStringLength);
HFASSERT(prefixLength <= previousStringLength);
replacementRange = NSMakeRange(prefixLength, previousStringLength - prefixLength);
replacementCharacters = [[NSString alloc] initWithBytesNoCopy:buff + prefixLength length:newStringLength - prefixLength encoding:NSASCIIStringEncoding freeWhenDone:NO];
NSUInteger glyphCount;
[textStorage replaceCharactersInRange:replacementRange withString:replacementCharacters];
if (previousTextStorageCharacterCount == 0) {
NSDictionary *atts = [[NSDictionary alloc] initWithObjectsAndKeys:_font, NSFontAttributeName, [NSColor colorWithCalibratedWhite:(CGFloat).1 alpha:(CGFloat).8], NSForegroundColorAttributeName, nil];
[textStorage setAttributes:atts range:NSMakeRange(0, newStringLength)];
[atts release];
}
glyphCount = [layoutManager numberOfGlyphs];
if (glyphCount > 0) {
CGFloat maxX = NSMaxX([layoutManager lineFragmentUsedRectForGlyphAtIndex:glyphCount - 1 effectiveRange:NULL]);
[layoutManager drawGlyphsForGlyphRange:NSMakeRange(0, glyphCount) atPoint:NSMakePoint(textRect.origin.x + textRect.size.width - maxX, textRect.origin.y)];
}
previousTextStorageCharacterCount = newStringLength;
[replacementCharacters release];
memcpy(previousBuff, buff, newStringLength + 1);
previousStringLength = newStringLength;
}
textRect.origin.y += _lineHeight;
lineIndex++;
lineValue = HFSum(lineValue, _bytesPerLine);
}
#if TIME_LINE_NUMBERS
CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Line number time: %f", endTime - startTime);
#endif
}
- (void)drawLineNumbersWithClipStringDrawing:(NSRect)clipRect {
CGFloat verticalOffset = ld2f(_lineRangeToDraw.location - floorl(_lineRangeToDraw.location));
NSRect textRect = self.bounds;
textRect.size.height = _lineHeight;
textRect.size.width -= 5;
textRect.origin.y -= verticalOffset * _lineHeight + 1;
unsigned long long lineIndex = HFFPToUL(floorl(_lineRangeToDraw.location));
unsigned long long lineValue = lineIndex * _bytesPerLine;
NSUInteger linesRemaining = ll2l(HFFPToUL(ceill(_lineRangeToDraw.length + _lineRangeToDraw.location) - floorl(_lineRangeToDraw.location)));
if (! textAttributes) {
NSMutableParagraphStyle *mutableStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[mutableStyle setAlignment:NSRightTextAlignment];
NSParagraphStyle *paragraphStyle = [mutableStyle copy];
[mutableStyle release];
textAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:_font, NSFontAttributeName, [NSColor colorWithCalibratedWhite:(CGFloat).1 alpha:(CGFloat).8], NSForegroundColorAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil];
[paragraphStyle release];
}
char formatString[64];
[self getLineNumberFormatString:formatString length:sizeof formatString];
while (linesRemaining--) {
if (NSIntersectsRect(textRect, clipRect)) {
char buff[256];
int newStringLength = snprintf(buff, sizeof buff, formatString, lineValue);
HFASSERT(newStringLength > 0);
NSString *string = [[NSString alloc] initWithBytesNoCopy:buff length:newStringLength encoding:NSASCIIStringEncoding freeWhenDone:NO];
[string drawInRect:textRect withAttributes:textAttributes];
[string release];
}
textRect.origin.y += _lineHeight;
lineIndex++;
if (linesRemaining > 0) lineValue = HFSum(lineValue, _bytesPerLine); //we could do this unconditionally, but then we risk overflow
}
}
- (NSUInteger)characterCountForLineRange:(HFRange)range {
HFASSERT(range.length <= NSUIntegerMax);
NSUInteger characterCount;
NSUInteger lineCount = ll2l(range.length);
const NSUInteger stride = _bytesPerLine;
HFLineCountingRepresenter *rep = self.representer;
HFLineNumberFormat format = self.lineNumberFormat;
if (format == HFLineNumberFormatDecimal) {
unsigned long long lineValue = HFProductULL(range.location, _bytesPerLine);
characterCount = lineCount /* newlines */;
while (lineCount--) {
characterCount += HFCountDigitsBase10(lineValue);
lineValue += stride;
}
}
else if (format == HFLineNumberFormatHexadecimal) {
characterCount = ([rep digitCount] + 1) * lineCount; // +1 for newlines
}
else {
characterCount = -1;
}
return characterCount;
}
- (NSString *)newLineStringForRange:(HFRange)range {
HFASSERT(range.length <= NSUIntegerMax);
if(range.length == 0)
return [[NSString alloc] init]; // Placate the analyzer.
NSUInteger lineCount = ll2l(range.length);
const NSUInteger stride = _bytesPerLine;
unsigned long long lineValue = HFProductULL(range.location, _bytesPerLine);
NSUInteger characterCount = [self characterCountForLineRange:range];
char *buffer = check_malloc(characterCount);
NSUInteger bufferIndex = 0;
char formatString[64];
[self getLineNumberFormatString:formatString length:sizeof formatString];
while (lineCount--) {
int charCount = sprintf(buffer + bufferIndex, formatString, lineValue + self.representer.valueOffset);
HFASSERT(charCount > 0);
bufferIndex += charCount;
buffer[bufferIndex++] = '\n';
lineValue += stride;
}
HFASSERT(bufferIndex == characterCount);
NSString *string = [[NSString alloc] initWithBytesNoCopy:(void *)buffer length:bufferIndex encoding:NSASCIIStringEncoding freeWhenDone:YES];
return string;
}
- (void)updateLayoutManagerWithLineIndex:(unsigned long long)startingLineIndex lineCount:(NSUInteger)linesRemaining {
const BOOL debug = NO;
[textStorage beginEditing];
if (storedLineCount == INVALID_LINE_COUNT) {
/* This usually indicates that our bytes per line or line number format changed, and we need to just recalculate everything */
NSString *string = [self newLineStringForRange:HFRangeMake(startingLineIndex, linesRemaining)];
[textStorage replaceCharactersInRange:NSMakeRange(0, [textStorage length]) withString:string];
[string release];
}
else {
HFRange leftRangeToReplace, rightRangeToReplace;
HFRange leftRangeToStore, rightRangeToStore;
HFRange oldRange = HFRangeMake(storedLineIndex, storedLineCount);
HFRange newRange = HFRangeMake(startingLineIndex, linesRemaining);
HFRange rangeToPreserve = HFIntersectionRange(oldRange, newRange);
if (rangeToPreserve.length == 0) {
leftRangeToReplace = oldRange;
leftRangeToStore = newRange;
rightRangeToReplace = HFZeroRange;
rightRangeToStore = HFZeroRange;
}
else {
if (debug) NSLog(@"Preserving %llu", rangeToPreserve.length);
HFASSERT(HFRangeIsSubrangeOfRange(rangeToPreserve, newRange));
HFASSERT(HFRangeIsSubrangeOfRange(rangeToPreserve, oldRange));
const unsigned long long maxPreserve = HFMaxRange(rangeToPreserve);
leftRangeToReplace = HFRangeMake(oldRange.location, rangeToPreserve.location - oldRange.location);
leftRangeToStore = HFRangeMake(newRange.location, rangeToPreserve.location - newRange.location);
rightRangeToReplace = HFRangeMake(maxPreserve, HFMaxRange(oldRange) - maxPreserve);
rightRangeToStore = HFRangeMake(maxPreserve, HFMaxRange(newRange) - maxPreserve);
}
if (debug) NSLog(@"Changing %@ -> %@", HFRangeToString(oldRange), HFRangeToString(newRange));
if (debug) NSLog(@"LEFT: %@ -> %@", HFRangeToString(leftRangeToReplace), HFRangeToString(leftRangeToStore));
if (debug) NSLog(@"RIGHT: %@ -> %@", HFRangeToString(rightRangeToReplace), HFRangeToString(rightRangeToStore));
HFASSERT(leftRangeToReplace.length == 0 || HFRangeIsSubrangeOfRange(leftRangeToReplace, oldRange));
HFASSERT(rightRangeToReplace.length == 0 || HFRangeIsSubrangeOfRange(rightRangeToReplace, oldRange));
if (leftRangeToReplace.length > 0 || leftRangeToStore.length > 0) {
NSUInteger charactersToDelete = [self characterCountForLineRange:leftRangeToReplace];
NSRange rangeToDelete = NSMakeRange(0, charactersToDelete);
if (leftRangeToStore.length == 0) {
[textStorage deleteCharactersInRange:rangeToDelete];
if (debug) NSLog(@"Left deleting text range %@", NSStringFromRange(rangeToDelete));
}
else {
NSString *leftRangeString = [self newLineStringForRange:leftRangeToStore];
[textStorage replaceCharactersInRange:rangeToDelete withString:leftRangeString];
if (debug) NSLog(@"Replacing text range %@ with %@", NSStringFromRange(rangeToDelete), leftRangeString);
[leftRangeString release];
}
}
if (rightRangeToReplace.length > 0 || rightRangeToStore.length > 0) {
NSUInteger charactersToDelete = [self characterCountForLineRange:rightRangeToReplace];
NSUInteger stringLength = [textStorage length];
HFASSERT(charactersToDelete <= stringLength);
NSRange rangeToDelete = NSMakeRange(stringLength - charactersToDelete, charactersToDelete);
if (rightRangeToStore.length == 0) {
[textStorage deleteCharactersInRange:rangeToDelete];
if (debug) NSLog(@"Right deleting text range %@", NSStringFromRange(rangeToDelete));
}
else {
NSString *rightRangeString = [self newLineStringForRange:rightRangeToStore];
[textStorage replaceCharactersInRange:rangeToDelete withString:rightRangeString];
if (debug) NSLog(@"Replacing text range %@ with %@ (for range %@)", NSStringFromRange(rangeToDelete), rightRangeString, HFRangeToString(rightRangeToStore));
[rightRangeString release];
}
}
}
if (! textAttributes) {
NSMutableParagraphStyle *mutableStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[mutableStyle setAlignment:NSRightTextAlignment];
NSParagraphStyle *paragraphStyle = [mutableStyle copy];
[mutableStyle release];
textAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:_font, NSFontAttributeName, [NSColor colorWithCalibratedWhite:(CGFloat).1 alpha:(CGFloat).8], NSForegroundColorAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil];
[paragraphStyle release];
[textStorage setAttributes:textAttributes range:NSMakeRange(0, [textStorage length])];
}
[textStorage endEditing];
#if ! NDEBUG
NSString *comparisonString = [self newLineStringForRange:HFRangeMake(startingLineIndex, linesRemaining)];
if (! [comparisonString isEqualToString:[textStorage string]]) {
NSLog(@"Not equal!");
NSLog(@"Expected:\n%@", comparisonString);
NSLog(@"Actual:\n%@", [textStorage string]);
}
HFASSERT([comparisonString isEqualToString:[textStorage string]]);
[comparisonString release];
#endif
storedLineIndex = startingLineIndex;
storedLineCount = linesRemaining;
}
- (void)drawLineNumbersWithClipSingleStringDrawing:(NSRect)clipRect {
USE(clipRect);
unsigned long long lineIndex = HFFPToUL(floorl(_lineRangeToDraw.location));
NSUInteger linesRemaining = ll2l(HFFPToUL(ceill(_lineRangeToDraw.length + _lineRangeToDraw.location) - floorl(_lineRangeToDraw.location)));
CGFloat linesToVerticallyOffset = ld2f(_lineRangeToDraw.location - floorl(_lineRangeToDraw.location));
CGFloat verticalOffset = linesToVerticallyOffset * _lineHeight + 1;
NSRect textRect = self.bounds;
textRect.size.width -= 5;
textRect.origin.y -= verticalOffset;
textRect.size.height += verticalOffset;
if (! textAttributes) {
NSMutableParagraphStyle *mutableStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[mutableStyle setAlignment:NSRightTextAlignment];
[mutableStyle setMinimumLineHeight:_lineHeight];
[mutableStyle setMaximumLineHeight:_lineHeight];
NSParagraphStyle *paragraphStyle = [mutableStyle copy];
[mutableStyle release];
textAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:_font, NSFontAttributeName, [NSColor colorWithCalibratedWhite:(CGFloat).1 alpha:(CGFloat).8], NSForegroundColorAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil];
[paragraphStyle release];
}
NSString *string = [self newLineStringForRange:HFRangeMake(lineIndex, linesRemaining)];
[string drawInRect:textRect withAttributes:textAttributes];
[string release];
}
- (void)drawLineNumbersWithClipSingleStringCellDrawing:(NSRect)clipRect {
USE(clipRect);
const CGFloat cellTextContainerPadding = 2.f;
unsigned long long lineIndex = HFFPToUL(floorl(_lineRangeToDraw.location));
NSUInteger linesRemaining = ll2l(HFFPToUL(ceill(_lineRangeToDraw.length + _lineRangeToDraw.location) - floorl(_lineRangeToDraw.location)));
CGFloat linesToVerticallyOffset = ld2f(_lineRangeToDraw.location - floorl(_lineRangeToDraw.location));
CGFloat verticalOffset = linesToVerticallyOffset * _lineHeight + 1;
NSRect textRect = self.bounds;
textRect.size.width -= 5;
textRect.origin.y -= verticalOffset;
textRect.origin.x += cellTextContainerPadding;
textRect.size.height += verticalOffset;
if (! textAttributes) {
NSMutableParagraphStyle *mutableStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[mutableStyle setAlignment:NSRightTextAlignment];
[mutableStyle setMinimumLineHeight:_lineHeight];
[mutableStyle setMaximumLineHeight:_lineHeight];
NSParagraphStyle *paragraphStyle = [mutableStyle copy];
[mutableStyle release];
textAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:_font, NSFontAttributeName, [NSColor colorWithCalibratedWhite:(CGFloat).1 alpha:(CGFloat).8], NSForegroundColorAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil];
[paragraphStyle release];
}
NSString *string = [self newLineStringForRange:HFRangeMake(lineIndex, linesRemaining)];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:string attributes:textAttributes];
[string release];
NSCell *cell = [[NSCell alloc] initTextCell:@""];
[cell setAttributedStringValue:attributedString];
[cell drawWithFrame:textRect inView:self];
[[NSColor purpleColor] set];
NSFrameRect(textRect);
[cell release];
[attributedString release];
}
- (void)drawLineNumbersWithClipFullLayoutManager:(NSRect)clipRect {
USE(clipRect);
unsigned long long lineIndex = HFFPToUL(floorl(_lineRangeToDraw.location));
NSUInteger linesRemaining = ll2l(HFFPToUL(ceill(_lineRangeToDraw.length + _lineRangeToDraw.location) - floorl(_lineRangeToDraw.location)));
if (lineIndex != storedLineIndex || linesRemaining != storedLineCount) {
[self updateLayoutManagerWithLineIndex:lineIndex lineCount:linesRemaining];
}
CGFloat verticalOffset = ld2f(_lineRangeToDraw.location - floorl(_lineRangeToDraw.location));
NSPoint textPoint = self.bounds.origin;
textPoint.y -= verticalOffset * _lineHeight;
[layoutManager drawGlyphsForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) atPoint:textPoint];
}
- (void)drawLineNumbersWithClip:(NSRect)clipRect {
#if TIME_LINE_NUMBERS
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
#endif
NSInteger drawingMode = (useStringDrawingPath ? 1 : 3);
switch (drawingMode) {
// Drawing can't be done right if fonts are wider than expected, but all
// of these have rather nasty behavior in that case. I've commented what
// that behavior is; the comment is hypothetical 'could' if it shouldn't
// actually be a problem in practice.
// TODO: Make a drawing mode that is "Fonts could get clipped if too wide"
// because that seems like better behavior than any of these.
case 0:
// Most fonts are too wide and every character gets piled on right (unreadable).
[self drawLineNumbersWithClipLayoutManagerPerLine:clipRect];
break;
case 1:
// Last characters could get omitted (*not* clipped) if too wide.
// Also, most fonts have bottoms clipped (very unsigntly).
[self drawLineNumbersWithClipStringDrawing:clipRect];
break;
case 2:
// Most fonts are too wide and wrap (breaks numbering).
[self drawLineNumbersWithClipFullLayoutManager:clipRect];
break;
case 3:
// Fonts could wrap if too wide (breaks numbering).
// *Note that that this is the only mode that generally works.*
[self drawLineNumbersWithClipSingleStringDrawing:clipRect];
break;
case 4:
// Most fonts are too wide and wrap (breaks numbering).
[self drawLineNumbersWithClipSingleStringCellDrawing:clipRect];
break;
}
#if TIME_LINE_NUMBERS
CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent();
NSLog(@"Line number time: %f", endTime - startTime);
#endif
}
- (void)drawRect:(NSRect)clipRect {
[self drawGradientWithClip:clipRect];
[self drawDividerWithClip:clipRect];
[self drawLineNumbersWithClip:clipRect];
}
- (void)setLineRangeToDraw:(HFFPRange)range {
if (! HFFPRangeEqualsRange(range, _lineRangeToDraw)) {
_lineRangeToDraw = range;
[self setNeedsDisplay:YES];
}
}
- (void)setBytesPerLine:(NSUInteger)val {
if (_bytesPerLine != val) {
_bytesPerLine = val;
storedLineCount = INVALID_LINE_COUNT;
[self setNeedsDisplay:YES];
}
}
- (void)setLineNumberFormat:(HFLineNumberFormat)format {
if (format != _lineNumberFormat) {
_lineNumberFormat = format;
storedLineCount = INVALID_LINE_COUNT;
[self setNeedsDisplay:YES];
}
}
- (BOOL)canUseStringDrawingPathForFont:(NSFont *)testFont {
NSString *name = [testFont fontName];
// No, Menlo does not work here.
return [name isEqualToString:@"Monaco"] || [name isEqualToString:@"Courier"] || [name isEqualToString:@"Consolas"];
}
- (void)setFont:(NSFont *)val {
if (val != _font) {
[_font release];
_font = [val copy];
[textStorage deleteCharactersInRange:NSMakeRange(0, [textStorage length])]; //delete the characters so we know to set the font next time we render
[textAttributes release];
textAttributes = nil;
storedLineCount = INVALID_LINE_COUNT;
useStringDrawingPath = [self canUseStringDrawingPathForFont:_font];
[self setNeedsDisplay:YES];
}
}
- (void)setLineHeight:(CGFloat)height {
if (_lineHeight != height) {
_lineHeight = height;
[self setNeedsDisplay:YES];
}
}
- (void)setFrameSize:(NSSize)size {
[super setFrameSize:size];
[textContainer setContainerSize:NSMakeSize(self.bounds.size.width, [textContainer containerSize].height)];
}
- (void)mouseDown:(NSEvent *)event {
USE(event);
// [_representer cycleLineNumberFormat];
}
- (void)scrollWheel:(NSEvent *)scrollEvent {
[_representer.controller scrollWithScrollEvent:scrollEvent];
}
+ (NSUInteger)digitsRequiredToDisplayLineNumber:(unsigned long long)lineNumber inFormat:(HFLineNumberFormat)format {
switch (format) {
case HFLineNumberFormatDecimal: return HFCountDigitsBase10(lineNumber);
#if HEX_LINE_NUMBERS_HAVE_0X_PREFIX
case HFLineNumberFormatHexadecimal: return 2 + HFCountDigitsBase16(lineNumber);
#else
case HFLineNumberFormatHexadecimal: return HFCountDigitsBase16(lineNumber);
#endif
default: return 0;
}
}
@end