forked from gnachman/iTerm2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBookmarkModel.m
904 lines (807 loc) · 29.6 KB
/
BookmarkModel.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
/*
** BookmarkModel.m
** iTerm
**
** Created by George Nachman on 8/24/10.
** Project: iTerm
**
** Description: Model for an ordered collection of bookmarks. Bookmarks have
** numerous attributes, but always have a name, set of tags, and a guid.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
*/
#import <iTerm/ITAddressBookMgr.h>
#import <iTerm/BookmarkModel.h>
#import "PreferencePanel.h"
id gAltOpenAllRepresentedObject;
// Set to true if a bookmark was changed automatically due to migration to a new
// standard.
int gMigrated;
@implementation BookmarkModel
+ (void)initialize
{
gAltOpenAllRepresentedObject = [[NSObject alloc] init];
}
+ (BOOL)migrated
{
return gMigrated;
}
- (BookmarkModel*)init
{
bookmarks_ = [[NSMutableArray alloc] init];
defaultBookmarkGuid_ = @"";
journal_ = [[NSMutableArray alloc] init];
return self;
}
+ (BookmarkModel*)sharedInstance
{
static BookmarkModel* shared = nil;
if (!shared) {
shared = [[BookmarkModel alloc] init];
shared->prefs_ = [NSUserDefaults standardUserDefaults];
shared->postChanges_ = YES;
}
return shared;
}
+ (BookmarkModel*)sessionsInstance
{
static BookmarkModel* shared = nil;
if (!shared) {
shared = [[BookmarkModel alloc] init];
shared->prefs_ = nil;
shared->postChanges_ = NO;
}
return shared;
}
- (void)dealloc
{
[super dealloc];
[journal_ release];
NSLog(@"Deallocating bookmark model!");
}
- (int)numberOfBookmarks
{
return [bookmarks_ count];
}
- (BOOL)_document:(NSArray *)nameWords containsToken:(NSString *)token
{
for (int k = 0; k < [nameWords count]; ++k) {
NSString* tagPart = [nameWords objectAtIndex:k];
NSRange range;
if ([token length] && [token characterAtIndex:0] == '*') {
range = [tagPart rangeOfString:[token substringFromIndex:1] options:NSCaseInsensitiveSearch];
} else {
range = [tagPart rangeOfString:token options:(NSCaseInsensitiveSearch | NSAnchoredSearch)];
}
if (range.location != NSNotFound) {
return YES;
}
}
return NO;
}
- (BOOL)doesBookmarkAtIndex:(int)theIndex matchFilter:(NSArray*)tokens
{
Bookmark* bookmark = [self bookmarkAtIndex:theIndex];
NSArray* tags = [bookmark objectForKey:KEY_TAGS];
NSArray* nameWords = [[bookmark objectForKey:KEY_NAME] componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
for (int i = 0; i < [tokens count]; ++i) {
NSString* token = [tokens objectAtIndex:i];
if (![token length]) {
continue;
}
// Search each word in tag until one has this token as a prefix.
bool found;
// First see if this token occurs in the title
found = [self _document:nameWords containsToken:token];
// If not try each tag.
for (int j = 0; !found && j < [tags count]; ++j) {
// Expand the jth tag into an array of the words in the tag
NSArray* tagWords = [[tags objectAtIndex:j] componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
found = [self _document:tagWords containsToken:token];
}
if (!found) {
// No tag had token i as a prefix.
return NO;
}
}
return YES;
}
- (NSArray*)parseFilter:(NSString*)filter
{
return [filter componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
- (NSArray*)bookmarkIndicesMatchingFilter:(NSString*)filter
{
NSMutableArray* result = [NSMutableArray arrayWithCapacity:[bookmarks_ count]];
NSArray* tokens = [self parseFilter:filter];
int count = [bookmarks_ count];
for (int i = 0; i < count; ++i) {
if ([self doesBookmarkAtIndex:i matchFilter:tokens]) {
[result addObject:[NSNumber numberWithInt:i]];
}
}
return result;
}
- (int)numberOfBookmarksWithFilter:(NSString*)filter
{
NSArray* tokens = [self parseFilter:filter];
int count = [bookmarks_ count];
int n = 0;
for (int i = 0; i < count; ++i) {
if ([self doesBookmarkAtIndex:i matchFilter:tokens]) {
++n;
}
}
return n;
}
- (Bookmark*)bookmarkAtIndex:(int)i
{
if (i < 0 || i >= [bookmarks_ count]) {
return nil;
}
return [bookmarks_ objectAtIndex:i];
}
- (Bookmark*)bookmarkAtIndex:(int)theIndex withFilter:(NSString*)filter
{
NSArray* tokens = [self parseFilter:filter];
int count = [bookmarks_ count];
int n = 0;
for (int i = 0; i < count; ++i) {
if ([self doesBookmarkAtIndex:i matchFilter:tokens]) {
if (n == theIndex) {
return [self bookmarkAtIndex:i];
}
++n;
}
}
return nil;
}
- (void)addBookmark:(Bookmark*)bookmark
{
[self addBookmark:bookmark inSortedOrder:NO];
}
+ (void)migratePromptOnCloseInMutableBookmark:(NSMutableDictionary *)dict
{
// Migrate global "prompt on close" to per-profile prompt enum
if ([dict objectForKey:KEY_PROMPT_CLOSE_DEPRECATED]) {
// The 8/28 build incorrectly ignored the OnlyWhenMoreTabs setting
// when migrating PromptOnClose to KEY_PRMOPT_CLOSE. Its preference
// key has been changed to KEY_PROMPT_CLOSE_DEPRECATED and a new
// pref key with the same intended usage has been added on 9/4 but
// with a different name. If the setting is PROMPT_ALWAYS, then it may
// have been migrated incorrectly. There are three ways to get here:
// 1. PromptOnClose && OnlyWhenMoreTabs was migrated wrong.
// 2. PromptOnClose && !OnlyWhenMoreTabs was migrated right.
// 3. Post migration, the user set it to PROMPT_ALWAYS
//
// For case 1, redoing the migration produces the correct result.
// For case 2, redoing the migration has no effect.
// For case 3, the user's pref is overwritten. This should be rare.
int value = [[dict objectForKey:KEY_PROMPT_CLOSE_DEPRECATED] intValue];
if (value != PROMPT_ALWAYS) {
[dict setObject:[NSNumber numberWithInt:value]
forKey:KEY_PROMPT_CLOSE];
}
}
if (![dict objectForKey:KEY_PROMPT_CLOSE]) {
BOOL promptOnClose = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PromptOnClose"] boolValue];
NSNumber *onlyWhenNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"OnlyWhenMoreTabs"];
if (!onlyWhenNumber || [onlyWhenNumber boolValue]) {
promptOnClose = NO;
}
NSNumber *newValue = [NSNumber numberWithBool:promptOnClose ? PROMPT_ALWAYS : PROMPT_NEVER];
[dict setObject:newValue forKey:KEY_PROMPT_CLOSE];
gMigrated = YES;
}
// This is a required field to avoid setting nil values in the bookmark
// dict later on.
if (![dict objectForKey:KEY_JOBS]) {
[dict setObject:[NSArray arrayWithObjects:@"rlogin", @"ssh", @"slogin", @"telnet", nil]
forKey:KEY_JOBS];
gMigrated = YES;
}
}
- (void)addBookmark:(Bookmark*)bookmark inSortedOrder:(BOOL)sort
{
NSMutableDictionary *newBookmark = [[bookmark mutableCopy] autorelease];
// Ensure required fields are present
if (![newBookmark objectForKey:KEY_NAME]) {
[newBookmark setObject:@"Bookmark" forKey:KEY_NAME];
}
if (![newBookmark objectForKey:KEY_TAGS]) {
[newBookmark setObject:[NSArray arrayWithObjects:nil] forKey:KEY_TAGS];
}
if (![newBookmark objectForKey:KEY_CUSTOM_COMMAND]) {
[newBookmark setObject:@"No" forKey:KEY_CUSTOM_COMMAND];
}
if (![newBookmark objectForKey:KEY_COMMAND]) {
[newBookmark setObject:@"/bin/bash --login" forKey:KEY_COMMAND];
}
if (![newBookmark objectForKey:KEY_GUID]) {
[newBookmark setObject:[BookmarkModel freshGuid] forKey:KEY_GUID];
}
if (![newBookmark objectForKey:KEY_DEFAULT_BOOKMARK]) {
[newBookmark setObject:@"No" forKey:KEY_DEFAULT_BOOKMARK];
}
[BookmarkModel migratePromptOnCloseInMutableBookmark:newBookmark];
bookmark = [[newBookmark copy] autorelease];
int theIndex;
if (sort) {
// Insert alphabetically. Sort so that objects with the "bonjour" tag come after objects without.
int insertionPoint = -1;
NSString* newName = [bookmark objectForKey:KEY_NAME];
BOOL hasBonjour = [self bookmark:bookmark hasTag:@"bonjour"];
for (int i = 0; i < [bookmarks_ count]; ++i) {
Bookmark* bookmarkAtI = [bookmarks_ objectAtIndex:i];
NSComparisonResult order = NSOrderedSame;
BOOL currentHasBonjour = [self bookmark:bookmarkAtI hasTag:@"bonjour"];
if (hasBonjour != currentHasBonjour) {
if (hasBonjour) {
order = NSOrderedAscending;
} else {
order = NSOrderedDescending;
}
}
if (order == NSOrderedSame) {
order = [[[bookmarks_ objectAtIndex:i] objectForKey:KEY_NAME] caseInsensitiveCompare:newName];
}
if (order == NSOrderedDescending) {
insertionPoint = i;
break;
}
}
if (insertionPoint == -1) {
theIndex = [bookmarks_ count];
[bookmarks_ addObject:[NSDictionary dictionaryWithDictionary:bookmark]];
} else {
theIndex = insertionPoint;
[bookmarks_ insertObject:[NSDictionary dictionaryWithDictionary:bookmark] atIndex:insertionPoint];
}
} else {
theIndex = [bookmarks_ count];
[bookmarks_ addObject:[NSDictionary dictionaryWithDictionary:bookmark]];
}
NSString* isDeprecatedDefaultBookmark = [bookmark objectForKey:KEY_DEFAULT_BOOKMARK];
// The call to setDefaultByGuid may add a journal entry so make sure this one comes first.
BookmarkJournalEntry* e = [BookmarkJournalEntry journalWithAction:JOURNAL_ADD bookmark:bookmark model:self];
e->index = theIndex;
[journal_ addObject:e];
if (![self defaultBookmark] || (isDeprecatedDefaultBookmark && [isDeprecatedDefaultBookmark isEqualToString:@"Yes"])) {
[self setDefaultByGuid:[bookmark objectForKey:KEY_GUID]];
}
[self postChangeNotification];
}
- (BOOL)bookmark:(Bookmark*)bookmark hasTag:(NSString*)tag
{
NSArray* tags = [bookmark objectForKey:KEY_TAGS];
return [tags containsObject:tag];
}
- (int)convertFilteredIndex:(int)theIndex withFilter:(NSString*)filter
{
NSArray* tokens = [self parseFilter:filter];
int count = [bookmarks_ count];
int n = 0;
for (int i = 0; i < count; ++i) {
if ([self doesBookmarkAtIndex:i matchFilter:tokens]) {
if (n == theIndex) {
return i;
}
++n;
}
}
return -1;
}
- (void)removeBookmarksAtIndices:(NSArray*)indices
{
NSArray* sorted = [indices sortedArrayUsingSelector:@selector(compare:)];
for (int j = [sorted count] - 1; j >= 0; j--) {
int i = [[sorted objectAtIndex:j] intValue];
assert(i >= 0);
[journal_ addObject:[BookmarkJournalEntry journalWithAction:JOURNAL_REMOVE bookmark:[bookmarks_ objectAtIndex:i] model:self]];
[bookmarks_ removeObjectAtIndex:i];
if (![self defaultBookmark] && [bookmarks_ count]) {
[self setDefaultByGuid:[[bookmarks_ objectAtIndex:0] objectForKey:KEY_GUID]];
}
}
[self postChangeNotification];
}
- (void)removeBookmarkAtIndex:(int)i
{
assert(i >= 0);
[journal_ addObject:[BookmarkJournalEntry journalWithAction:JOURNAL_REMOVE bookmark:[bookmarks_ objectAtIndex:i] model:self]];
[bookmarks_ removeObjectAtIndex:i];
if (![self defaultBookmark] && [bookmarks_ count]) {
[self setDefaultByGuid:[[bookmarks_ objectAtIndex:0] objectForKey:KEY_GUID]];
}
[self postChangeNotification];
}
- (void)removeBookmarkAtIndex:(int)i withFilter:(NSString*)filter
{
[self removeBookmarkAtIndex:[self convertFilteredIndex:i withFilter:filter]];
}
- (void)removeBookmarkWithGuid:(NSString*)guid
{
int i = [self indexOfBookmarkWithGuid:guid];
if (i >= 0) {
[self removeBookmarkAtIndex:i];
}
}
// A change in bookmarks is journal-worthy only if the name, shortcut, tags, or guid changes.
- (BOOL)bookmark:(Bookmark*)a differsJournalablyFrom:(Bookmark*)b
{
// Any field that is shown in a view (profiles window, menus, bookmark list views, etc.) must
// be a criteria for journalability for it to be updated immediately.
if (![[a objectForKey:KEY_NAME] isEqualToString:[b objectForKey:KEY_NAME]] ||
![[a objectForKey:KEY_SHORTCUT] isEqualToString:[b objectForKey:KEY_SHORTCUT]] ||
![[a objectForKey:KEY_TAGS] isEqualToArray:[b objectForKey:KEY_TAGS]] ||
![[a objectForKey:KEY_GUID] isEqualToString:[b objectForKey:KEY_GUID]] ||
![[a objectForKey:KEY_COMMAND] isEqualToString:[b objectForKey:KEY_COMMAND]] ||
![[a objectForKey:KEY_CUSTOM_COMMAND] isEqualToString:[b objectForKey:KEY_CUSTOM_COMMAND]]) {
return YES;
} else {
return NO;
}
}
- (void)setBookmark:(Bookmark*)bookmark atIndex:(int)i
{
Bookmark* orig = [bookmarks_ objectAtIndex:i];
BOOL isDefault = NO;
if ([[orig objectForKey:KEY_GUID] isEqualToString:defaultBookmarkGuid_]) {
isDefault = YES;
}
Bookmark* before = [bookmarks_ objectAtIndex:i];
BOOL needJournal = [self bookmark:bookmark differsJournalablyFrom:before];
if (needJournal) {
[journal_ addObject:[BookmarkJournalEntry journalWithAction:JOURNAL_REMOVE bookmark:[bookmarks_ objectAtIndex:i] model:self]];
}
[bookmarks_ replaceObjectAtIndex:i withObject:bookmark];
if (needJournal) {
BookmarkJournalEntry* e = [BookmarkJournalEntry journalWithAction:JOURNAL_ADD bookmark:bookmark model:self];
e->index = i;
[journal_ addObject:e];
}
if (isDefault) {
[self setDefaultByGuid:[bookmark objectForKey:KEY_GUID]];
}
if (needJournal) {
[self postChangeNotification];
}
}
- (void)setBookmark:(Bookmark*)bookmark withGuid:(NSString*)guid
{
int i = [self indexOfBookmarkWithGuid:guid];
if (i >= 0) {
[self setBookmark:bookmark atIndex:i];
}
}
- (void)removeAllBookmarks
{
[bookmarks_ removeAllObjects];
defaultBookmarkGuid_ = @"";
[journal_ addObject:[BookmarkJournalEntry journalWithAction:JOURNAL_REMOVE_ALL bookmark:nil model:self]];
[self postChangeNotification];
}
- (NSArray*)rawData
{
return bookmarks_;
}
- (void)load:(NSArray*)prefs
{
[bookmarks_ removeAllObjects];
for (int i = 0; i < [prefs count]; ++i) {
Bookmark* bookmark = [prefs objectAtIndex:i];
NSArray* tags = [bookmark objectForKey:KEY_TAGS];
if (![tags containsObject:@"bonjour"]) {
[self addBookmark:bookmark];
}
}
[bookmarks_ retain];
}
+ (NSString*)freshGuid
{
CFUUIDRef uuidObj = CFUUIDCreate(nil); //create a new UUID
//get the string representation of the UUID
NSString *uuidString = (NSString*)CFUUIDCreateString(nil, uuidObj);
CFRelease(uuidObj);
return [uuidString autorelease];
}
- (int)indexOfBookmarkWithGuid:(NSString*)guid
{
return [self indexOfBookmarkWithGuid:guid withFilter:@""];
}
- (int)indexOfBookmarkWithGuid:(NSString*)guid withFilter:(NSString*)filter
{
NSArray* tokens = [self parseFilter:filter];
int count = [bookmarks_ count];
int n = 0;
for (int i = 0; i < count; ++i) {
if (![self doesBookmarkAtIndex:i matchFilter:tokens]) {
continue;
}
if ([[[bookmarks_ objectAtIndex:i] objectForKey:KEY_GUID] isEqualToString:guid]) {
return n;
}
++n;
}
return -1;
}
- (Bookmark*)defaultBookmark
{
return [self bookmarkWithGuid:defaultBookmarkGuid_];
}
- (Bookmark*)bookmarkWithName:(NSString*)name
{
int count = [bookmarks_ count];
for (int i = 0; i < count; ++i) {
if ([[[bookmarks_ objectAtIndex:i] objectForKey:KEY_NAME] isEqualToString:name]) {
return [bookmarks_ objectAtIndex:i];
}
}
return nil;
}
- (Bookmark*)bookmarkWithGuid:(NSString*)guid
{
int count = [bookmarks_ count];
for (int i = 0; i < count; ++i) {
if ([[[bookmarks_ objectAtIndex:i] objectForKey:KEY_GUID] isEqualToString:guid]) {
return [bookmarks_ objectAtIndex:i];
}
}
return nil;
}
- (int)indexOfBookmarkWithName:(NSString*)name
{
int count = [bookmarks_ count];
for (int i = 0; i < count; ++i) {
if ([[[bookmarks_ objectAtIndex:i] objectForKey:KEY_NAME] isEqualToString:name]) {
return i;
}
}
return -1;
}
- (NSArray*)allTags
{
NSMutableDictionary* temp = [[[NSMutableDictionary alloc] init] autorelease];
for (int i = 0; i < [self numberOfBookmarks]; ++i) {
Bookmark* bookmark = [self bookmarkAtIndex:i];
NSArray* tags = [bookmark objectForKey:KEY_TAGS];
for (int j = 0; j < [tags count]; ++j) {
NSString* tag = [tags objectAtIndex:j];
[temp setObject:@"" forKey:tag];
}
}
return [temp allKeys];
}
- (Bookmark*)setObject:(id)object forKey:(NSString*)key inBookmark:(Bookmark*)bookmark
{
NSMutableDictionary* newDict = [NSMutableDictionary dictionaryWithDictionary:bookmark];
if (object == nil) {
[newDict removeObjectForKey:key];
} else {
[newDict setObject:object forKey:key];
}
NSString* guid = [bookmark objectForKey:KEY_GUID];
Bookmark* newBookmark = [NSDictionary dictionaryWithDictionary:newDict];
[self setBookmark:newBookmark
withGuid:guid];
return newBookmark;
}
- (void)setDefaultByGuid:(NSString*)guid
{
[guid retain];
[defaultBookmarkGuid_ release];
defaultBookmarkGuid_ = guid;
if (prefs_) {
[prefs_ setObject:defaultBookmarkGuid_ forKey:KEY_DEFAULT_GUID];
}
[journal_ addObject:[BookmarkJournalEntry journalWithAction:JOURNAL_SET_DEFAULT
bookmark:[self defaultBookmark]
model:self]];
[self postChangeNotification];
}
- (void)moveGuid:(NSString*)guid toRow:(int)destinationRow
{
int sourceRow = [self indexOfBookmarkWithGuid:guid];
if (sourceRow < 0) {
return;
}
Bookmark* bookmark = [bookmarks_ objectAtIndex:sourceRow];
[bookmark retain];
[bookmarks_ removeObjectAtIndex:sourceRow];
if (sourceRow < destinationRow) {
destinationRow--;
}
[bookmarks_ insertObject:bookmark atIndex:destinationRow];
[bookmark release];
}
- (void)rebuildMenus
{
[journal_ addObject:[BookmarkJournalEntry journalWithAction:JOURNAL_REMOVE_ALL bookmark:nil model:self]];
int i = 0;
for (Bookmark* b in bookmarks_) {
BookmarkJournalEntry* e = [BookmarkJournalEntry journalWithAction:JOURNAL_ADD bookmark:b model:self];
e->index = i++;
[journal_ addObject:e];
}
[self postChangeNotification];
}
- (void)postChangeNotification
{
if (postChanges_) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"iTermReloadAddressBook"
object:nil
userInfo:[NSDictionary dictionaryWithObject:journal_ forKey:@"array"]];
}
[journal_ release];
journal_ = [[NSMutableArray alloc] init];
}
- (void)dump
{
for (int i = 0; i < [self numberOfBookmarks]; ++i) {
Bookmark* bookmark = [self bookmarkAtIndex:i];
NSLog(@"%d: %@ %@", i, [bookmark objectForKey:KEY_NAME], [bookmark objectForKey:KEY_GUID]);
}
}
- (NSArray*)bookmarks
{
return bookmarks_;
}
- (NSArray*)guids
{
NSMutableArray* guids = [NSMutableArray arrayWithCapacity:[bookmarks_ count]];
for (Bookmark* bookmark in bookmarks_) {
[guids addObject:[bookmark objectForKey:KEY_GUID]];
}
return guids;
}
+ (NSMenu*)findOrCreateTagSubmenuInMenu:(NSMenu*)menu startingAtItem:(int)skip withName:(NSString*)name params:(JournalParams*)params
{
NSArray* items = [menu itemArray];
int pos = [menu numberOfItems];
int N = pos;
for (int i = skip; i < N; i++) {
NSMenuItem* cur = [items objectAtIndex:i];
if (![cur submenu] || [cur isSeparatorItem]) {
pos = i;
break;
}
int comp = [[cur title] caseInsensitiveCompare:name];
if (comp == 0) {
return [cur submenu];
} else if (comp > 0) {
pos = i;
break;
}
}
// Add menu item with submenu
NSMenuItem* newItem = [[NSMenuItem alloc] initWithTitle:name action:nil keyEquivalent:@""];
[newItem setSubmenu:[[NSMenu alloc] init]];
[menu insertItem:newItem atIndex:pos];
return [newItem submenu];
}
+ (void)addOpenAllToMenu:(NSMenu*)menu params:(JournalParams*)params
{
// Add separator + open all menu items
[menu addItem:[NSMenuItem separatorItem]];
NSMenuItem* openAll = [menu addItemWithTitle:@"Open All" action:params->openAllSelector keyEquivalent:@""];
[openAll setTarget:params->target];
// Add alternate open all menu
NSMenuItem* altOpenAll = [[NSMenuItem alloc] initWithTitle:@"Open All in New Window"
action:params->alternateOpenAllSelector
keyEquivalent:@""];
[altOpenAll setTarget:params->target];
[altOpenAll setKeyEquivalentModifierMask:NSAlternateKeyMask];
[altOpenAll setAlternate:YES];
[altOpenAll setRepresentedObject:gAltOpenAllRepresentedObject];
[menu addItem:altOpenAll];
[altOpenAll release];
}
+ (BOOL)menuHasOpenAll:(NSMenu*)menu
{
NSArray* items = [menu itemArray];
if ([items count] < 3) {
return NO;
}
int n = [items count];
return ([[items objectAtIndex:n-1] representedObject] == gAltOpenAllRepresentedObject);
}
- (int)positionOfBookmark:(Bookmark*)b startingAtItem:(int)skip inMenu:(NSMenu*)menu
{
// Find position of bookmark in menu
NSString* name = [b objectForKey:KEY_NAME];
int N = [menu numberOfItems];
if ([BookmarkModel menuHasOpenAll:menu]) {
N -= 3;
}
NSArray* items = [menu itemArray];
int pos = N;
for (int i = skip; i < N; i++) {
NSMenuItem* cur = [items objectAtIndex:i];
if ([cur isSeparatorItem]) {
break;
}
if ([cur isHidden] || [cur submenu]) {
continue;
}
if ([[cur title] caseInsensitiveCompare:name] > 0) {
pos = i;
break;
}
}
return pos;
}
- (int)positionOfBookmarkWithIndex:(int)theIndex startingAtItem:(int)skip inMenu:(NSMenu*)menu
{
// Find position of bookmark in menu
int N = [menu numberOfItems];
if ([BookmarkModel menuHasOpenAll:menu]) {
N -= 3;
}
NSArray* items = [menu itemArray];
int pos = N;
for (int i = skip; i < N; i++) {
NSMenuItem* cur = [items objectAtIndex:i];
if ([cur isSeparatorItem]) {
break;
}
if ([cur isHidden] || [cur submenu]) {
continue;
}
if ([cur tag] > theIndex) {
pos = i;
break;
}
}
return pos;
}
- (void)addBookmark:(Bookmark*)b
toMenu:(NSMenu*)menu
atPosition:(int)pos
withParams:(JournalParams*)params
isAlternate:(BOOL)isAlternate
withTag:(int)tag
{
NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:[b objectForKey:KEY_NAME]
action:isAlternate ? params->alternateSelector : params->selector
keyEquivalent:@""];
NSString* shortcut = [b objectForKey:KEY_SHORTCUT];
if ([shortcut length]) {
[item setKeyEquivalent:[shortcut lowercaseString]];
[item setKeyEquivalentModifierMask:NSCommandKeyMask | NSControlKeyMask | (isAlternate ? NSAlternateKeyMask : 0)];
} else if (isAlternate) {
[item setKeyEquivalentModifierMask:NSAlternateKeyMask];
}
[item setAlternate:isAlternate];
[item setTarget:params->target];
[item setRepresentedObject:[[[b objectForKey:KEY_GUID] copy] autorelease]];
[item setTag:tag];
[menu insertItem:item atIndex:pos];
[item release];
}
- (void)addBookmark:(Bookmark*)b toMenu:(NSMenu*)menu startingAtItem:(int)skip withTags:(NSArray*)tags params:(JournalParams*)params atPos:(int)theIndex
{
int pos;
if (theIndex == -1) {
// Add in sorted order
pos = [self positionOfBookmark:b startingAtItem:skip inMenu:menu];
} else {
pos = [self positionOfBookmarkWithIndex:theIndex startingAtItem:skip inMenu:menu];
}
if (![tags count]) {
// Add item & alternate if no tags
[self addBookmark:b toMenu:menu atPosition:pos withParams:params isAlternate:NO withTag:theIndex];
[self addBookmark:b toMenu:menu atPosition:pos+1 withParams:params isAlternate:YES withTag:theIndex];
}
// Add to tag submenus
for (NSString* tag in [NSSet setWithArray:tags]) {
NSMenu* tagSubMenu = [BookmarkModel findOrCreateTagSubmenuInMenu:menu
startingAtItem:skip
withName:tag
params:params];
[self addBookmark:b toMenu:tagSubMenu startingAtItem:0 withTags:nil params:params atPos:theIndex];
}
if ([menu numberOfItems] > skip + 2 && ![BookmarkModel menuHasOpenAll:menu]) {
[BookmarkModel addOpenAllToMenu:menu params:params];
}
}
+ (void)applyAddJournalEntry:(BookmarkJournalEntry*)e toMenu:(NSMenu*)menu startingAtItem:(int)skip params:(JournalParams*)params
{
BookmarkModel* model = e->model;
Bookmark* b = [model bookmarkWithGuid:e->guid];
if (!b) {
return;
}
[model addBookmark:b toMenu:menu startingAtItem:skip withTags:[b objectForKey:KEY_TAGS] params:params atPos:e->index];
}
+ (void)applyRemoveJournalEntry:(BookmarkJournalEntry*)e toMenu:(NSMenu*)menu startingAtItem:(int)skip params:(JournalParams*)params
{
int pos = [menu indexOfItemWithRepresentedObject:e->guid];
if (pos != -1) {
[menu removeItemAtIndex:pos];
[menu removeItemAtIndex:pos];
}
// Remove bookmark from each tag it belongs to
for (NSString* tag in e->tags) {
NSMenuItem* item = [menu itemWithTitle:tag];
NSMenu* submenu = [item submenu];
if (submenu) {
[BookmarkModel applyRemoveJournalEntry:e toMenu:submenu startingAtItem:0 params:params];
if ([submenu numberOfItems] == 0) {
[menu removeItem:item];
}
}
}
// Remove "open all" section if it's no longer needed.
// [0, ..., skip-1, bm1, bm1alt, separator, open all, open all alternate]
if (([BookmarkModel menuHasOpenAll:menu] && [menu numberOfItems] <= skip + 5)) {
[menu removeItemAtIndex:[menu numberOfItems] - 1];
[menu removeItemAtIndex:[menu numberOfItems] - 1];
[menu removeItemAtIndex:[menu numberOfItems] - 1];
}
}
+ (void)applyRemoveAllJournalEntry:(BookmarkJournalEntry*)e toMenu:(NSMenu*)menu startingAtItem:(int)skip params:(JournalParams*)params
{
while ([menu numberOfItems] > skip) {
[menu removeItemAtIndex:[menu numberOfItems] - 1];
}
}
+ (void)applySetDefaultJournalEntry:(BookmarkJournalEntry*)e toMenu:(NSMenu*)menu startingAtItem:(int)skip params:(JournalParams*)params
{
}
+ (void)applyJournal:(NSDictionary*)journalDict toMenu:(NSMenu*)menu startingAtItem:(int)skip params:(JournalParams*)params
{
NSArray* journal = [journalDict objectForKey:@"array"];
for (BookmarkJournalEntry* e in journal) {
switch (e->action) {
case JOURNAL_ADD:
[BookmarkModel applyAddJournalEntry:e toMenu:menu startingAtItem:skip params:params];
break;
case JOURNAL_REMOVE:
[BookmarkModel applyRemoveJournalEntry:e toMenu:menu startingAtItem:skip params:params];
break;
case JOURNAL_REMOVE_ALL:
[BookmarkModel applyRemoveAllJournalEntry:e toMenu:menu startingAtItem:skip params:params];
break;
case JOURNAL_SET_DEFAULT:
[BookmarkModel applySetDefaultJournalEntry:e toMenu:menu startingAtItem:skip params:params];
break;
default:
assert(false);
}
}
}
+ (void)applyJournal:(NSDictionary*)journal toMenu:(NSMenu*)menu params:(JournalParams*)params
{
[BookmarkModel applyJournal:journal toMenu:menu startingAtItem:0 params:params];
}
@end
@implementation BookmarkJournalEntry
+ (BookmarkJournalEntry*)journalWithAction:(JournalAction)action
bookmark:(Bookmark*)bookmark
model:(BookmarkModel*)model
{
BookmarkJournalEntry* entry = [[[BookmarkJournalEntry alloc] init] autorelease];
entry->action = action;
entry->guid = [[bookmark objectForKey:KEY_GUID] copy];
entry->model = model;
entry->tags = [[NSArray alloc] initWithArray:[bookmark objectForKey:KEY_TAGS]];
return entry;
}
- (void)dealloc
{
[guid release];
[tags release];
[super dealloc];
}
@end