Debian Codegraph @

src/macosx/osxgl.m

raw
1 /* ______ ___ ___
2 * /\ _ \ /\_ \ /\_ \
3 * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
4 * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
5 * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
6 * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
7 * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
8 * /\____/
9 * \_/__/
10 *
11 * MacOS X OpenGL gfx driver
12 *
13 * By Peter Hull.
14 *
15 * See readme.txt for copyright information.
16 */
17
18
19 #include "allegro5/allegro.h"
20 #include "allegro5/allegro_opengl.h"
21 #include "allegro5/internal/aintern.h"
22 #include "allegro5/internal/aintern_bitmap.h"
23 #include "allegro5/internal/aintern_system.h"
24 #include "allegro5/internal/aintern_keyboard.h"
25 #include "allegro5/internal/aintern_opengl.h"
26 #include "allegro5/internal/aintern_osxclipboard.h"
27 #include "allegro5/platform/aintosx.h"
28 #include "./osxgl.h"
29 #include "allegro5/allegro_osx.h"
30 #ifndef ALLEGRO_MACOSX
31 #error something is wrong with the makefile
32 #endif
33
34 #import <Cocoa/Cocoa.h>
35 #import <OpenGL/OpenGL.h>
36
37 ALLEGRO_DEBUG_CHANNEL("MacOSX")
38
39 /* Many Cocoa methods can only be called from the main thread, but Allegro runs the
40 user's code on a separate thread or threads. It relies on `dispatch_sync` or
41 `[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]` to make sure the
42 operation happens on the main thread. Comments on functions in this file indicate their
43 thread requirements, if any.
44 #define EXTRA_THREAD_CHECKS to catch any issues during development (don't leave it defined though.) */
45 #undef EXTRA_THREAD_CHECKS
46 #ifdef EXTRA_THREAD_CHECKS
47 #define ASSERT_MAIN_THREAD() NSCAssert([NSThread isMainThread], @"Must be run on main thread")
48 #define ASSERT_USER_THREAD() NSCAssert(![NSThread isMainThread], @"Must be run on user thread")
49 #else
50 #define ASSERT_MAIN_THREAD()
51 #define ASSERT_USER_THREAD()
52 #endif
53
54 /* This constant isn't available on OS X < 10.7, define
55 * it here so the library can be built on < 10.7 (10.6
56 * tested so far.)
57 */
58 #if (MAC_OS_X_VERSION_MAX_ALLOWED < 1070 && !defined(NSWindowCollectionBehaviorFullScreenPrimary))
59 enum {
60 NSWindowCollectionBehaviorFullScreenPrimary = (1 << 7)
61 };
62 #endif
63
64 /* Defines */
65 #define MINIMUM_WIDTH 48
66 #define MINIMUM_HEIGHT 48
67
68 /* Unsigned integer; data type only avaliable for OS X >= 10.5 */
69 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
70 typedef unsigned int NSUInteger;
71 #endif
72
73 /* Module Variables */
74 static BOOL _osx_mouse_installed = NO, _osx_keyboard_installed = NO;
75 static NSPoint last_window_pos;
76 static unsigned int next_display_group = 1;
77
78 /* The parameters are passed to initialiseDisplay manually, as it runs
79 * in a separate thread which renders TLS values incorrect.
80 */
81 typedef struct OSX_DISPLAY_PARAMS {
82 ALLEGRO_DISPLAY_OSX_WIN* dpy;
83 int new_window_pos_x;
84 int new_window_pos_y;
85 int new_display_adapter;
86 /* A copy of the new window title. */
87 char* new_window_title;
88 } _OSX_DISPLAY_PARAMS;
89
90 /* Dictionary to map Allegro's DISPLAY_OPTIONS to OS X
91 * PixelFormatAttributes.
92 * The first column is Allegro's name, the second column is the OS X
93 * PixelFormatAttribute (or 0), the third column indicates whether we
94 * need an extra parameter or not (eg, colour depth).
95 */
96 static const unsigned int allegro_to_osx_settings[][3] = {
97 { ALLEGRO_RED_SIZE, 0, 0}, // Not supported per component
98 { ALLEGRO_GREEN_SIZE, 0, 0}, // Not supported per component
99 { ALLEGRO_BLUE_SIZE, 0, 0}, // Not supported per component
100 { ALLEGRO_ALPHA_SIZE, NSOpenGLPFAAlphaSize, 1},
101 { ALLEGRO_RED_SHIFT, 0, 0}, // Not available
102 { ALLEGRO_GREEN_SHIFT, 0, 0}, // Not available
103 { ALLEGRO_BLUE_SHIFT, 0, 0}, // Not available
104 { ALLEGRO_ALPHA_SHIFT, 0, 0}, // Not available
105 { ALLEGRO_ACC_RED_SIZE, NSOpenGLPFAAccumSize, 1}, // Correct?
106 { ALLEGRO_ACC_GREEN_SIZE, NSOpenGLPFAAccumSize, 1}, // Correct?
107 { ALLEGRO_ACC_BLUE_SIZE, NSOpenGLPFAAccumSize, 1}, // Correct?
108 { ALLEGRO_ACC_ALPHA_SIZE, NSOpenGLPFAAccumSize, 1}, // Correct?
109 { ALLEGRO_STEREO, NSOpenGLPFAStereo, 0},
110 { ALLEGRO_AUX_BUFFERS, NSOpenGLPFAAuxBuffers, 1},
111 { ALLEGRO_COLOR_SIZE, NSOpenGLPFAColorSize, 1},
112 { ALLEGRO_DEPTH_SIZE, NSOpenGLPFADepthSize, 1},
113 { ALLEGRO_STENCIL_SIZE, NSOpenGLPFAStencilSize, 1},
114 { ALLEGRO_SAMPLE_BUFFERS, NSOpenGLPFASampleBuffers, 1},
115 { ALLEGRO_SAMPLES, NSOpenGLPFASamples, 1},
116 //{ ALLEGRO_RENDER_METHOD, NSOpenGLPFAAccelerated, 0}, handled separately
117 { ALLEGRO_FLOAT_COLOR, NSOpenGLPFAColorFloat, 0},
118 { ALLEGRO_FLOAT_DEPTH, 0, 0},
119 //{ ALLEGRO_SINGLE_BUFFER , 0, 0}, handled separately
120 { ALLEGRO_SWAP_METHOD, 0, 0},
121 { ALLEGRO_COMPATIBLE_DISPLAY, 0, 0},
122 { ALLEGRO_DISPLAY_OPTIONS_COUNT, 0, 0}
123 };
124 static const int number_of_settings =
125 sizeof(allegro_to_osx_settings)/sizeof(*allegro_to_osx_settings);
126
127 static const char *allegro_pixel_format_names[] = {
128 "ALLEGRO_RED_SIZE",
129 "ALLEGRO_GREEN_SIZE",
130 "ALLEGRO_BLUE_SIZE",
131 "ALLEGRO_ALPHA_SIZE",
132 "ALLEGRO_RED_SHIFT",
133 "ALLEGRO_GREEN_SHIFT",
134 "ALLEGRO_BLUE_SHIFT",
135 "ALLEGRO_ALPHA_SHIFT",
136 "ALLEGRO_ACC_RED_SIZE",
137 "ALLEGRO_ACC_GREEN_SIZE",
138 "ALLEGRO_ACC_BLUE_SIZE",
139 "ALLEGRO_ACC_ALPHA_SIZE",
140 "ALLEGRO_STEREO",
141 "ALLEGRO_AUX_BUFFERS",
142 "ALLEGRO_COLOR_SIZE",
143 "ALLEGRO_DEPTH_SIZE",
144 "ALLEGRO_STENCIL_SIZE",
145 "ALLEGRO_SAMPLE_BUFFERS",
146 "ALLEGRO_SAMPLES",
147 "ALLEGRO_RENDER_METHOD",
148 "ALLEGRO_FLOAT_COLOR",
149 "ALLEGRO_FLOAT_DEPTH",
150 "ALLEGRO_SINGLE_BUFFER",
151 "ALLEGRO_SWAP_METHOD",
152 "ALLEGRO_COMPATIBLE_DISPLAY",
153 "ALLEGRO_DISPLAY_OPTIONS_COUNT"
154 };
155
156 /* Module functions */
157 ALLEGRO_DISPLAY_INTERFACE* _al_osx_get_display_driver(void);
158 ALLEGRO_DISPLAY_INTERFACE* _al_osx_get_display_driver_win(void);
159 ALLEGRO_DISPLAY_INTERFACE* _al_osx_get_display_driver_fs(void);
160 static NSOpenGLContext* osx_create_shareable_context(NSOpenGLPixelFormat* fmt, unsigned int* group);
161 static bool set_display_flag(ALLEGRO_DISPLAY *display, int flag, bool onoff);
162 static bool resize_display_win(ALLEGRO_DISPLAY *d, int w, int h);
163 static bool resize_display_win_main_thread(ALLEGRO_DISPLAY *d, int w, int h);
164
165 static void clear_to_black(NSOpenGLContext *context)
166 {
167 /* Clear and flush (for double buffering) */
168 glClearColor(0, 0, 0, 1);
169 glClear(GL_COLOR_BUFFER_BIT);
170 [context flushBuffer];
171 glClear(GL_COLOR_BUFFER_BIT);
172 }
173
174 static NSTrackingArea *create_tracking_area(NSView *view)
175 {
176 NSTrackingAreaOptions options =
177 NSTrackingMouseEnteredAndExited |
178 NSTrackingMouseMoved |
179 NSTrackingCursorUpdate |
180 NSTrackingActiveAlways;
181 return [[NSTrackingArea alloc] initWithRect:[view bounds] options:options owner:view userInfo:nil];
182 }
183
184 /* _al_osx_change_cursor:
185 * Actually change the current cursor. This can be called fom any thread
186 * but ensures that the change is only called from the main thread.
187 */
188 static void _al_osx_change_cursor(ALLEGRO_DISPLAY_OSX_WIN *dpy, NSCursor* cursor)
189 {
190 NSCursor* old = dpy->cursor;
191 dpy->cursor = [cursor retain];
192 [old release];
193 if (dpy->show_cursor)
194 [cursor performSelectorOnMainThread: @selector(set) withObject: nil waitUntilDone: NO];
195 }
196
197 /* _al_osx_keyboard_was_installed:
198 * Called by the keyboard driver when the driver is installed or uninstalled.
199 * Set the variable so we can decide to pass events or not.
200 */
201 void _al_osx_keyboard_was_installed(BOOL install) {
202 _osx_keyboard_installed = install;
203 }
204
205 /* The main additions to this view are event-handling functions */
206 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
207 @interface ALOpenGLView : NSOpenGLView <NSWindowDelegate>
208 #else
209 @interface ALOpenGLView : NSOpenGLView
210 #endif
211 {
212 /* This is passed onto the event functions so we know where the event came from */
213 ALLEGRO_DISPLAY* dpy_ptr;
214 }
215 -(void)setAllegroDisplay: (ALLEGRO_DISPLAY*) ptr;
216 -(ALLEGRO_DISPLAY*) allegroDisplay;
217 -(void) reshape;
218 -(BOOL) acceptsFirstResponder;
219 -(void) keyDown:(NSEvent*) event;
220 -(void) keyUp:(NSEvent*) event;
221 -(void) flagsChanged:(NSEvent*) event;
222 -(void) mouseDown: (NSEvent*) evt;
223 -(void) mouseUp: (NSEvent*) evt;
224 -(void) mouseDragged: (NSEvent*) evt;
225 -(void) rightMouseDown: (NSEvent*) evt;
226 -(void) rightMouseUp: (NSEvent*) evt;
227 -(void) rightMouseDragged: (NSEvent*) evt;
228 -(void) otherMouseDown: (NSEvent*) evt;
229 -(void) otherMouseUp: (NSEvent*) evt;
230 -(void) otherMouseDragged: (NSEvent*) evt;
231 -(void) mouseMoved: (NSEvent*) evt;
232 -(void) cursorUpdate: (NSEvent*) evt;
233 -(void) scrollWheel: (NSEvent*) evt;
234 -(void) viewDidMoveToWindow;
235 -(void) viewWillMoveToWindow: (NSWindow*) newWindow;
236 -(void) mouseEntered: (NSEvent*) evt;
237 -(void) mouseExited: (NSEvent*) evt;
238 -(void) viewWillStartLiveResize;
239 -(void) viewDidEndLiveResize;
240 /* Window delegate methods */
241 -(void) windowDidBecomeMain:(NSNotification*) notification;
242 -(void) windowDidResignMain:(NSNotification*) notification;
243 -(void) windowDidResize:(NSNotification*) notification;
244 -(void) enterFullScreenWindowMode;
245 -(void) exitFullScreenWindowMode;
246 -(void) finishExitingFullScreenWindowMode;
247 -(void) maximize;
248 -(NSRect) windowWillUseStandardFrame:
249 (NSWindow *) window
250 defaultFrame: (NSRect) newFrame;
251 @end
252
253 @implementation ALWindow
254 @synthesize display;
255
256 -(BOOL) canBecomeKeyWindow
257 {
258 return YES;
259 }
260 // main thread only
261 -(void) zoom:(id)sender
262 {
263 self.display->flags ^= ALLEGRO_MAXIMIZED;
264 [super zoom:sender];
265 }
266
267 @end
268
269 /* _al_osx_mouse_was_installed:
270 * Called by the mouse driver when the driver is installed or uninstalled.
271 * Set the variable so we can decide to pass events or not, and notify all
272 * existing displays that they need to set up their tracking areas.
273 * User thread only
274 */
275 void _al_osx_mouse_was_installed(BOOL install) {
276 ASSERT_USER_THREAD();
277 if (_osx_mouse_installed == install) {
278 // done it already
279 return;
280 }
281 _osx_mouse_installed = install;
282 _AL_VECTOR* dpys = &al_get_system_driver()->displays;
283 dispatch_sync(dispatch_get_main_queue(), ^{
284 unsigned int i;
285 for (i = 0; i < _al_vector_size(dpys); ++i) {
286 ALLEGRO_DISPLAY_OSX_WIN* dpy = *(ALLEGRO_DISPLAY_OSX_WIN**) _al_vector_ref(dpys, i);
287 NSWindow* window = dpy->win;
288 if (window) {
289 [window setAcceptsMouseMovedEvents: _osx_mouse_installed];
290 }
291 }
292 });
293 }
294
295 @implementation ALOpenGLView
296
297 -(void) prepareOpenGL
298 {
299 [super prepareOpenGL];
300 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
301 if ([self respondsToSelector:@selector(setWantsBestResolutionOpenGLSurface:)]) {
302 [self setWantsBestResolutionOpenGLSurface:YES];
303 }
304 #endif
305 }
306
307 /* setDisplay:
308 * Set the display this view is associated with
309 */
310 -(void) setAllegroDisplay: (ALLEGRO_DISPLAY*) ptr
311 {
312 dpy_ptr = ptr;
313 }
314
315 /* display
316 * return the display this view is associated with
317 */
318 -(ALLEGRO_DISPLAY*) allegroDisplay
319 {
320 return dpy_ptr;
321 }
322
323 /* reshape
324 * Called when the view changes size */
325 - (void) reshape
326 {
327 [super reshape];
328
329 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
330 if (dpy->tracking) {
331 [self removeTrackingArea: dpy->tracking];
332 dpy->tracking = create_tracking_area(self);
333 [self addTrackingArea: dpy->tracking];
334 }
335 }
336
337 /* acceptsFirstResponder
338 * Overridden to return YES, so that
339 * this view will receive events
340 */
341 -(BOOL) acceptsFirstResponder
342 {
343 return YES;
344 }
345
346 /* Keyboard event handler */
347 -(void) keyDown:(NSEvent*) event
348 {
349 if (_osx_keyboard_installed)
350 _al_osx_keyboard_handler(true, event, dpy_ptr);
351 }
352
353 -(void) keyUp:(NSEvent*) event
354 {
355 if (_osx_keyboard_installed)
356 _al_osx_keyboard_handler(false, event, dpy_ptr);
357 }
358
359 -(void) flagsChanged:(NSEvent*) event
360 {
361 if (_osx_keyboard_installed) {
362 _al_osx_keyboard_modifiers([event modifierFlags], dpy_ptr);
363 }
364 }
365
366 /* Mouse handling
367 */
368 -(void) mouseDown: (NSEvent*) evt
369 {
370 if (_osx_mouse_installed)
371 _al_osx_mouse_generate_event(evt, dpy_ptr);
372 }
373 -(void) mouseUp: (NSEvent*) evt
374 {
375 if (_osx_mouse_installed)
376 _al_osx_mouse_generate_event(evt, dpy_ptr);
377 }
378 -(void) mouseDragged: (NSEvent*) evt
379 {
380 if (_osx_mouse_installed)
381 _al_osx_mouse_generate_event(evt, dpy_ptr);
382 }
383 -(void) rightMouseDown: (NSEvent*) evt
384 {
385 if (_osx_mouse_installed)
386 _al_osx_mouse_generate_event(evt, dpy_ptr);
387 }
388 -(void) rightMouseUp: (NSEvent*) evt
389 {
390 if (_osx_mouse_installed)
391 _al_osx_mouse_generate_event(evt, dpy_ptr);
392 }
393 -(void) rightMouseDragged: (NSEvent*) evt
394 {
395 if (_osx_mouse_installed)
396 _al_osx_mouse_generate_event(evt, dpy_ptr);
397 }
398 -(void) otherMouseDown: (NSEvent*) evt
399 {
400 if (_osx_mouse_installed)
401 _al_osx_mouse_generate_event(evt, dpy_ptr);
402 }
403 -(void) otherMouseUp: (NSEvent*) evt
404 {
405 if (_osx_mouse_installed)
406 _al_osx_mouse_generate_event(evt, dpy_ptr);
407 }
408 -(void) otherMouseDragged: (NSEvent*) evt
409 {
410 if (_osx_mouse_installed)
411 _al_osx_mouse_generate_event(evt, dpy_ptr);
412 }
413 -(void) mouseMoved: (NSEvent*) evt
414 {
415 if (_osx_mouse_installed)
416 _al_osx_mouse_generate_event(evt, dpy_ptr);
417 }
418 -(void) cursorUpdate: (NSEvent*) evt
419 {
420 if (_osx_mouse_installed) {
421 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
422 _al_osx_change_cursor(dpy, dpy->cursor);
423 }
424 }
425 -(void) scrollWheel: (NSEvent*) evt
426 {
427 if (_osx_mouse_installed)
428 _al_osx_mouse_generate_event(evt, dpy_ptr);
429 }
430 /* Cursor handling */
431 - (void) viewDidMoveToWindow {
432 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
433 if (dpy->tracking) {
434 [self removeTrackingArea: dpy->tracking];
435 }
436 dpy->tracking = create_tracking_area(self);
437 [self addTrackingArea: dpy->tracking];
438 }
439
440 - (void) viewWillMoveToWindow: (NSWindow*) newWindow {
441 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
442 (void)newWindow;
443 if (([self window] != nil) && (dpy->tracking != 0)) {
444 [self removeTrackingArea:dpy->tracking];
445 dpy->tracking = 0;
446 }
447 }
448
449 -(void) mouseEntered: (NSEvent*) evt
450 {
451 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
452 ALLEGRO_EVENT_SOURCE* src = &([self allegroDisplay]->es);
453 if (dpy->show_cursor) {
454 [dpy->cursor set];
455 }
456 else {
457 [NSCursor hide];
458 }
459 _al_event_source_lock(src);
460 _al_osx_switch_mouse_focus(dpy_ptr, true);
461 _al_event_source_unlock(src);
462 _al_osx_mouse_generate_event(evt, dpy_ptr);
463 }
464 -(void) mouseExited: (NSEvent*) evt
465 {
466 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
467 ALLEGRO_EVENT_SOURCE* src = &([self allegroDisplay]->es);
468 if (!dpy->show_cursor) {
469 [NSCursor unhide];
470 }
471 _al_event_source_lock(src);
472 _al_osx_switch_mouse_focus(dpy_ptr, false);
473 _al_event_source_unlock(src);
474 _al_osx_mouse_generate_event(evt, dpy_ptr);
475 }
476
477 /* windowShouldClose:
478 * Veto the close and post a message
479 */
480 - (BOOL)windowShouldClose:(id)sender
481 {
482 (void)sender;
483 ALLEGRO_EVENT_SOURCE* src = &([self allegroDisplay]->es);
484 _al_event_source_lock(src);
485 ALLEGRO_EVENT evt;
486 evt.type = ALLEGRO_EVENT_DISPLAY_CLOSE;
487 _al_event_source_emit_event(src, &evt);
488 _al_event_source_unlock(src);
489 return NO;
490 }
491
492 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1074
493 -(void) viewDidChangeBackingProperties
494 {
495 [super viewDidChangeBackingProperties];
496 if (!(al_get_display_flags(dpy_ptr) & ALLEGRO_RESIZABLE) &&
497 dpy_ptr->ogl_extras) {
498 resize_display_win_main_thread(dpy_ptr, al_get_display_width(dpy_ptr), al_get_display_height(dpy_ptr));
499 }
500 else {
501 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
502 NSWindow *window = dpy->win;
503 NSRect rc = [window frame];
504 NSRect content = [window contentRectForFrameRect: rc];
505 content = [self convertRectToBacking: content];
506 ALLEGRO_EVENT_SOURCE *es = &dpy->parent.es;
507
508 _al_event_source_lock(es);
509 if (_al_event_source_needs_to_generate_event(es)) {
510 ALLEGRO_EVENT event;
511 event.display.type = ALLEGRO_EVENT_DISPLAY_RESIZE;
512 event.display.timestamp = al_get_time();
513 event.display.width = NSWidth(content);
514 event.display.height = NSHeight(content);
515 _al_event_source_emit_event(es, &event);
516 ALLEGRO_INFO("Window finished resizing %d x %d\n", event.display.width, event.display.height);
517 }
518 _al_event_source_unlock(es);
519 }
520 }
521 #endif
522
523 -(void) viewWillStartLiveResize
524 {
525 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
526 ALLEGRO_EVENT_SOURCE *es = &dpy->parent.es;
527
528 if (dpy->send_halt_events) {
529 al_lock_mutex(dpy->halt_mutex);
530 dpy->halt_event_acknowledged = false;
531 al_unlock_mutex(dpy->halt_mutex);
532
533 _al_event_source_lock(es);
534 if (_al_event_source_needs_to_generate_event(es)) {
535 ALLEGRO_EVENT event;
536 event.display.type = ALLEGRO_EVENT_DISPLAY_HALT_DRAWING;
537 event.display.timestamp = al_get_time();
538 _al_event_source_emit_event(es, &event);
539 }
540 _al_event_source_unlock(es);
541
542 al_lock_mutex(dpy->halt_mutex);
543 while (!dpy->halt_event_acknowledged) {
544 al_wait_cond(dpy->halt_cond, dpy->halt_mutex);
545 }
546 al_unlock_mutex(dpy->halt_mutex);
547 }
548 }
549
550 -(void) viewDidEndLiveResize
551 {
552 [super viewDidEndLiveResize];
553
554 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
555 NSWindow *window = dpy->win;
556 NSRect rc = [window frame];
557 NSRect content = [window contentRectForFrameRect: rc];
558 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
559 content = [self convertRectToBacking: content];
560 #endif
561 ALLEGRO_EVENT_SOURCE *es = &dpy->parent.es;
562
563 _al_event_source_lock(es);
564 if (_al_event_source_needs_to_generate_event(es)) {
565 ALLEGRO_EVENT event;
566 event.display.type = ALLEGRO_EVENT_DISPLAY_RESIZE;
567 event.display.timestamp = al_get_time();
568 event.display.width = NSWidth(content);
569 event.display.height = NSHeight(content);
570 _al_event_source_emit_event(es, &event);
571 ALLEGRO_INFO("Window finished resizing %d x %d\n", event.display.width, event.display.height);
572
573 if (dpy->send_halt_events) {
574 event.display.type = ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING;
575 _al_event_source_emit_event(es, &event);
576 }
577 }
578 _al_event_source_unlock(es);
579 dpy->old_w = NSWidth(content);
580 dpy->old_h = NSWidth(content);
581 }
582 /* Window switch in/out */
583 -(void) windowDidBecomeMain:(NSNotification*) notification
584 {
585 (void)notification;
586 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
587 ALLEGRO_EVENT_SOURCE* src = &([self allegroDisplay]->es);
588 _al_event_source_lock(src);
589 ALLEGRO_EVENT evt;
590 evt.type = ALLEGRO_EVENT_DISPLAY_SWITCH_IN;
591 _al_event_source_emit_event(src, &evt);
592 _al_osx_switch_keyboard_focus(dpy_ptr, true);
593 _al_event_source_unlock(src);
594 _al_osx_change_cursor(dpy, dpy->cursor);
595 }
596 -(void) windowDidResignMain:(NSNotification*) notification
597 {
598 (void)notification;
599 ALLEGRO_EVENT_SOURCE* src = &([self allegroDisplay]->es);
600 _al_event_source_lock(src);
601 ALLEGRO_EVENT evt;
602 evt.type = ALLEGRO_EVENT_DISPLAY_SWITCH_OUT;
603 _al_event_source_emit_event(src, &evt);
604 _al_osx_switch_keyboard_focus(dpy_ptr, false);
605 _al_event_source_unlock(src);
606 }
607 -(void) windowDidResize:(NSNotification*) notification
608 {
609 (void)notification;
610 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
611 NSWindow *window = dpy->win;
612 NSRect rc = [window frame];
613 NSRect content = [window contentRectForFrameRect: rc];
614 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
615 content = [self convertRectToBacking: content];
616 #endif
617 ALLEGRO_EVENT_SOURCE *es = &dpy->parent.es;
618
619 /* Restore max. constraints when the window has been un-maximized.
620 * Note: isZoomed will return false in FullScreen mode.
621 */
622 if (dpy_ptr->use_constraints &&
623 !(dpy_ptr->flags & ALLEGRO_FULLSCREEN_WINDOW) && ![window isZoomed])
624 {
625 float scale_factor = 1.0;
626 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
627 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
628 scale_factor = [window backingScaleFactor];
629 }
630 #endif
631 NSSize max_size;
632 max_size.width = (dpy_ptr->max_w > 0) ? dpy_ptr->max_w / scale_factor : FLT_MAX;
633 max_size.height = (dpy_ptr->max_h > 0) ? dpy_ptr->max_h / scale_factor : FLT_MAX;
634 [window setContentMaxSize: max_size];
635 }
636
637 _al_event_source_lock(es);
638 if (_al_event_source_needs_to_generate_event(es)) {
639 ALLEGRO_EVENT event;
640 event.display.type = ALLEGRO_EVENT_DISPLAY_RESIZE;
641 event.display.timestamp = al_get_time();
642 event.display.width = NSWidth(content);
643 event.display.height = NSHeight(content);
644 _al_event_source_emit_event(es, &event);
645 ALLEGRO_INFO("Window was resized %d x %d\n", event.display.width, event.display.height);
646 }
647 _al_event_source_unlock(es);
648 }
649
650 -(void)windowWillEnterFullScreen:(NSNotification *)notification
651 {
652 (void)notification;
653 ALLEGRO_DISPLAY *display = dpy_ptr;
654 display->flags |= ALLEGRO_FULLSCREEN_WINDOW;
655 }
656
657 -(void)windowWillExitFullScreen:(NSNotification *)notification
658 {
659 (void)notification;
660 ALLEGRO_DISPLAY *display = dpy_ptr;
661 display->flags &= ~ALLEGRO_FULLSCREEN_WINDOW;
662 }
663
664 -(void) enterFullScreenWindowMode
665 {
666 #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
667 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
668 NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
669 int flags = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
670 [dict setObject:[NSNumber numberWithInt: flags] forKey:NSFullScreenModeApplicationPresentationOptions];
671 /* HACK? For some reason, we need to disable the chrome. If we don't, the fullscreen window
672 will be created with space left over for it. Are we creating a fullscreen window in the wrong way? */
673 [dpy->win setStyleMask: [dpy->win styleMask] & ~NSWindowStyleMaskTitled];
674 [dpy->view enterFullScreenMode: [dpy->win screen] withOptions: dict];
675 [dict release];
676 #endif
677 }
678
679 /* Toggles maximize state. In OSX 10.10 this is the same as double clicking the title bar. */
680 -(void) maximize
681 {
682 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
683 [dpy->win performZoom: nil];
684 }
685
686 /* Called by NSWindow's zoom: method while determining the frame
687 * a window may be zoomed to.
688 * We use it to update max. constraints values when the window changes
689 * its maximized state.
690 */
691 -(NSRect) windowWillUseStandardFrame:
692 (NSWindow *) window
693 defaultFrame: (NSRect) newFrame
694 {
695 NSSize max_size;
696
697 if (dpy_ptr->use_constraints) {
698 if (dpy_ptr->flags & ALLEGRO_MAXIMIZED) {
699 max_size.width = FLT_MAX;
700 max_size.height = FLT_MAX;
701 newFrame.size.width = max_size.width;
702 newFrame.size.height = max_size.height;
703 }
704 else {
705 float scale_factor = 1.0;
706 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
707 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
708 scale_factor = [window backingScaleFactor];
709 }
710 #endif
711 max_size.width = (dpy_ptr->max_w > 0) ? dpy_ptr->max_w / scale_factor : FLT_MAX;
712 max_size.height = (dpy_ptr->max_h > 0) ? dpy_ptr->max_h / scale_factor : FLT_MAX;
713 }
714
715 [window setContentMaxSize: max_size];
716 }
717
718 return newFrame;
719 }
720
721 -(void) exitFullScreenWindowMode
722 {
723 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
724
725 /* Going from a fullscreen window to a smaller window, the mouse may end up outside
726 * the window when it was inside before (not possible the other way.) This causes a
727 * crash. To avoid it, remove the tracking area and add it back after exiting fullscreen.
728 * (my theory)
729 */
730 [dpy->win orderOut: dpy->view];
731 [self exitFullScreenModeWithOptions: nil];
732 /* Restore the title bar disabled in enterFullScreenWindowMode. */
733 if (!(dpy_ptr->flags & ALLEGRO_FRAMELESS)) {
734 [dpy->win setStyleMask: [dpy->win styleMask] | NSWindowStyleMaskTitled];
735 }
736 }
737
738 -(void) finishExitingFullScreenWindowMode
739 {
740 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy_ptr;
741
742 [dpy->win center];
743 [dpy->win makeKeyAndOrderFront: dpy->view];
744 [[self window] makeFirstResponder: self];
745 }
746
747 /* End of ALOpenGLView implementation */
748 @end
749
750 /* set_current_display:
751 * Set the current windowed display to be current.
752 */
753 static bool set_current_display(ALLEGRO_DISPLAY* d) {
754 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) d;
755 if (dpy->ctx != nil) {
756 [dpy->ctx makeCurrentContext];
757 }
758 _al_ogl_set_extensions(d->ogl_extras->extension_api);
759 return true;
760 }
761
762 /* Helper to set up GL state as we want it. */
763 static void setup_gl(ALLEGRO_DISPLAY *d)
764 {
765 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) d;
766 [dpy->ctx performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:YES];
767 _al_ogl_setup_gl(d);
768 }
769
770
771 /* Fills the array of NSOpenGLPixelFormatAttributes, which has a specfied
772 * maximum size, with the options appropriate for the display.
773 */
774 static void osx_set_opengl_pixelformat_attributes(ALLEGRO_DISPLAY_OSX_WIN *dpy)
775 {
776 int i, n;
777 bool want_double_buffer;
778 NSOpenGLPixelFormatAttribute *a;
779 ALLEGRO_EXTRA_DISPLAY_SETTINGS *extras;
780 /* The following combination of flags indicates that multi-sampling is
781 * requested.
782 */
783 const int sample_flags = (1<<ALLEGRO_SAMPLES)|(1<<ALLEGRO_SAMPLE_BUFFERS);
784
785 /* Get extra display settings */
786 extras = _al_get_new_display_settings();
787
788 /* Begin by setting all elements in the array to 0 */
789 memset(dpy->attributes, 0, AL_OSX_NUM_PFA*sizeof(*dpy->attributes));
790
791 /* We normally want a double buffer */
792 want_double_buffer = true;
793
794 /* Begin with the first attribute */
795 a = dpy->attributes;
796
797 /* First, check the display flags, so we know if we want a fullscreen
798 * mode or a windowed mode.
799 */
800 if (dpy->parent.flags & ALLEGRO_FULLSCREEN) {
801 *a = NSOpenGLPFAFullScreen; a++;
802 // Take over the screen.
803 *a = NSOpenGLPFAScreenMask; a++;
804 *a = CGDisplayIDToOpenGLDisplayMask(dpy->display_id); a++;
805 }
806
807 /* Find the requested colour depth */
808 if (extras)
809 dpy->depth = extras->settings[ALLEGRO_COLOR_SIZE];
810 if (!dpy->depth) { /* Use default */
811 NSScreen *screen;
812 int adapter = al_get_new_display_adapter();
813 if ((adapter >= 0) && (adapter < al_get_num_video_adapters())) {
814 screen = [[NSScreen screens] objectAtIndex: adapter];
815 } else {
816 screen = [NSScreen mainScreen];
817 }
818 dpy->depth = NSBitsPerPixelFromDepth([screen depth]);
819 if (dpy->depth == 24)
820 dpy->depth = 32;
821 if (dpy->depth == 15)
822 dpy->depth = 16;
823 ALLEGRO_DEBUG("Using default colour depth %d\n", dpy->depth);
824 }
825 *a = NSOpenGLPFAColorSize; a++;
826 *a = dpy->depth; a++;
827
828 /* Say we don't need an exact match for the depth of the colour buffer.
829 * FIXME: right now, this is set whenever nothing is required or
830 * something is suggested. Probably need finer control over this...
831 */
832 if (!extras || !(extras->required) || extras->suggested) {
833 *a = NSOpenGLPFAClosestPolicy; a++;
834 }
835
836 /* Should we set double buffering? If it's not required we don't care
837 * and go with the default.
838 */
839 if (extras && (extras->required & (1 << ALLEGRO_SINGLE_BUFFER)) &&
840 extras->settings[ALLEGRO_SINGLE_BUFFER]) {
841 want_double_buffer = false;
842 dpy->single_buffer = true;
843 }
844 if (want_double_buffer) {
845 *a = NSOpenGLPFADoubleBuffer; a++;
846 }
847
848 /* Detect if multi-sampling is requested */
849 /* Or "NSOpenGLPFASupersample" ? */
850 if (extras && (extras->required & sample_flags) &&
851 (extras->settings[ALLEGRO_SAMPLES]||extras->settings[ALLEGRO_SAMPLE_BUFFERS])) {
852 *a = NSOpenGLPFAMultisample; a++;
853 }
854
855 /* Now go through all other options, if set */
856 for (n = 0; n < number_of_settings; n++) {
857 i = allegro_to_osx_settings[n][0];
858 if (allegro_to_osx_settings[n][1] && extras &&
859 ((extras->required & (1 << i)) || (extras->suggested & (1 << i)))) {
860 /* Need to distinguish between boolean attributes and settings that
861 * require a value.
862 */
863 if (allegro_to_osx_settings[n][2]) { /* Value */
864 /* We must make sure the value is non-zero because the list are
865 * building is 0-terminated.
866 */
867 if (extras->settings[i]) {
868 *a = allegro_to_osx_settings[n][1]; a++;
869 *a = extras->settings[i]; a++;
870 ALLEGRO_DEBUG("Passing pixel format attribute %s = %d\n", allegro_pixel_format_names[n], extras->settings[i]);
871 }
872 } else if (extras->settings[i]) { /* Boolean, just turn this on */
873 *a = allegro_to_osx_settings[n][1]; a++;
874 ALLEGRO_DEBUG("Passing pixel format attribute %s = %d\n", allegro_pixel_format_names[n], extras->settings[i]);
875 }
876 }
877 }
878
879 /* Accelerated is always preferred, so we only set this for required not
880 * for suggested.
881 */
882 if (extras->required & (1UL << ALLEGRO_RENDER_METHOD)) {
883 *a++ = NSOpenGLPFAAccelerated;
884 }
885 /*
886 * OpenGL 3+ support
887 * Newer versions of macos support modern OpenGL, but won't create a view
888 * that supports it unless explicitly requested to. Note that even though
889 * this looks like 3.2 core, it is really >= 3.2, and it is quite strict
890 * about removing support for legacy OpenGL features, and requires versioned
891 * shaders.
892 */
893 if (dpy->parent.flags & ALLEGRO_OPENGL_3_0) {
894 *a++ = NSOpenGLPFAOpenGLProfile;
895 *a++ = (NSOpenGLPixelFormatAttribute) NSOpenGLProfileVersion3_2Core;
896 }
897 }
898
899
900 /* Set the extra_settings[] array in the display, to report which options
901 * we have selected.
902 */
903 static void osx_get_opengl_pixelformat_attributes(ALLEGRO_DISPLAY_OSX_WIN *dpy)
904 {
905 int n;
906
907 if (!dpy)
908 return;
909
910 /* Clear list of settings (none selected) */
911 memset(&dpy->parent.extra_settings, 0, sizeof(dpy->parent.extra_settings));
912
913 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
914 /* Get the pixel format associated with the OpenGL context.
915 * We use the Carbon API rather than the Cocoa API because that way we
916 * can use the same code in Windowed mode as in fullscreen mode (we
917 * don't have an NSOpenGLView in fullscreen mode).
918 */
919 CGLContextObj ctx = [dpy->ctx CGLContextObj];
920 CGLPixelFormatObj pixel_format = CGLGetPixelFormat(ctx);
921 GLint screen_id;
922 CGLGetVirtualScreen(ctx, &screen_id);
923 ALLEGRO_DEBUG("Screen has ID %d\n", (int)screen_id);
924 for (n = 0; n < number_of_settings; n++) {
925 /* Go through the list of options and relist the ones that we have
926 * set to Allegro's option list.
927 */
928
929 CGLPixelFormatAttribute attrib = allegro_to_osx_settings[n][1];
930 /* Skip options that don't exist on OS X */
931 if (attrib == 0)
932 continue;
933
934 /* Get value for this attribute */
935 GLint value;
936 CGLDescribePixelFormat(pixel_format, screen_id, attrib, &value);
937
938 int al_setting = allegro_to_osx_settings[n][0];
939 if (allegro_to_osx_settings[n][2] == 0) /* Boolean attribute */
940 value = 1;
941
942 dpy->parent.extra_settings.settings[al_setting] = value;
943 ALLEGRO_DEBUG("Pixel format attribute %s set to %d\n", allegro_pixel_format_names[n], value);
944 }
945 #else
946 /* CGLGetPixelFormat does not exist on Tiger, so we need to do something
947 * else.
948 * FIXME: right now, we just return the settings that were chosen by the
949 * user. To be correct, we should query the pixelformat corresponding to
950 * the display, using the NSOpenGLView pixelFormat method and the
951 * NSOpenGLPixelFormat getValues:forAttribute:forVirtualScreen: method,
952 * for which we need to know the logical screen number that the display
953 * is on. That doesn't work for fullscreen modes though...
954 */
955 NSOpenGLPixelFormatAttribute *attributes = dpy->attributes;
956
957 for (n = 0; n < number_of_settings; n++) {
958 /* Go through the list of options and relist the ones that we have
959 * set to Allegro's option list.
960 */
961 NSOpenGLPixelFormatAttribute *a = dpy->attributes;
962 while (*a) {
963 if (*a == allegro_to_osx_settings[n][1]) {
964 int al_setting = allegro_to_osx_settings[n][0];
965 int value = 1;
966 if (allegro_to_osx_settings[n][2])
967 value = a[1];
968 dpy->parent.extra_settings.settings[al_setting] = value;
969 ALLEGRO_DEBUG("Setting pixel format attribute %d to %d\n", al_setting, value);
970 }
971 /* Advance to next option */
972 if (allegro_to_osx_settings[n][2]) /* Has a parameter in the list */
973 a++;
974 a++;
975 }
976 }
977 #endif
978 dpy->parent.extra_settings.settings[ALLEGRO_COMPATIBLE_DISPLAY] = 1;
979
980 // Fill in the missing colour format options, as best we can
981 ALLEGRO_EXTRA_DISPLAY_SETTINGS *eds = &dpy->parent.extra_settings;
982 if (eds->settings[ALLEGRO_COLOR_SIZE] == 0) {
983 eds->settings[ALLEGRO_COLOR_SIZE] = 32;
984 eds->settings[ALLEGRO_RED_SIZE] = 8;
985 eds->settings[ALLEGRO_GREEN_SIZE] = 8;
986 eds->settings[ALLEGRO_BLUE_SIZE] = 8;
987 eds->settings[ALLEGRO_ALPHA_SIZE] = 8;
988 eds->settings[ALLEGRO_RED_SHIFT] = 0;
989 eds->settings[ALLEGRO_GREEN_SHIFT] = 8;
990 eds->settings[ALLEGRO_BLUE_SHIFT] = 16;
991 eds->settings[ALLEGRO_ALPHA_SHIFT] = 24;
992 } else {
993 int size = eds->settings[ALLEGRO_ALPHA_SIZE];
994 if (!size) {
995 switch (eds->settings[ALLEGRO_COLOR_SIZE]) {
996 case 32:
997 size = 8;
998 break;
999
1000 case 16:
1001 size = 5;
1002 break;
1003
1004 case 8:
1005 size = 8;
1006 break;
1007 }
1008 }
1009 if (!eds->settings[ALLEGRO_RED_SIZE])
1010 eds->settings[ALLEGRO_RED_SIZE] = size;
1011 if (!eds->settings[ALLEGRO_BLUE_SIZE])
1012 eds->settings[ALLEGRO_BLUE_SIZE] = size;
1013 if (!eds->settings[ALLEGRO_GREEN_SIZE])
1014 eds->settings[ALLEGRO_GREEN_SIZE] = size;
1015 if (!eds->settings[ALLEGRO_RED_SHIFT])
1016 eds->settings[ALLEGRO_RED_SHIFT] = 0;
1017 if (!eds->settings[ALLEGRO_GREEN_SHIFT])
1018 eds->settings[ALLEGRO_GREEN_SHIFT] = eds->settings[ALLEGRO_RED_SIZE];
1019 if (!eds->settings[ALLEGRO_BLUE_SHIFT])
1020 eds->settings[ALLEGRO_BLUE_SHIFT] = eds->settings[ALLEGRO_GREEN_SIZE]+eds->settings[ALLEGRO_GREEN_SHIFT];
1021 if (!eds->settings[ALLEGRO_ALPHA_SHIFT])
1022 eds->settings[ALLEGRO_ALPHA_SHIFT] = eds->settings[ALLEGRO_BLUE_SIZE]+eds->settings[ALLEGRO_BLUE_SHIFT];
1023 }
1024 }
1025
1026 /* This function must be run on the main thread */
1027 static void osx_run_fullscreen_display(ALLEGRO_DISPLAY_OSX_WIN* dpy)
1028 {
1029 ASSERT_MAIN_THREAD();
1030 ALLEGRO_DISPLAY* display = &dpy->parent;
1031 while (dpy->in_fullscreen) {
1032 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
1033 // Collect an event
1034 NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
1035 untilDate:[NSDate distantFuture]
1036 inMode:NSDefaultRunLoopMode
1037 dequeue:YES];
1038 // Process it as required.
1039 switch ([event type]) {
1040 case NSEventTypeKeyDown:
1041 _al_osx_keyboard_handler(true,event,display);
1042 break;
1043 case NSEventTypeKeyUp:
1044 _al_osx_keyboard_handler(false,event,display);
1045 break;
1046 case NSEventTypeFlagsChanged:
1047 _al_osx_keyboard_modifiers([event modifierFlags],display);
1048 break;
1049 case NSEventTypeLeftMouseDown:
1050 case NSEventTypeLeftMouseUp:
1051 case NSEventTypeRightMouseDown:
1052 case NSEventTypeRightMouseUp:
1053 case NSEventTypeOtherMouseDown:
1054 case NSEventTypeOtherMouseUp:
1055 case NSEventTypeMouseMoved:
1056 case NSEventTypeLeftMouseDragged:
1057 case NSEventTypeRightMouseDragged:
1058 case NSEventTypeOtherMouseDragged:
1059 if (_osx_mouse_installed)
1060 _al_osx_mouse_generate_event(event, display);
1061 break;
1062 default:
1063 [NSApp sendEvent: event];
1064 break;
1065 }
1066 [pool release];
1067 }
1068 }
1069
1070 /* osx_create_shareable_context:
1071 *
1072 * Create an NSOpenGLContext with a given pixel format. If possible, make
1073 * the context compatible with one that has already been created and
1074 * assigned to a display. If this can't be done, create an unshared one
1075 * (which may itself be shared in the future)
1076 * Each context is given a group number so that all shared contexts have the
1077 * same group number.
1078 *
1079 * Parameters:
1080 * fmt - The pixel format to use
1081 * group - Pointer to the assigned group for the new context
1082 *
1083 * Returns:
1084 * The new context or nil if it cannot be created.
1085 */
1086 static NSOpenGLContext* osx_create_shareable_context(NSOpenGLPixelFormat* fmt, unsigned int* group)
1087 {
1088 // Iterate through all existing displays and try and find one that's compatible
1089 _AL_VECTOR* dpys = &al_get_system_driver()->displays;
1090 unsigned int i;
1091 NSOpenGLContext* compat = nil;
1092
1093 for (i = 0; i < _al_vector_size(dpys); ++i) {
1094 ALLEGRO_DISPLAY_OSX_WIN* other = *(ALLEGRO_DISPLAY_OSX_WIN**) _al_vector_ref(dpys, i);
1095 compat = [[NSOpenGLContext alloc] initWithFormat:fmt shareContext: other->ctx];
1096 if (compat != nil) {
1097 // OK, we can share with this one
1098 *group = other->display_group;
1099 ALLEGRO_DEBUG("Sharing display group %d\n", *group);
1100 break;
1101 }
1102 }
1103 if (compat == nil) {
1104 // Set to a new group
1105 *group = next_display_group++;
1106 ALLEGRO_DEBUG("Creating new display group %d\n", *group);
1107 compat = [[NSOpenGLContext alloc] initWithFormat:fmt shareContext: nil];
1108 }
1109 return compat;
1110 }
1111
1112 #ifndef NSAppKitVersionNumber10_7
1113 #define NSAppKitVersionNumber10_7 1138
1114 #endif
1115
1116 static CVReturn display_link_callback(CVDisplayLinkRef display_link,
1117 const CVTimeStamp *now,
1118 const CVTimeStamp *output_time,
1119 CVOptionFlags flags_in,
1120 CVOptionFlags *flags_out,
1121 void *user_info)
1122 {
1123 (void)display_link;
1124 (void)now;
1125 (void)output_time;
1126 (void)flags_in;
1127 (void)flags_out;
1128 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN*)user_info;
1129
1130 al_lock_mutex(dpy->flip_mutex);
1131 dpy->num_flips += 1;
1132 al_signal_cond(dpy->flip_cond);
1133 al_unlock_mutex(dpy->flip_mutex);
1134
1135 return kCVReturnSuccess;
1136 }
1137
1138 static void init_new_vsync(ALLEGRO_DISPLAY_OSX_WIN *dpy)
1139 {
1140 dpy->flip_cond = al_create_cond();
1141 dpy->flip_mutex = al_create_mutex();
1142 CVDisplayLinkCreateWithActiveCGDisplays(&dpy->display_link);
1143 CVDisplayLinkSetOutputCallback(dpy->display_link, &display_link_callback, dpy);
1144 CGLContextObj ctx = [dpy->ctx CGLContextObj];
1145 CGLPixelFormatObj pixel_format = CGLGetPixelFormat(ctx);
1146 CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(dpy->display_link, ctx, pixel_format);
1147 CVDisplayLinkStart(dpy->display_link);
1148 }
1149
1150 static void init_halt_events(ALLEGRO_DISPLAY_OSX_WIN *dpy)
1151 {
1152 const char* value = al_get_config_value(al_get_system_config(), "osx", "allow_live_resize");
1153 if (value && strcmp(value, "false") == 0) {
1154 dpy->send_halt_events = true;
1155 }
1156 else {
1157 dpy->send_halt_events = false;
1158 }
1159 dpy->halt_mutex = al_create_mutex();
1160 dpy->halt_cond = al_create_cond();
1161 }
1162
1163 /* create_display_fs:
1164 * Create a fullscreen display - capture the display
1165 */
1166 static ALLEGRO_DISPLAY* create_display_fs(int w, int h)
1167 {
1168 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1169 ALLEGRO_DEBUG("Switching to fullscreen mode sized %dx%d\n", w, h);
1170
1171 #define IS_LION (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_7)
1172
1173 if (al_get_new_display_adapter() >= al_get_num_video_adapters()) {
1174 [pool drain];
1175 return NULL;
1176 }
1177 ALLEGRO_DISPLAY_OSX_WIN* dpy = al_malloc(sizeof(ALLEGRO_DISPLAY_OSX_WIN));
1178 if (dpy == NULL) {
1179 [pool drain];
1180 return NULL;
1181 }
1182 memset(dpy, 0, sizeof(*dpy));
1183 ALLEGRO_DISPLAY* display = &dpy->parent;
1184
1185 /* Set up the ALLEGRO_DISPLAY part */
1186 display->vt = _al_osx_get_display_driver_fs();
1187 display->refresh_rate = al_get_new_display_refresh_rate();
1188 display->flags = al_get_new_display_flags() | ALLEGRO_OPENGL | ALLEGRO_FULLSCREEN;
1189 #ifdef ALLEGRO_CFG_OPENGLES2
1190 display.flags |= ALLEGRO_PROGRAMMABLE_PIPELINE;
1191 #endif
1192 #ifdef ALLEGRO_CFG_OPENGLES
1193 display.flags |= ALLEGRO_OPENGL_ES_PROFILE;
1194 #endif
1195 display->w = w;
1196 display->h = h;
1197 _al_event_source_init(&display->es);
1198 dpy->cursor = [[NSCursor arrowCursor] retain];
1199 dpy->display_id = CGMainDisplayID();
1200 init_halt_events(dpy);
1201
1202 /* Get display ID for the requested display */
1203 if (al_get_new_display_adapter() > 0) {
1204 int adapter = al_get_new_display_adapter();
1205 NSScreen *screen = [[NSScreen screens] objectAtIndex: adapter];
1206 NSDictionary *dict = [screen deviceDescription];
1207 NSNumber *display_id = [dict valueForKey: @"NSScreenNumber"];
1208 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
1209 dpy->display_id = [display_id intValue];
1210 #else
1211 dpy->display_id = [display_id integerValue];
1212 #endif
1213 //dpy->display_id = (CGDirectDisplayID)[display_id pointerValue];
1214 }
1215
1216 // Set up a pixel format to describe the mode we want.
1217 osx_set_opengl_pixelformat_attributes(dpy);
1218 NSOpenGLPixelFormat* fmt =
1219 [[NSOpenGLPixelFormat alloc] initWithAttributes: dpy->attributes];
1220 if (fmt == nil) {
1221 ALLEGRO_DEBUG("Could not set pixel format\n");
1222 [pool drain];
1223 return NULL;
1224 }
1225
1226 // Create a context which shares with any other contexts with the same format
1227 NSOpenGLContext* context = osx_create_shareable_context(fmt, &dpy->display_group);
1228 [fmt release];
1229 if (context == nil) {
1230 ALLEGRO_DEBUG("Could not create rendering context\n");
1231 [pool drain];
1232 return NULL;
1233 }
1234 dpy->ctx = context;
1235
1236 // Prevent other apps from writing to this display and switch it to our
1237 // chosen mode.
1238 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
1239 CGDisplayCapture(dpy->display_id);
1240 CFDictionaryRef mode = CGDisplayBestModeForParametersAndRefreshRate(dpy->display_id, dpy->depth, w, h, display->refresh_rate, NULL);
1241 CGDisplaySwitchToMode(dpy->display_id, mode);
1242 #else
1243 CGDisplayModeRef mode = NULL;
1244 CFArrayRef modes = NULL;
1245 CFStringRef pixel_format = NULL;
1246 int i;
1247
1248 /* Set pixel format string */
1249 if (dpy->depth == 32)
1250 pixel_format = CFSTR(IO32BitDirectPixels);
1251 if (dpy->depth == 16)
1252 pixel_format = CFSTR(IO16BitDirectPixels);
1253 if (dpy->depth == 8)
1254 pixel_format = CFSTR(IO8BitIndexedPixels);
1255 modes = CGDisplayCopyAllDisplayModes(dpy->display_id, NULL);
1256 for (i = 0; i < CFArrayGetCount(modes); i++) {
1257 CGDisplayModeRef try_mode =
1258 (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);
1259
1260 CFStringRef pixel_encoding = CGDisplayModeCopyPixelEncoding(try_mode);
1261
1262 /* Found mode with matching size/colour depth */
1263 if ( w == (int)CGDisplayModeGetWidth(try_mode) &&
1264 h == (int)CGDisplayModeGetHeight(try_mode) &&
1265 CFStringCompare(pixel_encoding, pixel_format, 1) == 0) {
1266 mode = try_mode;
1267 CFRelease(pixel_encoding);
1268 break;
1269 }
1270
1271 /* Found mode with matching size; colour depth does not match, but
1272 * it's the best so far.
1273 */
1274 if ( w == (int)CGDisplayModeGetWidth(try_mode) &&
1275 h == (int)CGDisplayModeGetHeight(try_mode) &&
1276 mode == NULL) {
1277 mode = try_mode;
1278 }
1279
1280 CFRelease(pixel_encoding);
1281 }
1282 CFRelease(modes);
1283
1284 if (!mode) {
1285 /* Trouble! - we can't find a nice mode to set. */
1286 [dpy->ctx clearDrawable];
1287 CGDisplayRelease(dpy->display_id);
1288 al_free(dpy);
1289 [pool drain];
1290 return NULL;
1291 }
1292
1293 /* Switch display mode */
1294 dpy->original_mode = CGDisplayCopyDisplayMode(dpy->display_id);
1295 CGDisplayCapture(dpy->display_id);
1296 CGDisplaySetDisplayMode(dpy->display_id, mode, NULL);
1297 #endif
1298
1299 NSRect rect = NSMakeRect(0, 0, w, h);
1300 NSString* title = [NSString stringWithUTF8String: al_get_new_window_title()];
1301 dispatch_sync(dispatch_get_main_queue(), ^{
1302 dpy->win = [[ALWindow alloc] initWithContentRect:rect styleMask:(IS_LION ? NSWindowStyleMaskBorderless : 0) backing:NSBackingStoreBuffered defer:NO];
1303 [dpy->win setTitle: title];
1304 [dpy->win setAcceptsMouseMovedEvents:YES];
1305 [dpy->win setViewsNeedDisplay:NO];
1306
1307 NSView *window_view = [[NSView alloc] initWithFrame:rect];
1308 [window_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
1309 [[dpy->win contentView] addSubview:window_view];
1310 [dpy->win setLevel:CGShieldingWindowLevel()];
1311 [context setView:window_view];
1312 [context update];
1313 [window_view release];
1314 [dpy->win setHasShadow:NO];
1315 [dpy->win setOpaque:YES];
1316 [dpy->win makeKeyAndOrderFront:nil];
1317 });
1318 // This is set per-thread
1319 [context makeCurrentContext];
1320
1321 // Set up the Allegro OpenGL implementation
1322 display->ogl_extras = al_malloc(sizeof(ALLEGRO_OGL_EXTRAS));
1323 memset(display->ogl_extras, 0, sizeof(ALLEGRO_OGL_EXTRAS));
1324 _al_ogl_manage_extensions(&dpy->parent);
1325 _al_ogl_set_extensions(dpy->parent.ogl_extras->extension_api);
1326 display->ogl_extras->is_shared = true;
1327
1328 /* Retrieve the options that were set */
1329 osx_get_opengl_pixelformat_attributes(dpy);
1330 /* Turn on vsyncing possibly. The old way doesn't work on new OSX's,
1331 but works better than the new way when it does work. */
1332 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
1333 if (_al_get_new_display_settings()->settings[ALLEGRO_VSYNC] == 1) {
1334 init_new_vsync(dpy);
1335 }
1336 #else
1337 if (_al_get_new_display_settings()->settings[ALLEGRO_VSYNC] == 1) {
1338 GLint swapInterval = 1;
1339 [dpy->ctx setValues:&swapInterval forParameter: NSOpenGLCPSwapInterval];
1340 }
1341 else {
1342 GLint swapInterval = 0;
1343 [dpy->ctx setValues:&swapInterval forParameter: NSOpenGLCPSwapInterval];
1344 }
1345 #endif
1346
1347 /* Set up GL as we want */
1348 setup_gl(display);
1349
1350 clear_to_black(dpy->ctx);
1351
1352 /* Add to the display list */
1353 ALLEGRO_DISPLAY **add = _al_vector_alloc_back(&al_get_system_driver()->displays);
1354 *add = display;
1355 dpy->in_fullscreen = YES;
1356 // Begin the 'private' event loop
1357 // Necessary because there's no NSResponder (i.e. a view) to collect
1358 // events from the window server.
1359 dispatch_sync(dispatch_get_main_queue(), ^{
1360 osx_run_fullscreen_display(dpy);
1361 });
1362 [pool drain];
1363
1364 _al_osx_tell_dock();
1365 return &dpy->parent;
1366 }
1367 #if 0
1368 /* Alternative, Cocoa-based mode switching.
1369 * Works, but I can't get the display to respond to a resize request
1370 * properly - EG
1371 */
1372 static ALLEGRO_DISPLAY* create_display_fs(int w, int h)
1373 {
1374 ALLEGRO_DEBUG("Creating full screen mode sized %dx%d\n", w, h);
1375 if (al_get_new_display_adapter() >= al_get_num_video_adapters())
1376 return NULL;
1377 ALLEGRO_DISPLAY_OSX_WIN* dpy = al_malloc(sizeof(ALLEGRO_DISPLAY_OSX_WIN));
1378 if (dpy == NULL) {
1379 return NULL;
1380 }
1381 memset(dpy, 0, sizeof(*dpy));
1382
1383 /* Set up the ALLEGRO_DISPLAY part */
1384 dpy->parent.vt = _al_osx_get_display_driver_win();
1385 dpy->parent.refresh_rate = al_get_new_display_refresh_rate();
1386 dpy->parent.flags = al_get_new_display_flags() | ALLEGRO_OPENGL | ALLEGRO_FULLSCREEN;
1387 #ifdef ALLEGRO_CFG_OPENGLES2
1388 dpy->parent.flags |= ALLEGRO_PROGRAMMABLE_PIPELINE;
1389 #endif
1390 #ifdef ALLEGRO_CFG_OPENGLES
1391 dpy->parent.flags |= ALLEGRO_OPENGL_ES_PROFILE;
1392 #endif
1393 dpy->parent.w = w;
1394 dpy->parent.h = h;
1395 _al_event_source_init(&dpy->parent.es);
1396 osx_change_cursor(dpy, [NSCursor arrowCursor]);
1397 dpy->show_cursor = YES;
1398 init_halt_events(dpy);
1399
1400 // Set up a pixel format to describe the mode we want.
1401 osx_set_opengl_pixelformat_attributes(dpy);
1402
1403 // Clear last window position to 0 if there are no other open windows
1404 if (_al_vector_is_empty(&al_get_system_driver()->displays)) {
1405 last_window_pos = NSZeroPoint;
1406 }
1407
1408 /* OSX specific part - finish the initialisation on the main thread */
1409 [ALDisplayHelper performSelectorOnMainThread: @selector(initialiseDisplay:)
1410 withObject: [NSValue valueWithPointer:dpy]
1411 waitUntilDone: YES];
1412
1413 [dpy->ctx makeCurrentContext];
1414 [dpy->ctx setFullScreen];
1415
1416 NSScreen *screen = [dpy->win screen];
1417 NSDictionary *dict = [screen deviceDescription];
1418 NSNumber *display_id = [dict valueForKey: @"NSScreenNumber"];
1419 dpy->display_id = [display_id integerValue];
1420 //dpy->display_id = (CGDirectDisplayID)[display_id pointerValue];
1421 CGDisplayCapture(dpy->display_id);
1422
1423 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
1424 CFDictionaryRef mode = CGDisplayBestModeForParametersAndRefreshRate(dpy->display_id, dpy->depth, w, h, dpy->parent.refresh_rate, NULL);
1425 CGDisplaySwitchToMode(dpy->display_id, mode);
1426 #else
1427 CGDisplayModeRef mode = NULL;
1428 CFArrayRef modes = NULL;
1429 CFStringRef pixel_format = NULL;
1430 int i;
1431
1432 /* Set pixel format string */
1433 if (dpy->depth == 32)
1434 pixel_format = CFSTR(IO32BitDirectPixels);
1435 if (dpy->depth == 16)
1436 pixel_format = CFSTR(IO16BitDirectPixels);
1437 if (dpy->depth == 8)
1438 pixel_format = CFSTR(IO8BitIndexedPixels);
1439 modes = CGDisplayCopyAllDisplayModes(dpy->display_id, NULL);
1440 for (i = 0; i < CFArrayGetCount(modes); i++) {
1441 CGDisplayModeRef try_mode =
1442 (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);
1443
1444 CFStringRef pixel_encoding = CGDisplayModeCopyPixelEncoding(try_mode);
1445
1446 /* Found mode with matching size/colour depth */
1447 if ( w == (int)CGDisplayModeGetWidth(try_mode) &&
1448 h == (int)CGDisplayModeGetHeight(try_mode) &&
1449 CFStringCompare(pixel_encoding, pixel_format, 1) == 0) {
1450 mode = try_mode;
1451 CFRelease(pixel_encoding);
1452 break;
1453 }
1454
1455 /* Found mode with matching size; colour depth does not match, but
1456 * it's the best so far.
1457 */
1458 if ( w == (int)CGDisplayModeGetWidth(try_mode) &&
1459 h == (int)CGDisplayModeGetHeight(try_mode) &&
1460 mode == NULL) {
1461 mode = try_mode;
1462 }
1463
1464 CFRelease(pixel_encoding);
1465 }
1466
1467 if (!mode) {
1468 /* Trouble! - we can't find a nice mode to set. */
1469 [dpy->ctx clearDrawable];
1470 CGDisplayRelease(dpy->display_id);
1471 [dpy->win close];
1472 al_free(dpy);
1473 return NULL;
1474 }
1475
1476 /* Switch display mode */
1477 CFDictionaryRef options = CFDictionaryCreate(NULL, NULL, NULL, 0, NULL, NULL);
1478 CGDisplaySetDisplayMode(dpy->display_id, mode, NULL);
1479 CFRelease(options);
1480 CFRelease(modes);
1481 #endif
1482
1483 [[dpy->win contentView] enterFullScreenMode: screen withOptions: nil];
1484
1485 // Set up the Allegro OpenGL implementation
1486 dpy->parent.ogl_extras = al_malloc(sizeof(ALLEGRO_OGL_EXTRAS));
1487 memset(dpy->parent.ogl_extras, 0, sizeof(ALLEGRO_OGL_EXTRAS));
1488 _al_ogl_manage_extensions(&dpy->parent);
1489 _al_ogl_set_extensions(dpy->parent.ogl_extras->extension_api);
1490 dpy->parent.ogl_extras->is_shared = true;
1491
1492 /* Retrieve the options that were set */
1493 osx_get_opengl_pixelformat_attributes(dpy);
1494 /* Turn on vsyncing possibly. The old way doesn't work on new OSX's,
1495 but works better than the new way when it does work. */
1496 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
1497 if (_al_get_new_display_settings()->settings[ALLEGRO_VSYNC] == 1) {
1498 init_new_vsync(dpy);
1499 }
1500 #else
1501 if (_al_get_new_display_settings()->settings[ALLEGRO_VSYNC] == 1) {
1502 GLint swapInterval = 1;
1503 [dpy->ctx setValues:&swapInterval forParameter: NSOpenGLCPSwapInterval];
1504 }
1505 else {
1506 GLint swapInterval = 0;
1507 [dpy->ctx setValues:&swapInterval forParameter: NSOpenGLCPSwapInterval];
1508 }
1509 #endif
1510
1511 /* Set up GL as we want */
1512 setup_gl(&dpy->parent);
1513
1514 clear_to_black(dpy->ctx);
1515
1516 /* Add to the display list */
1517 ALLEGRO_DISPLAY **add = _al_vector_alloc_back(&al_get_system_driver()->displays);
1518 *add = &dpy->parent;
1519 dpy->in_fullscreen = YES;
1520
1521 return &dpy->parent;
1522 }
1523 #endif
1524
1525 /* create_display_win:
1526 * Create a windowed display - create the window with an ALOpenGLView
1527 * to be its content view
1528 * Call from user thread.
1529 */
1530 static ALLEGRO_DISPLAY* create_display_win(int w, int h) {
1531 ASSERT_USER_THREAD();
1532 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1533 /* Create a temporary view so that we can check whether a fullscreen
1534 * window can be created.
1535 */
1536 if (al_get_new_display_flags() & ALLEGRO_FULLSCREEN_WINDOW) {
1537 __block BOOL ok;
1538 dispatch_sync(dispatch_get_main_queue(), ^{
1539 NSRect rc = NSMakeRect(0, 0, w, h);
1540 ALOpenGLView* view = [[ALOpenGLView alloc] initWithFrame: rc];
1541 ok = [view respondsToSelector:
1542 @selector(enterFullScreenMode:withOptions:)];
1543 [view release];
1544 });
1545 if (!ok) {
1546 ALLEGRO_DEBUG("Cannot create FULLSCREEN_WINDOW");
1547 return NULL;
1548 }
1549 }
1550
1551 ALLEGRO_DEBUG("Creating window sized %dx%d\n", w, h);
1552 if (al_get_new_display_adapter() >= al_get_num_video_adapters()) {
1553 [pool drain];
1554 return NULL;
1555 }
1556 ALLEGRO_DISPLAY_OSX_WIN* dpy = al_malloc(sizeof(ALLEGRO_DISPLAY_OSX_WIN));
1557 if (dpy == NULL) {
1558 [pool drain];
1559 return NULL;
1560 }
1561 memset(dpy, 0, sizeof(*dpy));
1562 ALLEGRO_DISPLAY* display = &dpy->parent;
1563 /* Set up the ALLEGRO_DISPLAY part */
1564 display->vt = _al_osx_get_display_driver_win();
1565 display->refresh_rate = al_get_new_display_refresh_rate();
1566 display->flags = al_get_new_display_flags() | ALLEGRO_OPENGL | ALLEGRO_WINDOWED;
1567 #ifdef ALLEGRO_CFG_OPENGLES2
1568 display->flags |= ALLEGRO_PROGRAMMABLE_PIPELINE;
1569 #endif
1570 #ifdef ALLEGRO_CFG_OPENGLES
1571 display->flags |= ALLEGRO_OPENGL_ES_PROFILE;
1572 #endif
1573 display->w = w;
1574 display->h = h;
1575 dpy->old_w = w;
1576 dpy->old_h = h;
1577 _al_event_source_init(&display->es);
1578 _al_osx_change_cursor(dpy, [NSCursor arrowCursor]);
1579 dpy->show_cursor = YES;
1580 init_halt_events(dpy);
1581
1582 // Set up a pixel format to describe the mode we want.
1583 osx_set_opengl_pixelformat_attributes(dpy);
1584
1585 // Clear last window position to 0 if there are no other open windows
1586 if (_al_vector_is_empty(&al_get_system_driver()->displays)) {
1587 last_window_pos = NSZeroPoint;
1588 }
1589
1590 /* Get the new window position. This is stored in TLS, so we need to do
1591 * this before calling initialise_display, which runs on a different
1592 * thread.
1593 */
1594 int x, y;
1595 int adapter = al_get_new_display_adapter();
1596 const char* title = al_get_new_window_title();
1597 al_get_new_window_position(&x, &y);
1598
1599 /* OSX specific part - finish the initialisation on the main thread */
1600 dispatch_sync(dispatch_get_main_queue(), ^{
1601 NSRect rc = NSMakeRect(0, 0, w, h);
1602 ALWindow *alwin = dpy->win = [ALWindow alloc];
1603 NSWindow* win = alwin;
1604 NSScreen *screen;
1605 unsigned int mask = (display->flags & ALLEGRO_FRAMELESS) ? NSWindowStyleMaskBorderless :
1606 (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable);
1607 if (display->flags & ALLEGRO_RESIZABLE)
1608 mask |= NSWindowStyleMaskResizable;
1609 if (display->flags & ALLEGRO_FULLSCREEN)
1610 mask |= NSWindowStyleMaskResizable;
1611
1612 if ((adapter >= 0) &&
1613 (adapter < al_get_num_video_adapters())) {
1614 screen = [[NSScreen screens] objectAtIndex: adapter];
1615 } else {
1616 screen = [NSScreen mainScreen];
1617 }
1618 float screen_scale_factor = 1.0;
1619 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
1620 if ([screen respondsToSelector:@selector(backingScaleFactor)]) {
1621 screen_scale_factor = [screen backingScaleFactor];
1622 }
1623 #endif
1624 rc.size.width /= screen_scale_factor;
1625 rc.size.height /= screen_scale_factor;
1626 [win initWithContentRect: rc
1627 styleMask: mask
1628 backing: NSBackingStoreBuffered
1629 defer: NO
1630 screen: screen
1631 ];
1632 alwin.display = (ALLEGRO_DISPLAY *)dpy;
1633 if (display->flags & ALLEGRO_RESIZABLE) {
1634 if ([win respondsToSelector:NSSelectorFromString(@"setCollectionBehavior:")]) {
1635 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
1636 }
1637 }
1638 NSOpenGLPixelFormat* fmt =
1639 [[NSOpenGLPixelFormat alloc] initWithAttributes: dpy->attributes];
1640 ALOpenGLView* view = [[ALOpenGLView alloc] initWithFrame: rc];
1641 dpy->ctx = osx_create_shareable_context(fmt, &dpy->display_group);
1642 if (dpy->ctx == nil) {
1643 ALLEGRO_DEBUG("Could not create rendering context\n");
1644 [view release];
1645 [fmt release];
1646
1647 return;
1648 }
1649 dpy->view = view;
1650 /* Hook up the view to its display */
1651 [view setAllegroDisplay: &dpy->parent];
1652 [view setOpenGLContext: dpy->ctx];
1653 [view setPixelFormat: fmt];
1654 /* Realize the window on the main thread */
1655 [win setContentView: view];
1656 [win setDelegate: view];
1657 [win setReleasedWhenClosed: YES];
1658 [win setAcceptsMouseMovedEvents: _osx_mouse_installed];
1659 [win setTitle: [NSString stringWithUTF8String: title]];
1660 /* Set minimum size, otherwise the window can be resized so small we can't
1661 * grab the handle any more to make it bigger
1662 */
1663 [win setMinSize: NSMakeSize(MINIMUM_WIDTH / screen_scale_factor,
1664 MINIMUM_HEIGHT / screen_scale_factor)];
1665
1666 /* Maximize the window and update its width & height information */
1667 if (display->flags & ALLEGRO_MAXIMIZED) {
1668 [win setFrame: [screen visibleFrame] display: true animate: false];
1669 NSRect content = [win contentRectForFrameRect: [win frame]];
1670 display->w = content.size.width;
1671 display->h = content.size.height;
1672 }
1673
1674 /* Place the window, respecting the location set by the user with
1675 * al_set_new_window_position().
1676 * If the user never called al_set_new_window_position, we simply let
1677 * the window manager pick a suitable location.
1678 *
1679 * CAUTION: the window manager under OS X requires that x and y be in
1680 * the range -16000 ... 16000 (approximately, probably the range of a
1681 * signed 16 bit integer). Should we check for this?
1682 */
1683
1684 if ((x != INT_MAX) && (y != INT_MAX)) {
1685 /* The user gave us window coordinates */
1686 NSRect rc = [win frame];
1687 NSPoint origin;
1688 int primary_y = _al_osx_get_primary_screen_y();
1689
1690 /* We need to modify the y coordinate, cf. set_window_position */
1691 origin.x = x / screen_scale_factor;
1692 origin.y = primary_y / screen_scale_factor - rc.size.height - y / screen_scale_factor;
1693 [win setFrameOrigin: origin];
1694 }
1695 else {
1696 [win center];
1697 }
1698 [win makeKeyAndOrderFront:nil];
1699 if (mask != NSWindowStyleMaskBorderless) {
1700 [win makeMainWindow];
1701 }
1702 [fmt release];
1703 [view release];
1704 if (display->flags & ALLEGRO_FULLSCREEN_WINDOW) {
1705 NSRect sc = [[dpy->win screen] frame];
1706 dpy->parent.w = sc.size.width;
1707 dpy->parent.h = sc.size.height;
1708 }
1709 });
1710
1711 [dpy->ctx makeCurrentContext];
1712
1713 /* Print out OpenGL version info */
1714 ALLEGRO_INFO("OpenGL Version: %s\n", glGetString(GL_VERSION));
1715 ALLEGRO_INFO("Vendor: %s\n", glGetString(GL_VENDOR));
1716 ALLEGRO_INFO("Renderer: %s\n", glGetString(GL_RENDERER));
1717
1718 /* Set up a pixel format to describe the mode we want. */
1719 osx_set_opengl_pixelformat_attributes(dpy);
1720 /* Retrieve the options that were set */
1721 // Note: This initializes dpy->extra_settings
1722 osx_get_opengl_pixelformat_attributes(dpy);
1723
1724 // Set up the Allegro OpenGL implementation
1725 display->ogl_extras = al_malloc(sizeof(ALLEGRO_OGL_EXTRAS));
1726 memset(display->ogl_extras, 0, sizeof(ALLEGRO_OGL_EXTRAS));
1727 _al_ogl_manage_extensions(display);
1728 _al_ogl_set_extensions(display->ogl_extras->extension_api);
1729 display->ogl_extras->is_shared = true;
1730
1731 /* Turn on vsyncing possibly. The old way doesn't work on new OSX's,
1732 but works better than the new way when it does work. */
1733 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
1734 if (_al_get_new_display_settings()->settings[ALLEGRO_VSYNC] == 1) {
1735 init_new_vsync(dpy);
1736 }
1737 #else
1738 if (_al_get_new_display_settings()->settings[ALLEGRO_VSYNC] == 1) {
1739 GLint swapInterval = 1;
1740 [dpy->ctx setValues:&swapInterval forParameter: NSOpenGLCPSwapInterval];
1741 }
1742 else {
1743 GLint swapInterval = 0;
1744 [dpy->ctx setValues:&swapInterval forParameter: NSOpenGLCPSwapInterval];
1745 }
1746 #endif
1747
1748 /* Set up GL as we want */
1749 setup_gl(display);
1750
1751 clear_to_black(dpy->ctx);
1752
1753 /* Add to the display list */
1754 ALLEGRO_DISPLAY **add = _al_vector_alloc_back(&al_get_system_driver()->displays);
1755 *add = display;
1756 dpy->in_fullscreen = NO;
1757
1758 if (display->flags & ALLEGRO_FULLSCREEN_WINDOW) {
1759 display->flags ^= ALLEGRO_FULLSCREEN_WINDOW; /* Not set yet */
1760 set_display_flag(display, ALLEGRO_FULLSCREEN_WINDOW, true);
1761 }
1762
1763 [pool drain];
1764
1765 _al_osx_tell_dock();
1766 return display;
1767 }
1768
1769 /* destroy_display:
1770 * Destroy display, actually close the window or exit fullscreen on the main thread
1771 * Called from user thread
1772 */
1773 static void destroy_display(ALLEGRO_DISPLAY* d)
1774 {
1775 ASSERT_USER_THREAD();
1776 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1777 ALLEGRO_DISPLAY *old_dpy = al_get_current_display();
1778 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) d;
1779 ALLEGRO_DISPLAY_OSX_WIN* other = NULL;
1780 unsigned int i;
1781
1782 // Set the display as the current display; needed because we need to
1783 // make the context current.
1784 if (old_dpy != d) {
1785 _al_set_current_display_only(d);
1786 }
1787
1788 /* First of all, save video bitmaps attached to this display. */
1789 // Check for other displays in this display group
1790 _AL_VECTOR* dpys = &al_get_system_driver()->displays;
1791 for (i = 0; i < _al_vector_size(dpys); ++i) {
1792 ALLEGRO_DISPLAY_OSX_WIN* d = *(ALLEGRO_DISPLAY_OSX_WIN**) _al_vector_ref(dpys, i);
1793 if (d->display_group == dpy->display_group && (d!=dpy)) {
1794 other = d;
1795 break;
1796 }
1797 }
1798 if (other != NULL) {
1799 // Found another compatible display. Transfer our bitmaps to it.
1800 _AL_VECTOR* bmps = &dpy->parent.bitmaps;
1801 for (i = 0; i<_al_vector_size(bmps); ++i) {
1802 ALLEGRO_BITMAP **add = _al_vector_alloc_back(&other->parent.bitmaps);
1803 ALLEGRO_BITMAP **ref = _al_vector_ref(bmps, i);
1804 *add = *ref;
1805 (*add)->_display = &(other->parent);
1806 }
1807 }
1808 else {
1809 // This is the last in its group. Convert all its bitmaps to memory bmps
1810 while (dpy->parent.bitmaps._size > 0) {
1811 ALLEGRO_BITMAP **bptr = _al_vector_ref_back(&dpy->parent.bitmaps);
1812 ALLEGRO_BITMAP *bmp = *bptr;
1813 _al_convert_to_memory_bitmap(bmp);
1814 }
1815 }
1816 _al_vector_free(&dpy->parent.bitmaps);
1817 ALLEGRO_DISPLAY* display = &dpy->parent;
1818 ALLEGRO_OGL_EXTRAS *ogl = display->ogl_extras;
1819 _al_vector_find_and_delete(&al_get_system_driver()->displays, &display);
1820 if (ogl->backbuffer) {
1821 _al_ogl_destroy_backbuffer(ogl->backbuffer);
1822 ogl->backbuffer = NULL;
1823 ALLEGRO_DEBUG("destroy backbuffer.\n");
1824 }
1825 dispatch_sync(dispatch_get_main_queue(), ^{
1826 // Disconnect from its view or exit fullscreen mode
1827 [dpy->ctx clearDrawable];
1828 // Unlock the screen
1829 if (display->flags & ALLEGRO_FULLSCREEN) {
1830 CGDisplaySetDisplayMode(dpy->display_id, dpy->original_mode, NULL);
1831 CGDisplayModeRelease(dpy->original_mode);
1832 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
1833 if (dpy->win) {
1834 [dpy->view exitFullScreenModeWithOptions: nil];
1835 }
1836 #endif
1837 CGDisplayRelease(dpy->display_id);
1838 dpy->in_fullscreen = false;
1839 }
1840 else if (display->flags & ALLEGRO_FULLSCREEN_WINDOW) {
1841 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
1842 if (dpy->win) {
1843 [dpy->view exitFullScreenModeWithOptions: nil];
1844 }
1845 #endif
1846 }
1847 if (dpy->win) {
1848 // Destroy the containing window if there is one
1849 [dpy->win close];
1850 dpy->win = nil;
1851 }
1852 });
1853 _al_ogl_unmanage_extensions(&dpy->parent);
1854 [dpy->ctx release];
1855 [dpy->cursor release];
1856 _al_event_source_free(&d->es);
1857 al_free(d->ogl_extras);
1858
1859 // Restore original display from before this function was called.
1860 // If the display we just destroyed is actually current, set the current
1861 // display to NULL.
1862 if (old_dpy != d)
1863 _al_set_current_display_only(old_dpy);
1864 else {
1865 // Is this redundant? --pw
1866 _al_set_current_display_only(NULL);
1867 }
1868
1869 al_destroy_cond(dpy->halt_cond);
1870 al_destroy_mutex(dpy->halt_mutex);
1871 if (dpy->flip_mutex) {
1872 al_destroy_mutex(dpy->flip_mutex);
1873 al_destroy_cond(dpy->flip_cond);
1874 CVDisplayLinkRelease(dpy->display_link);
1875 }
1876 al_free(d->vertex_cache);
1877 al_free(d);
1878 [pool drain];
1879 }
1880
1881 /* create_display:
1882 * Create a display either fullscreen or windowed depending on flags
1883 * Call from user thread
1884 */
1885 static ALLEGRO_DISPLAY* create_display(int w, int h)
1886 {
1887 ASSERT_USER_THREAD();
1888 int flags = al_get_new_display_flags();
1889 if (flags & ALLEGRO_FULLSCREEN) {
1890 return create_display_fs(w,h);
1891 }
1892 else {
1893 return create_display_win(w,h);
1894 }
1895 }
1896
1897 /* Note: in windowed mode, contexts always behave like single-buffered
1898 * though in fact they are composited offscreen */
1899 static void flip_display(ALLEGRO_DISPLAY *disp)
1900 {
1901 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) disp;
1902
1903 ALLEGRO_BITMAP *old_target = NULL;
1904 if (!((ALLEGRO_BITMAP_EXTRA_OPENGL *)disp->ogl_extras->opengl_target->extra)->is_backbuffer) {
1905 old_target = al_get_target_bitmap();
1906 al_set_target_backbuffer(disp);
1907 }
1908
1909 if (dpy->flip_mutex) {
1910 al_lock_mutex(dpy->flip_mutex);
1911 int old_flips = dpy->num_flips;
1912 while (dpy->num_flips == old_flips) {
1913 al_wait_cond(dpy->flip_cond, dpy->flip_mutex);
1914 }
1915 dpy->num_flips = 0;
1916 al_unlock_mutex(dpy->flip_mutex);
1917 }
1918
1919 if (dpy->single_buffer) {
1920 glFlush();
1921 }
1922 else {
1923 [dpy->ctx flushBuffer];
1924 }
1925
1926 if (old_target) {
1927 al_set_target_bitmap(old_target);
1928 }
1929 }
1930
1931 static void update_display_region(ALLEGRO_DISPLAY *disp,
1932 int x, int y, int width, int height)
1933 {
1934 (void)x;
1935 (void)y;
1936 (void)width;
1937 (void)height;
1938 flip_display(disp);
1939 }
1940
1941 /* _al_osx_create_mouse_cursor:
1942 * creates a custom system cursor from the bitmap bmp.
1943 * (x_focus, y_focus) indicates the cursor hot-spot.
1944 */
1945 ALLEGRO_MOUSE_CURSOR *_al_osx_create_mouse_cursor(ALLEGRO_BITMAP *bmp,
1946 int x_focus, int y_focus)
1947 {
1948 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1949 ALLEGRO_MOUSE_CURSOR_OSX *cursor = NULL;
1950
1951 if (!bmp) {
1952 [pool drain];
1953 return NULL;
1954 }
1955
1956 NSImage* cursor_image = NSImageFromAllegroBitmap(bmp);
1957 cursor = al_malloc(sizeof *cursor);
1958 cursor->cursor = [[NSCursor alloc] initWithImage: cursor_image
1959 hotSpot: NSMakePoint(x_focus, y_focus)];
1960 [cursor_image release];
1961 [pool drain];
1962
1963 return (ALLEGRO_MOUSE_CURSOR *)cursor;
1964 }
1965
1966 /* _al_osx_destroy_mouse_cursor:
1967 * destroys a mouse cursor previously created with _al_osx_create_mouse_cursor
1968 */
1969 void _al_osx_destroy_mouse_cursor(ALLEGRO_MOUSE_CURSOR *curs)
1970 {
1971 ALLEGRO_MOUSE_CURSOR_OSX *cursor = (ALLEGRO_MOUSE_CURSOR_OSX *) curs;
1972 unsigned i;
1973
1974 if (!cursor)
1975 return;
1976
1977 /* XXX not at all thread safe */
1978
1979 _AL_VECTOR* dpys = &al_get_system_driver()->displays;
1980 for (i = 0; i < _al_vector_size(dpys); ++i) {
1981 ALLEGRO_DISPLAY* dpy = *(ALLEGRO_DISPLAY**) _al_vector_ref(dpys, i);
1982 ALLEGRO_DISPLAY_OSX_WIN *osx_dpy = (ALLEGRO_DISPLAY_OSX_WIN*) dpy;
1983
1984 if (osx_dpy->cursor == cursor->cursor) {
1985 _al_osx_change_cursor(osx_dpy, [NSCursor arrowCursor]);
1986 }
1987 }
1988
1989 [cursor->cursor release];
1990 al_free(cursor);
1991 }
1992
1993 /* osx_set_mouse_cursor:
1994 * change the mouse cursor for the active window to the cursor previously
1995 * allocated by osx_create_mouse_cursor
1996 */
1997 static bool osx_set_mouse_cursor(ALLEGRO_DISPLAY *display,
1998 ALLEGRO_MOUSE_CURSOR *cursor)
1999 {
2000 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN *)display;
2001 ALLEGRO_MOUSE_CURSOR_OSX *osxcursor = (ALLEGRO_MOUSE_CURSOR_OSX *)cursor;
2002
2003 _al_osx_change_cursor(dpy, osxcursor->cursor);
2004
2005 return true;
2006 }
2007
2008 /* osx_set_system_mouse_cursor:
2009 * change the mouse cursor to one of the system default cursors.
2010 * NOTE: Allegro defines four of these, but OS X has no dedicated "busy" or
2011 * "question" cursors, so we just set an arrow in those cases.
2012 */
2013 static bool osx_set_system_mouse_cursor(ALLEGRO_DISPLAY *display,
2014 ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id)
2015 {
2016 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN *)display;
2017 NSCursor *requested_cursor = NULL;
2018
2019 switch (cursor_id) {
2020 case ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT:
2021 case ALLEGRO_SYSTEM_MOUSE_CURSOR_ARROW:
2022 case ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY:
2023 case ALLEGRO_SYSTEM_MOUSE_CURSOR_QUESTION:
2024 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE:
2025 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_SW:
2026 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW:
2027 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_SE:
2028 case ALLEGRO_SYSTEM_MOUSE_CURSOR_PROGRESS:
2029 case ALLEGRO_SYSTEM_MOUSE_CURSOR_ALT_SELECT:
2030 requested_cursor = [NSCursor arrowCursor];
2031 break;
2032 case ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE:
2033 requested_cursor = [NSCursor operationNotAllowedCursor];
2034 break;
2035 case ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT:
2036 requested_cursor = [NSCursor IBeamCursor];
2037 break;
2038 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N:
2039 requested_cursor = [NSCursor resizeUpCursor];
2040 break;
2041 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_S:
2042 requested_cursor = [NSCursor resizeDownCursor];
2043 break;
2044 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E:
2045 requested_cursor = [NSCursor resizeRightCursor];
2046 break;
2047 case ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_W:
2048 requested_cursor = [NSCursor resizeLeftCursor];
2049 break;
2050 case ALLEGRO_SYSTEM_MOUSE_CURSOR_PRECISION:
2051 requested_cursor = [NSCursor crosshairCursor];
2052 break;
2053 case ALLEGRO_SYSTEM_MOUSE_CURSOR_LINK:
2054 requested_cursor = [NSCursor pointingHandCursor];
2055 break;
2056 default:
2057 return false;
2058 }
2059
2060 _al_osx_change_cursor(dpy, requested_cursor);
2061 return true;
2062 }
2063
2064 /* (show|hide)_cursor:
2065 Cursor show or hide. The same function works for both windowed and fullscreen.
2066 */
2067 static bool show_cursor(ALLEGRO_DISPLAY *d)
2068 {
2069 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) d;
2070 dpy->show_cursor = YES;
2071 [NSCursor unhide];
2072 return true;
2073 }
2074
2075 static bool hide_cursor(ALLEGRO_DISPLAY *d)
2076 {
2077 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) d;
2078 dpy->show_cursor = NO;
2079 [NSCursor hide];
2080 return true;
2081 }
2082
2083 /* Call from main thread. */
2084 static bool acknowledge_resize_display_win_main_thread(ALLEGRO_DISPLAY *d)
2085 {
2086 ASSERT_MAIN_THREAD();
2087
2088 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN *)d;
2089 NSWindow* window = dpy->win;
2090 NSRect frame = [window frame];
2091 NSRect content = [window contentRectForFrameRect: frame];
2092 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
2093 content = [window convertRectToBacking: content];
2094 #endif
2095
2096 /* At any moment when a window has been changed its size we either
2097 * clear ALLEGRO_MAXIMIZED flag (e.g. resize was done by a human)
2098 * or restore the flag back (at the end of live resize caused by zoom).
2099 * Note: affects zoom:(id)sender (if you will debug it).
2100 */
2101 if (!(d->flags & ALLEGRO_FULLSCREEN_WINDOW) && ![window isZoomed])
2102 d->flags &= ~ALLEGRO_MAXIMIZED;
2103 else if (!(d->flags & ALLEGRO_MAXIMIZED))
2104 d->flags |= ALLEGRO_MAXIMIZED;
2105
2106 d->w = NSWidth(content);
2107 d->h = NSHeight(content);
2108
2109 return true;
2110 }
2111
2112 /* Call from user thread */
2113 static bool acknowledge_resize_display_win(ALLEGRO_DISPLAY *d) {
2114 ASSERT_USER_THREAD();
2115 dispatch_sync(dispatch_get_main_queue(), ^{
2116 acknowledge_resize_display_win_main_thread(d);
2117 });
2118 // must be done on the thread the user calls it from, not the main thread
2119 setup_gl(d);
2120 return true;
2121 }
2122
2123 /* resize_display_win
2124 * Change the size of the display by altering the window size or changing the screen mode
2125 * This must be called from the User thread
2126 */
2127 static bool resize_display_win(ALLEGRO_DISPLAY *d, int w, int h)
2128 {
2129 ASSERT_USER_THREAD();
2130 /* Don't resize a fullscreen window */
2131 if (d->flags & ALLEGRO_FULLSCREEN_WINDOW) {
2132 return false;
2133 }
2134 bool __block rc;
2135 dispatch_sync(dispatch_get_main_queue(), ^{
2136 rc = resize_display_win_main_thread(d, w, h);
2137 });
2138 // must be done on the thread the user calls it from, not the main thread
2139 setup_gl(d);
2140 // Only update the old values in response to user-initiated resizes.
2141 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN *)d;
2142 dpy->old_w = w;
2143 dpy->old_h = h;
2144 return rc;
2145 }
2146
2147 /* resize_display_win_main_thread
2148 * Change the size of the display by altering the window size or changing the screen mode
2149 * This must be called from the Main thread
2150 */
2151 static bool resize_display_win_main_thread(ALLEGRO_DISPLAY *d, int w, int h)
2152 {
2153 ASSERT_MAIN_THREAD();
2154 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) d;
2155 NSWindow* window = dpy->win;
2156 NSRect current;
2157 float scale_factor = 1.0;
2158 NSRect content = NSMakeRect(0.0f, 0.0f, (float) w, (float) h);
2159
2160 current = [window frame];
2161 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
2162 content = [window convertRectFromBacking: content];
2163 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
2164 scale_factor = [window backingScaleFactor];
2165 }
2166 #endif
2167
2168 w = _ALLEGRO_MAX(w, MINIMUM_WIDTH / scale_factor);
2169 h = _ALLEGRO_MAX(h, MINIMUM_HEIGHT / scale_factor);
2170
2171 if (d->use_constraints) {
2172 if (d->min_w > 0 && w < d->min_w) {
2173 w = d->min_w;
2174 }
2175 if (d->min_h > 0 && h < d->min_h) {
2176 h = d->min_h;
2177 }
2178 /* Don't use max. constraints when a window is maximized. */
2179 if (!(d->flags & ALLEGRO_MAXIMIZED)) {
2180 if (d->max_w > 0 && w > d->max_w) {
2181 w = d->max_w;
2182 }
2183 if (d->max_h > 0 && h > d->max_h) {
2184 h = d->max_h;
2185 }
2186 }
2187 }
2188
2189 /* Set new width & height values to content rectangle
2190 * before calling 'set_frame' below.
2191 */
2192 content.size.width = w / scale_factor;
2193 content.size.height = h / scale_factor;
2194
2195 NSRect rc = [window frameRectForContentRect: content];
2196 rc.origin = current.origin;
2197 [window setFrame: rc display: YES animate: NO];
2198
2199 clear_to_black(dpy->ctx);
2200 return acknowledge_resize_display_win_main_thread(d);
2201 }
2202
2203 static bool resize_display_fs(ALLEGRO_DISPLAY *d, int w, int h)
2204 {
2205 ALLEGRO_DEBUG("Resize full screen display to %d x %d\n", w, h);
2206 bool success = true;
2207 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) d;
2208 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
2209 CFDictionaryRef current = CGDisplayCurrentMode(dpy->display_id);
2210 CFNumberRef bps = (CFNumberRef) CFDictionaryGetValue(current, kCGDisplayBitsPerPixel);
2211 int b;
2212 CFNumberGetValue(bps, kCFNumberSInt32Type,&b);
2213 CFDictionaryRef mode = CGDisplayBestModeForParameters(dpy->display_id, b, w, h, NULL);
2214 [dpy->ctx clearDrawable];
2215 CGError err = CGDisplaySwitchToMode(dpy->display_id, mode);
2216 success = (err == kCGErrorSuccess);
2217 #else
2218 CGDisplayModeRef current = CGDisplayCopyDisplayMode(dpy->display_id);
2219 CFStringRef bps = CGDisplayModeCopyPixelEncoding(current);
2220 CFRelease(current);
2221 CGDisplayModeRef mode = NULL;
2222 CFArrayRef modes = NULL;
2223 int i;
2224
2225 modes = CGDisplayCopyAllDisplayModes(dpy->display_id, NULL);
2226 for (i = 0; i < CFArrayGetCount(modes); i++) {
2227 CGDisplayModeRef try_mode =
2228 (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);
2229
2230 CFStringRef pixel_encoding = CGDisplayModeCopyPixelEncoding(try_mode);
2231
2232 /* Found mode with matching size/colour depth */
2233 if ( w == (int)CGDisplayModeGetWidth(try_mode) &&
2234 h == (int)CGDisplayModeGetHeight(try_mode) &&
2235 CFStringCompare(pixel_encoding, bps, 1) == 0) {
2236 mode = try_mode;
2237 CFRelease(pixel_encoding);
2238 break;
2239 }
2240
2241 CFRelease(pixel_encoding);
2242 }
2243 CFRelease(bps);
2244 CFRelease(modes);
2245 if (!mode) {
2246 ALLEGRO_DEBUG("Can't resize fullscreen display\n");
2247
2248 return false;
2249 }
2250
2251 /* Switch display mode */
2252 [dpy->ctx clearDrawable];
2253 CFDictionaryRef options = CFDictionaryCreate(NULL, NULL, NULL, 0, NULL, NULL);
2254 CGDisplaySetDisplayMode(dpy->display_id, mode, NULL);
2255 CFRelease(options);
2256 #endif
2257 d->w = w;
2258 d->h = h;
2259 [dpy->ctx setFullScreen];
2260 _al_ogl_resize_backbuffer(d->ogl_extras->backbuffer, d->w, d->h);
2261 setup_gl(d);
2262 return success;
2263 }
2264
2265 static bool is_compatible_bitmap(ALLEGRO_DISPLAY* disp, ALLEGRO_BITMAP* bmp)
2266 {
2267 return (_al_get_bitmap_display(bmp) == disp)
2268 || (((ALLEGRO_DISPLAY_OSX_WIN*) _al_get_bitmap_display(bmp))->display_group == ((ALLEGRO_DISPLAY_OSX_WIN*) disp)->display_group);
2269 }
2270
2271 /* set_window_position:
2272 * Set the position of the window that owns this display
2273 * Slightly complicated because Allegro measures from the top down to
2274 * the top left corner, OS X from the bottom up to the bottom left corner.
2275 * Call from user thread.
2276 */
2277 static void set_window_position(ALLEGRO_DISPLAY* display, int x, int y)
2278 {
2279 ASSERT_USER_THREAD();
2280 ALLEGRO_DISPLAY_OSX_WIN* d = (ALLEGRO_DISPLAY_OSX_WIN*) display;
2281 NSWindow* window = d->win;
2282
2283 int primary_y = _al_osx_get_primary_screen_y();
2284 float global_scale_factor = _al_osx_get_global_scale_factor();
2285
2286 /* Because the extended plane (see get_monitor_info) has holes in it, we need to
2287 * search which destination monitor to actually use.
2288 */
2289 NSArray *screen_list = [NSScreen screens];
2290 int found_screen = -1;
2291 for (int i = 0; i < al_get_num_video_adapters(); i++) {
2292 ALLEGRO_MONITOR_INFO info;
2293 al_get_monitor_info(i, &info);
2294 if (x > info.x1 && x < info.x2 && y > info.y1 && y < info.y2) {
2295 found_screen = i;
2296 break;
2297 }
2298 }
2299 if (found_screen < 0)
2300 return;
2301 NSScreen *screen = [screen_list objectAtIndex:found_screen];
2302 NSRect screen_rc = [screen frame];
2303
2304 /* Set the frame on the main thread. Because this is where
2305 * the window's frame was initially set, this is where it should be
2306 * modified too.
2307 */
2308 dispatch_sync(dispatch_get_main_queue(), ^{
2309 NSRect rc = [window frame];
2310 float scale_factor = 1.0;
2311 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
2312 if ([screen respondsToSelector:@selector(backingScaleFactor)]) {
2313 scale_factor = [screen backingScaleFactor];
2314 }
2315 #endif
2316 /* These two expressions are the inverses of get_window_position formulas. */
2317 rc.origin.x = (x + screen_rc.origin.x * scale_factor - screen_rc.origin.x * global_scale_factor) / scale_factor;
2318
2319 /* XXX: Handle non-resizeable displays! */
2320 rc.origin.y = (y + scale_factor * rc.size.height - scale_factor * (screen_rc.origin.y + screen_rc.size.height) - ((primary_y - screen_rc.origin.y - screen_rc.size.height) * global_scale_factor)) / (-scale_factor);
2321
2322 [window setFrame: rc display: YES animate: NO];
2323 });
2324 }
2325
2326 /* get_window_position:
2327 * Get the position of the window that owns this display. See comment for
2328 * set_window_position.
2329 * Call from user thread.
2330 */
2331 static void get_window_position(ALLEGRO_DISPLAY* display, int* px, int* py)
2332 {
2333 ASSERT_USER_THREAD();
2334 ALLEGRO_DISPLAY_OSX_WIN* d = (ALLEGRO_DISPLAY_OSX_WIN*) display;
2335 NSWindow* window = d->win;
2336
2337 int primary_y = _al_osx_get_primary_screen_y();
2338 float global_scale_factor = _al_osx_get_global_scale_factor();
2339 dispatch_sync(dispatch_get_main_queue(), ^{
2340 NSRect rc = [window frame];
2341 float scale_factor = 1.0;
2342 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
2343 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
2344 scale_factor = [window backingScaleFactor];
2345 }
2346 #endif
2347 NSRect screen_rc = [[window screen] frame];
2348 /* Use global scale to find the origin of the screen and then use the
2349 * local scale to handle the relative coordinates.
2350 */
2351 *px = (int) (screen_rc.origin.x * global_scale_factor + (rc.origin.x - screen_rc.origin.x) * scale_factor);
2352 *py = (int)((primary_y - screen_rc.origin.y - screen_rc.size.height) * global_scale_factor) - (int)(scale_factor * (rc.size.height + rc.origin.y - screen_rc.origin.y - screen_rc.size.height));
2353 });
2354 }
2355
2356 static bool set_window_constraints(ALLEGRO_DISPLAY* display,
2357 int min_w, int min_h, int max_w, int max_h)
2358 {
2359 if (min_w > 0 && min_w < MINIMUM_WIDTH) {
2360 min_w = MINIMUM_WIDTH;
2361 }
2362 if (min_h > 0 && min_h < MINIMUM_HEIGHT) {
2363 min_h = MINIMUM_HEIGHT;
2364 }
2365
2366 display->min_w = min_w;
2367 display->min_h = min_h;
2368 display->max_w = max_w;
2369 display->max_h = max_h;
2370
2371 return true;
2372 }
2373
2374 static bool get_window_constraints(ALLEGRO_DISPLAY* display,
2375 int* min_w, int* min_h, int* max_w, int* max_h)
2376 {
2377 *min_w = display->min_w;
2378 *min_h = display->min_h;
2379 *max_w = display->max_w;
2380 *max_h = display->max_h;
2381
2382 return true;
2383 }
2384 /* apply_window_constraints:
2385 * Tell Cocoa about new window min/max size.
2386 * Resize the window if needed.
2387 * Call from user thread.
2388 */
2389 static void apply_window_constraints(ALLEGRO_DISPLAY *display,
2390 bool onoff)
2391 {
2392 ASSERT_USER_THREAD();
2393 ALLEGRO_DISPLAY_OSX_WIN* d = (ALLEGRO_DISPLAY_OSX_WIN*) display;
2394
2395 NSWindow* window = d->win;
2396 float __block scale_factor = 1.0;
2397 NSSize max_size;
2398 NSSize min_size;
2399 dispatch_sync(dispatch_get_main_queue(), ^{
2400 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
2401 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
2402 scale_factor = [window backingScaleFactor];
2403 }
2404 #endif
2405 });
2406 if (onoff) {
2407 min_size.width = display->min_w / scale_factor;
2408 min_size.height = display->min_h / scale_factor;
2409
2410 if (display->max_w > 0)
2411 max_size.width = display->max_w / scale_factor;
2412 else
2413 max_size.width = FLT_MAX;
2414
2415 if (display->max_h > 0)
2416 max_size.height = display->max_h / scale_factor;
2417 else
2418 max_size.height = FLT_MAX;
2419
2420 al_resize_display(display, display->w, display->h);
2421 }
2422 else {
2423 min_size.width = MINIMUM_WIDTH / scale_factor;
2424 min_size.height = MINIMUM_HEIGHT / scale_factor;
2425 max_size.width = FLT_MAX;
2426 max_size.height = FLT_MAX;
2427 }
2428 dispatch_sync(dispatch_get_main_queue(), ^{
2429 [window setContentMaxSize:max_size];
2430 [window setContentMinSize:min_size];
2431 });
2432 }
2433
2434 /* set_window_title:
2435 * Set the title of the window with this display
2436 * Call from user thread
2437 */
2438 static void set_window_title(ALLEGRO_DISPLAY *display, const char *title)
2439 {
2440 ASSERT_USER_THREAD();
2441 ALLEGRO_DISPLAY_OSX_WIN* dpy = (ALLEGRO_DISPLAY_OSX_WIN*) display;
2442 NSString* string = [[NSString alloc] initWithUTF8String:title];
2443 [dpy->win performSelectorOnMainThread:@selector(setTitle:) withObject:string waitUntilDone:YES];
2444 [string release];
2445 }
2446
2447 /* set_icons:
2448 * Set the icon - OS X doesn't have per-window icons so
2449 * ignore the display parameter
2450 * Call from user thread
2451 */
2452 static void set_icons(ALLEGRO_DISPLAY *display, int num_icons, ALLEGRO_BITMAP* bitmaps[])
2453 {
2454 ASSERT_USER_THREAD();
2455 /* Multiple icons not yet implemented. */
2456 ALLEGRO_BITMAP *bitmap = bitmaps[num_icons - 1];
2457 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2458 NSImage *image = NSImageFromAllegroBitmap(bitmap);
2459 (void)display;
2460 [NSApp performSelectorOnMainThread: @selector(setApplicationIconImage:)
2461 withObject: image
2462 waitUntilDone: YES];
2463 [image release];
2464 [pool drain];
2465 }
2466
2467 /* set_display_flag:
2468 * Change settings for an already active display
2469 * Call from user thread.
2470 */
2471 static bool set_display_flag(ALLEGRO_DISPLAY *display, int flag, bool onoff)
2472 {
2473 ASSERT_USER_THREAD();
2474 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
2475 return false;
2476 #else
2477 if (!display)
2478 return false;
2479
2480 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN *)display;
2481 ALWindow *win = dpy->win;
2482
2483 if (!win)
2484 return false;
2485 bool __block need_setup_gl = false;
2486 bool __block retcode = true;
2487 dispatch_sync(dispatch_get_main_queue(), ^{
2488 NSWindowStyleMask mask = [win styleMask];
2489 ALOpenGLView *view = (ALOpenGLView *)dpy->view;
2490 switch (flag) {
2491 case ALLEGRO_FRAMELESS:
2492 if (onoff)
2493 display->flags |= ALLEGRO_FRAMELESS;
2494 else
2495 display->flags &= ~ALLEGRO_FRAMELESS;
2496 /* BUGS:
2497 - This causes the keyboard focus to be lost.
2498 - On 10.10, disabling the frameless mode causes the title bar to be partially drawn
2499 (resizing the window makes it appear again).
2500 */
2501 ALLEGRO_DEBUG("Toggle FRAME for display %p to %d\n", dpy, onoff);
2502 if (onoff)
2503 mask &= ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable);
2504 else
2505 mask |= NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable;
2506 NSString *title = [win title];
2507 [win setStyleMask:mask];
2508 /* When going from frameless to frameful, the title gets reset, so we have to manually put it back. */
2509 [win setTitle:title];
2510 break;
2511 case ALLEGRO_RESIZABLE:
2512 ALLEGRO_DEBUG("Toggle RESIZABLE for display %p to %d\n", dpy, onoff);
2513 if (onoff) {
2514 display->flags |= ALLEGRO_RESIZABLE;
2515 mask |= NSWindowStyleMaskResizable;
2516 } else {
2517 display->flags &= ~ALLEGRO_RESIZABLE;
2518 mask &= ~NSWindowStyleMaskResizable;
2519 }
2520 [win setStyleMask:mask];
2521 break;
2522 case ALLEGRO_MAXIMIZED:
2523 retcode= true;
2524 if ((!!(display->flags & ALLEGRO_MAXIMIZED)) == onoff)
2525 break;
2526 if (onoff)
2527 display->flags |= ALLEGRO_MAXIMIZED;
2528 else
2529 display->flags &= ~ALLEGRO_MAXIMIZED;
2530 [view maximize];
2531 break;
2532 case ALLEGRO_FULLSCREEN_WINDOW:
2533 if (onoff) {
2534 [view enterFullScreenWindowMode];
2535 NSRect sc = [[win screen] frame];
2536 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
2537 sc = [win convertRectToBacking: sc];
2538 #endif
2539 resize_display_win_main_thread(display, sc.size.width, sc.size.height);
2540 display->flags |= ALLEGRO_FULLSCREEN_WINDOW;
2541 } else {
2542 [view exitFullScreenWindowMode];
2543 display->flags &= ~ALLEGRO_FULLSCREEN_WINDOW;
2544 resize_display_win_main_thread(display, dpy->old_w, dpy->old_h);
2545 [view finishExitingFullScreenWindowMode];
2546 }
2547 need_setup_gl = true;
2548 break;
2549 default:
2550 retcode = false;
2551 break;
2552 }
2553 });
2554 if (need_setup_gl) {
2555 setup_gl(display);
2556 }
2557 return retcode;
2558 #endif
2559 }
2560
2561 static void acknowledge_drawing_halt(ALLEGRO_DISPLAY *display)
2562 {
2563 ALLEGRO_DISPLAY_OSX_WIN *dpy = (ALLEGRO_DISPLAY_OSX_WIN *)display;
2564 al_lock_mutex(dpy->halt_mutex);
2565 dpy->halt_event_acknowledged = true;
2566 al_signal_cond(dpy->halt_cond);
2567 al_unlock_mutex(dpy->halt_mutex);
2568 }
2569
2570 ALLEGRO_DISPLAY_INTERFACE* _al_osx_get_display_driver_win(void)
2571 {
2572 static ALLEGRO_DISPLAY_INTERFACE* vt = NULL;
2573 if (vt == NULL) {
2574 vt = al_malloc(sizeof(*vt));
2575 memset(vt, 0, sizeof(ALLEGRO_DISPLAY_INTERFACE));
2576 vt->create_display = create_display_win;
2577 vt->destroy_display = destroy_display;
2578 vt->set_current_display = set_current_display;
2579 vt->flip_display = flip_display;
2580 vt->update_display_region = update_display_region;
2581 vt->resize_display = resize_display_win;
2582 vt->acknowledge_resize = acknowledge_resize_display_win;
2583 vt->create_bitmap = _al_ogl_create_bitmap;
2584 vt->set_target_bitmap = _al_ogl_set_target_bitmap;
2585 vt->get_backbuffer = _al_ogl_get_backbuffer;
2586 vt->is_compatible_bitmap = is_compatible_bitmap;
2587 vt->show_mouse_cursor = show_cursor;
2588 vt->hide_mouse_cursor = hide_cursor;
2589 vt->set_mouse_cursor = osx_set_mouse_cursor;
2590 vt->set_system_mouse_cursor = osx_set_system_mouse_cursor;
2591 vt->get_window_position = get_window_position;
2592 vt->set_window_position = set_window_position;
2593 vt->get_window_constraints = get_window_constraints;
2594 vt->set_window_constraints = set_window_constraints;
2595 vt->apply_window_constraints = apply_window_constraints;
2596 vt->set_window_title = set_window_title;
2597 vt->set_display_flag = set_display_flag;
2598 vt->set_icons = set_icons;
2599 vt->update_render_state = _al_ogl_update_render_state;
2600 vt->acknowledge_drawing_halt = acknowledge_drawing_halt;
2601 _al_ogl_add_drawing_functions(vt);
2602 _al_osx_add_clipboard_functions(vt);
2603 }
2604 return vt;
2605 }
2606
2607 ALLEGRO_DISPLAY_INTERFACE* _al_osx_get_display_driver_fs(void)
2608 {
2609 static ALLEGRO_DISPLAY_INTERFACE* vt = NULL;
2610 if (vt == NULL) {
2611 vt = al_malloc(sizeof(*vt));
2612 memset(vt, 0, sizeof(ALLEGRO_DISPLAY_INTERFACE));
2613 vt->create_display = create_display_fs;
2614 vt->destroy_display = destroy_display;
2615 vt->set_current_display = set_current_display;
2616 vt->flip_display = flip_display;
2617 vt->resize_display = resize_display_fs;
2618 vt->create_bitmap = _al_ogl_create_bitmap;
2619 vt->set_target_bitmap = _al_ogl_set_target_bitmap;
2620 vt->show_mouse_cursor = show_cursor;
2621 vt->hide_mouse_cursor = hide_cursor;
2622 vt->set_mouse_cursor = osx_set_mouse_cursor;
2623 vt->set_system_mouse_cursor = osx_set_system_mouse_cursor;
2624 vt->get_backbuffer = _al_ogl_get_backbuffer;
2625 vt->is_compatible_bitmap = is_compatible_bitmap;
2626 vt->update_render_state = _al_ogl_update_render_state;
2627 _al_ogl_add_drawing_functions(vt);
2628 }
2629 return vt;
2630 }
2631
2632 /* Mini VT just for creating displays */
2633 ALLEGRO_DISPLAY_INTERFACE* _al_osx_get_display_driver(void)
2634 {
2635 static ALLEGRO_DISPLAY_INTERFACE* vt = NULL;
2636 if (vt == NULL) {
2637 vt = al_malloc(sizeof(*vt));
2638 memset(vt, 0, sizeof(ALLEGRO_DISPLAY_INTERFACE));
2639 vt->create_display = create_display;
2640 }
2641 return vt;
2642 }
2643
2644 /* Function: al_osx_get_window
2645 */
2646 NSWindow* al_osx_get_window(ALLEGRO_DISPLAY *display)
2647 {
2648 if (!display)
2649 return NULL;
2650 return ((ALLEGRO_DISPLAY_OSX_WIN *)display)->win;
2651 }