forked from ttscoff/nv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotesTableView.m
executable file
·1439 lines (1143 loc) · 51.9 KB
/
NotesTableView.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
/*Copyright (c) 2010, Zachary Schneirov. All rights reserved.
This file is part of Notational Velocity.
Notational Velocity 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 3 of the License, or
(at your option) any later version.
Notational Velocity 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 Notational Velocity. If not, see <http://www.gnu.org/licenses/>. */
#import "NotesTableView.h"
#import "AppController_Importing.h"
#import "FastListDataSource.h"
#import "NoteAttributeColumn.h"
#import "ExternalEditorListController.h"
#import "GlobalPrefs.h"
#import "NotationPrefs.h"
#import "NoteObject.h"
#import "NSCollection_utils.h"
#import "LabelColumnCell.h"
#import "UnifiedCell.h"
#import "HeaderViewWithMenu.h"
#import "NSString_NV.h"
#import "NotesTableHeaderCell.h"
#import "LinkingEditor.h"
#import "AppController.h"
//#import "NotesTableCornerView.h"
#define STATUS_STRING_FONT_SIZE 16.0f
#define SET_DUAL_HIGHLIGHTS 0
#define SYNTHETIC_TAGS_COLUMN_INDEX 200
static void _CopyItemWithSelectorFromMenu(NSMenu *destMenu, NSMenu *sourceMenu, SEL aSel, id target, NSInteger tag);
@implementation NotesTableView
//there's something wrong with this initialization under panther, I think
- (id)initWithCoder:(NSCoder *)decoder {
if ((self = [super initWithCoder:decoder])) {
globalPrefs = [GlobalPrefs defaultPrefs];
userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults registerDefaults: [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool: NO], @"UseCtrlForSwitchingNotes", nil]];
loadStatusString = NSLocalizedString(@"Loading Notes...",nil);
loadStatusAttributes = [[NSDictionary dictionaryWithObjectsAndKeys:
[NSFont fontWithName:@"Helvetica" size:STATUS_STRING_FONT_SIZE], NSFontAttributeName,
[NSColor colorWithCalibratedRed:0.0f green:0.0f blue:0.0f alpha:0.5f], NSForegroundColorAttributeName, nil] retain];
loadStatusStringWidth = [loadStatusString sizeWithAttributes:loadStatusAttributes].width;
affinity = 0;
shouldUseSecondaryHighlightColor = viewMenusValid = NO;
firstRowIndexBeforeSplitResize = NSNotFound;
headerView = [[HeaderViewWithMenu alloc] init];
[headerView setTableView:self];
[headerView setFrame:[[self headerView] frame]];
NSArray *columnsToDisplay = [globalPrefs visibleTableColumns];
allColumns = [[NSMutableArray alloc] initWithCapacity:4];
allColsDict = [[NSMutableDictionary alloc] initWithCapacity:4];
id (*titleReferencor)(id, id, NSInteger) = [globalPrefs horizontalLayout] ?
([globalPrefs tableColumnsShowPreview] ? unifiedCellForNote : unifiedCellSingleLineForNote) :
([globalPrefs tableColumnsShowPreview] ? tableTitleOfNote : titleOfNote2);
NSString *colStrings[] = { NoteTitleColumnString, NoteLabelsColumnString, NoteDateModifiedColumnString, NoteDateCreatedColumnString };
SEL colMutators[] = { @selector(setTitleString:), @selector(setLabelString:), NULL, NULL };
id (*colReferencors[])(id, id, NSInteger) = {titleReferencor, labelColumnCellForNote, dateModifiedStringOfNote, dateCreatedStringOfNote };
NSInteger (*sortFunctions[])(id*, id*) = { compareTitleString, compareLabelString, compareDateModified, compareDateCreated };
NSInteger (*reverseSortFunctions[])(id*, id*) = { compareTitleStringReverse, compareLabelStringReverse, compareDateModifiedReverse,
compareDateCreatedReverse };
NSUInteger i;
for (i=0; i<sizeof(colStrings)/sizeof(NSString*); i++) {
NoteAttributeColumn *column = [[NoteAttributeColumn alloc] initWithIdentifier:colStrings[i]];
[column setEditable:(colMutators[i] != NULL)];
[column setHeaderCell:[[[NotesTableHeaderCell alloc] initTextCell:[[NSBundle mainBundle] localizedStringForKey:colStrings[i] value:@"" table:nil]] autorelease]];
[column setMutatingSelector:colMutators[i]];
[column setDereferencingFunction:colReferencors[i]];
[column setSortingFunction:sortFunctions[i]];
[column setReverseSortingFunction:reverseSortFunctions[i]];
[column setResizingMask:NSTableColumnUserResizingMask];
[allColsDict setObject:column forKey:colStrings[i]];
[allColumns addObject:column];
[column release];
}
[[self noteAttributeColumnForIdentifier:NoteLabelsColumnString] setDataCell: [[[LabelColumnCell alloc] init] autorelease]];
[self _configureAttributesForCurrentLayout];
[self setAllowsColumnSelection:NO];
//[self setVerticalMotionCanBeginDrag:NO];
BOOL hideHeader = (([columnsToDisplay count] == 1 && [columnsToDisplay containsObject:NoteTitleColumnString]) || [globalPrefs horizontalLayout]);
[[self cornerView] setFrameOrigin:NSMakePoint(-1000,-1000)];
[self setCornerView:nil];
[self setHeaderView:hideHeader ? nil : headerView];
[[self noteAttributeColumnForIdentifier:NoteTitleColumnString] setResizingMask:NSTableColumnUserResizingMask | NSTableColumnAutoresizingMask];
[self setColumnAutoresizingStyle:NSTableViewUniformColumnAutoresizingStyle];
//[self setSortDirection:[globalPrefs tableIsReverseSorted]
// inTableColumn:[self tableColumnWithIdentifier:[globalPrefs sortedTableColumnKey]]];
}
return self;
}
- (void)dealloc {
[loadStatusAttributes release];
[allColumns release];
[allColsDict release];
[headerView release];
[super dealloc];
}
//extracted from initialization to run in a safe way
- (void)restoreColumns {
unsigned int i;
//if columns currently exist, then remove them first, so that nstableview's autosave/restore works properly
if ([[self tableColumns] count]) {
for (i=0; i<[allColumns count]; i++) {
[self removeTableColumn:[allColumns objectAtIndex:i]];
}
}
//horizontal view has only a single column; store column widths separately for it
NSArray *columnsToDisplay = [globalPrefs horizontalLayout] ? [NSArray arrayWithObject:NoteTitleColumnString] : [globalPrefs visibleTableColumns];
for (i=0; i<[allColumns count]; i++) {
NoteAttributeColumn *column = [allColumns objectAtIndex:i];
if ([columnsToDisplay containsObject:[column identifier]])
[self addTableColumn:column];
[column updateWidthForHighlight];
}
[self setAutosaveName:[globalPrefs horizontalLayout] ? @"unifiedNotesTable" : @"notesTable"];
[self setAutosaveTableColumns:YES];
[self sizeToFit];
[self setSortDirection:[globalPrefs tableIsReverseSorted]
inTableColumn:[self tableColumnWithIdentifier:[globalPrefs sortedTableColumnKey]]];
}
- (void)awakeFromNib {
[globalPrefs registerWithTarget:self forChangesInSettings:
@selector(setTableFontSize:sender:),
@selector(setHorizontalLayout:sender:),@selector(setShowGrid:sender:),@selector(setAlternatingRows:sender:), nil];
[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil]];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(windowDidBecomeMain:)
name:NSWindowDidBecomeMainNotification object:[self window]];
[center addObserver:self selector:@selector(windowDidResignMain:)
name:NSWindowDidResignMainNotification object:[self window]];
//[self setb]
[[self enclosingScrollView] setDrawsBackground:NO];
// [self setBackgroundColor:[NSColor clearColor]];
outletObjectAwoke(self);
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
if ([sender draggingSource] == self)
return NO;
return YES;
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
return NSDragOperationNone;
}
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender {
return NSDragOperationCopy;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
if ([sender draggingSource] == self)
return NO;
return [[NSApp delegate] addNotesFromPasteboard:[sender draggingPasteboard]];
}
- (void)paste:(id)sender {
[[NSApp delegate] addNotesFromPasteboard:[NSPasteboard generalPasteboard]];
}
- (float)tableFontHeight {
return tableFontHeight;
}
- (BOOL)isActiveStyle {
return isActiveStyle;
}
- (void)_setActiveStyleState:(BOOL)activeStyle {
NoteAttributeColumn *col = [self noteAttributeColumnForIdentifier:NoteTitleColumnString];
#if SET_DUAL_HIGHLIGHTS
activeStyle = YES;
#endif
isActiveStyle = activeStyle;
[col setDereferencingFunction: [globalPrefs horizontalLayout] ? ([globalPrefs tableColumnsShowPreview] ? unifiedCellForNote : unifiedCellSingleLineForNote) :
([globalPrefs tableColumnsShowPreview] ? (activeStyle ? properlyHighlightingTableTitleOfNote : tableTitleOfNote) : titleOfNote2)];
}
- (void)updateTitleDereferencorState {
NSWindow *win = [self window];
[self _setActiveStyleState: [win isMainWindow] && ([win firstResponder] == self || [self currentEditor]) ];
}
- (BOOL)becomeFirstResponder {
[self updateTitleDereferencorState];
return [super becomeFirstResponder];
}
- (BOOL)resignFirstResponder {
[self _setActiveStyleState:NO];
return [super resignFirstResponder];
}
- (void)reloadDataIfNotEditing {
if (![self currentEditor]) {
[self reloadData];
}
}
- (void)reloadData {
[headerView setIsReloading:YES];
[super reloadData];
[headerView setIsReloading:NO];
}
- (void)menuNeedsUpdate:(NSMenu *)menu {
if (!viewMenusValid && [menu delegate] == (id)self) {
[menu setSubmenu:[self menuForColumnConfiguration:nil] forItem:[menu itemWithTag:97]];
[menu setSubmenu:[self menuForColumnSorting] forItem:[menu itemWithTag:98]];
viewMenusValid = YES;
}
}
- (void)_configureAttributesForCurrentLayout {
BOOL horiz = [globalPrefs horizontalLayout];
[self setUsesAlternatingRowBackgroundColors:[globalPrefs alternatingRows]];
[self updateGrid];
NoteAttributeColumn *col = [self noteAttributeColumnForIdentifier:NoteTitleColumnString];
if (!cachedCell) cachedCell = [[col dataCell] retain];
[col setDataCell: horiz ? [[[UnifiedCell alloc] init] autorelease] : cachedCell];
NSFont *font = [NSFont systemFontOfSize:[globalPrefs tableFontSize]];
NSUInteger i;
for (i=0; i<[allColumns count]; i++) {
[[[allColumns objectAtIndex:i] dataCell] setFont:font];
}
BOOL isOneRow = !horiz || (![globalPrefs tableColumnsShowPreview] && !ColumnIsSet(NoteLabelsColumn, [globalPrefs tableColumnsBitmap]));
if (IsLeopardOrLater){
// [self setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleRegular];
[self setSelectionHighlightStyle:isOneRow ? NSTableViewSelectionHighlightStyleRegular : NSTableViewSelectionHighlightStyleSourceList];
}
NSLayoutManager *lm = [[NSLayoutManager alloc] init];
tableFontHeight = [lm defaultLineHeightForFont:font];
float h[4] = {(tableFontHeight * 3.0 + 5.0f), (tableFontHeight * 2.0 + 6.0f), (tableFontHeight + 2.0f), tableFontHeight + 2.0f};
[self setRowHeight: horiz ? ([globalPrefs tableColumnsShowPreview] ? h[0] :
(ColumnIsSet(NoteLabelsColumn,[globalPrefs tableColumnsBitmap]) ? h[1] : h[2])) : h[3]];
[lm release];
[self setIntercellSpacing:NSMakeSize(12.0, 2.0)];
//[self setGridStyleMask:horiz ? NSTableViewSolidHorizontalGridLineMask : NSTableViewGridNone];
}
- (void)settingChangedForSelectorString:(NSString*)selectorString {
if ([selectorString isEqualToString:SEL_STR(setTableFontSize:sender:)]) {
[self _configureAttributesForCurrentLayout];
} else if ([selectorString isEqualToString:SEL_STR(setHorizontalLayout:sender:)]) {
[self abortEditing];
//restore columns according to the current preferences
[self restoreColumns];
[self _configureAttributesForCurrentLayout];
[self updateTitleDereferencorState];
[self updateHeaderViewForColumns];
viewMenusValid = NO;
}else if (([selectorString isEqualToString:SEL_STR(setShowGrid:sender:)])||([selectorString isEqualToString:SEL_STR(setAlternatingRows:sender:)]) ) {
if (([selectorString isEqualToString:SEL_STR(setAlternatingRows:sender:)])) {
[self setUsesAlternatingRowBackgroundColors:[globalPrefs alternatingRows]];
}
[self updateGrid];
}
}
- (double)distanceFromRow:(NSUInteger)aRow forVisibleArea:(NSRect)visibleRect {
return [self rectOfRow:aRow].origin.y - visibleRect.origin.y;
}
- (ViewLocationContext)viewingLocation {
ViewLocationContext ctx;
NSUInteger pivotRow = [[self selectedRowIndexes] firstIndex];
NSUInteger nRows = (NSUInteger)[self numberOfRows];
NSRect visibleRect = [self visibleRect];
NSRange range = [self rowsInRect:visibleRect];
if (!NSLocationInRange(pivotRow, range)) {
if (NSLocationInRange(nRows - 1, range)) {
pivotRow = nRows - 1;
} else {
pivotRow = [self rowAtPoint:NSMakePoint(1, visibleRect.origin.y + [self rowHeight])];
}
}
ctx.pivotRowWasEdge = (pivotRow == 0 || pivotRow == nRows - 1);
ctx.nonRetainedPivotObject = nil;
ctx.verticalDistanceToPivotRow = 0;
if (pivotRow < nRows) {
if ((ctx.nonRetainedPivotObject = [(FastListDataSource*)[self dataSource] immutableObjects][pivotRow])) {
ctx.verticalDistanceToPivotRow = [self distanceFromRow:pivotRow forVisibleArea:visibleRect];
}
}
return ctx;
}
- (void)setViewingLocation:(ViewLocationContext)ctx {
if (ctx.nonRetainedPivotObject) {
NSInteger pivotIndex = [(FastListDataSource*)[self dataSource] indexOfObjectIdenticalTo:ctx.nonRetainedPivotObject];
if (pivotIndex != NSNotFound) {
//figure out how to determine top/bottom condition:
//if pivotRow was 0 or nRows-1, and pivotIndex is not either, then scroll maximally in the nearest direction?
NSInteger lastRow = [self numberOfRows] - 1;
if (ctx.pivotRowWasEdge && (pivotIndex != 0 && pivotIndex != lastRow)) {
pivotIndex = ABS(pivotIndex - 0) < ABS(pivotIndex - lastRow) ? 0 : lastRow;
ctx.verticalDistanceToPivotRow = 0;
//NSLog(@"edge pivot dislodged!");
}
//(scroll pivotNote by verticalDistanceToPivotRow from the top)
[self scrollRowToVisible:pivotIndex withVerticalOffset:ctx.verticalDistanceToPivotRow];
}
}
}
- (void)scrollRowToVisible:(NSInteger)rowIndex withVerticalOffset:(float)offset {
NSRect rowRect = [self rectOfRow:rowIndex];
rowRect.origin.y -= offset;
NSClipView *clipView = [[self enclosingScrollView] contentView];
[clipView scrollToPoint:[clipView constrainScrollPoint:rowRect.origin]];
[[self enclosingScrollView] reflectScrolledClipView:clipView];
}
- (void)editRowAtColumnWithIdentifier:(id)identifier {
NSInteger colIndex = -1;
NSInteger selected = [self selectedRow];
if (selected < 0) {
NSBeep();
return;
}
if ([globalPrefs horizontalLayout]) {
//default to editing title if this is attempted in horizontal mode for any column other than tags
//(which currently are the only two editable columns, anyway)
colIndex = [identifier isEqualToString:NoteLabelsColumnString] ? SYNTHETIC_TAGS_COLUMN_INDEX : 0;
} else if ((colIndex = [self columnWithIdentifier:identifier]) < 0) {
//always move title column to 0 index
NSInteger newColIndex = (NSInteger)(![identifier isEqualToString:NoteTitleColumnString]);
NSTableColumn *column = [self noteAttributeColumnForIdentifier:identifier];
if (column && [self addPermanentTableColumn:column]) {
NSUInteger addedColIndex = [[self tableColumns] indexOfObjectIdenticalTo:column];
if (addedColIndex < [[self tableColumns] count]) {
[self moveColumn:addedColIndex toColumn:newColIndex];
colIndex = newColIndex;
[self sizeToFit];
}
}
}
if (colIndex > -1) {
[self editColumn:colIndex row:selected withEvent:[[self window] currentEvent] select:YES];
} else {
NSBeep();
}
}
- (NoteAttributeColumn*)noteAttributeColumnForIdentifier:(NSString*)identifier {
return [allColsDict objectForKey:identifier];
}
- (BOOL)addPermanentTableColumn:(NSTableColumn*)column {
if (![globalPrefs horizontalLayout]) {
[self addTableColumn:column];
}
[globalPrefs addTableColumn:[column identifier] sender:self];
if ([globalPrefs horizontalLayout]) //for now, for extending rowheight when tags are shown/hidden
[self _configureAttributesForCurrentLayout];
if ([[column identifier] isEqualToString:[globalPrefs sortedTableColumnKey]]) {
[(NoteAttributeColumn*)[self highlightedTableColumn] updateWidthForHighlight];
[self setHighlightedTableColumn:column];
[(NoteAttributeColumn*)column updateWidthForHighlight];
}
[self updateHeaderViewForColumns];
viewMenusValid = NO;
return YES;
}
- (void)updateHeaderViewForColumns {
id oldHeader = [self headerView];
id newHeader = headerView;
if ([[self tableColumns] count] == 1 && [self tableColumnWithIdentifier:NoteTitleColumnString]) {
//if only displaying title, remove the column header; it is redundant
newHeader = nil;
}
if (oldHeader != newHeader) {
//[headerView setTableView:newHeader ? self : nil];
[self setHeaderView:newHeader];
[self setCornerView: nil];
if ([self respondsToSelector:@selector(_sizeRowHeaderToFitIfNecessary)]) {
//hopefully 10.5 has this
[self _sizeRowHeaderToFitIfNecessary];
} else if ([self respondsToSelector:@selector(_sizeToFitIfNecessary)]) {
//probably only on 10.3.x
[self _sizeToFitIfNecessary];
[[self enclosingScrollView] setNeedsDisplay:YES];
} else {
//anything else
NSWindow *win = [self window];
NSRect frame = [win frame];
//this is a nasty little hack
frame.size.height -= 2.6f;
frame.size.width -= 2.6f;
[win setFrame:frame display:NO];
frame.size.height += 2.6f;
frame.size.width += 2.6f;
[win setFrame:frame display:YES];
}
//[self tile];
}
}
- (IBAction)actionHideShowColumn:(id)sender {
NSTableColumn *column = [sender representedObject];
if ([globalPrefs horizontalLayout] && [[column identifier] isEqualToString:NoteTitleColumnString]) {
NSBeep();
return;
}
if ([[globalPrefs visibleTableColumns] containsObject:[column identifier]]) {
if ([[globalPrefs visibleTableColumns] count] > 1) {
[self abortEditing];
if([[globalPrefs sortedTableColumnKey] isEqualToString:[column identifier]]){
if(![[column identifier] isEqualToString:NoteTitleColumnString]&&[[globalPrefs visibleTableColumns] containsObject:NoteTitleColumnString]){
[self setStatusForSortedColumn: [self tableColumnWithIdentifier:NoteTitleColumnString]];
}else{
NSUInteger idex=[[globalPrefs visibleTableColumns]indexOfObjectPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
return ![obj isEqualToString:[column identifier]];
}];
if(idex!=NSNotFound){
[self setStatusForSortedColumn:[self tableColumnWithIdentifier:[[globalPrefs visibleTableColumns]objectAtIndex:idex]]];
}
}
}
[self removeTableColumn:column];
[globalPrefs removeTableColumn:[column identifier] sender:self];
viewMenusValid = NO;
if ([globalPrefs horizontalLayout]) //for now, in case we are hiding tags when previews are not visible
[self _configureAttributesForCurrentLayout];
} else {
NSBeep();
}
[self updateHeaderViewForColumns];
} else {
[self addPermanentTableColumn:column];
NSArray *cols = [self tableColumns];
NSUInteger addedColIndex = [cols indexOfObjectIdenticalTo:column];
NSInteger clickedColIndex = [sender tag];
if ((NSUInteger)clickedColIndex < [cols count] && addedColIndex < [cols count])
[self moveColumn:addedColIndex toColumn:clickedColIndex + 1];
}
[self sizeToFit];
}
- (void)sizeToFit{
[super sizeToFit];
}
- (IBAction)toggleNoteBodyPreviews:(id)sender {
[globalPrefs setTableColumnsShowPreview: ![globalPrefs tableColumnsShowPreview] sender:self];
[self _configureAttributesForCurrentLayout];
[self setNeedsDisplay:YES];
}
- (NSMenu *)menuForColumnSorting {
NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
NSEnumerator *theEnumerator = [allColumns objectEnumerator];
NSTableColumn *theColumn = nil;
NSString *sortKey = [globalPrefs sortedTableColumnKey];
NSImage *sortArrow;
if([globalPrefs tableIsReverseSorted] ){
sortArrow=[NSImage imageNamed:@"NSDescendingSortIndicator"];
}else{
sortArrow=[NSImage imageNamed:@"NSAscendingSortIndicator"];
}
while ((theColumn = [theEnumerator nextObject]) != nil) {
NSMenuItem *theMenuItem = [[[NSMenuItem alloc] initWithTitle:[[theColumn headerCell] stringValue]
action:@selector(setStatusForSortedColumn:)
keyEquivalent:@""] autorelease];
[theMenuItem setTarget:self];
[theMenuItem setRepresentedObject:theColumn];
[theMenuItem setState:[[theColumn identifier] isEqualToString:sortKey]];
[theMenuItem setOnStateImage:[NSImage imageNamed:nil]];
[theMenuItem setOnStateImage:sortArrow];
[theMenu addItem:theMenuItem];
}
return theMenu;
}
- (NSMenu *)menuForColumnConfiguration:(NSTableColumn *)inSelectedColumn {
NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
NSArray *prefsCols = [globalPrefs visibleTableColumns];
NSEnumerator *theEnumerator = [allColumns objectEnumerator];
NSTableColumn *theColumn = nil;
while ((theColumn = [theEnumerator nextObject]) != nil) {
NSMenuItem *theMenuItem = [[[NSMenuItem alloc] initWithTitle:[[theColumn headerCell] stringValue]
action:@selector(actionHideShowColumn:)
keyEquivalent:@""] autorelease];
[theMenuItem setTarget:self];
[theMenuItem setRepresentedObject:theColumn];
[theMenuItem setState:[prefsCols containsObject:[theColumn identifier]]];
[theMenuItem setTag:(inSelectedColumn ? [[self tableColumns] indexOfObjectIdenticalTo:inSelectedColumn] : 0)];
[theMenu addItem:theMenuItem];
}
return theMenu;
}
//- (BOOL)validateMenuItem:(NSMenuItem *)menuItem{
// SEL selector = [menuItem action];
//// if (selector==@selector(setStatusForSortedColumn:)) {
//// if (![[globalPrefs visibleTableColumns]containsObject:[[menuItem representedObject] identifier]]) {
//// return NO;
//// }
//// }else
// if([globalPrefs horizontalLayout]&&(selector==@selector(actionHideShowColumn:))){
// BOOL retNo=NO;
// BOOL gotMod=[[globalPrefs visibleTableColumns]containsObject:NoteDateModifiedColumnString];//&&[[globalPrefs visibleTableColumns]containsObject:NoteDateCreatedColumnString]);
// NSString *key=[globalPrefs sortedTableColumnKey];
// if ([key isEqualToString:NoteDateCreatedColumnString]) {
// retNo=[[[menuItem representedObject] identifier] isEqualToString:NoteDateModifiedColumnString];
// }else if ([key isEqualToString:NoteDateModifiedColumnString]) {
// retNo=[[[menuItem representedObject] identifier] isEqualToString:NoteDateCreatedColumnString];
// }else{
// retNo=(gotMod&&[[[menuItem representedObject] identifier] isEqualToString:NoteDateCreatedColumnString]);
// }
//
// if (gotMod&&retNo) {
// [menuItem setState:0];
// return NO;
// }
// }
// return YES;
//}
- (void)setStatusForSortedColumn:(id)sender {
NSTableColumn* tableColumn = (NSTableColumn*)sender;
NSString *lastColumnName = [globalPrefs sortedTableColumnKey];
BOOL sortDescending = [globalPrefs tableIsReverseSorted];
if ([sender isKindOfClass:[NSMenuItem class]]){
tableColumn = [sender representedObject];
[sender setOnStateImage:[NSImage imageNamed:nil]];
NSImage *sortArrow;
if(!sortDescending){
sortArrow=[NSImage imageNamed:@"NSDescendingSortIndicator"];
}else{
sortArrow=[NSImage imageNamed:@"NSAscendingSortIndicator"];
}
[sender setOnStateImage:sortArrow];
}
if ([lastColumnName isEqualToString:[tableColumn identifier]]) {
//User clicked same column, change sort order
sortDescending = !sortDescending;
} else {
//user clicked new column
//sortDescending = NO;
viewMenusValid = NO;
}
// save new sorting selector, and re-sort the array.
NoteAttributeColumn *lastCol = nil;
if (lastColumnName) {
lastCol = [self noteAttributeColumnForIdentifier:lastColumnName];
[self setIndicatorImage:nil inTableColumn:lastCol];
}
[self setSortDirection:sortDescending inTableColumn:tableColumn];
[globalPrefs setSortedTableColumnKey:[tableColumn identifier] reversed:sortDescending sender:self];
[lastCol updateWidthForHighlight];
}
- (void)setSortDirection:(BOOL)direction inTableColumn:(NSTableColumn*)tableColumn {
[self setHighlightedTableColumn:tableColumn];
// Set the graphic for the new column header
[self setIndicatorImage: (direction ? [NSImage imageNamed:@"NSDescendingSortIndicator"] :
[NSImage imageNamed:@"NSAscendingSortIndicator"]) inTableColumn:tableColumn];
[(NoteAttributeColumn*)tableColumn updateWidthForHighlight];
}
- (BOOL)acceptsFirstMouse:(NSEvent *)e {
return YES;
}
- (NSMenu *)menuForEvent:(NSEvent *)theEvent {
// [[NSNotificationCenter defaultCenter] postNotificationName:@"ModTimersShouldReset" object:nil];
NSPoint mousePoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
NSInteger row = [self rowAtPoint:mousePoint];
if (row >= 0) {
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:row]
byExtendingSelection:[[self selectedRowIndexes] containsIndex:(NSUInteger)row] && [[self selectedRowIndexes] count] > 1];
}
if (![self numberOfSelectedRows])
return nil;
return [self defaultNoteCommandsMenuWithTarget:[NSApp delegate]];
}
static void _CopyItemWithSelectorFromMenu(NSMenu *destMenu, NSMenu *sourceMenu, SEL aSel, id target, NSInteger tag) {
NSInteger idx = [sourceMenu indexOfItemWithTag:tag];
if (idx > -1 || (idx = [sourceMenu indexOfItemWithTarget:target andAction:aSel]) > -1) {
[destMenu addItem:[[(NSMenuItem*)[sourceMenu itemAtIndex:idx] copy] autorelease]];
}
}
- (NSMenu *)defaultNoteCommandsMenuWithTarget:(id)target {
NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@"Contextual Note Commands Menu"] autorelease];
NSMenu *notesMenu = [[[NSApp mainMenu] itemWithTag:NOTES_MENU_ID] submenu];
_CopyItemWithSelectorFromMenu(theMenu, notesMenu, @selector(renameNote:), target, -1);
_CopyItemWithSelectorFromMenu(theMenu, notesMenu, @selector(tagNote:), target, -1);
_CopyItemWithSelectorFromMenu(theMenu, notesMenu, @selector(deleteNote:), target, -1);
[theMenu addItem:[NSMenuItem separatorItem]];
NSMenuItem *noteLinkItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Copy URL",@"contextual menu item title to copy urls")
action:@selector(copyNoteLink:) keyEquivalent:@"c"];
[noteLinkItem setKeyEquivalentModifierMask:NSCommandKeyMask|NSAlternateKeyMask];
[noteLinkItem setTarget:target];
[theMenu addItem:[noteLinkItem autorelease]];
_CopyItemWithSelectorFromMenu(theMenu, notesMenu, @selector(exportNote:), target, -1);
_CopyItemWithSelectorFromMenu(theMenu, notesMenu, @selector(revealNote:), target, -1);
_CopyItemWithSelectorFromMenu(theMenu, notesMenu, NULL, target, 88);
[theMenu setSubmenu:[[ExternalEditorListController sharedInstance] addEditNotesMenu] forItem:[theMenu itemAtIndex:[theMenu numberOfItems] - 1]];
[theMenu addItem:[NSMenuItem separatorItem]];
_CopyItemWithSelectorFromMenu(theMenu, notesMenu, @selector(printNote:), target, -1);
NSArray *notes = [(FastListDataSource*)[self dataSource] objectsAtFilteredIndexes:[self selectedRowIndexes]];
[notes addMenuItemsForURLsInNotes:theMenu];
return theMenu;
}
- (void)windowDidBecomeMain:(NSNotification *)aNotification {
[self setShouldUseSecondaryHighlightColor:hadHighlightInForeground];
[self updateTitleDereferencorState];
}
- (void)windowDidResignMain:(NSNotification *)aNotification {
BOOL highlightBefore = shouldUseSecondaryHighlightColor;
[self setShouldUseSecondaryHighlightColor:YES];
hadHighlightInForeground = highlightBefore;
[self updateTitleDereferencorState];
}
- (void)setShouldUseSecondaryHighlightColor:(BOOL)value {
#if SET_DUAL_HIGHLIGHTS
if (![[self window] isKeyWindow]) {
hadHighlightInForeground = value;
value = YES;
}
shouldUseSecondaryHighlightColor = value;
[self setNeedsDisplay:YES];
#endif
}
#if SET_DUAL_HIGHLIGHTS
- (BOOL)_shouldUseSecondaryHighlightColor {
return shouldUseSecondaryHighlightColor;
}
#endif
- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal {
return isLocal ? NSDragOperationNone : NSDragOperationCopy;
}
//- (void)mouseUp:(NSEvent *)theEvent{
// // [[NSApp delegate] resetModTimers];
// [[NSNotificationCenter defaultCenter] postNotificationName:@"ModTimersShouldReset" object:nil];
// [super mouseUp:theEvent];
//}
- (void)mouseDown:(NSEvent*)event {
// [[NSNotificationCenter defaultCenter] postNotificationName:@"ModTimersShouldReset" object:nil];
if ([event clickCount]==1) {
[(AppController *)[self delegate] setIsEditing:NO];
}
//this seems like it should happen automatically, but it does not.
if (![NSApp isActive]) {
[NSApp activateIgnoringOtherApps:YES];
}
if (![[self window] isKeyWindow]) {
[[self window] makeKeyAndOrderFront:self];
}
NSUInteger flags = [event modifierFlags];
if (flags & NSAlternateKeyMask) { // option click starts a drag
NSPoint mousePoint = [self convertPoint:[event locationInWindow] fromView:nil];
NSPoint dragPoint = NSMakePoint(mousePoint.x - 16, mousePoint.y + 16);
NSIndexSet *selectedRows = [self selectedRowIndexes];
NSInteger row = [self rowAtPoint:mousePoint];
if (row >= 0) {
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:row]
byExtendingSelection:[selectedRows containsIndex:(NSUInteger)row] && [selectedRows count] > 1];
//changed selected rows:
selectedRows = [self selectedRowIndexes];
}
NSArray *notes = [(FastListDataSource*)[self dataSource] objectsAtFilteredIndexes:selectedRows];
NSMutableArray *paths = [NSMutableArray arrayWithCapacity:[notes count]];
unsigned int i;
for (i=0;i<[notes count]; i++) {
NoteObject *note = [notes objectAtIndex:i];
//for now, allow option-dragging-out only for notes with separate file-backing stores
if (storageFormatOfNote(note) != SingleDatabaseFormat) {
NSString *aPath = [note noteFilePath];
if (aPath) [paths addObject:aPath];
}
}
if ([paths count] > 0) {
NSImage *image = [[NSWorkspace sharedWorkspace] iconForFile:[paths lastObject]];
NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
[pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil];
[pboard setPropertyList:paths forType:NSFilenamesPboardType];
[NSApp preventWindowOrdering];
[self dragImage:image at:dragPoint offset:NSZeroSize event:event pasteboard:pboard source:self slideBack:YES];
return;
} else {
NSBeep();
}
}
[super mouseDown:event];
}
#define DOWNCHAR(x) ((x) == NSDownArrowFunctionKey || (x) == NSDownTextMovement)
#define UPCHAR(x) ((x) == NSUpArrowFunctionKey || (x) == NSUpTextMovement)
- (void)keyDown:(NSEvent*)theEvent {
// [[NSApp delegate] resetModTimers];
// [[NSNotificationCenter defaultCenter] postNotificationName:@"ModTimersShouldReset" object:nil];
unichar keyChar = [theEvent firstCharacter];
if (keyChar == NSNewlineCharacter || keyChar == NSCarriageReturnCharacter || keyChar == NSEnterCharacter) {
NSInteger sel = [self selectedRow];
if (sel < (unsigned)[self numberOfRows] && [self numberOfSelectedRows] == 1) {
NSInteger colIndex = [self columnWithIdentifier:NoteTitleColumnString];
if (colIndex > -1) {
[self editColumn:colIndex row:sel withEvent:theEvent select:YES];
} else {
[[self window] selectNextKeyView:self];
}
return;
}
} else if (keyChar == NSDeleteCharacter || keyChar == NSDeleteFunctionKey || keyChar == NSDeleteCharFunctionKey) {
[[NSApp delegate] deleteNote:self];
return;
} else if (keyChar == NSTabCharacter) {
[[self window] selectNextKeyView:self];
return;
} else if (keyChar == 0x1B) {
//should be escape--just handle it normally to avoid re-forwarding flicker
[super keyDown:theEvent];
return;
}
NSUInteger modifiers = [theEvent modifierFlags];
if (modifiers & NSCommandKeyMask) {
//replicating up/down with option key
if (UPCHAR(keyChar)) {
[self selectRowAndScroll:0];
return;
} else if (DOWNCHAR(keyChar)) {
[self selectRowAndScroll:[self numberOfRows]-1];
return;
}
}
if (modifiers & NSShiftKeyMask) {
if (DOWNCHAR(keyChar) || UPCHAR(keyChar)) {
NSIndexSet *indexes = [self selectedRowIndexes];
NSUInteger count = [indexes count];
if (count <= 1) { // reset affinity, since there's at most one item selected
affinity = 0;
} else if (affinity == 0) { // affinity not set, so take current direction
affinity = DOWNCHAR(keyChar) ? 1 : -1; // down == down-document == means positive affinity
} else {
NSUInteger row = NSNotFound; // affinity had been set, so enforce it
if (DOWNCHAR(keyChar) && (affinity != 1)) { // down not allowed here
row = [indexes firstIndex];
} else if (UPCHAR(keyChar) && (affinity != -1)) { // up not allowed here
row = [indexes lastIndex];
}
if (row !=NSNotFound) {
NSInteger scrollTo = (NSInteger)row - affinity;
[self scrollRowToVisible:scrollTo]; // make sure we can see things
[self deselectRow:row]; // deselect the last row
return; // skip further processing of the key event
}
}
}
}
if (DOWNCHAR(keyChar) || UPCHAR(keyChar)) {
[super keyDown:theEvent];
return;
}
NSWindow *win = [self window];
if ([win firstResponder] == self) {
//forward keystroke to first responder, which should be controlField's field editor
[win makeFirstResponder:controlField];
NSTextView *fieldEditor = (NSTextView*)[controlField currentEditor];
[fieldEditor keyDown:theEvent];
} else{
[super keyDown:theEvent];
}
}
enum { kNext_Tag = 'j', kPrev_Tag = 'k' };
//use this method to catch next note/prev note before View menu does
//thus avoiding annoying flicker and slow-down
- (BOOL)performKeyEquivalent:(NSEvent *)theEvent {
// [[NSApp delegate] resetModTimers];
// [[NSNotificationCenter defaultCenter] postNotificationName:@"ModTimersShouldReset" object:nil];
NSUInteger mods = [theEvent modifierFlags];
BOOL isControlKeyPressed = (mods & NSControlKeyMask) != 0 && [userDefaults boolForKey: @"UseCtrlForSwitchingNotes"];
BOOL isCommandKeyPressed = (mods & NSCommandKeyMask) != 0;
// Also catch Ctrl-J/-K to match the shortcuts of other apps
if ((isControlKeyPressed || isCommandKeyPressed) && ((mods & NSShiftKeyMask) == 0)) {
unichar keyChar = ' ';
if (isCommandKeyPressed) {
keyChar = [theEvent firstCharacter]; /*cannot use ignoringModifiers here as it subverts the Dvorak-Qwerty-CMD keyboard layout */
}
if (isControlKeyPressed) {
keyChar = [theEvent firstCharacterIgnoringModifiers]; /* first gets '\n' when control key is set, so fall back to ignoringModifiers */
}
// Handle J and K for both Control and Command
if ( keyChar == kNext_Tag || keyChar == kPrev_Tag ) {
if (mods & NSAlternateKeyMask) {
[self selectRowAndScroll:((keyChar == kNext_Tag) ? [self numberOfRows] - 1 : 0)];
} else {
[self _incrementNoteSelectionByTag:keyChar];
}
return YES;
}
// Handle N and P, but only when Control is pressed
if ( (keyChar == 'n' || keyChar == 'p') && (!isCommandKeyPressed)) {
// Determine if the note editing pane is selected:
if (![[[self window] firstResponder] isKindOfClass:[LinkingEditor class]]) {
[self _incrementNoteSelectionByTag:(keyChar == 'n') ? kNext_Tag : kPrev_Tag];
return YES;
}
}
// Make Control-[ equivalent to Escape
if ( (keyChar == '[' ) && (!isCommandKeyPressed)) {
[self cancelOperation:nil];
return YES;
}
}
return [super performKeyEquivalent:theEvent];
}
- (void)_incrementNoteSelectionByTag:(NSInteger)tag {
NSInteger rowNumber = [self selectedRow];
NSInteger totalNotes = [self numberOfRows];
if (rowNumber == -1) {
rowNumber = (tag == kPrev_Tag ? totalNotes - 1 : 0);
} else {
rowNumber = (tag == kPrev_Tag ?
(rowNumber < 1 ? rowNumber : rowNumber - 1) :
(rowNumber >= totalNotes - 1 ? rowNumber : rowNumber + 1));
}
[self selectRowAndScroll:rowNumber];
}
- (void)incrementNoteSelection:(id)sender {
[self _incrementNoteSelectionByTag:[sender tag]];
}