summaryrefslogtreecommitdiff
path: root/src/SFML/Window/Cocoa/AppController.mm
blob: a6b7310f5c2582831bb0a15c8998291da20158e7 (plain)
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
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2008 Lucas Soltic (elmerod@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#import <SFML/Window/Cocoa/AppController.h>
#import <SFML/Window/Cocoa/WindowController.h>
#import <SFML/Window/Cocoa/WindowImplCocoa.hpp>
#import <SFML/System.hpp>
#import <ApplicationServices/ApplicationServices.h>
#import <iostream>


// AppController singleton
static AppController *shared = nil;


/* setAppleMenu disappeared from the headers in 10.4 */
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
@interface NSApplication (SFML)
- (void)setAppleMenu:(NSMenu *)menu;
@end
#endif

@implementation NSApplication (SFML)

- (void)setRunning:(BOOL)flag
{
	// Note: _running is a short, not a BOOL
	if (flag)
		_running = 1;
	else
		_running = 0;
}

@end


@implementation AppController

- (id)init
{
	self = [super init];
	
	if (self != nil) {
		windows = new std::vector <sf::priv::WindowImplCocoa *>;
		cleaner = new sf::Clock;
	}
	
	return self;
}


- (void)dealloc
{
	delete windows;
	delete cleaner;
	[super dealloc];
}


////////////////////////////////////////////////////////////
/// Return the shared AppController object. Makes one if needed
////////////////////////////////////////////////////////////
+ (AppController *)sharedController
{
	if (nil == shared) {
		shared = [massert([AppController alloc]) init];
	}
	
	return shared;
}


////////////////////////////////////////////////////////////
/// Reallocate main pool to release autoreleased objects
////////////////////////////////////////////////////////////
- (void)resetPool
{
	[mainPool release];
	
	mainPool = [massert([NSAutoreleasePool alloc]) init];
}


////////////////////////////////////////////////////////////
/// Register our application and launch it if needed
////////////////////////////////////////////////////////////
- (void)runApplication
{
	if ([NSApp isRunning])
		return;
	
	// We want our application to appear in the Dock and be able
	// to get focus
	ProcessSerialNumber psn;
	
    if (!GetCurrentProcess(&psn)) {
        TransformProcessType(&psn, kProcessTransformToForegroundApplication);
        SetFrontProcess(&psn);
    }
	
    if (NSApp == nil) {
        massert([NSApplication sharedApplication]);
    }
	
	if ([NSApp mainMenu] == nil) {
		[self makeMenuBar];
	}
	
	[NSApp finishLaunching];
    [NSApp setRunning:YES];
	[NSApp setDelegate:self];
	
	desktopMode = sf::VideoMode::GetDesktopMode();
}


////////////////////////////////////////////////////////////
/// Terminate the current running application
////////////////////////////////////////////////////////////
- (void)quitApplication:(id)sender
{
	// Close all windows
	// SFML user has to detect when all windows are closed
	NSWindow *current = nil;
	sf::priv::WindowImplCocoa *priv = NULL;
	
	while (windows->size()) {
		priv = windows->at(0);
		current = static_cast <NSWindow *> (priv->CocoaWindow());
		[current close];
		windows->erase(windows->begin());
	}
}


////////////////////////////////////////////////////////////
/// Returns the first full screen window found or nil
////////////////////////////////////////////////////////////
- (SFWindow *)fullscreenWindow
{
	SFWindow *window = nil;
	std::vector<sf::priv::WindowImplCocoa *>::size_type sz = windows->size();
	std::vector<sf::priv::WindowImplCocoa *>::size_type idx;
	
	for (idx = 0; idx < sz; idx++) {
		sf::priv::WindowImplCocoa *win = windows->at(idx);
		if (win && win->IsFullscreen()) {
			window = static_cast <SFWindow *> (win->CocoaWindow());
			break;
		}
	}
	
	return window;
}


////////////////////////////////////////////////////////////
/// Hide all the fullscreen windows and switch to desktop display mode
////////////////////////////////////////////////////////////
- (void)applicationWillHide:(NSNotification *)aNotification
{
	if ([self isUsingFullscreen]) {
		prevMode = sf::VideoMode::GetDesktopMode();
		
		CFDictionaryRef displayMode = CGDisplayBestModeForParameters (kCGDirectMainDisplay,
																	  desktopMode.BitsPerPixel,
																	  desktopMode.Width,
																	  desktopMode.Height,
																	  NULL);
		
		CGDisplayFadeReservationToken token = kCGDisplayFadeReservationInvalidToken;
		
		// Fade to black screen
		[SharedAppController doFadeOperation:FillScreen time:0.2f sync:true token:&token];
		
		// Make all the full screen SFML windows unvisible
		std::vector<sf::priv::WindowImplCocoa *>::size_type sz = windows->size();
		std::vector<sf::priv::WindowImplCocoa *>::size_type idx;
		
		for (idx = 0; idx < sz; idx++) {
			sf::priv::WindowImplCocoa *win = windows->at(idx);
			
			if (win->IsFullscreen()) {
				[static_cast <SFWindow *> (win->CocoaWindow()) setAlphaValue:0.0f];
			}
		}
		
		// Switch to the wished display mode
		CGDisplaySwitchToMode(kCGDirectMainDisplay, displayMode);
		
		// Fade to normal screen
		[SharedAppController doFadeOperation:CleanScreen time:0.5f sync:false token:&token];
	}
}


////////////////////////////////////////////////////////////
/// Unhide all the fullscreen windows and switch to full screen display mode
////////////////////////////////////////////////////////////
- (void)applicationWillUnhide:(NSNotification *)aNotification
{
	if ([self isUsingFullscreen]) {
		CFDictionaryRef displayMode = CGDisplayBestModeForParameters (kCGDirectMainDisplay,
																	  prevMode.BitsPerPixel,
																	  prevMode.Width,
																	  prevMode.Height,
																	  NULL);
		
		CGDisplayFadeReservationToken token = kCGDisplayFadeReservationInvalidToken;
		
		// Fade to a black screen
		[SharedAppController doFadeOperation:FillScreen time:0.5f sync:true token:&token];
		[NSMenu setMenuBarVisible:NO];
		
		// Switch to the wished display mode
		CGDisplaySwitchToMode(kCGDirectMainDisplay, displayMode);
		
		// Make all the SFML windows visible
		std::vector<sf::priv::WindowImplCocoa *>::size_type sz = windows->size();
		std::vector<sf::priv::WindowImplCocoa *>::size_type idx;
		
		for (idx = 0; idx < sz; idx++) {
			sf::priv::WindowImplCocoa *win = windows->at(idx);
			
			if (win->IsFullscreen()) {
				[static_cast <SFWindow *> (win->CocoaWindow()) setAlphaValue:1.0f];
				[static_cast <SFWindow *> (win->CocoaWindow()) center];
			}
		}
		
		// Fade to normal screen
		[SharedAppController doFadeOperation:CleanScreen time:0.5f sync:false token:&token];
	}
}


////////////////////////////////////////////////////////////
/// Make menu bar
////////////////////////////////////////////////////////////
- (void)makeMenuBar
{
	// Source taken from SDL 1.3
	
	NSString *appName = nil;
	NSString *title = nil;
	NSMenu *appleMenu = nil;
	NSMenu *fileMenu = nil;
	NSMenu *windowMenu = nil;
	NSMenuItem *menuItem = nil;
	NSMenuItem *quitMenuItem = nil;
	
	// Determine the application name
	appName = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleName"];
	
	if (![appName length])
		appName = [[NSProcessInfo processInfo] processName];
	
	
	// Create the main menu bar
	[NSApp setMainMenu:[massert([NSMenu alloc]) init]];
	
	// Create the application menu
	appleMenu = [massert([NSMenu alloc]) initWithTitle:@""];
	
	// Put menu items
	// + 'About' menu item
	title = [@"About " stringByAppendingString:appName];
	[appleMenu addItemWithTitle:title
						 action:@selector(orderFrontStandardAboutPanel:)
				  keyEquivalent:@""];
	
	[appleMenu addItem:[NSMenuItem separatorItem]];
	
	// + 'Hide' menu item
	title = [@"Hide " stringByAppendingString:appName];
	[appleMenu addItemWithTitle:title
						 action:@selector(hide:)
				  keyEquivalent:@"h"];
	
	// + 'Hide other' menu item
	menuItem = static_cast <NSMenuItem *> ([appleMenu addItemWithTitle:@"Hide Others"
																action:@selector(hideOtherApplications:)
														 keyEquivalent:@"h"]);
	[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
	
	// + 'Show all' menu item
	[appleMenu addItemWithTitle:@"Show All"
						 action:@selector(unhideAllApplications:)
				  keyEquivalent:@""];
	
	[appleMenu addItem:[NSMenuItem separatorItem]];
	
	// + 'Quit' menu item
	title = [@"Quit " stringByAppendingString:appName];
	quitMenuItem = [[massert([NSMenuItem alloc])
					 initWithTitle:title 
					 action:@selector(quitApplication:)
					 keyEquivalent:@"q"] autorelease];
	[quitMenuItem setTarget:self];
	[appleMenu addItem:quitMenuItem];
	
	// Put the menu into the menubar
	menuItem = [massert([NSMenuItem alloc])
				initWithTitle:@""
				action:nil
				keyEquivalent:@""];
	[menuItem setSubmenu:appleMenu];
	[[NSApp mainMenu] addItem:menuItem];
	[menuItem release];
	
	// Tell the application object that this is now the application menu
	[NSApp setAppleMenu:appleMenu];
	[appleMenu release];
	
	// 'File' menu
	fileMenu = [massert([NSMenu alloc])
				initWithTitle:@"File"];
	
	// + 'Close' menu item
	menuItem = [massert([NSMenuItem alloc]) 
				initWithTitle:@"Close"
				action:@selector(performClose:)
				keyEquivalent:@"w"];
	[fileMenu addItem:menuItem];
	[menuItem release];
	
	// + 'File' menu item (head)
	menuItem = [massert([NSMenuItem alloc])
				initWithTitle:@"File"
				action:nil
				keyEquivalent:@""];
	[menuItem setSubmenu:fileMenu];
	[[NSApp mainMenu] addItem:menuItem];
	[menuItem release];
	
	// 'Window' menu
	windowMenu = [massert([NSMenu alloc])
				  initWithTitle:@"Window"];
	
	// + 'Minimize' menu item
	menuItem = [massert([NSMenuItem alloc])
				initWithTitle:@"Minimize"
				action:@selector(performMiniaturize:)
				keyEquivalent:@"m"];
	[windowMenu addItem:menuItem];
	[menuItem release];
	
	// + 'Window' menu item (head)
	menuItem = [massert([NSMenuItem alloc])
				initWithTitle:@"Window"
				action:nil keyEquivalent:@""];
	[menuItem setSubmenu:windowMenu];
	[[NSApp mainMenu] addItem:menuItem];
	[menuItem release];
	
	// Tell the application object that this is now the window menu
	[NSApp setWindowsMenu:windowMenu];
	[windowMenu release];
}


////////////////////////////////////////////////////////////
/// Delegate method in order to prevent usual -terminate:
////////////////////////////////////////////////////////////
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
	[self quitApplication:nil];
	return NSTerminateCancel;
}


////////////////////////////////////////////////////////////
/// Get the events and put them into an array for each window
////////////////////////////////////////////////////////////
- (void)processEvents
{
	// Release the main autorelease pool every second
	if (cleaner->GetElapsedTime() > 1.0f) {
		cleaner->Reset();
		[self resetPool];
	}
	
	NSEvent *event = nil;
	
	while (nil != (event = [NSApp nextEventMatchingMask:NSAnyEventMask
											  untilDate:nil
												 inMode:NSEventTrackingRunLoopMode
												dequeue:YES])) {
		NSWindow *keyWindow = [NSApp keyWindow];
		
		if (keyWindow == nil) {
			// Is there a fullscreen WindowImpl object ?
			[NSApp sendEvent:event];
		} else {
			
			std::vector<sf::priv::WindowImplCocoa *>::size_type cnt = windows->size();
			std::vector<sf::priv::WindowImplCocoa *>::size_type idx;
			
			// is the key window a SFML window ?
			for (idx = 0;idx < cnt; idx++) {
				sf::priv::WindowImplCocoa *ptr = windows->at(idx);;
				
				if (ptr->CocoaWindow() == keyWindow) {
					// yup, it is
					ptr->HandleEvent(static_cast <void *> (event));
					break;
				}
			}
			
			// nop, it isn't
			if (idx == cnt) {
				[NSApp sendEvent:event];
			}
		}
	}
}


////////////////////////////////////////////////////////////
/// Add the 'windowImplObj' object to the list of known windows
////////////////////////////////////////////////////////////
- (void)registerWindow:(sf::priv::WindowImplCocoa *)windowImplObj
{
	
	if (windowImplObj != NULL) {
		std::vector<sf::priv::WindowImplCocoa *>::size_type sz = windows->size();
		std::vector<sf::priv::WindowImplCocoa *>::size_type idx;
		
		for (idx = 0; idx < sz; idx++) {
			if (windows->at(idx) == windowImplObj) {
				break;
			}
		}
		
		
		// Register window only if not already registered
		if (sz == idx) {
			windows->push_back(windowImplObj);
		}
	}
}


////////////////////////////////////////////////////////////
/// Remove the 'windowImplObj' object from the list of known windows
////////////////////////////////////////////////////////////
- (void)unregisterWindow:(sf::priv::WindowImplCocoa *)windowImplObj
{
	if (windowImplObj != NULL) {
		std::vector<sf::priv::WindowImplCocoa *>::size_type sz = windows->size();
		std::vector<sf::priv::WindowImplCocoa *>::size_type idx;
		
		for (idx = 0; idx < sz; idx++) {
			if (windows->at(idx) == windowImplObj) {
				break;
			}
		}
		
		if (idx < sz) {
			windows->erase(windows->begin() + idx);
		}
	}
}


////////////////////////////////////////////////////////////
/// Return true is one of the registered window is a full screen one
////////////////////////////////////////////////////////////
- (bool)isUsingFullscreen
{
	bool isUsing = false;
	std::vector<sf::priv::WindowImplCocoa *>::size_type sz = windows->size();
	std::vector<sf::priv::WindowImplCocoa *>::size_type idx;
	
	for (idx = 0; idx < sz; idx++) {
		sf::priv::WindowImplCocoa *win = windows->at(idx);
		if (win && win->IsFullscreen()) {
			isUsing = true;
			break;
		}
	}
	
	return isUsing;
}


////////////////////////////////////////////////////////////
/// Perform fade operation where 'operation' is one of { FillScreen, CleanScreen}
/// and 'time' is the time during which you wish the operation to be performed.
/// Set 'sync' to true if you do not want the method to end before the end
/// of the fade operation. Pass the last used token or a new one if you are
/// using this method for the first time. This lets the method release some
/// resources when doing CleanScreen operation.
////////////////////////////////////////////////////////////
- (void) doFadeOperation:(int)operation time:(float)time sync:(bool)sync token:(CGDisplayFadeReservationToken *)prevToken
{
	CGDisplayFadeReservationToken token = kCGDisplayFadeReservationInvalidToken;
	if (prevToken)
		token = *prevToken;
	
	CGError result = 0, capture = 0;
	
	if (operation == FillScreen) {
		// Get access for the fade operation
		result = CGAcquireDisplayFadeReservation((int)(3 + time), &token);
		
		if (!result) {
			// Capture display but do not fill the screen with black
			// so that we can see the fade operation
			capture = CGDisplayCaptureWithOptions(kCGDirectMainDisplay, kCGCaptureNoFill);
			
			if (!capture) {
				// Do the increasing fade operation
				CGDisplayFade(token, time,
							  kCGDisplayBlendNormal,
							  kCGDisplayBlendSolidColor,
							  0.0, 0.0, 0.0, sync);
				
				// Now, release the non black-filling capture
				CGDisplayRelease(kCGDirectMainDisplay);
				
				// And capture with filling
				// so that we don't see the switching in the meantime
				CGDisplayCaptureWithOptions(kCGDirectMainDisplay, kCGCaptureNoOptions);
			}
			
			if (prevToken)
				*prevToken = token;
		}
	} else if (operation == CleanScreen) {
		// Get access for the fade operation
		if (token == kCGDisplayFadeReservationInvalidToken)
			result = CGAcquireDisplayFadeReservation((int)(3 + time), &token);
		
		if (!result) {
			if (!capture) {
				// Release the black-filling capture
				CGDisplayRelease(kCGDirectMainDisplay);
				
				// Capture the display but do not fill with black (still for the fade operation)
				CGDisplayCaptureWithOptions(kCGDirectMainDisplay, kCGCaptureNoFill);
				
				// Do the decreasing fading
				CGDisplayFade(token, time,
							  kCGDisplayBlendSolidColor,
							  kCGDisplayBlendNormal,
							  0.0, 0.0, 0.0, sync);
				
				// Release the fade operation token
				CGReleaseDisplayFadeReservation(token);
				
				// Invalidate the given token
				if (prevToken)
					*prevToken = kCGDisplayFadeReservationInvalidToken;
			}
			
			// Release the captured display
			CGDisplayRelease(kCGDirectMainDisplay);
		}
	}
}

@end


template <typename T>
T *massert(T *ptr)
{
	if (NULL == ptr) {
		throw std::bad_alloc();
	}
	
	return ptr;
}