This repository has been archived by the owner on Oct 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
BMAppController.m
976 lines (832 loc) · 29.1 KB
/
BMAppController.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
/*
The MIT License
Copyright (c) 2009 Booglemarks Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>
#import <WebKit/WebKit.h>
#import "BMAppController.h"
#import "BMModels.h"
#import <objc/objc-class.h>
void Swizzle(Class c, SEL orig, SEL new)
{
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
else
method_exchangeImplementations(origMethod, newMethod);
}
@implementation NSArray (Booglemarks)
//#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
//- (id) selectFirst: (BOOL(^)(id)) block;
//{
// for (id obj in self) if (block(obj)) return obj;
// return nil;
//}
//#else
- (id) selectFirstCpationed: (NSString*) caption
{
for (id obj in self)
{
NSMenuItem* menuItem = (NSMenuItem *) obj;
if ([[menuItem title] compare: caption] == NSOrderedSame)
return menuItem;
}
return nil;
}
//#endif
@end
@implementation NSMutableArray (Booglemarks)
- (void) addReduancyObjectsFromArray: (NSArray *) array
{
NSMutableSet* uniSet = [[NSMutableSet alloc] initWithArray: self];
[uniSet addObjectsFromArray: array];
[self removeAllObjects];
[self addObjectsFromArray: [uniSet allObjects]];
[uniSet release];
}
@end
@implementation BMAppController
#pragma mark Loader
+ (void) load
{
[BMAppController sharedInstance];
}
+ (BMAppController *) sharedInstance
{
static BMAppController* plugin = nil;
if (plugin == nil)
plugin = [[BMAppController alloc] init];
return plugin;
}
#pragma mark Override
- (id) init
{
//NSLog(@"BMAppController %p - init", self);
self = [super init];
if (! self)
return nil;
reloading = NO;
//
// init images
//
NSSize iconSize;
iconSize.width = iconSize.height = 16;
folderIcon = [[NSWorkspace sharedWorkspace] iconForFileType: NSFileTypeForHFSTypeCode(kGenericFolderIcon)];
[folderIcon setSize: iconSize];
[folderIcon retain];
bookmarkIcon = [NSImage imageNamed:@"BookmarkPreferences~snowleopard.tiff"];
if (!bookmarkIcon)
bookmarkIcon = [NSImage imageNamed:@"BookmarkPreferences.tiff"];
[bookmarkIcon setSize: iconSize];
[bookmarkIcon retain];
historyIcon = [NSImage imageNamed:@"History.png"];
if (!historyIcon)
historyIcon = [NSImage imageNamed:@"History.tif"];
[historyIcon setSize: iconSize];
[historyIcon retain];
bookmarksIcon = [bookmarkIcon retain];
addBookmarkIcon = [bookmarkIcon retain];
reloadIcon = nil;
// NSBundle* myBundle = [NSBundle bundleForClass:[self class]];
// NSImage* startImg = [[NSImage alloc] initWithContentsOfFile:[myBundle pathForImageResource:@"star.png"]];
tags = [[NSMutableArray alloc] init];
//
// init menus
//
topMenu = [[NSMenu alloc] init];
[topMenu setTitle: BMLocalizedString(@"Booglemarks")];
//- (void)menuWillOpen:(NSMenu *)menu;
menuItemShowBookmarks = [[NSMenuItem alloc] init];
[menuItemShowBookmarks setTitle: BMLocalizedString(@"Show Bookmarks")];
[menuItemShowBookmarks setAction: @selector(didClickShowBookmarks:) ];
[menuItemShowBookmarks setKeyEquivalent: @"b"];
[menuItemShowBookmarks setKeyEquivalentModifierMask: (NSControlKeyMask | NSCommandKeyMask)];
[menuItemShowBookmarks setImage: bookmarksIcon];
[menuItemShowBookmarks setTarget: self];
[menuItemShowBookmarks retain];
menuItemAddBookmark = [[NSMenuItem alloc] init];
[menuItemAddBookmark setTitle: BMLocalizedString(@"Add Bookmark")];
[menuItemAddBookmark setAction: @selector(didClickAddBookmark:) ];
[menuItemAddBookmark setKeyEquivalent: @"d"];
[menuItemAddBookmark setKeyEquivalentModifierMask: (NSControlKeyMask | NSCommandKeyMask)];
[menuItemAddBookmark setImage: addBookmarkIcon];
[menuItemAddBookmark setTarget: self];
[menuItemAddBookmark retain];
menuItemReloadBookmarks = [[NSMenuItem alloc] init];
[menuItemReloadBookmarks setTitle: BMLocalizedString(@"Reload Bookmarks")];
[menuItemReloadBookmarks setAction: @selector(didClickReloadAll:) ];
//[menuItemReloadBookmarks setKeyEquivalent: @"r"];
//[menuItemReloadBookmarks setKeyEquivalentModifierMask: NSControlKeyMask];
[menuItemReloadBookmarks setImage: reloadIcon];
[menuItemReloadBookmarks setTarget: self];
[menuItemReloadBookmarks retain];
menuItemReloading = [[NSMenuItem alloc] init];
[menuItemReloading setTitle: BMLocalizedString(@"Reloading")];
[menuItemReloadBookmarks setImage: reloadIcon];
[menuItemReloading retain];
menuItemSignIn = [[NSMenuItem alloc] init];
[menuItemSignIn setTitle: BMLocalizedString(@"Sign In")];
[menuItemSignIn setAction: @selector(didClickShowSignIn:) ];
[menuItemSignIn setImage: bookmarkIcon];
[menuItemSignIn setTarget: self];
[menuItemSignIn retain];
menuItemOops = [[NSMenuItem alloc] init];
[menuItemOops setTitle: @""];
[menuItemOops retain];
//
// insert menu on the right of original Bookmarks item
//
NSMenuItem* topMenuItem = [[NSMenuItem alloc] init];
[topMenuItem setSubmenu: topMenu];
[topMenu release];
NSInteger insertPos = [[NSApp mainMenu] numberOfItems] - 1;
{
// NSBundle* appBundle = [NSBundle bundleForClass: [NSApp class]];
// NSString* orgBookmarksCaption = [appBundle localizedStringForKey:@"Bookmarks" value:@"" table:(nil)];
//NSLog(@"%@", bookmarksCaption);
NSArray* appMenus = [[NSApp mainMenu] itemArray];
// #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
// NSMenuItem* orgBookmarksItem = [appMenus selectFirst: ^(id obj) {
// NSMenuItem* menuItem = (NSMenuItem *) obj;
// return (BOOL) ([[menuItem title] compare: orgBookmarksCaption] == NSOrderedSame);
// }];
// #else
// NSMenuItem* orgBookmarksItem = [appMenus selectFirstCpationed: orgBookmarksCaption];
NSMenuItem* orgBookmarksItem = [appMenus objectAtIndex:5];
// #endif
if (orgBookmarksItem)
insertPos = [appMenus indexOfObject:orgBookmarksItem];
}
[[NSApp mainMenu] insertItem: topMenuItem atIndex: insertPos + 1];
[topMenuItem release];
//
// insert about menu
//
NSMenuItem* aboutMenuItem = [[NSMenuItem alloc] init];
[aboutMenuItem setTitle: BMLocalizedString(@"About Booglemarks")];
[aboutMenuItem setAction: @selector(showAboutBox:)];
[aboutMenuItem setKeyEquivalent: @""];
[aboutMenuItem setTarget: self];
[[[[NSApp mainMenu] itemAtIndex:0] submenu] insertItem: aboutMenuItem atIndex: 1];
[aboutMenuItem release];
//
// register self as observer
//
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver: self
selector: @selector(didSafariFinishLoadForFrame:)
name: WebViewProgressFinishedNotification
object: nil];
[self performSelector:@selector(doReload)];
return self;
}
- (void) dealloc
{
//NSLog(@"BMAppController - dealloc");
//
// unregister self from observer list
//
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center removeObserver: self];
[menuItemShowBookmarks release];
[menuItemAddBookmark release];
[menuItemReloadBookmarks release];
[menuItemReloading release];
[menuItemSignIn release];
[menuItemOops release];
[bookmarksIcon release];
[addBookmarkIcon release];
[reloadIcon release];
[folderIcon release];
[bookmarkIcon release];
[historyIcon release];
[tags release];
[super dealloc];
}
#pragma mark App Function
- (void) inspectClassMethods: (Class) clazz
{
unsigned int outCount, i;
Method *methods = class_copyMethodList(clazz, &outCount);
for(i = 0; i < outCount; i++) {
Method method = methods[i];
NSLog(@"- %@", NSStringFromSelector(method_getName(method)) );
}
free(methods);
}
- (void) inspectClassProperties: (Class) clazz
{
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(clazz, &outCount);
for(i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}
free(properties);
}
- (void) inspect: (NSView *) theView
{
//NSLog(@"%@", theView);
for (int i=0; i<[theView.subviews count]; i++)
[self inspect: [theView.subviews objectAtIndex: i]];
}
- (id) searchSubClassNamed: (NSString *) classDesc in: (NSView *) theView
{
if ([[[theView class] description] compare:classDesc] == NSOrderedSame)
return theView;
for (NSUInteger i = 0; i < [theView.subviews count]; i++)
{
id found = [self searchSubClassNamed: classDesc in: [theView.subviews objectAtIndex:i]];
if (found)
return found;
}
return nil;
}
- (id) searchSubClassOf: (Class) superclass in: (NSView *) theView
{
if ([[theView class] isSubclassOfClass: [superclass class]])
return theView;
for (NSUInteger i = 0; i < [theView.subviews count]; i++)
{
//NSLog(@"%@", [[theView.subviews objectAtIndex: i] class]);
id found = [self searchSubClassOf: superclass in: [theView.subviews objectAtIndex: i]];
if (found)
return found;
}
return nil;
}
- (id) searchOrderedTabBarView: (id) sender animated: (BOOL) animated
{
NSWindow* window = nil;
NSView* tabBarView = nil;
for (window in [NSApp orderedWindows])
{
tabBarView = (id) [self searchSubClassNamed: @"TabBarView" in: [window contentView]];
if (tabBarView)
break;
}
if (tabBarView && animated)
[window makeKeyAndOrderFront:self];
return tabBarView;
}
- (id) searchOrderedWebView: (id) sender animated: (BOOL) animated
{
NSWindow* window = nil;
WebView* webView = nil;
for (window in [NSApp orderedWindows])
{
NSTabView* tabview = [self searchSubClassNamed:@"NSTabView" in: [window contentView]];
if (tabview)
webView = (id)[tabview selectedTabViewItem];
if (!webView)
webView = (WebView *) [self searchSubClassOf: [WebView class] in: [window contentView]];
if (webView)
break;
}
if (webView && animated)
[window makeKeyAndOrderFront:self];
return webView;
}
- (void) openUrl: (NSString *) url newTab: (BOOL) newTab
{
if (newTab)
{
id tabBarView = [self searchOrderedTabBarView: self animated: YES];
if (tabBarView)
{
if ([tabBarView respondsToSelector: @selector(_createTab:)])
[tabBarView performSelector: @selector(_createTab:) withObject: self];
}
}
id webView = [self searchOrderedWebView: self animated: YES];
if (webView)
{
SEL selectorToOpenUrl = nil;
if ([webView respondsToSelector: @selector(setURLString:)])
selectorToOpenUrl = @selector(setURLString:);
else if ([webView respondsToSelector: @selector(setMainFrameURL:)])
selectorToOpenUrl = @selector(setMainFrameURL:);
if (selectorToOpenUrl)
[webView performSelector:selectorToOpenUrl withObject: url];
}
else
[[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: url]];
}
- (void) openUrl: (NSString *) url
{
[self openUrl: url newTab: NO];
}
- (NSDictionary *) pageDictionary
{
NSMutableDictionary* result = [[[NSMutableDictionary alloc] initWithCapacity: 2] autorelease];
id webView = [self searchOrderedWebView: self animated: YES];
if (webView)
{
id urlString = nil;
if ([webView respondsToSelector: @selector(setURLString:)])
urlString = [webView performSelector:@selector(URLString)];
else if ([webView respondsToSelector: @selector(setMainFrameURL:)])
urlString = [webView performSelector:@selector(mainFrameURL)];
if (urlString)
{
[result setObject:urlString forKey:@"url"];
[result setObject:urlString forKey:@"title"];
}
if ([webView respondsToSelector:@selector(title)])
{
[result setObject:[webView performSelector:@selector(title)] forKey:@"title"];
}
else if ([webView respondsToSelector:@selector(mainFrame)])
{
DOMDocument* domDoc = [[webView mainFrame] DOMDocument];
if (domDoc)
{
DOMNodeList* titles = [domDoc getElementsByTagNameNS: @"http://www.w3.org/1999/xhtml"
localName: @"title"];
if ([titles length])
[result setObject: [[titles item:0] textContent] forKey:@"title"];
}
}
}
return result;
}
- (void) addBookmarkWithLabels: (NSString *) labels
{
NSDictionary* pageDict = [self pageDictionary];
NSString* label = (labels)?labels:@"";
NSString* url = [pageDict objectForKey: @"url"];
NSString* title = [pageDict objectForKey: @"title"];
url = (url)?url:@"";
title = (title)?title:@"";
NSString* escapedAddr = BMLocalizedString(@"URL_ADD");
NSString* escapedBkmk = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString* escapedTitle = [title stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString* escapedLable = [label stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
[self openUrl: [NSString stringWithFormat: escapedAddr, escapedLable, escapedBkmk, escapedTitle] newTab: YES];
}
#pragma mark NSXMLParserDelegate
- (void) parser: (NSXMLParser *) parser
didStartElement: (NSString *) elementName
namespaceURI: (NSString *) namespaceURI
qualifiedName: (NSString *) qName
attributes: (NSDictionary *) attributeDict
{
if ([elementName isEqual:@"h3"]) {
tagInProgress = [[Tag alloc] init];
keyInProgress = [elementName copy];
textInProgress = [[NSMutableString alloc] init];
}
if ([elementName isEqual:@"a"]) {
bookmarkInProgress = [[BookmarkItem alloc] init];
bookmarkInProgress.url = [attributeDict objectForKey:@"href"];
bookmarkInProgress.updatedOn = [attributeDict objectForKey:@"add_date"];
keyInProgress = [elementName copy];
textInProgress = [[NSMutableString alloc] init];
}
}
- (void) parser: (NSXMLParser *) parser
didEndElement: (NSString *) elementName
namespaceURI: (NSString *) namespaceURI
qualifiedName: (NSString *) qName
{
if ([elementName isEqual:@"h3"])
{
tagInProgress.name = textInProgress;
[tags addObject: tagInProgress];
[textInProgress release];
textInProgress = nil;
[keyInProgress release];
keyInProgress = nil;
}
if ([elementName isEqual:@"a"])
{
bookmarkInProgress.title = textInProgress;
[tagInProgress.items addObject:bookmarkInProgress];
[bookmarkInProgress release];
bookmarkInProgress = nil;
[textInProgress release];
textInProgress = nil;
[keyInProgress release];
keyInProgress = nil;
}
}
- (void) parser: (NSXMLParser *) parser
foundCharacters:(NSString *)string
{
[textInProgress appendString: string];
}
- (NSData *) parser: (NSXMLParser *) parser resolveExternalEntityName: (NSString *) name
systemID:(NSString *) systemID
{
NSString* entityName = [NSString stringWithFormat:@"&%@;", name];
NSAttributedString *entityString = [[[NSAttributedString alloc]
initWithHTML:[entityName
dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:NULL]
autorelease];
//NSLog(@"resolved entity name: %@", [entityString string]);
return [[entityString string] dataUsingEncoding:NSUTF8StringEncoding];
}
- (void) parser: (NSXMLParser *) parser parseErrorOccurred: (NSError *) parseError
{
NSLog(@"%@", parseError);
}
- (void) parser: (NSXMLParser *) parser validationErrorOccurred: (NSError *) validationError
{
NSLog(@"%@", validationError);
}
- (void) parserDidEndDocument: (NSXMLParser *) parser
{
NSError* error = [parser parserError];//NSXMLParserErrorDomain
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotification:[NSNotification notificationWithName: didReloadNotificationName
object: error]];
}
#pragma mark Method
- (NSMenuItem *) menuItemAddBookmarkHereWithTag: (Tag *) tag
{
NSMenuItem* addBookmarkHereMenuItem = [[[NSMenuItem alloc] init] autorelease];
[addBookmarkHereMenuItem setRepresentedObject: tag];
[addBookmarkHereMenuItem setTitle: BMLocalizedString(@"Add Bookmark Here")];
[addBookmarkHereMenuItem setAction: @selector(didClickAddBookmarkHere:)];
[addBookmarkHereMenuItem setKeyEquivalent:@""];
[addBookmarkHereMenuItem setTarget: self];
return addBookmarkHereMenuItem;
}
- (NSMenuItem *) menuItemOpenInTabsWithTag: (Tag *) tag
{
NSMenuItem* openInTabsMenuItem = [[[NSMenuItem alloc] init] autorelease];
[openInTabsMenuItem setRepresentedObject: tag];
[openInTabsMenuItem setTitle: BMLocalizedString(@"Open in Tabs")];
[openInTabsMenuItem setAction: @selector(didClickOpenInTabs:)];
[openInTabsMenuItem setKeyEquivalent:@""];
[openInTabsMenuItem setTarget: self];
return openInTabsMenuItem;
}
- (NSMenuItem *) menuItemWithBookmark: (BookmarkItem *) bookmark
{
NSMenuItem* bookmarkMenuItem = [[[NSMenuItem alloc] init] autorelease];
[bookmarkMenuItem setRepresentedObject: bookmark];
[bookmarkMenuItem setTitle: [bookmark title]];
[bookmarkMenuItem setImage: bookmarkIcon];
[bookmarkMenuItem setAction: @selector(didClickBookmarkItem:)];
[bookmarkMenuItem setKeyEquivalent:@""];
[bookmarkMenuItem setTarget: self];
return bookmarkMenuItem;
}
- (Tag*) searchOrCreateTagNamed: (NSArray*) nameChain withTags: (NSMutableArray*) _tags
{
for (int t=0; t<[_tags count]; t++)
{
Tag* tag = [_tags objectAtIndex: t];
if ([[tag name] compare: [nameChain objectAtIndex:0]] == NSOrderedSame)
{
if ([nameChain count] == 0)
return tag;
else
{
NSMutableArray* tagNames = [NSMutableArray arrayWithArray: nameChain];
[tagNames removeObjectAtIndex: 0];
return [self searchOrCreateTagNamed: tagNames withTags: tag.tags];
}
}
}
Tag* newTag = [[[Tag alloc] init] autorelease];
newTag.name = [nameChain objectAtIndex:0];
[_tags addObject: newTag];
NSMutableArray* tagNames = [NSMutableArray arrayWithArray: nameChain];
[tagNames removeObjectAtIndex: 0];
if ([tagNames count] > 0)
return [self searchOrCreateTagNamed: tagNames withTags: newTag.tags];
else
return newTag;
}
- (void) willAppendMenuItemWithTags: (NSMutableArray*) _tags
{
[_tags sortUsingSelector: @selector(nameComparator:)];
NSMutableArray* tagsToBeRemoved = [[NSMutableArray alloc] init];
for (int t=0; t<[_tags count]; t++)
{
Tag* tag = [_tags objectAtIndex: t];
NSArray* nameChain = [[tag name] componentsSeparatedByString: tagSeperator];
if ([nameChain count] > 1)
{
Tag* t = [self searchOrCreateTagNamed: nameChain withTags: _tags];
t.items = tag.items;
[tagsToBeRemoved addObject: tag];
}
}
[_tags removeObjectsInArray: tagsToBeRemoved];
[tagsToBeRemoved release];
}
- (void) sortMostRecentWithTags: (NSMutableArray*) _tags recentUpdated: (NSMutableArray*) recentUpdated
{
NSInteger recentBound = 10;
for (int t=0; t<[_tags count]; t++)
{
Tag* tag = [_tags objectAtIndex: t];
[self sortMostRecentWithTags: tag.tags recentUpdated: recentUpdated];
[recentUpdated addReduancyObjectsFromArray: tag.items];
[recentUpdated sortUsingSelector: @selector(recentUpdatedComparator:)];
if ([recentUpdated count] > recentBound)
[recentUpdated removeObjectsInRange: NSMakeRange(recentBound, [recentUpdated count]-recentBound)];
}
}
- (void) appendMenuItemMostRecentWithTags: (NSMutableArray*) _tags toMenu: (NSMenu*) menu
{
NSMutableArray* recentUpdated = [[NSMutableArray alloc] init];
[self sortMostRecentWithTags: _tags recentUpdated: recentUpdated];
if ([recentUpdated count] > 0)
{
NSMenuItem* tagMenuItem = [[[NSMenuItem alloc] init] autorelease];
[tagMenuItem setRepresentedObject: nil];
[tagMenuItem setTitle: BMLocalizedString(@"Most Recent")];
[tagMenuItem setImage: historyIcon];
[menu insertItem: tagMenuItem atIndex: 5];
NSMenu* submenu = [[NSMenu alloc] init];
for (BookmarkItem* bookmark in recentUpdated)
[submenu addItem: [self menuItemWithBookmark: bookmark]];
[tagMenuItem setSubmenu: submenu];
[submenu release];
}
[recentUpdated release];
}
- (NSMenuItem *) appendMenuItemWithTag: (Tag *) tag toMenu: (NSMenu *) submenu
{
NSMenuItem* tagMenuItem = [[[NSMenuItem alloc] init] autorelease];
[tagMenuItem setRepresentedObject: tag];
[tagMenuItem setTitle: tag.name];
[tagMenuItem setImage: folderIcon];
[submenu addItem: tagMenuItem];
return tagMenuItem;
}
- (void) appendMenuItemWithTags: (NSMutableArray*) _tags toMenu: (NSMenu*) menu
{
[_tags sortUsingSelector: @selector(nameComparator:)];
Tag* unlabeledTag = nil;
for (int t=0; t<[_tags count]; t++)
{
Tag* tag = [_tags objectAtIndex: t];
[tag.items sortUsingSelector: @selector(titleComparator:)];
if ([[tag name] compare: @"Unlabeled"] == NSOrderedSame)
{
unlabeledTag = tag;
}
else
{
NSMenuItem* tagMenuItem = [self appendMenuItemWithTag: tag toMenu: menu];
NSMenu* submenu = [[NSMenu alloc] init];
if ([tag.tags count] > 0)
[self appendMenuItemWithTags: tag.tags toMenu: submenu];
for (int b=0; b<[tag.items count]; b++)
{
BookmarkItem* bookmark = [tag.items objectAtIndex: b];
[submenu addItem: [self menuItemWithBookmark: bookmark]];
}
[tagMenuItem setSubmenu: submenu];
[submenu release];
[submenu addItem: [NSMenuItem separatorItem]];
[submenu addItem: [self menuItemAddBookmarkHereWithTag: tag]];
[submenu addItem: [self menuItemOpenInTabsWithTag: tag]];
}
}
if (unlabeledTag)
{
for (int b=0; b<[unlabeledTag.items count]; b++)
{
BookmarkItem* bookmark = [unlabeledTag.items objectAtIndex: b];
[menu addItem: [self menuItemWithBookmark: bookmark]];
}
}
}
- (void) addStaticMenus
{
[topMenu addItem: menuItemShowBookmarks];
[topMenu addItem: menuItemAddBookmark];
}
- (void) didReload: (NSNotification *) n
{
//
// unregister observer
//
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center removeObserver: self
name: didReloadNotificationName
object: nil];
//
// reconstruct menu items
//
if ([topMenu respondsToSelector:@selector(removeAllItems)])
[topMenu removeAllItems];
else
while ([[topMenu itemArray] count])
[topMenu removeItemAtIndex:0];
[self addStaticMenus];
[topMenu addItem: [NSMenuItem separatorItem]];
[topMenu addItem: menuItemReloadBookmarks];
NSError* error = [n object];
//NSLog(@"didReload: %@", error);
if (! error || [error code] == 0 || [error code] == 27)
{
[topMenu addItem:[NSMenuItem separatorItem]];
[self willAppendMenuItemWithTags: tags];
[self appendMenuItemMostRecentWithTags: tags toMenu: topMenu];
[self appendMenuItemWithTags: tags toMenu: topMenu];
}
else
{
[topMenu addItem:[NSMenuItem separatorItem]];
if ([[error domain] compare: NSURLErrorDomain] == NSOrderedSame)
{
[menuItemOops setTitle: [error localizedDescription]];
[topMenu addItem: menuItemOops];
}
else if ([[error domain] compare: BMAppControllerErrorDomain] == NSOrderedSame)
{
[menuItemOops setTitle: [error localizedDescription]];
[topMenu addItem: menuItemOops];
if ([error code] == 1)
[topMenu addItem: menuItemSignIn];
}
}
reloading = NO;
}
- (void) webView: (WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
//
// may redirected if not logged yet
//
if ([[sender mainFrameURL] compare: BMLocalizedString(@"URL_EXPORT")] != NSOrderedSame)
{
NSDictionary* userInfo = [NSDictionary dictionaryWithObject: BMLocalizedString(@"Not Logged Yet")
forKey: NSLocalizedDescriptionKey];
NSError* error = [NSError errorWithDomain: BMAppControllerErrorDomain code:1 userInfo: userInfo];
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotification:[NSNotification notificationWithName: didReloadNotificationName
object: error]];
return;
}
//
// chop unclosed tags
//
DOMDocument* domDoc = [frame DOMDocument];
NSString* innerHTML = @"";
if ([domDoc respondsToSelector:@selector(body)])
innerHTML = [[domDoc body] innerHTML];
else if ([domDoc respondsToSelector:@selector(documentElement)])
innerHTML = [[domDoc documentElement] innerHTML];
NSArray* messTags = [NSArray arrayWithObjects:@"<dl>", @"</dl>", @"<dt>", @"</dt>", @"<p>", @"</p>", nil];
for (NSString* tag in messTags)
innerHTML = [innerHTML stringByReplacingOccurrencesOfString: tag withString: @""];
//
// encapsulate into DTD XHTML 1.1
//
NSMutableString* html = [[[NSMutableString alloc] init] autorelease];
[html appendString: @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
[html appendString: @"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"xhtml11.dtd\">"];
[html appendString: @"<html xmlns=\"http://www.w3.org/1999/xhtml\">"];
[html appendString: @"<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\"/>"];
[html appendString: @"\%@"];
[html appendString: @"</html>"];
html = [NSString stringWithFormat:html, innerHTML];
//NSLog(@"%@", html);
//
// start parsing
//
NSData* data = [html dataUsingEncoding: NSUTF8StringEncoding];
NSXMLParser* parser = [[NSXMLParser alloc] initWithData: data];
[parser setDelegate: self];
[parser setShouldResolveExternalEntities: YES];
[parser parse];
[parser release];
}
- (void)webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
{
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotification:[NSNotification notificationWithName: didReloadNotificationName
object: error]];
}
- (void) webView: (WebView *) sender didFailLoadWithError: (NSError *) error forFrame: (WebFrame *) frame
{
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotification:[NSNotification notificationWithName: didReloadNotificationName
object: error]];
}
- (void) doReload
{
if (reloading)
return;
reloading = YES;
[tags removeAllObjects];
//
// register observer
//
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver: self
selector: @selector(didReload:)
name: didReloadNotificationName
object: nil];
//
// display *Reloading...* on top menu
//
if ([topMenu respondsToSelector:@selector(removeAllItems)])
[topMenu removeAllItems];
else
while ([[topMenu itemArray] count])
[topMenu removeItemAtIndex:0];
[self addStaticMenus];
[topMenu addItem: [NSMenuItem separatorItem]];
[topMenu addItem: menuItemReloading];
//
// try to grab exported bookmarks
//
WebView* webView = [[WebView alloc] init];
[webView setFrameLoadDelegate: self];
[webView setMainFrameURL: BMLocalizedString(@"URL_EXPORT")];
[webView release];
}
- (void) didSafariFinishLoadForFrame: (NSNotification *) n
{
WebView* webView = (WebView *) [n object];
//NSLog(@"didSafariFinishLoadForFrame: %@", [webView mainFrameURL]);
NSString* predFmt = @"SELF MATCHES %@";
NSArray* predicates = [NSArray arrayWithObjects:
[NSPredicate predicateWithFormat: predFmt, BMLocalizedString(@"URL_LOGGED_MASK_1")],
[NSPredicate predicateWithFormat: predFmt, BMLocalizedString(@"URL_LOGGED_MASK_2")],
[NSPredicate predicateWithFormat: predFmt, BMLocalizedString(@"URL_LOGOUT_MASK")],
nil];
for (NSPredicate* predicate in predicates)
{
if ([predicate evaluateWithObject: [webView mainFrameURL]])
{
//NSLog(@"Matched!");
[self doReload];
break;
}
}
}
#pragma mark Menu Action
- (IBAction) showAboutBox: (id) sender
{
NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:
//bookmarkIcon, @"ApplicationIcon",
BMLocalizedString(@"CFBundleName"), @"ApplicationName",
BMLocalizedString(@"CFBundleVersion"), @"ApplicationVersion",
BMLocalizedString(@"CFBundleShortVersionString"), @"Version",
[[[NSAttributedString alloc] initWithString: BMLocalizedString(@"CREDIT")] autorelease],
@"Credits",
BMLocalizedString(@"NSHumanReadableCopyright"), @"Copyright",
nil];
[NSApp orderFrontStandardAboutPanelWithOptions: options];
}
- (IBAction) didClickReloadAll: (id) sender
{
[self doReload];
}
- (IBAction) didClickShowBookmarks: (id) sender
{
[self openUrl: BMLocalizedString(@"URL_HOME") newTab: YES];
}
- (IBAction) didClickShowSignIn: (id) sender
{
[self openUrl: BMLocalizedString(@"URL_SIGN_IN") newTab: YES];
}
- (IBAction) didClickAddBookmark: (id) sender
{
[self addBookmarkWithLabels: @""];
}
- (IBAction) didClickAddBookmarkHere: (id) sender
{
Tag* tag = [(NSMenuItem *)sender representedObject];
[self addBookmarkWithLabels: [tag name]];
}
- (IBAction) didClickOpenInTabs: (id) sender
{
Tag* tag = [(NSMenuItem *)sender representedObject];
for (BookmarkItem* bookmark in tag.items)
[self openUrl: bookmark.url newTab: YES];
}
- (IBAction) didClickBookmarkItem: (id) sender
{
BookmarkItem* bookmark = [(NSMenuItem *)sender representedObject];
[self openUrl: bookmark.url];
// [bookmark retriveFaviconForMenuItem: sender];
}
@end