OSDN Git Service

HMBookmarkManagerをSwiftに変換した
[kcd/KCD.git] / KCD / HMAppDelegate.m
1 //
2 //  HMAppDelegate.m
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2013/12/31.
6 //  Copyright (c) 2013年 Hori,Masaki. All rights reserved.
7 //
8
9 #import "HMAppDelegate.h"
10
11 #import "KCD-Swift.h"
12
13 #import "HMUserDefaults.h"
14
15
16 #import "HMTSVSupport.h"
17
18 #import "CustomHTTPProtocol.h"
19
20
21 #ifndef UI_TEST
22 #       define UI_TEST 1
23 #endif
24
25 //@interface NSObject (HMM_NSUserNotificationCenterPrivateMethods)
26 //- (void)_removeDisplayedNotification:(id)obj;
27 //@end
28
29 @interface HMAppDelegate () <NSUserNotificationCenterDelegate, NSTouchBarProvider>
30
31 @property (nonatomic, strong) HMBroserWindowController *browserWindowController;
32 @property (nonatomic, strong) HMHistoryWindowController *historyWindowController;
33 @property (nonatomic, strong) HMSlotItemWindowController *slotItemWindowController;
34 @property (nonatomic, strong) HMPreferencePanelController *preferencePanelController;
35 @property (nonatomic, strong) HMUpgradableShipsWindowController *upgradableShipWindowController;
36 @property (nonatomic, strong) HMAirBaseWindowController *airBaseWindowController;
37
38 //@property (strong) HMExternalBrowserWindowController *externalBrowserWindowController;
39 @property (nonatomic, strong) HMBrowserContentAdjuster *browserContentAdjuster;
40
41 @property (nonatomic, strong) NSMutableArray *browserWindowControllers;
42
43 @property (nonatomic, strong) NSMutableArray *updaters;
44
45 @property (nonatomic, strong) HMFleetManager *fleetManager;
46
47 @property (nonatomic, strong) HMPeriodicNotifier *historyCleanNotifer;
48
49 @property (nonatomic, strong) IBOutlet NSTouchBar *mainTouchBar;
50
51 #ifdef DEBUG
52 @property (nonatomic, strong) HMShipWindowController *shipWindowController;
53 @property (nonatomic, strong) HMShipMasterDetailWindowController *shipMDWindowController;
54 @property (nonatomic, strong) HMEquipmentWindowController *equipmentWindowController;
55 @property (nonatomic, strong) HMMapWindowController *mapWindowController;
56 #endif
57
58 #if UI_TEST
59 @property (nonatomic, strong) HMUITestWindowController *uiTestWindowController;
60 #endif
61 #if ENABLE_JSON_LOG
62 @property (nonatomic, strong) HMJSONViewWindowController *logedJSONViewWindowController;
63 #endif
64
65 @property (nonatomic, strong) HMJSONTracker *jsonTracker;
66 @property (nonatomic, strong) HMTimeSignalNotifier *timeSignalNotifier;
67 @property (nonatomic, strong) HMResourceHistoryManager* resourceHistory;
68 @end
69
70 @implementation HMAppDelegate
71
72 @synthesize screenshotListWindowController = _screenshotListWindowController;
73
74 - (void)logLineReturn:(NSString *)format, ...
75 {
76         @synchronized (self) {
77                 va_list ap;
78                 va_start(ap, format);
79                 NSString *str = [[NSString alloc] initWithFormat:format arguments:ap];
80                 fprintf(stderr, "%s\n", [str UTF8String]);
81                 va_end(ap);
82         }
83 }
84 - (void)log:(NSString *)format, ...
85 {
86         @synchronized (self) {
87                 va_list ap;
88                 va_start(ap, format);
89                 NSString *str = [[NSString alloc] initWithFormat:format arguments:ap];
90                 fprintf(stderr, "%s", [str UTF8String]);
91                 va_end(ap);
92         }
93 }
94
95 - (instancetype)init
96 {
97         self = [super init];
98         if(self) {
99         [ValueTransformerRegister registerAll];
100         [CommandRegister register];
101                 self.updaters = [NSMutableArray new];
102                 _fleetManager = [HMFleetManager new];
103         
104         _jsonTracker = [HMJSONTracker new];
105         _timeSignalNotifier = [HMTimeSignalNotifier new];
106         _resourceHistory = [HMResourceHistoryManager new];
107     }
108         return self;
109 }
110
111 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
112 {
113         [CustomHTTPProtocol setupCache];
114         
115         NSUserNotificationCenter *unc = [NSUserNotificationCenter defaultUserNotificationCenter];
116         [unc setDelegate:self];
117         
118         self.browserWindowControllers = [NSMutableArray new];
119         
120         [NSTimer scheduledTimerWithTimeInterval:0.33
121                                                                          target:self
122                                                                    selector:@selector(fire:)
123                                                                    userInfo:nil
124                                                                         repeats:YES];
125 }
126
127 - (void)awakeFromNib
128 {
129     if(self.browserWindowController) return;
130     
131     [HMBookmarkManager shared];
132     
133         self.browserWindowController = [HMBroserWindowController new];
134         [self.browserWindowController showWindow:nil];
135         
136 #if ENABLE_JSON_LOG
137         self.jsonViewWindowController = [HMJSONViewWindowController new];
138         [self.jsonViewWindowController showWindow:nil];
139 #endif
140
141 #if UI_TEST
142         self.uiTestWindowController = [HMUITestWindowController new];
143         [self.uiTestWindowController showWindow:nil];
144 #endif
145         if(!HMStandardDefaults.showsDebugMenu) {
146                 [self.debugMenuItem setHidden:YES];
147         }
148         
149         NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
150         _historyCleanNotifer = [[HMPeriodicNotifier alloc] initWithHour:0 minutes:7];
151         [nc addObserverForName:[HMPeriodicNotifier notificationName]
152                                         object:_historyCleanNotifer
153                                          queue:nil
154                                 usingBlock:^(NSNotification * _Nonnull note) {
155                                         HMHistoryItemCleaner *historyItemCleaner = [HMHistoryItemCleaner new];
156                                         [historyItemCleaner cleanOldHistoryItems];
157                                 }];
158 }
159
160 - (void)addCounterUpdateBlock:(void(^)())updater
161 {
162         [self.updaters addObject:updater];
163 }
164 - (void)fire:(NSTimer *)timer
165 {
166         for(void (^updater)() in self.updaters) {
167                 updater();
168         }
169 }
170
171 - (void)clearCache
172 {
173         [CustomHTTPProtocol clearCache];
174 }
175
176 - (HMScreenshotListWindowController *)screenshotListWindowController
177 {
178         if(_screenshotListWindowController) return _screenshotListWindowController;
179         _screenshotListWindowController = [HMScreenshotListWindowController new];
180     id w = _screenshotListWindowController.window;
181     if( !w ) {
182         NSLog(@"Can not load ScreenshotListWindow");
183     }
184         return _screenshotListWindowController;
185 }
186
187 - (void)setScreenShotSaveDirectory:(NSString *)screenShotSaveDirectory
188 {
189         HMStandardDefaults.screenShotSaveDirectory = screenShotSaveDirectory;
190 }
191 - (NSString *)screenShotSaveDirectory
192 {
193         NSString *path = HMStandardDefaults.screenShotSaveDirectory;
194         if(!path) {
195                 path = [[self picturesDirectory] path];
196         }
197         
198         return path;
199 }
200 - (NSURL *)documentsFilesDirectory
201 {
202     NSFileManager *fileManager = [NSFileManager defaultManager];
203         return [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
204 }
205 - (NSURL *)picturesDirectory
206 {
207         NSFileManager *fileManager = [NSFileManager defaultManager];
208         return [[fileManager URLsForDirectory:NSPicturesDirectory inDomains:NSUserDomainMask] lastObject];
209 }
210 - (NSURL *)supportDirectory
211 {
212         NSFileManager *fileManager = [NSFileManager defaultManager];
213         NSURL *appSupportURL = [[fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] lastObject];
214         NSURL *ownAppSuportURL = [appSupportURL URLByAppendingPathComponent:@"com.masakih.KCD"];
215         return ownAppSuportURL;
216 }
217
218
219 - (NSString *)appNameForUserAgent
220 {
221         return @"Version/9.1.2 Safari/601.7.7";
222 }
223
224 - (NSFont *)monospaceSystemFont11
225 {
226         NSFont *font11 = nil;
227         if([NSFont respondsToSelector:@selector(monospacedDigitSystemFontOfSize:weight:)]) {
228                 font11 = [NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightRegular];
229         } else {
230                 font11 = [NSFont systemFontOfSize:11];
231         }
232         
233         return font11;
234 }
235 - (NSFont *)monospaceSystemFont12
236 {
237         NSFont *font12 = nil;
238         if([NSFont respondsToSelector:@selector(monospacedDigitSystemFontOfSize:weight:)]) {
239                 font12 = [NSFont monospacedDigitSystemFontOfSize:12 weight:NSFontWeightRegular];
240         } else {
241                 font12 = [NSFont systemFontOfSize:12];
242         }
243         
244         return font12;
245 }
246 - (NSFont *)monospaceSystemFont13
247 {
248         NSFont *font13 = nil;
249         if([NSFont respondsToSelector:@selector(monospacedDigitSystemFontOfSize:weight:)]) {
250                 font13 = [NSFont monospacedDigitSystemFontOfSize:13 weight:NSFontWeightRegular];
251         } else {
252                 font13 = [NSFont systemFontOfSize:13];
253         }
254         
255         return font13;
256 }
257
258
259 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
260 {
261         SEL action = [menuItem action];
262         if(action == @selector(showHideHistory:)) {
263                 NSWindow *window = self.historyWindowController.window;
264                 if(!window.isVisible || !window.isMainWindow) {
265                         [menuItem setTitle:NSLocalizedString(@"Show History", @"")];
266                 } else {
267                         [menuItem setTitle:NSLocalizedString(@"Hide History", @"")];
268                 }
269                 return YES;
270         } else if(action == @selector(showHideSlotItemWindow:)) {
271                 NSWindow *window = self.slotItemWindowController.window;
272                 if(!window.isVisible || !window.isMainWindow) {
273                         [menuItem setTitle:NSLocalizedString(@"Show Slot Item", @"")];
274                 } else {
275                         [menuItem setTitle:NSLocalizedString(@"Hide Slot Item", @"")];
276                 }
277                 return YES;
278         } else if(action == @selector(showHideUpgradableShipWindow:)) {
279                 NSWindow *window = self.upgradableShipWindowController.window;
280                 if(!window.isVisible || !window.isMainWindow) {
281                         [menuItem setTitle:NSLocalizedString(@"Show Upgradable Ships", @"")];
282                 } else {
283                         [menuItem setTitle:NSLocalizedString(@"Hide Upgradable Ships", @"")];
284                 }
285                 return YES;
286     } else if(action == @selector(showHideScreenshotListWindow:)) {
287         NSWindow *window = self.screenshotListWindowController.window;
288         if(!window.isVisible || !window.isMainWindow) {
289             [menuItem setTitle:NSLocalizedString(@"Show Screenshot List", @"")];
290         } else {
291             [menuItem setTitle:NSLocalizedString(@"Hide Screenshot List", @"")];
292         }
293         return YES;
294     } else if(action == @selector(showHideAirBaseInfoWindow:)) {
295         NSWindow *window = self.airBaseWindowController.window;
296         if(!window.isVisible || !window.isMainWindow) {
297             [menuItem setTitle:NSLocalizedString(@"Show Air Base Info", @"")];
298         } else {
299             [menuItem setTitle:NSLocalizedString(@"Hide Air Base Info", @"")];
300         }
301         return YES;
302     } else if(action == @selector(saveLocalData:) || action == @selector(loadLocalData:)) {
303                 return YES;
304         } else if(action == @selector(showHidePreferencePanle:)) {
305                 return YES;
306         } else if(action == @selector(openNewBrowser:) || action == @selector(selectBookmark:)) {
307                 return YES;
308         } else if(action == @selector(showWindowAduster:)) {
309                 return YES;
310         }
311 #if ENABLE_JSON_LOG
312         else if(action == @selector(saveDocument:) || action == @selector(openDocument:)) {
313                 return YES;
314         } else if(action == @selector(removeDatabaseFile:)) {
315                 return YES;
316         }
317 #endif
318 #ifdef DEBUG
319         else if(action == @selector(showShipWindow:) || action == @selector(showEquipmentWindow:)
320                         || action == @selector(showMapWindow:) || action == @selector(showOwnershipShipWindow:) ) {
321                 return YES;
322         }
323 #endif
324         return NO;
325 }
326
327 - (IBAction)showHideHistory:(id)sender
328 {
329         if(!self.historyWindowController) {
330                 self.historyWindowController = [HMHistoryWindowController new];
331         }
332         
333         NSWindow *window = self.historyWindowController.window;
334         if(!window.isVisible || !window.isMainWindow) {
335                 [window makeKeyAndOrderFront:nil];
336         } else {
337                 [window orderOut:nil];
338         }
339 }
340
341 - (IBAction)showHideSlotItemWindow:(id)sender
342 {
343         if(!self.slotItemWindowController) {
344                 self.slotItemWindowController = [HMSlotItemWindowController new];
345         }
346         
347         NSWindow *window = self.slotItemWindowController.window;
348         if(!window.isVisible || !window.isMainWindow) {
349                 [window makeKeyAndOrderFront:nil];
350         } else {
351                 [window orderOut:nil];
352         }
353 }
354
355 - (IBAction)showHidePreferencePanle:(id)sender
356 {
357         if(!self.preferencePanelController) {
358                 self.preferencePanelController = [HMPreferencePanelController new];
359         }
360         
361         NSWindow *window = self.preferencePanelController.window;
362         if(!window.isVisible || !window.isMainWindow) {
363                 [window makeKeyAndOrderFront:nil];
364         } else {
365                 [window orderOut:nil];
366         }
367 }
368
369 - (IBAction)showHideUpgradableShipWindow:(id)sender
370 {
371         if(!self.upgradableShipWindowController) {
372                 self.upgradableShipWindowController = [HMUpgradableShipsWindowController new];
373         }
374         
375         NSWindow *window = self.upgradableShipWindowController.window;
376         if(!window.isVisible || !window.isMainWindow) {
377                 [window makeKeyAndOrderFront:nil];
378         } else {
379                 [window orderOut:nil];
380         }
381 }
382
383 - (IBAction)showHideScreenshotListWindow:(id)sender
384 {
385         NSWindow *window = self.screenshotListWindowController.window;
386         if(!window.isVisible || !window.isMainWindow) {
387                 [window makeKeyAndOrderFront:nil];
388         } else {
389                 [window orderOut:nil];
390         }
391 }
392 - (IBAction)showHideAirBaseInfoWindow:(id)sender
393 {
394     if(!self.airBaseWindowController) {
395         self.airBaseWindowController = [HMAirBaseWindowController new];
396     }
397     
398     NSWindow *window = self.airBaseWindowController.window;
399     if(!window.isVisible || !window.isMainWindow) {
400         [window makeKeyAndOrderFront:nil];
401     } else {
402         [window orderOut:nil];
403     }
404 }
405
406 - (IBAction)openNewBrowser:(id)sender
407 {
408         [self createNewBrowser];
409 }
410 - (IBAction)selectBookmark:(id)sender
411 {
412         HMExternalBrowserWindowController *browser = [self createNewBrowser];
413         
414         [browser selectBookmark:sender];
415 }
416 - (HMExternalBrowserWindowController *)createNewBrowser
417 {
418         HMExternalBrowserWindowController *browser = [HMExternalBrowserWindowController new];
419         [self.browserWindowControllers addObject:browser];
420         [browser.window makeKeyAndOrderFront:nil];
421         
422         NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
423         [nc addObserver:self
424                    selector:@selector(windowWillClose:)
425                            name:NSWindowWillCloseNotification
426                          object:browser.window];
427         
428         return browser;
429 }
430 - (IBAction)showWindowAduster:(id)sender
431 {
432         if(! self.browserContentAdjuster) {
433                 self.browserContentAdjuster = [HMBrowserContentAdjuster new];
434         }
435         [self.browserContentAdjuster showWindow:nil];
436 }
437
438 - (void)windowWillClose:(NSNotification *)notification
439 {
440         id object = [notification object];
441         if([self.browserWindowControllers containsObject:object]) {
442                 [[NSNotificationCenter defaultCenter] removeObserver:self
443                                                                                                                 name:NSWindowWillCloseNotification
444                                                                                                           object:object];
445                 [self.browserWindowControllers removeObject:object];
446         }
447 }
448
449 - (IBAction)removeDatabaseFile:(id)sender
450 {
451         NSBundle *mainBundle = [NSBundle mainBundle];
452         NSString *appleScriptPath = [mainBundle pathForResource:@"RemoveDatabaseFileAndRestart"
453                                                                                                          ofType:@"app"];
454         NSTask *task = [NSTask new];
455         task.launchPath = @"/usr/bin/open";
456         task.arguments = @[appleScriptPath];
457         [task launch];
458 }
459
460 - (IBAction)showMainBrowser:(id)sender
461 {
462     [self.browserWindowController showWindow:nil];
463 }
464
465 #ifdef DEBUG
466
467 - (IBAction)showShipWindow:(id)sender
468 {
469         if(!_shipWindowController) {
470                 self.shipWindowController = [HMShipWindowController new];
471         }
472         [self.shipWindowController showWindow:nil];
473 }
474 - (IBAction)showEquipmentWindow:(id)sender
475 {
476         if(!_equipmentWindowController) {
477                 self.equipmentWindowController = [HMEquipmentWindowController new];
478         }
479         [self.equipmentWindowController showWindow:nil];
480 }
481 - (IBAction)showMapWindow:(id)sender
482 {
483         if(!_mapWindowController) {
484                 self.mapWindowController = [HMMapWindowController new];
485         }
486         [self.mapWindowController showWindow:nil];
487 }
488 - (IBAction)showOwnershipShipWindow:(id)sender
489 {
490         if(!_shipMDWindowController) {
491                 self.shipMDWindowController = [HMShipMasterDetailWindowController new];
492         }
493         [self.shipMDWindowController showWindow:nil];
494 }
495 #endif
496
497 - (NSTouchBar *)touchBar
498 {
499     if(NSClassFromString(@"NSTouchBar") == Nil) return nil;
500     
501     NSWindow *mainWindow = [NSApplication sharedApplication].mainWindow;
502     if(mainWindow == self.browserWindowController.window) return nil;
503     
504     if(self.mainTouchBar) return self.mainTouchBar;
505     
506     NSArray *toplevel = nil;
507     NSBundle *mainBundle = [NSBundle mainBundle];
508     [mainBundle loadNibNamed:@"MainTouchBar"
509                        owner:self
510              topLevelObjects:&toplevel];
511     
512     return self.mainTouchBar;
513 }
514
515 #pragma mark - NSApplicationDelegate
516 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
517 {
518         return YES;
519 }
520
521 #pragma mark - NSUserNotificationCenterDelegate
522 //- (void)removeUserNotification:(NSDictionary *)dict
523 //{
524 //      NSUserNotificationCenter *center = [dict objectForKey:@"center"];
525 //      NSUserNotification *notification = [dict objectForKey:@"notification"];
526 //      [center removeDeliveredNotification:notification];
527 //      //      [center _removeDisplayedNotification:notification];
528 //}
529
530 - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
531 {
532         return YES;
533 }
534
535 //- (void)userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification
536 //{
537 //      [self performSelector:@selector(removeUserNotification:)
538 //                         withObject:@{@"center":center, @"notification":notification}
539 //                         afterDelay:3];
540 //}
541 //- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
542 //{
543 //      [center removeDeliveredNotification:notification];
544 //}
545 #if ENABLE_JSON_LOG
546 - (IBAction)saveDocument:(id)sender
547 {
548         NSSavePanel *panel = [NSSavePanel savePanel];
549         [panel setAllowedFileTypes:@[@"plist"]];
550         [panel setPrompt:@"Save log"];
551         [panel setTitle:@"Save log"];
552         [panel beginWithCompletionHandler:^(NSInteger result) {
553                 if(result == NSModalResponseOK) {
554                         NSArray *array = [self.jsonViewWindowController.commands copy];
555                         NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
556                         if(!data) {
557                                 NSLog(@"can not convert log.");
558                                 return;
559                         }
560                         NSError *error = nil;
561                         [data writeToURL:panel.URL
562                                          options:NSDataWritingAtomic
563                                            error:&error];
564                         if(error) {
565                                 NSLog(@"can not save property list.: %@", error);
566                         }
567                 }
568         }];
569 }
570
571 - (IBAction)openDocument:(id)sender
572 {
573         NSOpenPanel *panel = [NSOpenPanel openPanel];
574         [panel setAllowedFileTypes:@[@"plist"]];
575         [panel setAllowsMultipleSelection:NO];
576         [panel setPrompt:@"Open log"];
577         [panel setTitle:@"Open log"];
578         [panel beginWithCompletionHandler:^(NSInteger result) {
579                 if(result == NSModalResponseOK) {
580                         NSData *data = [NSData dataWithContentsOfURL:panel.URL];
581                         id array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
582                         if(!array || ![array isKindOfClass:[NSArray class]]) {
583                                 NSLog(@"Can not convert data to log.");
584                                 return;
585                         }
586                         
587                         self.logedJSONViewWindowController = [HMJSONViewWindowController new];
588                         [self.logedJSONViewWindowController setCommandArray:array];
589                         [[self.logedJSONViewWindowController window] setTitle:@"SAVED LOG FILE VIEWER"];
590                         
591                         [self.logedJSONViewWindowController showWindow:nil];
592                 }
593         }];
594 }
595 #endif
596
597 - (IBAction)saveLocalData:(id)sender
598 {
599         [[HMTSVSupport new] save:sender];
600 }
601 - (IBAction)loadLocalData:(id)sender
602 {
603         [[HMTSVSupport new] load:sender];
604 }
605
606 @end