OSDN Git Service

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