Debian Codegraph @

platforms/apple/CocoaWrapper/mac/CocoaWrapper.mm

raw
1 /* GemRB - Infinity Engine Emulator
2 * Copyright (C) 2011 The GemRB Project
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 *
18 *
19 */
20
21 #import "CocoaWrapper.h"
22
23 #import "AppleLogger.h"
24 #import "Interface.h"
25 #import "Logging/Logging.h"
26 #import "PluginMgr.h"
27 #import "Streams/FileStream.h"
28
29 using namespace GemRB;
30
31 /* The main class of the application, the application's delegate */
32 @implementation CocoaWrapper
33 @synthesize configWindow=_configWindow;
34
35 - (id)init
36 {
37 self = [super init];
38 if (self) {
39 _configWindow = nil;
40 _showConfigWindow = NO;
41 }
42 return self;
43 }
44
45 - (void)dealloc
46 {
47 [_configWindow release];
48 [super dealloc];
49 }
50
51 - (BOOL)application:(NSApplication *) __unused theApplication openFile:(NSString *) filename
52 {
53 NSFileManager* fm = [NSFileManager defaultManager];
54 // only open if passed a directory
55 BOOL isDir = NO;
56 if ([fm fileExistsAtPath:filename isDirectory:&isDir] && isDir) {
57 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
58 [defaults setObject:filename forKey:@"GamePath"];
59
60 if (_showConfigWindow == NO) {
61 // opened via means other than config window
62 [self launchGame:self];
63 }
64
65 return YES;
66 }
67 return NO;
68 }
69
70 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *) __unused sender
71 {
72 //override this method using plugin categories.
73 NSLog(@"Application preparing for termination...");
74 return NSTerminateNow;
75 }
76
77 - (void)applicationWillTerminate:(NSNotification *) __unused aNotification
78 {
79
80 }
81
82 // always called before openFile when launched via CLI/DragDrop
83 - (void)applicationWillFinishLaunching:(NSNotification *) __unused aNotification
84 {
85 // Load default defaults
86 NSString* defaultsPath = [[NSBundle mainBundle] pathForResource:@"defaults" ofType:@"plist"];
87 NSMutableDictionary* defaultDict = [NSMutableDictionary dictionaryWithContentsOfFile:defaultsPath];
88
89 NSString* path = [[NSBundle mainBundle].resourcePath stringByAppendingFormat:@"/GUIScripts"];
90 NSFileManager* fm = [NSFileManager defaultManager];
91 NSError* error = nil;
92 NSArray* items = [fm contentsOfDirectoryAtPath:path error:&error];
93
94 NSMutableArray* gameTypes = [NSMutableArray arrayWithObject:@"auto"];
95 for (NSString* subPath in items) {
96 BOOL isDir = NO;
97 if ([fm fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", path, subPath] isDirectory:&isDir] && isDir) {
98 [gameTypes addObject:[subPath lastPathComponent]];
99 }
100 }
101 [defaultDict setValue:gameTypes forKey:@"gameTypes"];
102
103 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
104 [defaults registerDefaults:defaultDict];
105
106 if (![defaults stringForKey:@"CachePath"]) {
107 NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, NO);
108 NSString* cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"gemrb"];
109 [defaults setValue:cachePath forKey:@"CachePath"];
110 }
111
112 NSMutableDictionary* additionalPaths = [[defaults dictionaryForKey:@"AdditionalPaths"] mutableCopy];
113 if ([additionalPaths valueForKey:@"CustomFontPath"] == nil) {
114 NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, NO);
115 NSString* fontPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Fonts"];
116 [additionalPaths setValue:fontPath forKey:@"CustomFontPath"];
117 }
118 if ([additionalPaths valueForKey:@"SavePath"] == nil) {
119 [additionalPaths setValue:[defaults valueForKey:@"GamePath"] forKey:@"SavePath"];
120 }
121 [defaults setObject:additionalPaths forKey:@"AdditionalPaths"];
122 [additionalPaths release];
123 }
124
125 /* Called when the internal event loop has just started running */
126 - (void) applicationDidFinishLaunching: (NSNotification *) __unused aNotification
127 {
128 // we configure this here so that when GemRB is launched though means such as Drag/Drop we dont show the config window
129
130 _showConfigWindow = YES; //still need to set this to YES in case an error occurs
131 [[NSBundle mainBundle] loadNibNamed:@"GemRB" owner:self topLevelObjects:nil];
132
133 if (core == NULL) {
134 [_configWindow makeKeyAndOrderFront:nil];
135 }
136 }
137
138 - (IBAction)openGame:(id) __unused sender
139 {
140 // be careful to use only methods available in 10.5!
141 NSOpenPanel* op = [NSOpenPanel openPanel];
142 [op setCanChooseDirectories:YES];
143 [op setCanChooseFiles:NO];
144 [op setAllowsMultipleSelection:NO];
145 [op setMessage:@"Select a folder containing an IE game (has a chitin.key)."];
146 [op setPrompt:@"Select Game"];
147 if ([op runModal] == NSModalResponseOK) { //blocks till user selection
148 [self application:NSApp openFile:op.URL.path];
149 }
150 }
151
152 - (IBAction)launchGame:(id) sender
153 {
154 if (core) {
155 Log(FATAL, "Launch Game", "GemRB game is currently running. Please close it before trying to open another.");
156 return;
157 }
158 if (sender) {
159 // Note: use NSRunLoop over NSObject performSelector!
160 NSArray* modes = [NSArray arrayWithObject:NSDefaultRunLoopMode];
161 [[NSRunLoop mainRunLoop] performSelector:@selector(launchGame:) target:self argument:nil order:0 modes:modes];
162 return;
163 }
164
165 // load NSUserDefaults into config
166 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
167 NSDictionary* userValues = [defaults persistentDomainForName:@"org.gemrb.gemrb"];
168 NSDictionary* defaultValues = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"defaults" ofType:@"plist"]];
169
170 NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithDictionary:defaultValues];
171 [dict addEntriesFromDictionary:userValues];
172
173 for ( NSString* key in dict.allKeys ) {
174 id obj = [dict objectForKey:key];
175 if ( [obj isKindOfClass:[NSDictionary class]] ) {
176 // move it to the root level
177 [dict addEntriesFromDictionary:obj];
178 [dict removeObjectForKey:key];
179 }
180 }
181
182 InterfaceConfig config;
183
184 for ( NSString* key in dict ) {
185 NSString* value = nil;
186 id obj = [dict objectForKey:key];
187 if ([obj isKindOfClass:[NSNumber class]]) {
188 value = [(NSNumber*)obj stringValue];
189 } else if ([obj isKindOfClass:[NSString class]]) {
190 value = (NSString*)obj;
191 }
192 if (value && ![value isEqualToString:@""]) {
193 std::string ckey = [key cStringUsingEncoding:NSASCIIStringEncoding];
194 config.Set(ckey, [value cStringUsingEncoding:NSASCIIStringEncoding]);
195 }
196 }
197
198 try {
199 CoreSettings settings = LoadFromDictionary(std::move(config));
200 ToggleLogging(settings.Logging);
201
202 if (getenv("TERM") && isatty(STDOUT_FILENO)) {
203 AddLogWriter(createStdioLogWriter());
204 } else {
205 AddLogWriter(std::make_shared<AppleLogger>());
206 }
207
208 Interface gemrb(std::move(settings));
209 [_configWindow close];
210 // pass control to GemRB
211 gemrb.Main();
212 VideoDriver.reset();
213 } catch (std::exception& e) {
214 Log(FATAL, "Cocoa Wrapper", "Unable to initialize core: {}. Terminating.", e);
215 }
216
217 PluginMgr::Get()->RunCleanup();
218
219 if ([defaults boolForKey:@"TerminateOnClose"]) {
220 [NSApp terminate:self];
221 }
222 }
223
224 - (id)validRequestorForSendType:(NSString *) __unused sendType returnType:(NSString *) __unused returnType
225 {
226 return nil;
227 }
228
229 - (BOOL)respondsToSelector:(SEL)aSelector
230 {
231 if ([NSApp respondsToSelector:aSelector]) {
232 return YES;
233 }
234 return [super respondsToSelector:aSelector];
235 }
236
237 - (NSMethodSignature*) methodSignatureForSelector:(SEL)selector
238 {
239 NSMethodSignature* signature = [super methodSignatureForSelector:selector];
240
241 if (!signature)
242 signature = [NSApp methodSignatureForSelector:selector];
243
244 return signature;
245 }
246
247 - (void)forwardInvocation:(NSInvocation *)invocation
248 {
249 SEL selector = [invocation selector];
250
251 if ([NSApp respondsToSelector:selector])
252 {
253 [invocation invokeWithTarget:NSApp];
254 } else {
255 [super forwardInvocation:invocation];
256 }
257 }
258
259 @end
260
261 /* Main entry point to executable - should *not* be GemRB_main! */
262 int main (int __unused argc, char ** __unused argv)
263 {
264 CocoaWrapper* wrapper = [[CocoaWrapper alloc] init];
265 @autoreleasepool {
266 /* Ensure the application object is initialized */
267 NSApplication* app = [NSApplication sharedApplication];
268
269 /* Set up the menubar */
270 [NSApp setMainMenu:[[[NSMenu alloc] init] autorelease]];
271 [app setDelegate:wrapper];
272 }
273 [NSApp run];
274 [wrapper release];
275 return 0;
276 }
277