forked from LIJI32/SameBoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHFController.m
1905 lines (1695 loc) · 81.7 KB
/
HFController.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
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
//
// HFController.m
// HexFiend_2
//
// Copyright 2007 ridiculous_fish. All rights reserved.
//
#import <HexFiend/HFController.h>
#import <HexFiend/HFRepresenter_Internal.h>
#import <HexFiend/HFByteArray_Internal.h>
#import <HexFiend/HFFullMemoryByteArray.h>
#import <HexFiend/HFBTreeByteArray.h>
#import <HexFiend/HFFullMemoryByteSlice.h>
#import <HexFiend/HFSharedMemoryByteSlice.h>
#import <objc/runtime.h>
#import <objc/message.h>
#import <objc/objc-auto.h>
/* Used for the anchor range and location */
#define NO_SELECTION ULLONG_MAX
#define VALIDATE_SELECTION() [self _ensureSelectionIsValid]
#define BENCHMARK_BYTEARRAYS 0
#define BEGIN_TRANSACTION() NSUInteger token = [self beginPropertyChangeTransaction]
#define END_TRANSACTION() [self endPropertyChangeTransaction:token]
static const CGFloat kScrollMultiplier = (CGFloat)1.5;
static const CFTimeInterval kPulseDuration = .2;
static void *KVOContextChangesAreLocked = &KVOContextChangesAreLocked;
NSString * const HFPrepareForChangeInFileNotification = @"HFPrepareForChangeInFileNotification";
NSString * const HFChangeInFileByteArrayKey = @"HFChangeInFileByteArrayKey";
NSString * const HFChangeInFileModifiedRangesKey = @"HFChangeInFileModifiedRangesKey";
NSString * const HFChangeInFileShouldCancelKey = @"HFChangeInFileShouldCancelKey";
NSString * const HFChangeInFileHintKey = @"HFChangeInFileHintKey";
NSString * const HFControllerDidChangePropertiesNotification = @"HFControllerDidChangePropertiesNotification";
NSString * const HFControllerChangedPropertiesKey = @"HFControllerChangedPropertiesKey";
typedef NS_ENUM(NSInteger, HFControllerSelectAction) {
eSelectResult,
eSelectAfterResult,
ePreserveSelection,
NUM_SELECTION_ACTIONS
};
@interface HFController (ForwardDeclarations)
- (void)_commandInsertByteArrays:(NSArray *)byteArrays inRanges:(NSArray *)ranges withSelectionAction:(HFControllerSelectAction)selectionAction;
- (void)_removeUndoManagerNotifications;
- (void)_removeAllUndoOperations;
- (void)_registerUndoOperationForInsertingByteArrays:(NSArray *)byteArrays inRanges:(NSArray *)ranges withSelectionAction:(HFControllerSelectAction)selectionAction;
- (void)_updateBytesPerLine;
- (void)_updateDisplayedRange;
@end
@interface NSEvent (HFLionStuff)
- (CGFloat)scrollingDeltaY;
- (BOOL)hasPreciseScrollingDeltas;
- (CGFloat)deviceDeltaY;
@end
static inline Class preferredByteArrayClass(void) {
return [HFBTreeByteArray class];
}
@implementation HFController
- (void)_sharedInit {
selectedContentsRanges = [[NSMutableArray alloc] initWithObjects:[HFRangeWrapper withRange:HFRangeMake(0, 0)], nil];
byteArray = [[preferredByteArrayClass() alloc] init];
[byteArray addObserver:self forKeyPath:@"changesAreLocked" options:0 context:KVOContextChangesAreLocked];
selectionAnchor = NO_SELECTION;
undoOperations = [[NSMutableSet alloc] init];
}
- (instancetype)init {
self = [super init];
[self _sharedInit];
bytesPerLine = 16;
bytesPerColumn = 1;
_hfflags.editable = YES;
_hfflags.antialias = YES;
_hfflags.showcallouts = YES;
_hfflags.hideNullBytes = NO;
_hfflags.selectable = YES;
representers = [[NSMutableArray alloc] init];
[self setFont:[NSFont fontWithName:HFDEFAULT_FONT size:HFDEFAULT_FONTSIZE]];
return self;
}
- (void)dealloc {
[representers makeObjectsPerformSelector:@selector(_setController:) withObject:nil];
[representers release];
[selectedContentsRanges release];
[self _removeUndoManagerNotifications];
[self _removeAllUndoOperations];
[undoOperations release];
[undoManager release];
[undoCoalescer release];
[_font release];
[byteArray removeObserver:self forKeyPath:@"changesAreLocked"];
[byteArray release];
[cachedData release];
[additionalPendingTransactions release];
[super dealloc];
}
- (void)encodeWithCoder:(NSCoder *)coder {
HFASSERT([coder allowsKeyedCoding]);
[coder encodeObject:representers forKey:@"HFRepresenters"];
[coder encodeInt64:bytesPerLine forKey:@"HFBytesPerLine"];
[coder encodeInt64:bytesPerColumn forKey:@"HFBytesPerColumn"];
[coder encodeObject:_font forKey:@"HFFont"];
[coder encodeDouble:lineHeight forKey:@"HFLineHeight"];
[coder encodeBool:_hfflags.antialias forKey:@"HFAntialias"];
[coder encodeBool:_hfflags.colorbytes forKey:@"HFColorBytes"];
[coder encodeBool:_hfflags.showcallouts forKey:@"HFShowCallouts"];
[coder encodeBool:_hfflags.hideNullBytes forKey:@"HFHidesNullBytes"];
[coder encodeBool:_hfflags.livereload forKey:@"HFLiveReload"];
[coder encodeInt:_hfflags.editMode forKey:@"HFEditMode"];
[coder encodeBool:_hfflags.editable forKey:@"HFEditable"];
[coder encodeBool:_hfflags.selectable forKey:@"HFSelectable"];
}
- (instancetype)initWithCoder:(NSCoder *)coder {
HFASSERT([coder allowsKeyedCoding]);
self = [super init];
[self _sharedInit];
bytesPerLine = (NSUInteger)[coder decodeInt64ForKey:@"HFBytesPerLine"];
bytesPerColumn = (NSUInteger)[coder decodeInt64ForKey:@"HFBytesPerColumn"];
_font = [[coder decodeObjectForKey:@"HFFont"] retain];
lineHeight = (CGFloat)[coder decodeDoubleForKey:@"HFLineHeight"];
_hfflags.antialias = [coder decodeBoolForKey:@"HFAntialias"];
_hfflags.colorbytes = [coder decodeBoolForKey:@"HFColorBytes"];
_hfflags.livereload = [coder decodeBoolForKey:@"HFLiveReload"];
if ([coder containsValueForKey:@"HFEditMode"])
_hfflags.editMode = [coder decodeIntForKey:@"HFEditMode"];
else {
_hfflags.editMode = ([coder decodeBoolForKey:@"HFOverwriteMode"]
? HFOverwriteMode : HFInsertMode);
}
_hfflags.editable = [coder decodeBoolForKey:@"HFEditable"];
_hfflags.selectable = [coder decodeBoolForKey:@"HFSelectable"];
_hfflags.hideNullBytes = [coder decodeBoolForKey:@"HFHidesNullBytes"];
representers = [[coder decodeObjectForKey:@"HFRepresenters"] retain];
return self;
}
- (NSArray *)representers {
return [[representers copy] autorelease];
}
- (void)notifyRepresentersOfChanges:(HFControllerPropertyBits)bits {
FOREACH(HFRepresenter*, rep, representers) {
[rep controllerDidChange:bits];
}
/* Post the HFControllerDidChangePropertiesNotification */
NSNumber *number = [[NSNumber alloc] initWithUnsignedInteger:bits];
NSDictionary *userInfo = [[NSDictionary alloc] initWithObjects:&number forKeys:(id *)&HFControllerChangedPropertiesKey count:1];
[number release];
[[NSNotificationCenter defaultCenter] postNotificationName:HFControllerDidChangePropertiesNotification object:self userInfo:userInfo];
[userInfo release];
}
- (void)_firePropertyChanges {
NSMutableArray *pendingTransactions = additionalPendingTransactions;
NSUInteger pendingTransactionCount = [pendingTransactions count];
additionalPendingTransactions = nil;
HFControllerPropertyBits propertiesToUpdate = propertiesToUpdateInCurrentTransaction;
propertiesToUpdateInCurrentTransaction = 0;
if (pendingTransactionCount > 0 || propertiesToUpdate != 0) {
BEGIN_TRANSACTION();
while (pendingTransactionCount--) {
HFControllerPropertyBits propertiesInThisTransaction = [pendingTransactions[0] unsignedIntegerValue];
[pendingTransactions removeObjectAtIndex:0];
HFASSERT(propertiesInThisTransaction != 0);
[self notifyRepresentersOfChanges:propertiesInThisTransaction];
}
[pendingTransactions release];
if (propertiesToUpdate) {
[self notifyRepresentersOfChanges:propertiesToUpdate];
}
END_TRANSACTION();
}
}
/* Inserts a "fence" so that all prior property change bits will be complete before any new ones */
- (void)_insertPropertyChangeFence {
if (currentPropertyChangeToken == 0) {
HFASSERT(additionalPendingTransactions == nil);
/* There can be no prior property changes */
HFASSERT(propertiesToUpdateInCurrentTransaction == 0);
return;
}
if (propertiesToUpdateInCurrentTransaction == 0) {
/* Nothing to fence */
return;
}
if (additionalPendingTransactions == nil) additionalPendingTransactions = [[NSMutableArray alloc] init];
[additionalPendingTransactions addObject:@(propertiesToUpdateInCurrentTransaction)];
propertiesToUpdateInCurrentTransaction = 0;
}
- (void)_addPropertyChangeBits:(HFControllerPropertyBits)bits {
propertiesToUpdateInCurrentTransaction |= bits;
if (currentPropertyChangeToken == 0) {
[self _firePropertyChanges];
}
}
- (NSUInteger)beginPropertyChangeTransaction {
HFASSERT(currentPropertyChangeToken < NSUIntegerMax);
return ++currentPropertyChangeToken;
}
- (void)endPropertyChangeTransaction:(NSUInteger)token {
if (currentPropertyChangeToken != token) {
[NSException raise:NSInvalidArgumentException format:@"endPropertyChangeTransaction passed token %lu, but expected token %lu", (unsigned long)token, (unsigned long)currentPropertyChangeToken];
}
HFASSERT(currentPropertyChangeToken > 0);
if (--currentPropertyChangeToken == 0) [self _firePropertyChanges];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == KVOContextChangesAreLocked) {
HFASSERT([keyPath isEqual:@"changesAreLocked"]);
[self _addPropertyChangeBits:HFControllerEditable];
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)addRepresenter:(HFRepresenter *)representer {
REQUIRE_NOT_NULL(representer);
HFASSERT([representers indexOfObjectIdenticalTo:representer] == NSNotFound);
HFASSERT([representer controller] == nil);
[representer _setController:self];
[representers addObject:representer];
[representer controllerDidChange: -1];
}
- (void)removeRepresenter:(HFRepresenter *)representer {
REQUIRE_NOT_NULL(representer);
HFASSERT([representers indexOfObjectIdenticalTo:representer] != NSNotFound);
[representers removeObjectIdenticalTo:representer];
[representer _setController:nil];
}
- (HFRange)_maximumDisplayedRangeSet {
unsigned long long contentsLength = [self contentsLength];
HFRange maximumDisplayedRangeSet = HFRangeMake(0, HFRoundUpToNextMultipleSaturate(contentsLength, bytesPerLine));
return maximumDisplayedRangeSet;
}
- (unsigned long long)totalLineCount {
return HFDivideULLRoundingUp(HFRoundUpToNextMultipleSaturate([self contentsLength] - 1, bytesPerLine), bytesPerLine);
}
- (HFFPRange)displayedLineRange {
#if ! NDEBUG
HFASSERT(displayedLineRange.location >= 0);
HFASSERT(displayedLineRange.length >= 0);
HFASSERT(displayedLineRange.location + displayedLineRange.length <= HFULToFP([self totalLineCount]));
#endif
return displayedLineRange;
}
- (void)setDisplayedLineRange:(HFFPRange)range {
#if ! NDEBUG
HFASSERT(range.location >= 0);
HFASSERT(range.length >= 0);
#endif
if (range.location + range.length > HFULToFP([self totalLineCount])) {
range.location = [self totalLineCount] - range.length;
if (range.location < 0) {
return;
}
}
if (! HFFPRangeEqualsRange(range, displayedLineRange)) {
displayedLineRange = range;
[self _addPropertyChangeBits:HFControllerDisplayedLineRange];
}
}
- (CGFloat)lineHeight {
return lineHeight;
}
- (void)setFont:(NSFont *)val {
if (val != _font) {
CGFloat priorLineHeight = [self lineHeight];
[_font release];
_font = [val copy];
NSLayoutManager *manager = [[NSLayoutManager alloc] init];
lineHeight = [manager defaultLineHeightForFont:_font];
[manager release];
HFControllerPropertyBits bits = HFControllerFont;
if (lineHeight != priorLineHeight) bits |= HFControllerLineHeight;
[self _addPropertyChangeBits:bits];
[self _insertPropertyChangeFence];
[self _addPropertyChangeBits:HFControllerViewSizeRatios];
[self _updateDisplayedRange];
}
}
- (BOOL)shouldAntialias {
return _hfflags.antialias;
}
- (void)setShouldAntialias:(BOOL)antialias {
antialias = !! antialias;
if (antialias != _hfflags.antialias) {
_hfflags.antialias = antialias;
[self _addPropertyChangeBits:HFControllerAntialias];
}
}
- (BOOL)shouldColorBytes {
return _hfflags.colorbytes;
}
- (void)setShouldColorBytes:(BOOL)colorbytes {
colorbytes = !! colorbytes;
if (colorbytes != _hfflags.colorbytes) {
_hfflags.colorbytes = colorbytes;
[self _addPropertyChangeBits:HFControllerColorBytes];
}
}
- (BOOL)shouldShowCallouts {
return _hfflags.showcallouts;
}
- (void)setShouldShowCallouts:(BOOL)showcallouts {
showcallouts = !! showcallouts;
if (showcallouts != _hfflags.showcallouts) {
_hfflags.showcallouts = showcallouts;
[self _addPropertyChangeBits:HFControllerShowCallouts];
}
}
- (BOOL)shouldHideNullBytes {
return _hfflags.hideNullBytes;
}
- (void)setShouldHideNullBytes:(BOOL)hideNullBytes
{
hideNullBytes = !! hideNullBytes;
if (hideNullBytes != _hfflags.hideNullBytes) {
_hfflags.hideNullBytes = hideNullBytes;
[self _addPropertyChangeBits:HFControllerHideNullBytes];
}
}
- (BOOL)shouldLiveReload {
return _hfflags.livereload;
}
- (void)setShouldLiveReload:(BOOL)livereload {
_hfflags.livereload = !!livereload;
}
- (void)setBytesPerColumn:(NSUInteger)val {
if (val != bytesPerColumn) {
bytesPerColumn = val;
[self _addPropertyChangeBits:HFControllerBytesPerColumn];
}
}
- (NSUInteger)bytesPerColumn {
return bytesPerColumn;
}
- (BOOL)_shouldInvertSelectedRangesByAnchorRange {
return _hfflags.selectionInProgress && _hfflags.commandExtendSelection;
}
- (NSArray *)_invertedSelectedContentsRanges {
HFASSERT([selectedContentsRanges count] > 0);
HFASSERT(selectionAnchorRange.location != NO_SELECTION);
if (selectionAnchorRange.length == 0) return [NSArray arrayWithArray:selectedContentsRanges];
NSArray *cleanedRanges = [HFRangeWrapper organizeAndMergeRanges:selectedContentsRanges];
NSMutableArray *result = [NSMutableArray array];
/* Our algorithm works as follows - add any ranges outside of the selectionAnchorRange, clipped by the selectionAnchorRange. Then extract every "index" in our cleaned selected arrays that are within the selectionAnchorArray. An index is the location where a range starts or stops. Then use those indexes to create the inverted arrays. A range parity of 1 means that we are adding the range. */
/* Add all the ranges that are outside of selectionAnchorRange, clipping them if necessary */
HFASSERT(HFSumDoesNotOverflow(selectionAnchorRange.location, selectionAnchorRange.length));
FOREACH(HFRangeWrapper*, outsideWrapper, cleanedRanges) {
HFRange range = [outsideWrapper HFRange];
if (range.location < selectionAnchorRange.location) {
HFRange clippedRange;
clippedRange.location = range.location;
HFASSERT(MIN(HFMaxRange(range), selectionAnchorRange.location) >= clippedRange.location);
clippedRange.length = MIN(HFMaxRange(range), selectionAnchorRange.location) - clippedRange.location;
[result addObject:[HFRangeWrapper withRange:clippedRange]];
}
if (HFMaxRange(range) > HFMaxRange(selectionAnchorRange)) {
HFRange clippedRange;
clippedRange.location = MAX(range.location, HFMaxRange(selectionAnchorRange));
HFASSERT(HFMaxRange(range) >= clippedRange.location);
clippedRange.length = HFMaxRange(range) - clippedRange.location;
[result addObject:[HFRangeWrapper withRange:clippedRange]];
}
}
HFASSERT(HFSumDoesNotOverflow(selectionAnchorRange.location, selectionAnchorRange.length));
NEW_ARRAY(unsigned long long, partitions, 2*[cleanedRanges count] + 2);
NSUInteger partitionCount, partitionIndex = 0;
partitions[partitionIndex++] = selectionAnchorRange.location;
FOREACH(HFRangeWrapper*, wrapper, cleanedRanges) {
HFRange range = [wrapper HFRange];
if (! HFIntersectsRange(range, selectionAnchorRange)) continue;
partitions[partitionIndex++] = MAX(selectionAnchorRange.location, range.location);
partitions[partitionIndex++] = MIN(HFMaxRange(selectionAnchorRange), HFMaxRange(range));
}
// For some reason, using HFMaxRange confuses the static analyzer
partitions[partitionIndex++] = HFSum(selectionAnchorRange.location, selectionAnchorRange.length);
partitionCount = partitionIndex;
HFASSERT((partitionCount % 2) == 0);
partitionIndex = 0;
while (partitionIndex < partitionCount) {
HFASSERT(partitionIndex + 1 < partitionCount);
HFASSERT(partitions[partitionIndex] <= partitions[partitionIndex + 1]);
if (partitions[partitionIndex] < partitions[partitionIndex + 1]) {
HFRange range = HFRangeMake(partitions[partitionIndex], partitions[partitionIndex + 1] - partitions[partitionIndex]);
[result addObject:[HFRangeWrapper withRange:range]];
}
partitionIndex += 2;
}
FREE_ARRAY(partitions);
if ([result count] == 0) [result addObject:[HFRangeWrapper withRange:HFRangeMake(selectionAnchor, 0)]];
return [HFRangeWrapper organizeAndMergeRanges:result];
}
- (void)_ensureSelectionIsValid {
HFASSERT(selectedContentsRanges != nil);
HFASSERT([selectedContentsRanges count] > 0);
BOOL onlyOneWrapper = ([selectedContentsRanges count] == 1);
FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
EXPECT_CLASS(wrapper, HFRangeWrapper);
HFRange range = [wrapper HFRange];
if (!HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength]))){
[self setSelectedContentsRanges:@[[HFRangeWrapper withRange:HFRangeMake(0, 0)]]];
return;
}
if (onlyOneWrapper == NO) HFASSERT(range.length > 0); /* If we have more than one wrapper, then none of them should be zero length */
}
}
- (void)_setSingleSelectedContentsRange:(HFRange)newSelection {
HFASSERT(HFRangeIsSubrangeOfRange(newSelection, HFRangeMake(0, [self contentsLength])));
BOOL selectionChanged;
if ([selectedContentsRanges count] == 1) {
selectionChanged = ! HFRangeEqualsRange([selectedContentsRanges[0] HFRange], newSelection);
}
else {
selectionChanged = YES;
}
if (selectionChanged) {
[selectedContentsRanges removeAllObjects];
[selectedContentsRanges addObject:[HFRangeWrapper withRange:newSelection]];
[self _addPropertyChangeBits:HFControllerSelectedRanges];
}
VALIDATE_SELECTION();
}
- (NSArray *)selectedContentsRanges {
VALIDATE_SELECTION();
if ([self _shouldInvertSelectedRangesByAnchorRange]) return [self _invertedSelectedContentsRanges];
else return [NSArray arrayWithArray:selectedContentsRanges];
}
- (unsigned long long)contentsLength {
if (! byteArray) return 0;
else return [byteArray length];
}
- (NSData *)dataForRange:(HFRange)range {
HFASSERT(range.length <= NSUIntegerMax); // it doesn't make sense to ask for a buffer larger than can be stored in memory
HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
if(range.length == 0) {
// Don't throw out cache for an empty request! Also makes the analyzer happier.
return [NSData data];
}
NSUInteger newGenerationIndex = [byteArray changeGenerationCount];
if (cachedData == nil || newGenerationIndex != cachedGenerationIndex || ! HFRangeIsSubrangeOfRange(range, cachedRange)) {
[cachedData release];
cachedGenerationIndex = newGenerationIndex;
cachedRange = range;
NSUInteger length = ll2l(range.length);
unsigned char *data = check_malloc(length);
[byteArray copyBytes:data range:range];
cachedData = [[NSData alloc] initWithBytesNoCopy:data length:length freeWhenDone:YES];
}
if (HFRangeEqualsRange(range, cachedRange)) {
return cachedData;
}
else {
HFASSERT(cachedRange.location <= range.location);
NSRange cachedDataSubrange;
cachedDataSubrange.location = ll2l(range.location - cachedRange.location);
cachedDataSubrange.length = ll2l(range.length);
return [cachedData subdataWithRange:cachedDataSubrange];
}
}
- (void)copyBytes:(unsigned char *)bytes range:(HFRange)range {
HFASSERT(range.length <= NSUIntegerMax); // it doesn't make sense to ask for a buffer larger than can be stored in memory
HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
[byteArray copyBytes:bytes range:range];
}
- (void)_updateDisplayedRange {
HFRange proposedNewDisplayRange;
HFFPRange proposedNewLineRange;
HFRange maxRangeSet = [self _maximumDisplayedRangeSet];
NSUInteger maxBytesForViewSize = NSUIntegerMax;
double maxLines = DBL_MAX;
FOREACH(HFRepresenter*, rep, representers) {
NSView *view = [rep view];
double repMaxLines = [rep maximumAvailableLinesForViewHeight:NSHeight([view frame])];
if (repMaxLines != DBL_MAX) {
/* bytesPerLine may be ULONG_MAX. We want to compute the smaller of maxBytesForViewSize and ceil(repMaxLines) * bytesPerLine. If the latter expression overflows, the smaller is the former. */
NSUInteger repMaxLinesUInt = (NSUInteger)ceil(repMaxLines);
NSUInteger maxLinesTimesBytesPerLine = repMaxLinesUInt * bytesPerLine;
/* Check if we overflowed */
BOOL overflowed = (repMaxLinesUInt != 0 && (maxLinesTimesBytesPerLine / repMaxLinesUInt != bytesPerLine));
if (! overflowed) {
maxBytesForViewSize = MIN(maxLinesTimesBytesPerLine, maxBytesForViewSize);
}
}
maxLines = MIN(repMaxLines, maxLines);
}
if (maxLines == DBL_MAX) {
proposedNewDisplayRange = HFRangeMake(0, 0);
proposedNewLineRange = (HFFPRange){0, 0};
}
else {
unsigned long long maximumDisplayedBytes = MIN(maxRangeSet.length, maxBytesForViewSize);
HFASSERT(HFMaxRange(maxRangeSet) >= maximumDisplayedBytes);
proposedNewDisplayRange.location = MIN(HFMaxRange(maxRangeSet) - maximumDisplayedBytes, displayedContentsRange.location);
proposedNewDisplayRange.location -= proposedNewDisplayRange.location % bytesPerLine;
proposedNewDisplayRange.length = MIN(HFMaxRange(maxRangeSet) - proposedNewDisplayRange.location, maxBytesForViewSize);
if (maxBytesForViewSize % bytesPerLine != 0) {
NSLog(@"Bad max bytes: %lu (%lu)", (unsigned long)maxBytesForViewSize, (unsigned long)bytesPerLine);
}
if (HFMaxRange(maxRangeSet) != ULLONG_MAX && (HFMaxRange(maxRangeSet) - proposedNewDisplayRange.location) % bytesPerLine != 0) {
NSLog(@"Bad max range minus: %llu (%lu)", HFMaxRange(maxRangeSet) - proposedNewDisplayRange.location, (unsigned long)bytesPerLine);
}
long double lastLine = HFULToFP([self totalLineCount]);
proposedNewLineRange.length = MIN(maxLines, lastLine);
proposedNewLineRange.location = MIN(displayedLineRange.location, lastLine - proposedNewLineRange.length);
}
HFASSERT(HFRangeIsSubrangeOfRange(proposedNewDisplayRange, maxRangeSet));
HFASSERT(proposedNewDisplayRange.location % bytesPerLine == 0);
if (! HFRangeEqualsRange(proposedNewDisplayRange, displayedContentsRange) || ! HFFPRangeEqualsRange(proposedNewLineRange, displayedLineRange)) {
displayedContentsRange = proposedNewDisplayRange;
displayedLineRange = proposedNewLineRange;
[self _addPropertyChangeBits:HFControllerDisplayedLineRange];
}
}
- (void)_ensureVisibilityOfLocation:(unsigned long long)location {
HFASSERT(location <= [self contentsLength]);
unsigned long long lineInt = location / bytesPerLine;
long double line = HFULToFP(lineInt);
HFASSERT(line >= 0);
line = MIN(line, HFULToFP([self totalLineCount]) - 1);
HFFPRange lineRange = [self displayedLineRange];
HFFPRange newLineRange = lineRange;
if (line < lineRange.location) {
newLineRange.location = line;
}
else if (line >= lineRange.location + lineRange.length) {
HFASSERT(lineRange.location + lineRange.length >= 1);
newLineRange.location = lineRange.location + (line - (lineRange.location + lineRange.length - 1));
}
[self setDisplayedLineRange:newLineRange];
}
- (void)maximizeVisibilityOfContentsRange:(HFRange)range {
HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
// Find the minimum move necessary to make range visible
HFFPRange displayRange = [self displayedLineRange];
HFFPRange newDisplayRange = displayRange;
unsigned long long startLine = range.location / bytesPerLine;
unsigned long long endLine = HFDivideULLRoundingUp(HFRoundUpToNextMultipleSaturate(HFMaxRange(range), bytesPerLine), bytesPerLine);
HFASSERT(endLine > startLine || endLine == ULLONG_MAX);
long double linesInRange = HFULToFP(endLine - startLine);
long double linesToDisplay = MIN(displayRange.length, linesInRange);
HFASSERT(linesToDisplay <= linesInRange);
long double linesToMoveDownToMakeLastLineVisible = HFULToFP(endLine) - (displayRange.location + displayRange.length);
long double linesToMoveUpToMakeFirstLineVisible = displayRange.location - HFULToFP(startLine);
//HFASSERT(linesToMoveUpToMakeFirstLineVisible <= 0 || linesToMoveDownToMakeLastLineVisible <= 0);
// in general, we expect either linesToMoveUpToMakeFirstLineVisible to be <= zero, or linesToMoveDownToMakeLastLineVisible to be <= zero. However, if the available space is smaller than one line, then that won't be true.
if (linesToMoveDownToMakeLastLineVisible > 0) {
newDisplayRange.location += linesToMoveDownToMakeLastLineVisible;
}
else if (linesToMoveUpToMakeFirstLineVisible > 0 && linesToDisplay >= 1) {
// the >= 1 check prevents some wacky behavior when we have less than one line's worth of space, that caused bouncing between the top and bottom of the line
newDisplayRange.location -= linesToMoveUpToMakeFirstLineVisible;
}
// Use the minimum movement if it would be visually helpful; otherwise just center.
if (HFFPIntersectsRange(displayRange, newDisplayRange)) {
[self setDisplayedLineRange:newDisplayRange];
} else {
[self centerContentsRange:range];
}
}
- (void)centerContentsRange:(HFRange)range {
HFASSERT(HFRangeIsSubrangeOfRange(range, HFRangeMake(0, [self contentsLength])));
HFFPRange displayRange = [self displayedLineRange];
const long double numDisplayedLines = displayRange.length;
HFFPRange newDisplayRange;
unsigned long long startLine = range.location / bytesPerLine;
unsigned long long endLine = HFDivideULLRoundingUp(HFRoundUpToNextMultipleSaturate(HFMaxRange(range), bytesPerLine), bytesPerLine);
HFASSERT(endLine > startLine || endLine == ULLONG_MAX);
long double linesInRange = HFULToFP(endLine - startLine);
/* Handle the case of a line range bigger than we can display by choosing the top lines. */
if (numDisplayedLines <= linesInRange) {
newDisplayRange = (HFFPRange){startLine, numDisplayedLines};
}
else {
/* Construct a newDisplayRange that centers {startLine, endLine} */
long double center = startLine + (endLine - startLine) / 2.;
newDisplayRange = (HFFPRange){center - numDisplayedLines / 2., numDisplayedLines};
}
/* Move the newDisplayRange up or down as necessary */
newDisplayRange.location = fmaxl(newDisplayRange.location, (long double)0.);
newDisplayRange.location = fminl(newDisplayRange.location, HFULToFP([self totalLineCount]) - numDisplayedLines);
[self setDisplayedLineRange:newDisplayRange];
}
/* Clips the selection to a given length. If this would clip the entire selection, returns a zero length selection at the end. Indicates HFControllerSelectedRanges if the selection changes. */
- (void)_clipSelectedContentsRangesToLength:(unsigned long long)newLength {
NSMutableArray *newTempSelection = [selectedContentsRanges mutableCopy];
NSUInteger i, max = [newTempSelection count];
for (i=0; i < max; i++) {
HFRange range = [newTempSelection[i] HFRange];
if (HFMaxRange(range) > newLength) {
if (range.location > newLength) {
/* The range starts past our new max. Just remove this range entirely */
[newTempSelection removeObjectAtIndex:i];
i--;
max--;
}
else {
/* Need to clip this range */
range.length = newLength - range.location;
newTempSelection[i] = [HFRangeWrapper withRange:range];
}
}
}
[newTempSelection setArray:[HFRangeWrapper organizeAndMergeRanges:newTempSelection]];
/* If there are multiple empty ranges, remove all but the first */
BOOL foundEmptyRange = NO;
max = [newTempSelection count];
for (i=0; i < max; i++) {
HFRange range = [newTempSelection[i] HFRange];
HFASSERT(HFMaxRange(range) <= newLength);
if (range.length == 0) {
if (foundEmptyRange) {
[newTempSelection removeObjectAtIndex:i];
i--;
max--;
}
foundEmptyRange = YES;
}
}
if (max == 0) {
/* Removed all ranges - insert one at the end */
[newTempSelection addObject:[HFRangeWrapper withRange:HFRangeMake(newLength, 0)]];
}
/* If something changed, set the new selection and post the change bit */
if (! [selectedContentsRanges isEqualToArray:newTempSelection]) {
[selectedContentsRanges setArray:newTempSelection];
[self _addPropertyChangeBits:HFControllerSelectedRanges];
}
[newTempSelection release];
}
- (void)setByteArray:(HFByteArray *)val {
REQUIRE_NOT_NULL(val);
BEGIN_TRANSACTION();
[byteArray removeObserver:self forKeyPath:@"changesAreLocked"];
[val retain];
[byteArray release];
byteArray = val;
[cachedData release];
cachedData = nil;
[byteArray addObserver:self forKeyPath:@"changesAreLocked" options:0 context:KVOContextChangesAreLocked];
[self _updateDisplayedRange];
[self _addPropertyChangeBits: HFControllerContentValue | HFControllerContentLength];
[self _clipSelectedContentsRangesToLength:[byteArray length]];
END_TRANSACTION();
}
- (HFByteArray *)byteArray {
return byteArray;
}
- (void)_undoNotification:note {
USE(note);
}
- (void)_removeUndoManagerNotifications {
if (undoManager) {
NSNotificationCenter *noter = [NSNotificationCenter defaultCenter];
[noter removeObserver:self name:NSUndoManagerWillUndoChangeNotification object:undoManager];
}
}
- (void)_addUndoManagerNotifications {
if (undoManager) {
NSNotificationCenter *noter = [NSNotificationCenter defaultCenter];
[noter addObserver:self selector:@selector(_undoNotification:) name:NSUndoManagerWillUndoChangeNotification object:undoManager];
}
}
- (void)_removeAllUndoOperations {
/* Remove all the undo operations, because some undo operation is unsupported. Note that if we were smarter we would keep a stack of undo operations and only remove ones "up to" a certain point. */
[undoManager removeAllActionsWithTarget:self];
[undoOperations makeObjectsPerformSelector:@selector(invalidate)];
[undoOperations removeAllObjects];
}
- (void)setUndoManager:(NSUndoManager *)manager {
[self _removeUndoManagerNotifications];
[self _removeAllUndoOperations];
[manager retain];
[undoManager release];
undoManager = manager;
[self _addUndoManagerNotifications];
}
- (NSUndoManager *)undoManager {
return undoManager;
}
- (NSUInteger)bytesPerLine {
return bytesPerLine;
}
- (BOOL)editable {
return _hfflags.editable && ! [byteArray changesAreLocked] && _hfflags.editMode != HFReadOnlyMode;
}
- (void)setEditable:(BOOL)flag {
if (flag != _hfflags.editable) {
_hfflags.editable = flag;
[self _addPropertyChangeBits:HFControllerEditable];
}
}
- (void)_updateBytesPerLine {
NSUInteger newBytesPerLine = NSUIntegerMax;
FOREACH(HFRepresenter*, rep, representers) {
NSView *view = [rep view];
CGFloat width = [view frame].size.width;
NSUInteger repMaxBytesPerLine = [rep maximumBytesPerLineForViewWidth:width];
HFASSERT(repMaxBytesPerLine > 0);
newBytesPerLine = MIN(repMaxBytesPerLine, newBytesPerLine);
}
if (newBytesPerLine != bytesPerLine) {
HFASSERT(newBytesPerLine > 0);
bytesPerLine = newBytesPerLine;
BEGIN_TRANSACTION();
[self _addPropertyChangeBits:HFControllerBytesPerLine];
END_TRANSACTION();
}
}
- (void)representer:(HFRepresenter *)rep changedProperties:(HFControllerPropertyBits)properties {
USE(rep);
HFControllerPropertyBits remainingProperties = properties;
BEGIN_TRANSACTION();
if (remainingProperties & HFControllerBytesPerLine) {
[self _updateBytesPerLine];
remainingProperties &= ~HFControllerBytesPerLine;
}
if (remainingProperties & HFControllerDisplayedLineRange) {
[self _updateDisplayedRange];
remainingProperties &= ~HFControllerDisplayedLineRange;
}
if (remainingProperties & HFControllerByteRangeAttributes) {
[self _addPropertyChangeBits:HFControllerByteRangeAttributes];
remainingProperties &= ~HFControllerByteRangeAttributes;
}
if (remainingProperties & HFControllerViewSizeRatios) {
[self _addPropertyChangeBits:HFControllerViewSizeRatios];
remainingProperties &= ~HFControllerViewSizeRatios;
}
if (remainingProperties) {
NSLog(@"Unknown properties: %lx", (long)remainingProperties);
}
END_TRANSACTION();
}
- (HFByteArray *)byteArrayForSelectedContentsRanges {
HFByteArray *result = nil;
HFByteArray *bytes = [self byteArray];
VALIDATE_SELECTION();
FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
HFRange range = [wrapper HFRange];
HFByteArray *additionalBytes = [bytes subarrayWithRange:range];
if (! result) {
result = additionalBytes;
}
else {
[result insertByteArray:additionalBytes inRange:HFRangeMake([result length], 0)];
}
}
return result;
}
/* Flattens the selected range to a single range (the selected range becomes any character within or between the selected ranges). Modifies the selectedContentsRanges and returns the new single HFRange. Does not call notifyRepresentersOfChanges: */
- (HFRange)_flattenSelectionRange {
HFASSERT([selectedContentsRanges count] >= 1);
HFRange resultRange = [selectedContentsRanges[0] HFRange];
if ([selectedContentsRanges count] == 1) return resultRange; //already flat
FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
HFRange selectedRange = [wrapper HFRange];
if (selectedRange.location < resultRange.location) {
/* Extend our result range backwards */
resultRange.length += resultRange.location - selectedRange.location;
resultRange.location = selectedRange.location;
}
if (HFRangeExtendsPastRange(selectedRange, resultRange)) {
HFASSERT(selectedRange.location >= resultRange.location); //must be true by if statement above
resultRange.length = HFSum(selectedRange.location - resultRange.location, selectedRange.length);
}
}
[self _setSingleSelectedContentsRange:resultRange];
return resultRange;
}
- (unsigned long long)_minimumSelectionLocation {
HFASSERT([selectedContentsRanges count] >= 1);
unsigned long long minSelection = ULLONG_MAX;
FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
HFRange range = [wrapper HFRange];
minSelection = MIN(minSelection, range.location);
}
return minSelection;
}
- (unsigned long long)_maximumSelectionLocation {
HFASSERT([selectedContentsRanges count] >= 1);
unsigned long long maxSelection = 0;
FOREACH(HFRangeWrapper*, wrapper, selectedContentsRanges) {
HFRange range = [wrapper HFRange];
maxSelection = MAX(maxSelection, HFMaxRange(range));
}
return maxSelection;
}
- (unsigned long long)minimumSelectionLocation {
return [self _minimumSelectionLocation];
}
- (unsigned long long)maximumSelectionLocation {
return [self _maximumSelectionLocation];
}
/* Put the selection at the left or right end of the current selection, with zero length. Modifies the selectedContentsRanges and returns the new single HFRange. Does not call notifyRepresentersOfChanges: */
- (HFRange)_telescopeSelectionRangeInDirection:(HFControllerMovementDirection)direction {
HFRange resultRange;
HFASSERT(direction == HFControllerDirectionLeft || direction == HFControllerDirectionRight);
resultRange.location = (direction == HFControllerDirectionLeft ? [self _minimumSelectionLocation] : [self _maximumSelectionLocation]);
resultRange.length = 0;
[self _setSingleSelectedContentsRange:resultRange];
return resultRange;
}
- (void)beginSelectionWithEvent:(NSEvent *)event forByteIndex:(unsigned long long)characterIndex {
USE(event);
HFASSERT(characterIndex <= [self contentsLength]);
/* Determine how to perform the selection - normally, with command key, or with shift key. Command + shift is the same as command. The shift key closes the selection - the selected range becomes the single range containing the first and last selected character. */
_hfflags.shiftExtendSelection = NO;
_hfflags.commandExtendSelection = NO;
NSUInteger flags = [event modifierFlags];
if (flags & NSCommandKeyMask) _hfflags.commandExtendSelection = YES;
else if (flags & NSShiftKeyMask) _hfflags.shiftExtendSelection = YES;
selectionAnchor = NO_SELECTION;
selectionAnchorRange = HFRangeMake(NO_SELECTION, 0);
_hfflags.selectionInProgress = YES;
if (_hfflags.commandExtendSelection) {
/* The selection anchor is used to track the "invert" range. All characters within this range have their selection inverted. This is tracked by the _shouldInvertSelectedRangesByAnchorRange method. */
selectionAnchor = characterIndex;
selectionAnchorRange = HFRangeMake(characterIndex, 0);
}
else if (_hfflags.shiftExtendSelection) {
/* The selection anchor is used to track the single (flattened) selected range. */
HFRange selectedRange = [self _flattenSelectionRange];
unsigned long long distanceFromRangeStart = HFAbsoluteDifference(selectedRange.location, characterIndex);
unsigned long long distanceFromRangeEnd = HFAbsoluteDifference(HFMaxRange(selectedRange), characterIndex);
if (selectedRange.length == 0) {
HFASSERT(distanceFromRangeStart == distanceFromRangeEnd);
selectionAnchor = selectedRange.location;
selectedRange.location = MIN(characterIndex, selectedRange.location);
selectedRange.length = distanceFromRangeStart;
}
else if (distanceFromRangeStart >= distanceFromRangeEnd) {
/* Push the "end forwards" */
selectedRange.length = distanceFromRangeStart;
selectionAnchor = selectedRange.location;
}
else {
/* Push the "start back" */
selectedRange.location = selectedRange.location + selectedRange.length - distanceFromRangeEnd;
selectedRange.length = distanceFromRangeEnd;
selectionAnchor = HFSum(selectedRange.length, selectedRange.location);
}
HFASSERT(HFRangeIsSubrangeOfRange(selectedRange, HFRangeMake(0, [self contentsLength])));
selectionAnchorRange = selectedRange;
[self _setSingleSelectedContentsRange:selectedRange];
}
else {
/* No modifier key selection. The selection anchor is not used. */
[self _setSingleSelectedContentsRange:HFRangeMake(characterIndex, 0)];
selectionAnchor = characterIndex;
}
}
- (void)continueSelectionWithEvent:(NSEvent *)event forByteIndex:(unsigned long long)byteIndex {
USE(event);
HFASSERT(_hfflags.selectionInProgress);
HFASSERT(byteIndex <= [self contentsLength]);
BEGIN_TRANSACTION();
if (_hfflags.commandExtendSelection) {
/* Clear any zero-length ranges, unless there's only one */
NSUInteger rangeCount = [selectedContentsRanges count];
NSUInteger rangeIndex = rangeCount;
while (rangeIndex-- > 0) {
if (rangeCount > 1 && [selectedContentsRanges[rangeIndex] HFRange].length == 0) {
[selectedContentsRanges removeObjectAtIndex:rangeIndex];
rangeCount--;
}
}
selectionAnchorRange.location = MIN(byteIndex, selectionAnchor);
selectionAnchorRange.length = MAX(byteIndex, selectionAnchor) - selectionAnchorRange.location;
[self _addPropertyChangeBits:HFControllerSelectedRanges];
}
else if (_hfflags.shiftExtendSelection) {
HFASSERT(selectionAnchorRange.location != NO_SELECTION);
HFASSERT(selectionAnchor != NO_SELECTION);
HFRange range;
if (! HFLocationInRange(byteIndex, selectionAnchorRange)) {
/* The character index is outside of the selection anchor range. The new range is just the selected anchor range combined with the character index. */
range.location = MIN(byteIndex, selectionAnchorRange.location);
unsigned long long rangeEnd = MAX(byteIndex, HFSum(selectionAnchorRange.location, selectionAnchorRange.length));
HFASSERT(rangeEnd >= range.location);
range.length = rangeEnd - range.location;
}
else {
/* The character is within the selection anchor range. We use the selection anchor index to determine which "side" of the range is selected. */