OSDN Git Service

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