forked from ViennaRSS/vienna-rss
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AppController.m
4719 lines (4221 loc) · 151 KB
/
AppController.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
//
// AppController.m
// Vienna
//
// Created by Steve on Sat Jan 24 2004.
// Copyright (c) 2004-2005 Steve Palmer. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "AppController.h"
#import "NewPreferencesController.h"
#import "FoldersTree.h"
#import "ArticleListView.h"
#import "UnifiedDisplayView.h"
#import "Import.h"
#import "Export.h"
#import "RefreshManager.h"
#import "ArrayExtensions.h"
#import "StringExtensions.h"
#import "SplitViewExtensions.h"
#import "SquareWindow.h"
#import "ViewExtensions.h"
#import "BrowserView.h"
#import "SearchFolder.h"
#import "NewSubscription.h"
#import "NewGroupFolder.h"
#import "ViennaApp.h"
#import "XMLSourceWindow.h"
#import "ActivityLog.h"
#import "BrowserPaneTemplate.h"
#import "Constants.h"
#import "ArticleView.h"
#import "BrowserPane.h"
#import "EmptyTrashWarning.h"
#import "Preferences.h"
#import "InfoWindow.h"
#import "DownloadManager.h"
#import "HelperFunctions.h"
#import "ArticleFilter.h"
#import "ToolbarItem.h"
#import "ClickableProgressIndicator.h"
#import "SearchPanel.h"
#import "SearchMethod.h"
#import <Sparkle/Sparkle.h>
#import <WebKit/WebKit.h>
#import <Growl/GrowlDefines.h>
#include <mach/mach_port.h>
#include <mach/mach_interface.h>
#include <mach/mach_init.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/IOMessage.h>
#import "GoogleReader.h"
#import "VTPG_Common.h"
@interface AppController (Private)
-(NSMenu *)searchFieldMenu;
-(void)installSleepHandler;
-(void)installScriptsFolderWatcher;
-(void)handleTabChange:(NSNotification *)nc;
-(void)handleFolderSelection:(NSNotification *)nc;
-(void)handleCheckFrequencyChange:(NSNotification *)nc;
-(void)handleFolderNameChange:(NSNotification *)nc;
-(void)handleDidBecomeKeyWindow:(NSNotification *)nc;
-(void)handleReloadPreferences:(NSNotification *)nc;
-(void)handleShowAppInStatusBar:(NSNotification *)nc;
-(void)handleShowStatusBar:(NSNotification *)nc;
-(void)handleShowFilterBar:(NSNotification *)nc;
-(void)setAppStatusBarIcon;
-(void)localiseMenus:(NSArray *)arrayOfMenus;
-(void)updateNewArticlesNotification;
-(void)showAppInStatusBar;
-(void)initSortMenu;
-(void)initColumnsMenu;
-(void)initScriptsMenu;
-(void)initFiltersMenu;
-(NSMenu *)getStylesMenu;
-(void)startProgressIndicator;
-(void)stopProgressIndicator;
-(void)doEditFolder:(Folder *)folder;
-(void)refreshOnTimer:(NSTimer *)aTimer;
-(BOOL)installFilename:(NSString *)srcFile toPath:(NSString *)path;
-(void)setStatusBarState:(BOOL)isVisible withAnimation:(BOOL)doAnimate;
-(void)setFilterBarState:(BOOL)isVisible withAnimation:(BOOL)doAnimate;
-(void)setPersistedFilterBarState:(BOOL)isVisible withAnimation:(BOOL)doAnimate;
-(void)doConfirmedDelete:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
-(void)doConfirmedEmptyTrash:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
-(void)runAppleScript:(NSString *)scriptName;
-(NSString *)appName;
-(void)sendBlogEvent:(NSString *)externalEditorBundleIdentifier title:(NSString *)title url:(NSString *)url body:(NSString *)body author:(NSString *)author guid:(NSString *)guid;
-(void)setLayout:(int)newLayout withRefresh:(BOOL)refreshFlag;
-(void)updateAlternateMenuTitle;
-(void)updateSearchPlaceholderAndSearchMethod;
-(void)toggleOptionKeyButtonStates;
-(FoldersTree *)foldersTree;
-(void)updateCloseCommands;
-(void)loadOpenTabs;
-(BOOL)isFilterBarVisible;
-(BOOL)isStatusBarVisible;
-(NSDictionary *)registrationDictionaryForGrowl;
-(NSTimer *)checkTimer;
-(ToolbarItem *)toolbarItemWithIdentifier:(NSString *)theIdentifier;
-(void)searchArticlesWithString:(NSString *)searchString;
-(void)sourceWindowWillClose:(NSNotification *)notification;
-(IBAction)cancelAllRefreshesToolbar:(id)sender;
@end
// Static constant strings that are typically never tweaked
static const int MA_Minimum_Folder_Pane_Width = 80;
static const int MA_Minimum_BrowserView_Pane_Width = 200;
static const int MA_StatusBarHeight = 23;
// Awake from sleep
static io_connect_t root_port;
static void MySleepCallBack(void * x, io_service_t y, natural_t messageType, void * messageArgument);
@implementation AppController
// C array of NSDateFormatter's : creating a NSDateFormatter is very expensive, so we create
// those we need early in the program launch and keep them in memory.
#define kNumberOfDateFormatters 8
static NSDateFormatter * dateFormatterArray[kNumberOfDateFormatters];
static NSLock * dateFormatters_lock;
/* init
* Class instance initialisation.
*/
-(id)init
{
if ((self = [super init]) != nil)
{
scriptPathMappings = [[NSMutableDictionary alloc] init];
progressCount = 0;
persistedStatusText = nil;
lastCountOfUnread = 0;
growlAvailable = NO;
appStatusItem = nil;
scriptsMenuItem = nil;
isStatusBarVisible = YES;
checkTimer = nil;
didCompleteInitialisation = NO;
emptyTrashWarning = nil;
searchString = nil;
}
return self;
}
/* awakeFromNib
* Do all the stuff that only makes sense after our NIB has been loaded and connected.
*/
-(void)awakeFromNib
{
#if ( MAC_OS_X_VERSION_MAX_ALLOWED < 1070 && !defined(NSWindowCollectionBehaviorFullScreenPrimary) )
enum {
NSWindowCollectionBehaviorFullScreenPrimary = (1 << 7)
};
#endif
//Enable FullScreen Support if we are on Lion 10.7.x
[mainWindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
Preferences * prefs = [Preferences standardPreferences];
[self installCustomEventHandler];
// Restore the most recent layout
[self setLayout:[prefs layout] withRefresh:NO];
// Localise the menus
[self localiseMenus:[[NSApp mainMenu] itemArray]];
// Set the delegates and title
[mainWindow setDelegate:self];
[mainWindow setTitle:[self appName]];
[NSApp setDelegate:self];
[mainWindow setMinSize: NSMakeSize(MA_Default_Main_Window_Min_Width, MA_Default_Main_Window_Min_Height)];
// Initialise the plugin manager now that the UI is ready
pluginManager = [[PluginManager alloc] init];
[pluginManager resetPlugins];
// Retain views which might be removed from the toolbar and therefore released;
// we will need them if they are added back later.
[spinner retain];
[searchField retain];
}
/* installCustomEventHandler
* This is our custom event handler that tells us when a modifier key is pressed
* or released anywhere in the system. Needed for iTunes-like button. The other
* half of the magic happens in ViennaApp.
*/
-(void)installCustomEventHandler
{
EventTypeSpec eventType;
eventType.eventClass = kEventClassKeyboard;
eventType.eventKind = kEventRawKeyModifiersChanged;
EventHandlerUPP handlerFunction = NewEventHandlerUPP(keyPressed);
InstallEventHandler(GetEventMonitorTarget(), handlerFunction, 1, &eventType, NULL, NULL);
}
/* applicationDidResignActive
* Do the things we need to do when Vienna becomes inactive, like greying out.
*/
-(void)applicationDidResignActive:(NSNotification *)aNotification
{
[foldersTree setOutlineViewBackgroundColor: [NSColor colorWithCalibratedRed:0.91 green:0.91 blue:0.91 alpha:1.00]];
[statusText setTextColor:[NSColor colorWithCalibratedRed:0.43 green:0.43 blue:0.43 alpha:1.00]];
[currentFilterTextField setTextColor:[NSColor colorWithCalibratedRed:0.43 green:0.43 blue:0.43 alpha:1.00]];
[filterIconInStatusBarButton setEnabled:NO];
}
/* applicationDidResignActive
* Do the things we need to do when Vienna becomes inactive, like re-coloring view backgrounds.
*/
-(void)applicationDidBecomeActive:(NSNotification *)notification
{
[foldersTree setOutlineViewBackgroundColor: [NSColor colorWithCalibratedRed:0.84 green:0.87 blue:0.90 alpha:1.00]];
[statusText setTextColor:[NSColor blackColor]];
[currentFilterTextField setTextColor:[NSColor blackColor]];
[filterIconInStatusBarButton setEnabled:YES];
}
/* doSafeInitialisation
* Do the stuff that requires that all NIBs are awoken. I can't find a notification
* from Cocoa for this so we hack it.
*/
-(void)doSafeInitialisation
{
static BOOL doneSafeInit = NO;
if (!doneSafeInit)
{
[foldersTree initialiseFoldersTree];
[mainArticleView initialiseArticleView];
// If the statusbar is hidden, also hide the highlight line on its top and the filter button.
if (![self isStatusBarVisible])
{
if ([mainWindow respondsToSelector:@selector(setBottomCornerRounded:)])
[mainWindow setBottomCornerRounded:NO];
[cosmeticStatusBarHighlightLine setHidden:YES];
[currentFilterTextField setHidden:YES];
[filterIconInStatusBarButton setHidden:YES];
}
// Select the folder and article from the last session
Preferences * prefs = [Preferences standardPreferences];
int previousFolderId = [prefs integerForKey:MAPref_CachedFolderID];
NSString * previousArticleGuid = [prefs stringForKey:MAPref_CachedArticleGUID];
if ([previousArticleGuid isBlank])
previousArticleGuid = nil;
[[articleController mainArticleView] selectFolderAndArticle:previousFolderId guid:previousArticleGuid];
// Set the initial filter bar state
[self setFilterBarState:[prefs showFilterBar] withAnimation:NO];
// Make article list the first responder
[mainWindow makeFirstResponder:[[browserView primaryTabItemView] mainView]];
// Start opening the old tabs once everything else has finished initializing and setting up
[self performSelector:@selector(loadOpenTabs)
withObject:nil
afterDelay:0];
doneSafeInit = YES;
}
didCompleteInitialisation = YES;
}
/* localiseMenus
* As of 2.0.1, the menu localisation is now done through the Localizable.strings file rather than
* the NIB file due to the effort in managing localised NIBs for an increasing number of languages.
* Also, note care is taken not to localise those commands that were added by the OS. If there is
* no equivalent in the Localizable.strings file, we do nothing.
*/
-(void)localiseMenus:(NSArray *)arrayOfMenus
{
int count = [arrayOfMenus count];
int index;
for (index = 0; index < count; ++index)
{
NSMenuItem * menuItem = [arrayOfMenus objectAtIndex:index];
if (menuItem != nil && ![menuItem isSeparatorItem])
{
NSString * localisedMenuTitle = NSLocalizedString([menuItem title], nil);
if ([menuItem submenu])
{
NSMenu * subMenu = [menuItem submenu];
if (localisedMenuTitle != nil)
[subMenu setTitle:localisedMenuTitle];
[self localiseMenus:[subMenu itemArray]];
}
if (localisedMenuTitle != nil)
[menuItem setTitle:localisedMenuTitle];
}
}
}
#pragma mark IORegisterForSystemPower
/* MySleepCallBack
* Called in response to an I/O event that we established via IORegisterForSystemPower. The
* messageType parameter allows us to distinguish between which event occurred.
*/
static void MySleepCallBack(void * refCon, io_service_t service, natural_t messageType, void * messageArgument)
{
if (messageType == kIOMessageSystemHasPoweredOn)
{
AppController * app = (AppController *)[NSApp delegate];
Preferences * prefs = [Preferences standardPreferences];
int frequency = [prefs refreshFrequency];
if (frequency > 0)
{
NSDate * lastRefresh = [prefs objectForKey:MAPref_LastRefreshDate];
if ((lastRefresh == nil) || ([app checkTimer] == nil))
[app handleCheckFrequencyChange:nil];
else
{
// Wait at least 15 seconds after waking to avoid refresh errors.
NSTimeInterval interval = -[lastRefresh timeIntervalSinceNow];
if (interval > frequency)
{
[NSTimer scheduledTimerWithTimeInterval:15.0
target:app
selector:@selector(refreshOnTimer:)
userInfo:nil
repeats:NO];
[app handleCheckFrequencyChange:nil];
}
else
{
[[app checkTimer] setFireDate:[NSDate dateWithTimeIntervalSinceNow:15.0 + frequency - interval]];
}
}
}
}
else if (messageType == kIOMessageCanSystemSleep)
{
// Idle sleep is about to kick in. Allow it otherwise the system
// will wait 30 seconds then go to sleep.
IOAllowPowerChange(root_port, (long)messageArgument);
}
else if (messageType == kIOMessageSystemWillSleep)
{
// The system WILL go to sleep. Allow it otherwise the system will
// wait 30 seconds then go to sleep.
IOAllowPowerChange(root_port, (long)messageArgument);
}
}
/* installSleepHandler
* Registers our handler to be notified when the system awakes from sleep. We use this to kick
* off a refresh if necessary.
*/
-(void)installSleepHandler
{
IONotificationPortRef notify;
io_object_t anIterator;
root_port = IORegisterForSystemPower(self, ¬ify, MySleepCallBack, &anIterator);
if (root_port != 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
}
/* MyScriptsFolderWatcherCallBack
* This is the callback function which is invoked when the file system detects changes in the Scripts
* folder. We use this to trigger a refresh of the scripts menu.
*/
static void MyScriptsFolderWatcherCallBack(FNMessage message, OptionBits flags, void * refcon, FNSubscriptionRef subscription)
{
AppController * app = (AppController *)refcon;
[app initScriptsMenu];
}
/* installScriptsFolderWatcher
* Install a handler to notify of changes in the scripts folder.
*/
-(void)installScriptsFolderWatcher
{
NSString * path = [[Preferences standardPreferences] scriptsFolder];
FNSubscriptionRef refCode;
FNSubscribeByPath((const UInt8 *)[path UTF8String], MyScriptsFolderWatcherCallBack, self, kNilOptions, &refCode);
}
/* layoutManager
* Return a cached instance of NSLayoutManager for calculating the font height.
*/
-(NSLayoutManager *)layoutManager
{
static NSLayoutManager * theManager = nil;
if (theManager == nil)
theManager = [[NSLayoutManager alloc] init];
return theManager;
}
#pragma mark Application Delegate
/* applicationDidFinishLaunching
* Handle post-load activities.
*/
-(void)applicationDidFinishLaunching:(NSNotification *)aNot
{
Preferences * prefs = [Preferences standardPreferences];
// Register a bunch of notifications
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(handleFolderSelection:) name:@"MA_Notify_FolderSelectionChange" object:nil];
[nc addObserver:self selector:@selector(handleCheckFrequencyChange:) name:@"MA_Notify_CheckFrequencyChange" object:nil];
[nc addObserver:self selector:@selector(handleEditFolder:) name:@"MA_Notify_EditFolder" object:nil];
[nc addObserver:self selector:@selector(handleRefreshStatusChange:) name:@"MA_Notify_RefreshStatus" object:nil];
[nc addObserver:self selector:@selector(handleTabChange:) name:@"MA_Notify_TabChanged" object:nil];
[nc addObserver:self selector:@selector(handleTabCountChange:) name:@"MA_Notify_TabCountChanged" object:nil];
[nc addObserver:self selector:@selector(handleFolderNameChange:) name:@"MA_Notify_FolderNameChanged" object:nil];
[nc addObserver:self selector:@selector(handleDidBecomeKeyWindow:) name:NSWindowDidBecomeKeyNotification object:nil];
[nc addObserver:self selector:@selector(handleReloadPreferences:) name:@"MA_Notify_PreferenceChange" object:nil];
[nc addObserver:self selector:@selector(handleShowAppInStatusBar:) name:@"MA_Notify_ShowAppInStatusBarChanged" object:nil];
[nc addObserver:self selector:@selector(handleShowStatusBar:) name:@"MA_Notify_StatusBarChanged" object:nil];
[nc addObserver:self selector:@selector(handleShowFilterBar:) name:@"MA_Notify_FilterBarChanged" object:nil];
//Google Reader Notifications
[nc addObserver:self selector:@selector(handleGoogleAuthFailed:) name:@"MA_Notify_GoogleAuthFailed" object:nil];
// Init the progress counter and status bar.
[self setStatusMessage:nil persist:NO];
// Initialize the database
if ((db = [Database sharedDatabase]) == nil)
{
[NSApp terminate:nil];
return;
}
// Create the toolbar.
NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"MA_Toolbar"] autorelease];
// Set the appropriate toolbar options. We are the delegate, customization is allowed,
// changes made by the user are automatically saved and we start in icon mode.
[toolbar setDelegate:self];
[toolbar setAllowsUserCustomization:YES];
[toolbar setAutosavesConfiguration:YES];
[toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
[toolbar setShowsBaselineSeparator:NO];
[mainWindow setToolbar:toolbar];
// Give the status bar and filter string an embossed look
[[statusText cell] setBackgroundStyle:NSBackgroundStyleRaised];
[[currentFilterTextField cell] setBackgroundStyle:NSBackgroundStyleRaised];
[currentFilterTextField setStringValue:@""];
// Preload dictionary of standard URLs
NSString * pathToPList = [[NSBundle mainBundle] pathForResource:@"StandardURLs.plist" ofType:@""];
if (pathToPList != nil)
standardURLs = [[NSDictionary dictionaryWithContentsOfFile:pathToPList] retain];
// Initialize the Sort By and Columns menu
[self initSortMenu];
[self initColumnsMenu];
[self initFiltersMenu];
// Initialize the Styles menu.
[stylesMenu setSubmenu:[self getStylesMenu]];
// Restore the splitview layout
[splitView1 setLayout:[[Preferences standardPreferences] objectForKey:@"SplitView1Positions"]];
[splitView1 setDelegate:self];
// Show the current unread count on the app icon
originalIcon = [[NSApp applicationIconImage] copy];
[self showUnreadCountOnApplicationIconAndWindowTitle];
// Set alternate in main menu for opening pages, and check for correct title of menu item
// This is a hack, because Interface Builder refuses to set alternates with only the shift key as modifier.
NSMenuItem * alternateItem = menuItemWithAction(@selector(viewSourceHomePageInAlternateBrowser:));
if (alternateItem != nil)
{
[alternateItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
[alternateItem setAlternate:YES];
}
alternateItem = menuItemWithAction(@selector(viewArticlePagesInAlternateBrowser:));
if (alternateItem != nil)
{
[alternateItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
[alternateItem setAlternate:YES];
}
[self updateAlternateMenuTitle];
// Create a menu for the search field
// The menu title doesn't appear anywhere so we don't localise it. The titles of each
// item is localised though.
[[searchField cell] setSearchMenuTemplate:[self searchFieldMenu]];
[[filterSearchField cell] setSearchMenuTemplate:[self searchFieldMenu]];
// Set the placeholder string for the global search field
SearchMethod * currentSearchMethod = [[Preferences standardPreferences] searchMethod];
[[searchField cell] setPlaceholderString:NSLocalizedString([currentSearchMethod friendlyName], nil)];
// Add Scripts menu if we have any scripts
if (!hasOSScriptsMenu())
[self initScriptsMenu];
// Show/hide the status bar based on the last session state
[self setStatusBarState:[prefs showStatusBar] withAnimation:NO];
// Add the app to the status bar if needed.
[self showAppInStatusBar];
// Use Growl if it is installed
[GrowlApplicationBridge setGrowlDelegate:self];
// Start the check timer
[self handleCheckFrequencyChange:nil];
// Register to be informed when the system awakes from sleep
[self installSleepHandler];
// Register to be notified when the scripts folder changes.
if (!hasOSScriptsMenu())
[self installScriptsFolderWatcher];
// Fix up the Close commands
[self updateCloseCommands];
// Do safe initialisation.
[self doSafeInitialisation];
[self showMainWindow:self];
// Hook up the key sequence properly now that all NIBs are loaded.
[[foldersTree mainView] setNextKeyView:[[browserView primaryTabItemView] mainView]];
if ([prefs refreshOnStartup])
[self refreshAllSubscriptions:self];
}
/* applicationShouldHandleReopen
* Handle the notification sent when the application is reopened such as when the dock icon
* is clicked. If the main window was previously hidden, we show it again here.
*/
-(BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
{
if (!didCompleteInitialisation)
return NO;
[self showMainWindow:self];
if (emptyTrashWarning != nil)
[emptyTrashWarning showWindow:self];
return YES;
}
/* updaterWillRelaunchApplication
* This is a delegate for Sparkle.framwork
*/
- (void)updaterWillRelaunchApplication:(SUUpdater *)updater
{
[[Preferences standardPreferences] handleUpdateRestart];
}
/* applicationShouldTerminate
* This function is called when the user wants to close Vienna. First we check to see
* if a connection or import is running and that all articles are saved.
*/
-(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
int returnCode;
if ([[DownloadManager sharedInstance] activeDownloads] > 0)
{
returnCode = NSRunAlertPanel(NSLocalizedString(@"Downloads Running", nil),
NSLocalizedString(@"Downloads Running text", nil),
NSLocalizedString(@"Quit", nil),
NSLocalizedString(@"Cancel", nil),
nil);
if (returnCode == NSAlertAlternateReturn)
return NSTerminateCancel;
}
if (!didCompleteInitialisation)
{
return NSTerminateNow;
}
switch ([[Preferences standardPreferences] integerForKey:MAPref_EmptyTrashNotification])
{
case MA_EmptyTrash_None: break;
case MA_EmptyTrash_WithoutWarning:
if (![db isTrashEmpty])
{
[[RefreshManager articlesUpdateSemaphore] lock];
[db purgeDeletedArticles];
[[RefreshManager articlesUpdateSemaphore] unlock];
}
break;
case MA_EmptyTrash_WithWarning:
if (![db isTrashEmpty])
{
if (emptyTrashWarning == nil)
emptyTrashWarning = [[EmptyTrashWarning alloc] init];
if ([emptyTrashWarning shouldEmptyTrash])
{
[[RefreshManager articlesUpdateSemaphore] lock];
[db purgeDeletedArticles];
[[RefreshManager articlesUpdateSemaphore] unlock];
}
[emptyTrashWarning release];
emptyTrashWarning = nil;
}
break;
default: break;
}
return NSTerminateNow;
}
/* applicationWillTerminate
* This is where we put the clean-up code.
*/
-(void)applicationWillTerminate:(NSNotification *)aNotification
{
if (didCompleteInitialisation)
{
// Save the splitview layout
Preferences * prefs = [Preferences standardPreferences];
[prefs setObject:[splitView1 layout] forKey:@"SplitView1Positions"];
// Close the activity window explicitly to force it to
// save its split bar position to the preferences.
NSWindow * activityWindow = [activityViewer window];
[activityWindow performClose:self];
// Put back the original app icon
[NSApp setApplicationIconImage:originalIcon];
// Save the open tabs
[browserView saveOpenTabs];
// Remember the article list column position, sizes, etc.
[mainArticleView saveTableSettings];
[foldersTree saveFolderSettings];
// Finally save preferences
[prefs savePreferences];
}
[db close];
}
/* splitView:effectiveRect:forDrawnRect:ofDividerAtIndex [delegate]
* Makes the dragable area around the SplitView divider larger, so that it is easier to grab.
*/
- (NSRect)splitView:(NSSplitView *)splitView effectiveRect:(NSRect)proposedEffectiveRect forDrawnRect:(NSRect)drawnRect ofDividerAtIndex:(NSInteger)dividerIndex
{
if([splitView isVertical]) {
drawnRect.origin.x -= 4;
drawnRect.size.width += 6;
return drawnRect;
}
else
return drawnRect;
}
/* openFile [delegate]
* Called when the user opens a data file associated with Vienna by clicking in the finder or dragging it onto the dock.
*/
-(BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
Preferences * prefs = [Preferences standardPreferences];
if ([[filename pathExtension] isEqualToString:@"viennastyle"])
{
NSString * styleName = [[filename lastPathComponent] stringByDeletingPathExtension];
if (![self installFilename:filename toPath:[prefs stylesFolder]])
[[Preferences standardPreferences] setDisplayStyle:styleName];
else
{
Preferences * prefs = [Preferences standardPreferences];
[stylesMenu setSubmenu:[self getStylesMenu]];
[[self toolbarItemWithIdentifier:@"Styles"] setPopup:@"stylesMenuButton" withMenu:[self getStylesMenu]];
[prefs setDisplayStyle:styleName];
if ([[prefs displayStyle] isEqualToString:styleName])
runOKAlertPanel(NSLocalizedString(@"New style title", nil), NSLocalizedString(@"New style body", nil), styleName);
}
return YES;
}
if ([[filename pathExtension] isEqualToString:@"viennaplugin"])
{
NSString * path = [prefs pluginsFolder];
if ([self installFilename:filename toPath:path])
{
runOKAlertPanel(NSLocalizedString(@"Plugin installed", nil), NSLocalizedString(@"A new plugin has been installed. It is now available from the menu and you can add it to the toolbar.", nil));
NSString * fullPath = [path stringByAppendingPathComponent:[filename lastPathComponent]];
[pluginManager loadPlugin:fullPath];
}
return YES;
}
if ([[filename pathExtension] isEqualToString:@"scpt"])
{
if ([self installFilename:filename toPath:[prefs scriptsFolder]])
{
if (!hasOSScriptsMenu())
[self initScriptsMenu];
}
}
if ([[filename pathExtension] isEqualToString:@"opml"])
{
BOOL returnCode = NSRunAlertPanel(NSLocalizedString(@"Import subscriptions from OPML file?", nil), NSLocalizedString(@"Do you really want to import the subscriptions from the specified OPML file?", nil), NSLocalizedString(@"Import", nil), NSLocalizedString(@"Cancel", nil), nil);
if (returnCode == NSAlertAlternateReturn)
return NO;
[self importFromFile:filename];
}
return NO;
}
/* installFilename
* Copies the folder at srcFile to the specified path. The path is created if it doesn't already exist and
* an error is reported if we fail to create the path. The return value is the result of copying the source
* folder to the new path.
*/
-(BOOL)installFilename:(NSString *)srcFile toPath:(NSString *)path
{
NSString * fullPath = [path stringByAppendingPathComponent:[srcFile lastPathComponent]];
// Make sure we actually have a destination folder.
NSFileManager * fileManager = [NSFileManager defaultManager];
BOOL isDir = NO;
if (![fileManager fileExistsAtPath:path isDirectory:&isDir])
{
if (![fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:NULL error:NULL])
{
runOKAlertPanel(NSLocalizedString(@"Cannot create folder title", nil), NSLocalizedString(@"Cannot create folder body", nil), path);
return NO;
}
}
[fileManager removeItemAtPath:fullPath error:nil];
return [fileManager copyItemAtPath:srcFile toPath:fullPath error:nil];
}
/* searchFieldMenu
* Allocates a popup menu for one of the search fields we use.
*/
-(NSMenu *)searchFieldMenu
{
NSMenu * cellMenu = [[NSMenu alloc] initWithTitle:@"Search Menu"];
NSMenuItem * item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Recent Searches", nil) action:NULL keyEquivalent:@""];
[item setTag:NSSearchFieldRecentsTitleMenuItemTag];
[cellMenu insertItem:item atIndex:0];
[item release];
item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Recents", nil) action:NULL keyEquivalent:@""];
[item setTag:NSSearchFieldRecentsMenuItemTag];
[cellMenu insertItem:item atIndex:1];
[item release];
item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Clear", nil) action:NULL keyEquivalent:@""];
[item setTag:NSSearchFieldClearRecentsMenuItemTag];
[cellMenu insertItem:item atIndex:2];
[item release];
SearchMethod * searchMethod;
NSString * friendlyName;
[cellMenu addItem: [NSMenuItem separatorItem]];
// Add all built-in search methods to the menu.
for (searchMethod in [SearchMethod builtInSearchMethods])
{
friendlyName = [searchMethod friendlyName];
item = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(friendlyName, nil) action:@selector(setSearchMethod:) keyEquivalent:@""];
[item setRepresentedObject: searchMethod];
// Is this the currently set search method? If yes, mark it as such.
if ( [friendlyName isEqualToString:[[[Preferences standardPreferences] searchMethod] friendlyName]] )
[item setState:NSOnState];
[cellMenu addItem:item];
[item release];
}
// Add all available plugged-in search methods to the menu.
NSMutableArray * searchMethods = [NSMutableArray arrayWithArray:[pluginManager searchMethods]];
if ([searchMethods count] > 0)
{
[cellMenu addItem: [NSMenuItem separatorItem]];
for (searchMethod in searchMethods)
{
if (![searchMethod friendlyName])
continue;
item = [[NSMenuItem alloc] initWithTitle:[searchMethod friendlyName] action:@selector(setSearchMethod:) keyEquivalent:@""];
[item setRepresentedObject: searchMethod];
// Is this the currently set search method? If yes, mark it as such.
if ( [[searchMethod friendlyName] isEqualToString: [[[Preferences standardPreferences] searchMethod] friendlyName]] )
[item setState:NSOnState];
[cellMenu addItem:item];
[item release];
}
}
[cellMenu setDelegate:self];
return [cellMenu autorelease];
}
/* setSearchMethod
*/
-(void)setSearchMethod:(NSMenuItem *)sender
{
[[Preferences standardPreferences] setSearchMethod: [sender representedObject]];
[[searchField cell] setPlaceholderString:[sender title]];
}
/* standardURLs
*/
-(NSDictionary *)standardURLs
{
return standardURLs;
}
/* browserView
*/
-(BrowserView *)browserView
{
return browserView;
}
/* constrainMinCoordinate
* Make sure the folder width isn't shrunk beyond a minimum width. Otherwise it looks
* untidy.
*/
-(CGFloat)splitView:(NSSplitView *)sender constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)offset
{
return (sender == splitView1 && offset == 0) ? MA_Minimum_Folder_Pane_Width : proposedMin;
}
/* constrainMaxCoordinate
* Make sure that the browserview isn't shrunk beyond a minimum size otherwise the splitview
* or controls within it start resizing odd.
*/
-(CGFloat)splitView:(NSSplitView *)sender constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)offset
{
if (sender == splitView1 && offset == 0)
{
NSRect mainFrame = [[splitView1 superview] frame];
return mainFrame.size.width - MA_Minimum_BrowserView_Pane_Width;
}
return proposedMax;
}
/* resizeSubviewsWithOldSize
* Constrain the folder pane to a fixed width.
*/
-(void)splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize
{
CGFloat dividerThickness = [sender dividerThickness];
id sv1 = [[sender subviews] objectAtIndex:0];
id sv2 = [[sender subviews] objectAtIndex:1];
NSRect leftFrame = [sv1 frame];
NSRect rightFrame = [sv2 frame];
NSRect newFrame = [sender frame];
if (sender == splitView1)
{
leftFrame.size.height = newFrame.size.height;
leftFrame.origin = NSMakePoint(0, 0);
rightFrame.size.width = newFrame.size.width - leftFrame.size.width - dividerThickness;
rightFrame.size.height = newFrame.size.height;
rightFrame.origin.x = leftFrame.size.width + dividerThickness;
[sv1 setFrame:leftFrame];
[sv2 setFrame:rightFrame];
}
}
/* folderMenu
* Dynamically create the popup menu. This is one less thing to
* explicitly localise in the NIB file.
*/
-(NSMenu *)folderMenu
{
NSMenu * folderMenu = [[[NSMenu alloc] init] autorelease];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(refreshSelectedSubscriptions:))];
[folderMenu addItem:[NSMenuItem separatorItem]];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(editFolder:))];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(deleteFolder:))];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(renameFolder:))];
[folderMenu addItem:[NSMenuItem separatorItem]];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(markAllRead:))];
[folderMenu addItem:[NSMenuItem separatorItem]];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(viewSourceHomePage:))];
NSMenuItem * alternateItem = copyOfMenuItemWithAction(@selector(viewSourceHomePageInAlternateBrowser:));
[alternateItem setKeyEquivalentModifierMask:NSAlternateKeyMask];
[alternateItem setAlternate:YES];
[folderMenu addItem:alternateItem];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(getInfo:))];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(showXMLSource:))];
[folderMenu addItem:[NSMenuItem separatorItem]];
[folderMenu addItem:copyOfMenuItemWithAction(@selector(forceRefreshSelectedSubscriptions:))];
return folderMenu;
}
/* exitVienna
* Alias for the terminate command.
*/
-(IBAction)exitVienna:(id)sender
{
[NSApp terminate:nil];
}
/* reportLayout
* Switch to report layout
*/
-(IBAction)reportLayout:(id)sender
{
[self setLayout:MA_Layout_Report withRefresh:YES];
}
/* condensedLayout
* Switch to condensed layout
*/
-(IBAction)condensedLayout:(id)sender
{
[self setLayout:MA_Layout_Condensed withRefresh:YES];
}
/* unifiedLayout
* Switch to unified layout.
*/
-(IBAction)unifiedLayout:(id)sender
{
[self setLayout:MA_Layout_Unified withRefresh:YES];
}
/* setLayout
* Changes the layout of the panes.
*/
-(void)setLayout:(int)newLayout withRefresh:(BOOL)refreshFlag
{
BOOL visibleFilterBar = NO;
// Turn off the filter bar when switching layouts. This is simpler than
// trying to graft it onto the new layout.
if ([self isFilterBarVisible])
{ visibleFilterBar = YES;
[self setPersistedFilterBarState:NO withAnimation:NO];
}
switch (newLayout)
{
case MA_Layout_Report:
[browserView setPrimaryTabItemView:mainArticleView];
if (refreshFlag)
[mainArticleView refreshFolder:MA_Refresh_RedrawList];
[articleController setMainArticleView:mainArticleView];
break;
case MA_Layout_Condensed:
[browserView setPrimaryTabItemView:mainArticleView];
if (refreshFlag)
[mainArticleView refreshFolder:MA_Refresh_RedrawList];
[articleController setMainArticleView:mainArticleView];
break;
case MA_Layout_Unified:
[browserView setPrimaryTabItemView:unifiedListView];
if (refreshFlag)
[unifiedListView refreshFolder:MA_Refresh_RedrawList];
[articleController setMainArticleView:unifiedListView];
break;
}
[[Preferences standardPreferences] setLayout:newLayout];
//restore filter bar state if necessary
if (visibleFilterBar)
[self setPersistedFilterBarState:YES withAnimation:NO];
[self updateSearchPlaceholderAndSearchMethod];
[[foldersTree mainView] setNextKeyView:[[browserView primaryTabItemView] mainView]];
}
+ (void) initialize
{