6460bf3d028986ac9a2fd44f52f9fc6cf34fce14
[vlc.git] / modules / gui / macosx / VLCVoutWindowController.m
1 /*****************************************************************************
2  * VLCVoutWindowController.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2012-2014 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Felix Paul K├╝hne <fkuehne -at- videolan -dot- org>
8  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #include <vlc_vout_display.h>
26
27 #import "CompatibilityFixes.h"
28 #import "VLCVoutWindowController.h"
29 #import "VLCMain.h"
30 #import "VLCMainWindow.h"
31 #import "VLCVoutView.h"
32
33 #import "VLCVideoEffectsWindowController.h"
34 #import "VLCAudioEffectsWindowController.h"
35 #import "VLCPlaylistInfo.h"
36 #import "VLCBookmarksWindowController.h"
37 #import "VLCTrackSynchronizationWindowController.h"
38 #import "VLCResumeDialogController.h"
39 #import "VLCPlaylist.h"
40 #import "NSScreen+VLCAdditions.h"
41
42 static atomic_bool b_intf_starting = ATOMIC_VAR_INIT(false);
43
44 static int WindowControl(vout_window_t *, int i_query, va_list);
45
46 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
47 {
48     @autoreleasepool {
49         if (cfg->type != VOUT_WINDOW_TYPE_INVALID
50             && cfg->type != VOUT_WINDOW_TYPE_NSOBJECT)
51             return VLC_EGENERIC;
52
53         msg_Dbg(p_wnd, "Opening video window");
54
55         if (!atomic_load(&b_intf_starting)) {
56             msg_Err(p_wnd, "Cannot create vout as Mac OS X interface was not found");
57             return VLC_EGENERIC;
58         }
59
60         NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
61
62         VLCVoutWindowController *voutController = [[VLCMain sharedInstance] voutController];
63         if (!voutController) {
64             return VLC_EGENERIC;
65         }
66         [voutController.lock lock];
67
68         SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
69         NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[voutController methodSignatureForSelector:sel]];
70         [inv setTarget:voutController];
71         [inv setSelector:sel];
72         [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
73         [inv setArgument:&proposedVideoViewPosition atIndex:3];
74
75         [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
76                            waitUntilDone:YES];
77
78         VLCVoutView *videoView = nil;
79         [inv getReturnValue:&videoView];
80
81         // this method is not supposed to fail
82         assert(videoView != nil);
83
84         msg_Dbg(getIntf(), "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
85         p_wnd->handle.nsobject = (void *)CFBridgingRetain(videoView);
86
87         [voutController.lock unlock];
88
89         p_wnd->type = VOUT_WINDOW_TYPE_NSOBJECT;
90         p_wnd->control = WindowControl;
91     }
92     vout_window_SetFullScreen(p_wnd, cfg->is_fullscreen);
93     return VLC_SUCCESS;
94 }
95
96 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
97 {
98     @autoreleasepool {
99         VLCVoutWindowController *voutController = [[VLCMain sharedInstance] voutController];
100         if (!voutController) {
101             return VLC_EGENERIC;
102         }
103         [voutController.lock lock];
104
105         switch(i_query) {
106             case VOUT_WINDOW_SET_STATE:
107             {
108                 unsigned i_state = va_arg(args, unsigned);
109
110                 if (i_state & VOUT_WINDOW_STATE_BELOW)
111                 {
112                     msg_Dbg(p_wnd, "Ignore change to VOUT_WINDOW_STATE_BELOW");
113                     goto out;
114                 }
115
116                 NSInteger i_cooca_level = NSNormalWindowLevel;
117                 if (i_state & VOUT_WINDOW_STATE_ABOVE)
118                     i_cooca_level = NSStatusWindowLevel;
119
120                 dispatch_async(dispatch_get_main_queue(), ^{
121                     [voutController setWindowLevel:i_cooca_level forWindow:p_wnd];
122                 });
123
124                 break;
125             }
126             case VOUT_WINDOW_SET_SIZE:
127             {
128                 unsigned int i_width  = va_arg(args, unsigned int);
129                 unsigned int i_height = va_arg(args, unsigned int);
130
131                 dispatch_async(dispatch_get_main_queue(), ^{
132                     [voutController setNativeVideoSize:NSMakeSize(i_width, i_height)
133                                              forWindow:p_wnd];
134                 });
135
136                 break;
137             }
138             case VOUT_WINDOW_SET_FULLSCREEN:
139             {
140                 if (var_InheritBool(getIntf(), "video-wallpaper")) {
141                     msg_Dbg(p_wnd, "Ignore fullscreen event as video-wallpaper is on");
142                     goto out;
143                 }
144
145                 int i_full = va_arg(args, int);
146                 BOOL b_animation = YES;
147
148                 dispatch_async(dispatch_get_main_queue(), ^{
149                     [voutController setFullscreen:i_full
150                                         forWindow:p_wnd
151                                     withAnimation:b_animation];
152                 });
153
154                 break;
155             }
156             default:
157             {
158                 msg_Warn(p_wnd, "unsupported control query: %i", i_query );
159                 [voutController.lock unlock];
160                 return VLC_EGENERIC;
161             }
162         }
163
164         out:
165         [voutController.lock unlock];
166         return VLC_SUCCESS;
167     }
168 }
169
170 void WindowClose(vout_window_t *p_wnd)
171 {
172     @autoreleasepool {
173         VLCVoutWindowController *voutController = [[VLCMain sharedInstance] voutController];
174         if (!voutController) {
175             return;
176         }
177
178         [voutController.lock lock];
179         dispatch_async(dispatch_get_main_queue(), ^{
180             [voutController removeVoutForDisplay:[NSValue valueWithPointer:p_wnd]];
181         });
182         [voutController.lock unlock];
183     }
184 }
185
186 @interface VLCVoutWindowController ()
187 {
188     NSMutableDictionary *voutWindows;
189     VLCKeyboardBacklightControl *keyboardBacklight;
190
191     NSPoint topLeftPoint;
192
193     // save the status level if at least one video window is on status level
194     NSUInteger statusLevelWindowCounter;
195     NSInteger currentWindowLevel;
196
197     BOOL mainWindowHasVideo;
198 }
199 @end
200
201 @implementation VLCVoutWindowController
202
203 - (id)init
204 {
205     self = [super init];
206     if (self) {
207         atomic_store(&b_intf_starting, true);
208         voutWindows = [[NSMutableDictionary alloc] init];
209         keyboardBacklight = [[VLCKeyboardBacklightControl alloc] init];
210         currentWindowLevel = NSNormalWindowLevel;
211         _currentStatusWindowLevel = NSFloatingWindowLevel;
212     }
213     return self;
214 }
215
216 - (void)dealloc
217 {
218     NSArray *keys = [voutWindows allKeys];
219     for (NSValue *key in keys)
220         [self removeVoutForDisplay:key];
221
222     if (var_InheritBool(getIntf(), "macosx-dim-keyboard")) {
223         [keyboardBacklight switchLightsInstantly:YES];
224     }
225 }
226
227 #pragma mark -
228 #pragma mark Methods for vout provider
229
230 - (VLCVoutView *)setupVoutForWindow:(vout_window_t *)p_wnd withProposedVideoViewPosition:(NSRect)videoViewPosition
231 {
232     BOOL isEmbedded = YES;
233     BOOL isNativeFullscreen = [[VLCMain sharedInstance] nativeFullscreenMode];
234     BOOL windowDecorations = var_InheritBool(getIntf(), "video-deco");
235     BOOL videoWallpaper = var_InheritBool(getIntf(), "video-wallpaper");
236     BOOL multipleVoutWindows = [voutWindows count] > 0;
237     VLCVoutView *voutView;
238     VLCVideoWindowCommon *newVideoWindow;
239
240     // should be called before any window resizing occurs
241     if (!multipleVoutWindows)
242         [[[VLCMain sharedInstance] mainWindow] videoplayWillBeStarted];
243
244     if (multipleVoutWindows && videoWallpaper)
245         videoWallpaper = false;
246
247     // TODO: make lion fullscreen compatible with video-wallpaper
248     if ((videoWallpaper || !windowDecorations) && !isNativeFullscreen) {
249         // videoWallpaper is priorized over !windowDecorations
250
251         msg_Dbg(getIntf(), "Creating background / blank window");
252         NSScreen *screen = [NSScreen screenWithDisplayID:(CGDirectDisplayID)var_InheritInteger(getIntf(), "macosx-vdev")];
253         if (!screen)
254             screen = [[[VLCMain sharedInstance] mainWindow] screen];
255
256         NSRect window_rect;
257         if (videoWallpaper)
258             window_rect = [screen frame];
259         else
260             window_rect = [[[VLCMain sharedInstance] mainWindow] frame];
261
262         NSUInteger mask = NSBorderlessWindowMask;
263         if (!windowDecorations)
264             mask |= NSResizableWindowMask;
265
266         newVideoWindow = [[VLCVideoWindowCommon alloc] initWithContentRect:window_rect styleMask:mask backing:NSBackingStoreBuffered defer:YES];
267         [newVideoWindow setDelegate:newVideoWindow];
268         [newVideoWindow setReleasedWhenClosed: NO];
269
270         if (videoWallpaper)
271             [newVideoWindow setLevel:CGWindowLevelForKey(kCGDesktopWindowLevelKey) + 1];
272
273         [newVideoWindow setBackgroundColor: [NSColor blackColor]];
274         [newVideoWindow setCanBecomeKeyWindow: !videoWallpaper];
275         [newVideoWindow setCanBecomeMainWindow: !videoWallpaper];
276         [newVideoWindow setAcceptsMouseMovedEvents: !videoWallpaper];
277         [newVideoWindow setMovableByWindowBackground: !videoWallpaper];
278         [newVideoWindow useOptimizedDrawing: YES];
279
280         voutView = [[VLCVoutView alloc] initWithFrame:[[newVideoWindow contentView] bounds]];
281         [voutView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
282         [[newVideoWindow contentView] addSubview:voutView positioned:NSWindowAbove relativeTo:nil];
283         [newVideoWindow setVideoView:voutView];
284
285
286         if (videoWallpaper)
287             [newVideoWindow orderBack:nil];
288         else {
289             // no frame autosave for additional vout windows
290             if (!multipleVoutWindows) {
291                 // initial window position
292                 [newVideoWindow center];
293                 [newVideoWindow setFrameAutosaveName:@"extra-videowindow"];
294             }
295
296             [newVideoWindow setContentMinSize: NSMakeSize(f_min_video_height, f_min_video_height)];
297         }
298
299         isEmbedded = NO;
300     } else {
301         if ((var_InheritBool(getIntf(), "embedded-video") && !mainWindowHasVideo)) {
302             // setup embedded video
303             newVideoWindow = [[VLCMain sharedInstance] mainWindow] ;
304             voutView = [newVideoWindow videoView];
305             mainWindowHasVideo = YES;
306             isEmbedded = YES;
307         } else {
308             // setup detached window with controls
309             NSWindowController *o_controller = [[NSWindowController alloc] initWithWindowNibName:@"DetachedVideoWindow"];
310             [o_controller loadWindow];
311             newVideoWindow = (VLCDetachedVideoWindow *)[o_controller window];
312
313             // no frame autosave for additional vout windows
314             if (multipleVoutWindows)
315                 [newVideoWindow setFrameAutosaveName:@""];
316
317             [newVideoWindow setDelegate: newVideoWindow];
318             [newVideoWindow setLevel:NSNormalWindowLevel];
319             [newVideoWindow useOptimizedDrawing: YES];
320             voutView = [newVideoWindow videoView];
321             isEmbedded = NO;
322         }
323     }
324
325     NSSize videoViewSize = NSMakeSize(videoViewPosition.size.width, videoViewPosition.size.height);
326
327     // Avoid flashes if video will directly start in fullscreen
328     NSDisableScreenUpdates();
329
330     if (!videoWallpaper) {
331         // set (only!) window origin if specified
332         if (!isEmbedded) {
333             NSRect window_rect = [newVideoWindow frame];
334             if (videoViewPosition.origin.x > 0.)
335                 window_rect.origin.x = videoViewPosition.origin.x;
336             if (videoViewPosition.origin.y > 0.)
337                 window_rect.origin.y = videoViewPosition.origin.y;
338
339             [newVideoWindow setFrame:window_rect display:YES];
340         }
341
342         // cascade windows if we have more than one vout
343         if (multipleVoutWindows) {
344             if ([voutWindows count] == 1) {
345                 NSWindow * firstWindow = [voutWindows objectForKey: [[voutWindows allKeys] firstObject]];
346
347                 NSRect topleftBaseRect = NSMakeRect(0, [firstWindow frame].size.height, 0, 0);
348                 topLeftPoint = [firstWindow convertRectToScreen: topleftBaseRect].origin;
349             }
350
351             topLeftPoint = [newVideoWindow cascadeTopLeftFromPoint: topLeftPoint];
352             [newVideoWindow setFrameTopLeftPoint: topLeftPoint];
353         }
354
355         // resize window
356         [newVideoWindow setNativeVideoSize:videoViewSize];
357
358         [newVideoWindow makeKeyAndOrderFront: self];
359     }
360
361     [newVideoWindow setAlphaValue: config_GetFloat(getIntf(), "macosx-opaqueness")];
362
363     [voutView setVoutThread:(vout_thread_t *)p_wnd->obj.parent];
364     [newVideoWindow setHasActiveVideo: YES];
365     [voutWindows setObject:newVideoWindow forKey:[NSValue valueWithPointer:p_wnd]];
366
367     [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
368     [[[VLCMain sharedInstance] mainWindow] setNonembedded:!mainWindowHasVideo];
369
370     // beware of order, setActiveVideoPlayback:, setHasActiveVideo: and setNonembedded: must be called before
371     if ([newVideoWindow class] == [VLCMainWindow class])
372         [[[VLCMain sharedInstance] mainWindow] changePlaylistState: psVideoStartedOrStoppedEvent];
373
374     if (!isEmbedded) {
375         // events might be posted before window is created, so call them again
376         [[[VLCMain sharedInstance] mainWindow] updateName];
377         [[[VLCMain sharedInstance] mainWindow] updateWindow]; // update controls bar
378     }
379
380     // TODO: find a cleaner way for "start in fullscreen"
381     // Start in fs, because either prefs settings, or fullscreen button was pressed before
382     char *psz_splitter = var_GetString(pl_Get(getIntf()), "video-splitter");
383     BOOL b_have_splitter = psz_splitter != NULL && *psz_splitter != '\0';
384     free(psz_splitter);
385
386     if (!videoWallpaper && !b_have_splitter && (var_InheritBool(getIntf(), "fullscreen") || var_GetBool(pl_Get(getIntf()), "fullscreen"))) {
387
388         // this is not set when we start in fullscreen because of
389         // fullscreen settings in video prefs the second time
390         var_SetBool(p_wnd->obj.parent, "fullscreen", 1);
391
392         [self setFullscreen:1 forWindow:p_wnd withAnimation:NO];
393     }
394
395     NSEnableScreenUpdates();
396
397     return voutView;
398 }
399
400 - (void)removeVoutForDisplay:(NSValue *)o_key
401 {
402     VLCVideoWindowCommon *o_window = [voutWindows objectForKey:o_key];
403     if (!o_window) {
404         msg_Err(getIntf(), "Cannot close nonexisting window");
405         return;
406     }
407
408     [[o_window videoView] releaseVoutThread];
409
410     // set active video to no BEFORE closing the window and exiting fullscreen
411     // (avoid stopping playback due to NSWindowWillCloseNotification, preserving fullscreen state)
412     [o_window setHasActiveVideo: NO];
413
414     // prevent visible extra window if in fullscreen
415     NSDisableScreenUpdates();
416     BOOL b_native = [[[VLCMain sharedInstance] mainWindow] nativeFullscreenMode];
417
418     // close fullscreen, without changing fullscreen vars
419     if (!b_native && ([o_window fullscreen] || [o_window inFullscreenTransition]))
420         [o_window leaveFullscreenWithAnimation:NO];
421
422     // native fullscreen window will not be closed if
423     // fullscreen was triggered without video
424     if ((b_native && [o_window class] == [VLCMainWindow class] && [o_window fullscreen] && [o_window windowShouldExitFullscreenWhenFinished])) {
425         [o_window toggleFullScreen:self];
426     }
427
428     if ([o_window class] != [VLCMainWindow class]) {
429         [o_window close];
430     }
431     NSEnableScreenUpdates();
432
433     [voutWindows removeObjectForKey:o_key];
434     if ([voutWindows count] == 0) {
435         [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
436         statusLevelWindowCounter = 0;
437     }
438
439     if ([o_window class] == [VLCMainWindow class]) {
440         mainWindowHasVideo = NO;
441
442         // video in main window might get stopped while another vout is open
443         if ([voutWindows count] > 0)
444             [[[VLCMain sharedInstance] mainWindow] setNonembedded:YES];
445
446         // beware of order, setActiveVideoPlayback:, setHasActiveVideo: and setNonembedded: must be called before
447         [[[VLCMain sharedInstance] mainWindow] changePlaylistState: psVideoStartedOrStoppedEvent];
448     }
449 }
450
451
452 - (void)setNativeVideoSize:(NSSize)size forWindow:(vout_window_t *)p_wnd
453 {
454     VLCVideoWindowCommon *o_window = [voutWindows objectForKey:[NSValue valueWithPointer:p_wnd]];
455     if (!o_window) {
456         msg_Err(getIntf(), "Cannot set size for nonexisting window");
457         return;
458     }
459
460     [o_window setNativeVideoSize:size];
461 }
462
463 - (void)setWindowLevel:(NSInteger)i_level forWindow:(vout_window_t *)p_wnd
464 {
465     VLCVideoWindowCommon *o_window = [voutWindows objectForKey:[NSValue valueWithPointer:p_wnd]];
466     if (!o_window) {
467         msg_Err(getIntf(), "Cannot set level for nonexisting window");
468         return;
469     }
470
471     // only set level for helper windows to normal if no status vout window exist anymore
472     if(i_level == NSStatusWindowLevel) {
473         statusLevelWindowCounter++;
474         // window level need to stay on normal in fullscreen mode
475         if (![o_window fullscreen] && ![o_window inFullscreenTransition])
476             [self updateWindowLevelForHelperWindows:i_level];
477     } else {
478         if (statusLevelWindowCounter > 0)
479             statusLevelWindowCounter--;
480
481         if (statusLevelWindowCounter == 0) {
482             [self updateWindowLevelForHelperWindows:i_level];
483         }
484     }
485
486     [o_window setWindowLevel:i_level];
487 }
488
489 - (void)setFullscreen:(int)i_full forWindow:(vout_window_t *)p_wnd withAnimation:(BOOL)b_animation
490 {
491     intf_thread_t *p_intf = getIntf();
492     BOOL b_nativeFullscreenMode = [[VLCMain sharedInstance] nativeFullscreenMode];
493
494     if (!p_intf || (!b_nativeFullscreenMode && !p_wnd))
495         return;
496     playlist_t *p_playlist = pl_Get(p_intf);
497     BOOL b_fullscreen = i_full != 0;
498
499     if (!var_GetBool(p_playlist, "fullscreen") != !b_fullscreen)
500         var_SetBool(p_playlist, "fullscreen", b_fullscreen);
501
502     VLCVideoWindowCommon *o_current_window = nil;
503     if(p_wnd)
504         o_current_window = [voutWindows objectForKey:[NSValue valueWithPointer:p_wnd]];
505
506     if (var_InheritBool(p_intf, "macosx-dim-keyboard")) {
507         [keyboardBacklight switchLightsAsync:!b_fullscreen];
508     }
509
510     if (b_nativeFullscreenMode) {
511         if(!o_current_window)
512             o_current_window = [[VLCMain sharedInstance] mainWindow] ;
513         assert(o_current_window);
514
515         // fullscreen might be triggered twice (vout event)
516         // so ignore duplicate events here
517         if((b_fullscreen && !([o_current_window fullscreen] || [o_current_window inFullscreenTransition])) ||
518            (!b_fullscreen && [o_current_window fullscreen])) {
519
520             [o_current_window toggleFullScreen:self];
521         }
522     } else {
523         assert(o_current_window);
524
525         if (b_fullscreen) {
526             input_thread_t * p_input = pl_CurrentInput(p_intf);
527             if (p_input != NULL && [[VLCMain sharedInstance] activeVideoPlayback]) {
528                 // activate app, as method can also be triggered from outside the app (prevents nasty window layout)
529                 [NSApp activateIgnoringOtherApps:YES];
530                 [o_current_window enterFullscreenWithAnimation:b_animation];
531
532             }
533             if (p_input)
534                 vlc_object_release(p_input);
535         } else {
536             // leaving fullscreen is always allowed
537             [o_current_window leaveFullscreenWithAnimation:YES];
538         }
539     }
540 }
541
542 #pragma mark -
543 #pragma mark Misc methods
544
545 - (void)updateControlsBarsUsingBlock:(void (^)(VLCControlsBarCommon *controlsBar))block
546 {
547     [voutWindows enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
548
549         if ([obj respondsToSelector:@selector(controlsBar)]) {
550             VLCControlsBarCommon *o_controlsBar = [obj controlsBar];
551             if (o_controlsBar && block)
552                 block(o_controlsBar);
553         }
554     }];
555 }
556
557 - (void)updateWindowsUsingBlock:(void (^)(VLCVideoWindowCommon *o_window))windowUpdater
558 {
559     [voutWindows enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
560         if ([obj isKindOfClass: [NSWindow class]])
561             windowUpdater(obj);
562     }];
563 }
564
565 - (void)updateWindowLevelForHelperWindows:(NSInteger)i_level
566 {
567     if (var_InheritBool(getIntf(), "video-wallpaper"))
568         return;
569
570     currentWindowLevel = i_level;
571     if (i_level == NSNormalWindowLevel) {
572         _currentStatusWindowLevel = NSFloatingWindowLevel;
573     } else {
574         _currentStatusWindowLevel = i_level + 1;
575     }
576
577     NSInteger currentStatusWindowLevel = self.currentStatusWindowLevel;
578
579     VLCMain *main = [VLCMain sharedInstance];
580     [[[VLCMain sharedInstance] mainWindow] setWindowLevel:i_level];
581     [[main videoEffectsPanel] updateCocoaWindowLevel:currentStatusWindowLevel];
582     [[main audioEffectsPanel] updateCocoaWindowLevel:currentStatusWindowLevel];
583     [[main currentMediaInfoPanel] updateCocoaWindowLevel:currentStatusWindowLevel];
584     [[main bookmarks] updateCocoaWindowLevel:currentStatusWindowLevel];
585     [[main trackSyncPanel] updateCocoaWindowLevel:currentStatusWindowLevel];
586     [[main resumeDialog] updateCocoaWindowLevel:currentStatusWindowLevel];
587 }
588
589 @end