1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2009 the VideoLAN team
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
30 #include <stdlib.h> /* malloc(), free() */
31 #include <sys/param.h> /* for MAXPATHLEN */
33 #include <vlc_common.h>
35 #include <vlc_dialog.h>
36 #include <unistd.h> /* execl() */
37 #import <vlc_dialog.h>
44 #import "playlistinfo.h"
51 #import "coredialogs.h"
52 #import "embeddedwindow.h"
54 #import "AppleRemote.h"
56 #import "simple_prefs.h"
59 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
60 #import <IOKit/hidsystem/ev_keymap.h> /* for the media key support */
61 #import <Sparkle/Sparkle.h> /* we're the update delegate */
63 /*****************************************************************************
65 *****************************************************************************/
66 static void Run ( intf_thread_t *p_intf );
68 static void * ManageThread( void *user_data );
70 static unichar VLCKeyToCocoa( unsigned int i_key );
71 static unsigned int VLCModifiersToCocoa( unsigned int i_key );
73 static void updateProgressPanel (void *, const char *, float);
74 static bool checkProgressPanel (void *);
75 static void destroyProgressPanel (void *);
77 static void MsgCallback( msg_cb_data_t *, msg_item_t *, unsigned );
80 #pragma mark VLC Interface Object Callbacks
82 /*****************************************************************************
83 * OpenIntf: initialize interface
84 *****************************************************************************/
85 int OpenIntf ( vlc_object_t *p_this )
87 intf_thread_t *p_intf = (intf_thread_t*) p_this;
89 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
90 if( p_intf->p_sys == NULL )
93 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
95 /* subscribe to LibVLCCore's messages */
96 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
98 p_intf->b_should_run_on_first_thread = true;
103 /*****************************************************************************
104 * CloseIntf: destroy interface
105 *****************************************************************************/
106 void CloseIntf ( vlc_object_t *p_this )
108 intf_thread_t *p_intf = (intf_thread_t*) p_this;
110 free( p_intf->p_sys );
113 /*****************************************************************************
115 *****************************************************************************/
118 static void Run( intf_thread_t *p_intf )
122 /* Do it again - for some unknown reason, vlc_thread_create() often
123 * fails to go to real-time priority with the first launched thread
125 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
127 /* Make sure the "force quit" menu item does quit instantly.
128 * VLC overrides SIGTERM which is sent by the "force quit"
129 * menu item to make sure deamon mode quits gracefully, so
130 * we un-override SIGTERM here. */
132 sigaddset( &set, SIGTERM );
133 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
135 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
137 /* Install a jmpbuffer to where we can go back before the NSApp exit
138 * see applicationWillTerminate: */
139 [VLCApplication sharedApplication];
141 [[VLCMain sharedInstance] setIntf: p_intf];
142 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
144 /* Install a jmpbuffer to where we can go back before the NSApp exit
145 * see applicationWillTerminate: */
146 if(setjmp(jmpbuffer) == 0)
153 #pragma mark Variables Callback
155 /*****************************************************************************
156 * MsgCallback: Callback triggered by the core once a new debug message is
157 * ready to be displayed. We store everything in a NSArray in our Cocoa part
158 * of this file, so we are forwarding everything through notifications.
159 *****************************************************************************/
160 static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned int i )
162 int canc = vlc_savecancel();
163 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
165 /* this may happen from time to time, let's bail out as info would be useless anyway */
166 if( !item->psz_module || !item->psz_msg )
169 NSDictionary *o_dict = [NSDictionary dictionaryWithObjectsAndKeys:
170 [NSString stringWithUTF8String: item->psz_module], @"Module",
171 [NSString stringWithUTF8String: item->psz_msg], @"Message",
172 [NSNumber numberWithInt: item->i_type], @"Type", nil];
174 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCCoreMessageReceived"
179 vlc_restorecancel( canc );
182 /*****************************************************************************
183 * playlistChanged: Callback triggered by the intf-change playlist
184 * variable, to let the intf update the playlist.
185 *****************************************************************************/
186 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
187 vlc_value_t old_val, vlc_value_t new_val, void *param )
189 intf_thread_t * p_intf = VLCIntf;
190 if( p_intf && p_intf->p_sys )
192 p_intf->p_sys->b_intf_update = true;
193 p_intf->p_sys->b_playlist_update = true;
194 p_intf->p_sys->b_playmode_update = true;
195 p_intf->p_sys->b_current_title_update = true;
200 /*****************************************************************************
201 * ShowController: Callback triggered by the show-intf playlist variable
202 * through the ShowIntf-control-intf, to let us show the controller-win;
203 * usually when in fullscreen-mode
204 *****************************************************************************/
205 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
206 vlc_value_t old_val, vlc_value_t new_val, void *param )
208 intf_thread_t * p_intf = VLCIntf;
209 if( p_intf && p_intf->p_sys )
210 p_intf->p_sys->b_intf_show = true;
214 /*****************************************************************************
215 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
216 * variable, to let the intf update the controller.
217 *****************************************************************************/
218 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
219 vlc_value_t old_val, vlc_value_t new_val, void *param )
221 intf_thread_t * p_intf = VLCIntf;
222 if( p_intf && p_intf->p_sys )
223 p_intf->p_sys->b_fullscreen_update = true;
227 /*****************************************************************************
228 * DialogCallback: Callback triggered by the "dialog-*" variables
229 * to let the intf display error and interaction dialogs
230 *****************************************************************************/
231 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
233 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
234 VLCMain *interface = (VLCMain *)data;
236 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
238 /* the progress panel needs to update itself and therefore wants special treatment within this context */
239 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
241 p_dialog->pf_update = updateProgressPanel;
242 p_dialog->pf_check = checkProgressPanel;
243 p_dialog->pf_destroy = destroyProgressPanel;
244 p_dialog->p_sys = VLCIntf->p_libvlc;
247 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
248 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewCoreDialogEventNotification" object:[interface coreDialogProvider] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: o_value, @"VLCDialogPointer", [NSString stringWithUTF8String: type], @"VLCDialogType", nil]];
254 void updateProgressPanel (void *priv, const char *text, float value)
256 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
260 o_txt = [NSString stringWithUTF8String: text];
264 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
269 void destroyProgressPanel (void *priv)
271 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
272 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
276 bool checkProgressPanel (void *priv)
278 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
279 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
286 @interface VLCMain ()
287 - (void)_removeOldPreferences;
290 /*****************************************************************************
291 * VLCMain implementation
292 *****************************************************************************/
293 @implementation VLCMain
296 #pragma mark Initialization
298 static VLCMain *_o_sharedMainInstance = nil;
300 + (VLCMain *)sharedInstance
302 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
307 if( _o_sharedMainInstance)
310 return _o_sharedMainInstance;
313 _o_sharedMainInstance = [super init];
317 o_msg_lock = [[NSLock alloc] init];
318 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
319 /* subscribe to LibVLC's debug messages as early as possible (for us) */
320 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
322 o_about = [[VLAboutBox alloc] init];
324 o_open = [[VLCOpen alloc] init];
325 o_wizard = [[VLCWizard alloc] init];
326 o_vlm = [[VLCVLMController alloc] init];
328 o_bookmarks = [[VLCBookmarks alloc] init];
329 o_embedded_list = [[VLCEmbeddedList alloc] init];
330 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
331 o_info = [[VLCInfo alloc] init];
333 o_update = [[VLCUpdate alloc] init];
336 i_lastShownVolume = -1;
338 o_remote = [[AppleRemote alloc] init];
339 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
340 [o_remote setDelegate: _o_sharedMainInstance];
342 o_eyetv = [[VLCEyeTVController alloc] init];
344 /* announce our launch to a potential eyetv plugin */
345 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
346 object: @"VLCEyeTVSupport"
348 deliverImmediately: YES];
350 return _o_sharedMainInstance;
353 - (void)setIntf: (intf_thread_t *)p_mainintf {
357 - (intf_thread_t *)intf {
363 unsigned int i_key = 0;
364 playlist_t *p_playlist;
367 if( !p_intf ) return;
369 /* Check if we already did this once. Opening the other nibs calls it too,
370 because VLCMain is the owner */
371 if( nib_main_loaded ) return;
373 /* check whether the user runs a valid version of OS X */
374 if( MACOS_VERSION < 10.5f )
379 if( MACOS_VERSION == 10.4f )
380 o_blabla = _NS("VLC's last release for your OS is the 0.9 series." );
381 else if( MACOS_VERSION == 10.3f )
382 o_blabla = _NS("VLC's last release for your OS is VLC 0.8.6i, which is prone to known security issues." );
383 else // 10.2 and 10.1, still 3% of the OS X market share
384 o_blabla = _NS("VLC's last release for your OS is VLC 0.7.2, which is highly out of date and prone to " \
385 "known security issues. We recommend you to update your Mac to a modern version of Mac OS X.");
386 ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is no longer supported")
387 defaultButton: _NS("Quit")
388 alternateButton: NULL
390 informativeTextWithFormat: _NS("VLC media player %s requires Mac OS X 10.5 or higher.\n\n%@"), VLC_Version(), o_blabla];
391 [ourAlert setAlertStyle: NSCriticalAlertStyle];
392 i_returnValue = [ourAlert runModal];
393 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
399 [o_window setExcludedFromWindowsMenu: YES];
400 [o_msgs_panel setExcludedFromWindowsMenu: YES];
401 [o_msgs_panel setDelegate: self];
403 /* In code and not in Nib for 10.4 compat */
404 NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"mainControllerToolbar"] autorelease];
405 [toolbar setDelegate:self];
406 [toolbar setShowsBaselineSeparator:NO];
407 [toolbar setAllowsUserCustomization:NO];
408 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
409 [toolbar setAutosavesConfiguration:YES];
410 [o_window setToolbar:toolbar];
412 i_key = config_GetInt( p_intf, "key-quit" );
413 [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
414 [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
415 i_key = config_GetInt( p_intf, "key-play-pause" );
416 [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
417 [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
418 i_key = config_GetInt( p_intf, "key-stop" );
419 [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
420 [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
421 i_key = config_GetInt( p_intf, "key-faster" );
422 [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
423 [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
424 i_key = config_GetInt( p_intf, "key-slower" );
425 [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
426 [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
427 i_key = config_GetInt( p_intf, "key-prev" );
428 [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
429 [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
430 i_key = config_GetInt( p_intf, "key-next" );
431 [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
432 [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
433 i_key = config_GetInt( p_intf, "key-jump+short" );
434 [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
435 [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
436 i_key = config_GetInt( p_intf, "key-jump-short" );
437 [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
438 [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
439 i_key = config_GetInt( p_intf, "key-jump+medium" );
440 [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
441 [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
442 i_key = config_GetInt( p_intf, "key-jump-medium" );
443 [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
444 [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
445 i_key = config_GetInt( p_intf, "key-jump+long" );
446 [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
447 [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
448 i_key = config_GetInt( p_intf, "key-jump-long" );
449 [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
450 [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
451 i_key = config_GetInt( p_intf, "key-vol-up" );
452 [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
453 [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
454 i_key = config_GetInt( p_intf, "key-vol-down" );
455 [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
456 [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
457 i_key = config_GetInt( p_intf, "key-vol-mute" );
458 [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
459 [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
460 i_key = config_GetInt( p_intf, "key-fullscreen" );
461 [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
462 [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
463 i_key = config_GetInt( p_intf, "key-snapshot" );
464 [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
465 [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
466 i_key = config_GetInt( p_intf, "key-random" );
467 [o_mi_random setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
468 [o_mi_random setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
469 i_key = config_GetInt( p_intf, "key-zoom-half" );
470 [o_mi_half_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
471 [o_mi_half_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
472 i_key = config_GetInt( p_intf, "key-zoom-original" );
473 [o_mi_normal_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
474 [o_mi_normal_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
475 i_key = config_GetInt( p_intf, "key-zoom-double" );
476 [o_mi_double_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
477 [o_mi_double_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
479 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
481 [self setSubmenusEnabled: FALSE];
482 [o_volumeslider setEnabled: YES];
483 [self manageVolumeSlider];
484 [o_window setDelegate: self];
486 b_restore_size = false;
488 // Set that here as IB seems to be buggy
489 [o_window setContentMinSize:NSMakeSize(338., 30.)];
491 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
493 b_small_window = YES;
494 [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
495 [o_window frame].origin.y, [o_window frame].size.width,
496 [o_window minSize].height ) display: YES animate:YES];
497 [o_playlist_view setAutoresizesSubviews: NO];
502 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
503 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
504 [o_playlist_view setNeedsDisplay:YES];
505 [o_playlist_view setAutoresizesSubviews: YES];
506 [[o_window contentView] addSubview: o_playlist_view];
509 [self updateTogglePlaylistState];
511 o_size_with_playlist = [o_window contentRectForFrameRect:[o_window frame]].size;
513 p_playlist = pl_Hold( p_intf );
515 var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
518 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
519 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
521 pl_Release( p_intf );
523 /* load our Core Dialogs nib */
524 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
526 /* subscribe to various interactive dialogues */
527 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
528 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
529 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
530 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
531 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
532 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
533 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
534 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
535 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
536 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
537 dialog_Register( p_intf );
539 /* update the playmode stuff */
540 p_intf->p_sys->b_playmode_update = true;
542 [[NSNotificationCenter defaultCenter] addObserver: self
543 selector: @selector(refreshVoutDeviceMenu:)
544 name: NSApplicationDidChangeScreenParametersNotification
547 /* take care of tint changes during runtime */
548 o_img_play = [NSImage imageNamed: @"play"];
549 o_img_pause = [NSImage imageNamed: @"pause"];
550 [self controlTintChanged];
551 [[NSNotificationCenter defaultCenter] addObserver: self
552 selector: @selector( controlTintChanged )
553 name: NSControlTintDidChangeNotification
556 /* yeah, we are done */
557 nib_main_loaded = TRUE;
560 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
562 if( !p_intf ) return;
564 /* FIXME: don't poll */
565 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
566 target: self selector: @selector(manageIntf:)
567 userInfo: nil repeats: FALSE] retain];
569 /* Note: we use the pthread API to support pre-10.5 */
570 pthread_create( &manage_thread, NULL, ManageThread, self );
572 [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
573 var: "intf-add" selector: @selector(toggleVar:)];
575 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
578 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
580 if( !p_intf ) return;
582 [self _removeOldPreferences];
585 /* Check for update silently on startup */
586 if( !nib_update_loaded )
587 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
589 if([o_update shouldCheckForUpdate])
590 [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:nil];
593 /* Handle sleep notification */
594 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
595 name:NSWorkspaceWillSleepNotification object:nil];
597 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
602 if( !p_intf ) return;
604 [o_window setTitle: _NS("VLC media player")];
605 [self setScrollField:_NS("VLC media player") stopAfter:-1];
607 /* button controls */
608 [o_btn_prev setToolTip: _NS("Previous")];
609 [o_btn_rewind setToolTip: _NS("Rewind")];
610 [o_btn_play setToolTip: _NS("Play")];
611 [o_btn_stop setToolTip: _NS("Stop")];
612 [o_btn_ff setToolTip: _NS("Fast Forward")];
613 [o_btn_next setToolTip: _NS("Next")];
614 [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
615 [o_volumeslider setToolTip: _NS("Volume")];
616 [o_timeslider setToolTip: _NS("Position")];
617 [o_btn_playlist setToolTip: _NS("Playlist")];
620 [o_msgs_panel setTitle: _NS("Messages")];
621 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
622 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
625 [o_mi_about setTitle: [_NS("About VLC media player") \
626 stringByAppendingString: @"..."]];
627 [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
628 [o_mi_prefs setTitle: _NS("Preferences...")];
629 [o_mi_add_intf setTitle: _NS("Add Interface")];
630 [o_mu_add_intf setTitle: _NS("Add Interface")];
631 [o_mi_services setTitle: _NS("Services")];
632 [o_mi_hide setTitle: _NS("Hide VLC")];
633 [o_mi_hide_others setTitle: _NS("Hide Others")];
634 [o_mi_show_all setTitle: _NS("Show All")];
635 [o_mi_quit setTitle: _NS("Quit VLC")];
637 [o_mu_file setTitle: _ANS("1:File")];
638 [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
639 [o_mi_open_file setTitle: _NS("Open File...")];
640 [o_mi_open_disc setTitle: _NS("Open Disc...")];
641 [o_mi_open_net setTitle: _NS("Open Network...")];
642 [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
643 [o_mi_open_recent setTitle: _NS("Open Recent")];
644 [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
645 [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
647 [o_mu_edit setTitle: _NS("Edit")];
648 [o_mi_cut setTitle: _NS("Cut")];
649 [o_mi_copy setTitle: _NS("Copy")];
650 [o_mi_paste setTitle: _NS("Paste")];
651 [o_mi_clear setTitle: _NS("Clear")];
652 [o_mi_select_all setTitle: _NS("Select All")];
654 [o_mu_controls setTitle: _NS("Playback")];
655 [o_mi_play setTitle: _NS("Play")];
656 [o_mi_stop setTitle: _NS("Stop")];
657 [o_mi_faster setTitle: _NS("Faster")];
658 [o_mi_slower setTitle: _NS("Slower")];
659 [o_mi_previous setTitle: _NS("Previous")];
660 [o_mi_next setTitle: _NS("Next")];
661 [o_mi_random setTitle: _NS("Random")];
662 [o_mi_repeat setTitle: _NS("Repeat One")];
663 [o_mi_loop setTitle: _NS("Repeat All")];
664 [o_mi_fwd setTitle: _NS("Step Forward")];
665 [o_mi_bwd setTitle: _NS("Step Backward")];
667 [o_mi_program setTitle: _NS("Program")];
668 [o_mu_program setTitle: _NS("Program")];
669 [o_mi_title setTitle: _NS("Title")];
670 [o_mu_title setTitle: _NS("Title")];
671 [o_mi_chapter setTitle: _NS("Chapter")];
672 [o_mu_chapter setTitle: _NS("Chapter")];
674 [o_mu_audio setTitle: _NS("Audio")];
675 [o_mi_vol_up setTitle: _NS("Increase Volume")];
676 [o_mi_vol_down setTitle: _NS("Decrease Volume")];
677 [o_mi_mute setTitle: _NS("Mute")];
678 [o_mi_audiotrack setTitle: _NS("Audio Track")];
679 [o_mu_audiotrack setTitle: _NS("Audio Track")];
680 [o_mi_channels setTitle: _NS("Audio Channels")];
681 [o_mu_channels setTitle: _NS("Audio Channels")];
682 [o_mi_device setTitle: _NS("Audio Device")];
683 [o_mu_device setTitle: _NS("Audio Device")];
684 [o_mi_visual setTitle: _NS("Visualizations")];
685 [o_mu_visual setTitle: _NS("Visualizations")];
687 [o_mu_video setTitle: _NS("Video")];
688 [o_mi_half_window setTitle: _NS("Half Size")];
689 [o_mi_normal_window setTitle: _NS("Normal Size")];
690 [o_mi_double_window setTitle: _NS("Double Size")];
691 [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
692 [o_mi_fullscreen setTitle: _NS("Fullscreen")];
693 [o_mi_floatontop setTitle: _NS("Float on Top")];
694 [o_mi_snapshot setTitle: _NS("Snapshot")];
695 [o_mi_videotrack setTitle: _NS("Video Track")];
696 [o_mu_videotrack setTitle: _NS("Video Track")];
697 [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
698 [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
699 [o_mi_crop setTitle: _NS("Crop")];
700 [o_mu_crop setTitle: _NS("Crop")];
701 [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
702 [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
703 [o_mi_subtitle setTitle: _NS("Subtitles Track")];
704 [o_mu_subtitle setTitle: _NS("Subtitles Track")];
705 [o_mi_addSub setTitle: _NS("Open File...")];
706 [o_mi_deinterlace setTitle: _NS("Deinterlace")];
707 [o_mu_deinterlace setTitle: _NS("Deinterlace")];
708 [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
709 [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
710 [o_mi_teletext setTitle: _NS("Teletext")];
711 [o_mi_teletext_transparent setTitle: _NS("Transparent")];
712 [o_mi_teletext_index setTitle: _NS("Index")];
713 [o_mi_teletext_red setTitle: _NS("Red")];
714 [o_mi_teletext_green setTitle: _NS("Green")];
715 [o_mi_teletext_yellow setTitle: _NS("Yellow")];
716 [o_mi_teletext_blue setTitle: _NS("Blue")];
718 [o_mu_window setTitle: _NS("Window")];
719 [o_mi_minimize setTitle: _NS("Minimize Window")];
720 [o_mi_close_window setTitle: _NS("Close Window")];
721 [o_mi_player setTitle: _NS("Player...")];
722 [o_mi_controller setTitle: _NS("Controller...")];
723 [o_mi_equalizer setTitle: _NS("Equalizer...")];
724 [o_mi_extended setTitle: _NS("Extended Controls...")];
725 [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
726 [o_mi_playlist setTitle: _NS("Playlist...")];
727 [o_mi_info setTitle: _NS("Media Information...")];
728 [o_mi_messages setTitle: _NS("Messages...")];
729 [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
731 [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
733 [o_mu_help setTitle: _NS("Help")];
734 [o_mi_help setTitle: _NS("VLC media player Help...")];
735 [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
736 [o_mi_license setTitle: _NS("License")];
737 [o_mi_documentation setTitle: _NS("Online Documentation...")];
738 [o_mi_website setTitle: _NS("VideoLAN Website...")];
739 [o_mi_donation setTitle: _NS("Make a donation...")];
740 [o_mi_forum setTitle: _NS("Online Forum...")];
743 [o_dmi_play setTitle: _NS("Play")];
744 [o_dmi_stop setTitle: _NS("Stop")];
745 [o_dmi_next setTitle: _NS("Next")];
746 [o_dmi_previous setTitle: _NS("Previous")];
747 [o_dmi_mute setTitle: _NS("Mute")];
750 [o_vmi_play setTitle: _NS("Play")];
751 [o_vmi_stop setTitle: _NS("Stop")];
752 [o_vmi_prev setTitle: _NS("Previous")];
753 [o_vmi_next setTitle: _NS("Next")];
754 [o_vmi_volup setTitle: _NS("Volume Up")];
755 [o_vmi_voldown setTitle: _NS("Volume Down")];
756 [o_vmi_mute setTitle: _NS("Mute")];
757 [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
758 [o_vmi_snapshot setTitle: _NS("Snapshot")];
760 /* crash reporter panel */
761 [o_crashrep_send_btn setTitle: _NS("Send")];
762 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
763 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
764 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
765 [o_crashrep_desc_txt setStringValue: _NS("Do you want to send details on the crash to VLC's development team?\n\nIf you want, you can enter a few lines on what you did before VLC crashed along with other helpful information: a link to download a sample file, a URL of a network stream, ...")];
766 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
767 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
771 #pragma mark Termination
773 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
775 if( !p_intf ) return;
777 NSArray *menuitems_array = [the_menu itemArray];
778 for( int i=0; i<[menuitems_array count]; i++ )
780 NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
781 if( [one_item hasSubmenu] )
782 [self releaseRepresentedObjects: [one_item submenu]];
784 [one_item setRepresentedObject:NULL];
788 - (void)applicationWillTerminate:(NSNotification *)notification
790 playlist_t * p_playlist;
791 vout_thread_t * p_vout;
792 int returnedValue = 0;
794 if( !p_intf ) return;
796 msg_Dbg( p_intf, "Terminating" );
798 /* Make sure the manage_thread won't call -terminate: again */
799 pthread_cancel( manage_thread );
801 /* Make sure the intf object is getting killed */
802 vlc_object_kill( p_intf );
804 /* Make sure our manage_thread ends */
805 pthread_join( manage_thread, NULL );
807 /* Make sure the interfaceTimer is destroyed */
808 [interfaceTimer invalidate];
809 [interfaceTimer release];
810 interfaceTimer = nil;
812 /* make sure that the current volume is saved */
813 config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
815 /* save the prefs if they were changed in the extended panel */
816 if(o_extended && [o_extended configChanged])
818 [o_extended savePrefs];
821 /* unsubscribe from the interactive dialogues */
822 dialog_Unregister( p_intf );
823 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
824 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
825 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
826 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
827 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
829 /* remove global observer watching for vout device changes correctly */
830 [[NSNotificationCenter defaultCenter] removeObserver: self];
836 /* release some other objects here, because it isn't sure whether dealloc
837 * will be called later on */
838 if( nib_about_loaded )
841 if( nib_prefs_loaded )
847 if( nib_open_loaded )
850 if( nib_extended_loaded )
852 [o_extended release];
855 if( nib_bookmarks_loaded )
856 [o_bookmarks release];
864 if( nib_wizard_loaded )
867 [crashLogURLConnection cancel];
868 [crashLogURLConnection release];
870 [o_embedded_list release];
871 [o_coredialogs release];
874 [o_img_pause_pressed release];
875 [o_img_play_pressed release];
876 [o_img_pause release];
877 [o_img_play release];
879 /* unsubscribe from libvlc's debug messages */
880 msg_Unsubscribe( p_intf->p_sys->p_sub );
882 [o_msg_arr removeAllObjects];
885 [o_msg_lock release];
887 /* write cached user defaults to disk */
888 [[NSUserDefaults standardUserDefaults] synchronize];
890 /* Make sure the Menu doesn't have any references to vlc objects anymore */
891 [self releaseRepresentedObjects:[NSApp mainMenu]];
893 /* Kill the playlist, so that it doesn't accept new request
894 * such as the play request from vlc.c (we are a blocking interface). */
895 p_playlist = pl_Hold( p_intf );
896 vlc_object_kill( p_playlist );
897 pl_Release( p_intf );
899 libvlc_Quit( p_intf->p_libvlc );
903 /* Go back to Run() and make libvlc exit properly */
905 longjmp( jmpbuffer, 1 );
910 #pragma mark Sparkle delegate
911 /* received directly before the update gets installed, so let's shut down a bit */
912 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
914 [o_remote stopListening: self];
915 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
917 /* Close the window directly, because we do know that there
918 * won't be anymore video. It's currently waiting a bit. */
919 [[[o_controls voutView] window] orderOut:self];
923 #pragma mark Toolbar delegate
925 /* Our item identifiers */
926 static NSString * VLCToolbarMediaControl = @"VLCToolbarMediaControl";
928 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
930 return [NSArray arrayWithObjects:
931 // NSToolbarCustomizeToolbarItemIdentifier,
932 // NSToolbarFlexibleSpaceItemIdentifier,
933 // NSToolbarSpaceItemIdentifier,
934 // NSToolbarSeparatorItemIdentifier,
935 VLCToolbarMediaControl,
939 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
941 return [NSArray arrayWithObjects:
942 VLCToolbarMediaControl,
946 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
948 NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
950 if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
952 [toolbarItem setLabel:@"Media Controls"];
953 [toolbarItem setPaletteLabel:@"Media Controls"];
955 NSSize size = toolbarMediaControl.frame.size;
956 [toolbarItem setView:toolbarMediaControl];
957 [toolbarItem setMinSize:size];
959 [toolbarItem setMaxSize:size];
961 // Hack: For some reason we need to make sure
962 // that the those element are on top
963 // Add them again will put them frontmost
964 [toolbarMediaControl addSubview:o_scrollfield];
965 [toolbarMediaControl addSubview:o_timeslider];
966 [toolbarMediaControl addSubview:o_timefield];
967 [toolbarMediaControl addSubview:o_main_pgbar];
969 /* TODO: setup a menu */
973 /* itemIdentifier referred to a toolbar item that is not
974 * provided or supported by us or Cocoa
975 * Returning nil will inform the toolbar
976 * that this kind of item is not supported */
983 #pragma mark Other notification
985 - (void)controlTintChanged
989 if( [o_btn_play alternateImage] == o_img_play_pressed )
992 if( [NSColor currentControlTint] == NSGraphiteControlTint )
994 o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
995 o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
997 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
998 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
999 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
1000 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
1001 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
1002 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
1003 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
1004 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
1008 o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
1009 o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
1011 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
1012 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
1013 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
1014 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
1015 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
1016 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
1017 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
1018 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
1022 [o_btn_play setAlternateImage: o_img_play_pressed];
1024 [o_btn_play setAlternateImage: o_img_pause_pressed];
1027 /* Listen to the remote in exclusive mode, only when VLC is the active
1029 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1031 if( !p_intf ) return;
1032 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
1033 [o_remote startListening: self];
1035 - (void)applicationDidResignActive:(NSNotification *)aNotification
1037 if( !p_intf ) return;
1038 [o_remote stopListening: self];
1041 /* Triggered when the computer goes to sleep */
1042 - (void)computerWillSleep: (NSNotification *)notification
1045 if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
1047 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
1052 #pragma mark File opening
1054 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
1056 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
1057 NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
1059 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
1061 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
1066 /* When user click in the Dock icon our double click in the finder */
1067 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1069 if(!hasVisibleWindows)
1070 [o_window makeKeyAndOrderFront:self];
1076 #pragma mark Apple Remote Control
1078 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1079 increase/decrease as long as the user holds the left/right, plus/minus button */
1080 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1082 if(b_remote_button_hold)
1084 switch([buttonIdentifierNumber intValue])
1086 case kRemoteButtonRight_Hold:
1087 [o_controls forward: self];
1089 case kRemoteButtonLeft_Hold:
1090 [o_controls backward: self];
1092 case kRemoteButtonVolume_Plus_Hold:
1093 [o_controls volumeUp: self];
1095 case kRemoteButtonVolume_Minus_Hold:
1096 [o_controls volumeDown: self];
1099 if(b_remote_button_hold)
1102 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1103 withObject:buttonIdentifierNumber
1109 /* Apple Remote callback */
1110 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1111 pressedDown: (BOOL) pressedDown
1112 clickCount: (unsigned int) count
1114 switch( buttonIdentifier )
1116 case kRemoteButtonPlay:
1118 [o_controls toogleFullscreen:self];
1120 [o_controls play: self];
1123 case kRemoteButtonVolume_Plus:
1124 [o_controls volumeUp: self];
1126 case kRemoteButtonVolume_Minus:
1127 [o_controls volumeDown: self];
1129 case kRemoteButtonRight:
1130 [o_controls next: self];
1132 case kRemoteButtonLeft:
1133 [o_controls prev: self];
1135 case kRemoteButtonRight_Hold:
1136 case kRemoteButtonLeft_Hold:
1137 case kRemoteButtonVolume_Plus_Hold:
1138 case kRemoteButtonVolume_Minus_Hold:
1139 /* simulate an event as long as the user holds the button */
1140 b_remote_button_hold = pressedDown;
1143 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1144 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1145 withObject:buttonIdentifierNumber];
1148 case kRemoteButtonMenu:
1149 [o_controls showPosition: self];
1152 /* Add here whatever you want other buttons to do */
1158 #pragma mark String utility
1159 // FIXME: this has nothing to do here
1161 - (NSString *)localizedString:(const char *)psz
1163 NSString * o_str = nil;
1167 o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1171 msg_Err( VLCIntf, "could not translate: %s", psz );
1177 msg_Warn( VLCIntf, "can't translate empty strings" );
1186 - (char *)delocalizeString:(NSString *)id
1188 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1189 allowLossyConversion: NO];
1194 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1195 allowLossyConversion: YES];
1196 psz_string = malloc( [o_data length] + 1 );
1197 [o_data getBytes: psz_string];
1198 psz_string[ [o_data length] ] = '\0';
1199 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1204 psz_string = malloc( [o_data length] + 1 );
1205 [o_data getBytes: psz_string];
1206 psz_string[ [o_data length] ] = '\0';
1212 /* i_width is in pixels */
1213 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1215 NSMutableString *o_wrapped;
1216 NSString *o_out_string;
1217 NSRange glyphRange, effectiveRange, charRange;
1218 NSRect lineFragmentRect;
1219 unsigned glyphIndex, breaksInserted = 0;
1221 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1222 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1223 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1224 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1225 NSTextContainer *o_container = [[NSTextContainer alloc]
1226 initWithContainerSize: NSMakeSize(i_width, 2000)];
1228 [o_layout_manager addTextContainer: o_container];
1229 [o_container release];
1230 [o_storage addLayoutManager: o_layout_manager];
1231 [o_layout_manager release];
1233 o_wrapped = [o_in_string mutableCopy];
1234 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1236 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1237 glyphIndex += effectiveRange.length) {
1238 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1239 effectiveRange: &effectiveRange];
1240 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1241 actualGlyphRange: &effectiveRange];
1242 if([o_wrapped lineRangeForRange:
1243 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1244 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1248 o_out_string = [NSString stringWithString: o_wrapped];
1249 [o_wrapped release];
1250 [o_storage release];
1252 return o_out_string;
1257 #pragma mark Key Shortcuts
1262 unsigned int i_vlckey;
1263 } nskeys_to_vlckeys[] =
1265 { NSUpArrowFunctionKey, KEY_UP },
1266 { NSDownArrowFunctionKey, KEY_DOWN },
1267 { NSLeftArrowFunctionKey, KEY_LEFT },
1268 { NSRightArrowFunctionKey, KEY_RIGHT },
1269 { NSF1FunctionKey, KEY_F1 },
1270 { NSF2FunctionKey, KEY_F2 },
1271 { NSF3FunctionKey, KEY_F3 },
1272 { NSF4FunctionKey, KEY_F4 },
1273 { NSF5FunctionKey, KEY_F5 },
1274 { NSF6FunctionKey, KEY_F6 },
1275 { NSF7FunctionKey, KEY_F7 },
1276 { NSF8FunctionKey, KEY_F8 },
1277 { NSF9FunctionKey, KEY_F9 },
1278 { NSF10FunctionKey, KEY_F10 },
1279 { NSF11FunctionKey, KEY_F11 },
1280 { NSF12FunctionKey, KEY_F12 },
1281 { NSInsertFunctionKey, KEY_INSERT },
1282 { NSHomeFunctionKey, KEY_HOME },
1283 { NSEndFunctionKey, KEY_END },
1284 { NSPageUpFunctionKey, KEY_PAGEUP },
1285 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1286 { NSMenuFunctionKey, KEY_MENU },
1287 { NSTabCharacter, KEY_TAB },
1288 { NSCarriageReturnCharacter, KEY_ENTER },
1289 { NSEnterCharacter, KEY_ENTER },
1290 { NSBackspaceCharacter, KEY_BACKSPACE },
1291 { (unichar) ' ', KEY_SPACE },
1292 { (unichar) 0x1b, KEY_ESC },
1296 static unichar VLCKeyToCocoa( unsigned int i_key )
1300 for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1302 if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1304 return nskeys_to_vlckeys[i].i_nskey;
1307 return (unichar)(i_key & ~KEY_MODIFIER);
1310 unsigned int CocoaKeyToVLC( unichar i_key )
1314 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1316 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1318 return nskeys_to_vlckeys[i].i_vlckey;
1321 return (unsigned int)i_key;
1324 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1326 unsigned int new = 0;
1327 if( i_key & KEY_MODIFIER_COMMAND )
1328 new |= NSCommandKeyMask;
1329 if( i_key & KEY_MODIFIER_ALT )
1330 new |= NSAlternateKeyMask;
1331 if( i_key & KEY_MODIFIER_SHIFT )
1332 new |= NSShiftKeyMask;
1333 if( i_key & KEY_MODIFIER_CTRL )
1334 new |= NSControlKeyMask;
1338 /*****************************************************************************
1339 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1340 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1341 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1342 *****************************************************************************/
1343 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1347 unsigned int i_pressed_modifiers = 0;
1348 const struct hotkey *p_hotkeys;
1352 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1354 i_pressed_modifiers = [o_event modifierFlags];
1356 if( i_pressed_modifiers & NSShiftKeyMask )
1357 val.i_int |= KEY_MODIFIER_SHIFT;
1358 if( i_pressed_modifiers & NSControlKeyMask )
1359 val.i_int |= KEY_MODIFIER_CTRL;
1360 if( i_pressed_modifiers & NSAlternateKeyMask )
1361 val.i_int |= KEY_MODIFIER_ALT;
1362 if( i_pressed_modifiers & NSCommandKeyMask )
1363 val.i_int |= KEY_MODIFIER_COMMAND;
1365 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1369 case NSDeleteCharacter:
1370 case NSDeleteFunctionKey:
1371 case NSDeleteCharFunctionKey:
1372 case NSBackspaceCharacter:
1373 case NSUpArrowFunctionKey:
1374 case NSDownArrowFunctionKey:
1375 case NSRightArrowFunctionKey:
1376 case NSLeftArrowFunctionKey:
1377 case NSEnterCharacter:
1378 case NSCarriageReturnCharacter:
1382 val.i_int |= CocoaKeyToVLC( key );
1384 for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1386 if( p_hotkeys[i].i_key == val.i_int )
1388 var_Set( p_intf->p_libvlc, "key-pressed", val );
1397 #pragma mark Other objects getters
1407 - (id)simplePreferences
1412 if( !nib_prefs_loaded )
1413 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1423 if( !nib_prefs_loaded )
1424 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1437 - (BOOL)isPlaylistCollapsed
1439 return ![o_btn_playlist state];
1473 if( o_embedded_list )
1474 return o_embedded_list;
1479 - (id)coreDialogProvider
1482 return o_coredialogs;
1490 return o_main_pgbar;
1495 - (id)controllerWindow
1507 - (id)eyeTVController
1515 - (id)appleRemoteController
1521 #pragma mark Polling
1523 /*****************************************************************************
1524 * ManageThread: An ugly thread that polls
1525 *****************************************************************************/
1526 static void * ManageThread( void *user_data )
1528 id self = user_data;
1535 struct manage_cleanup_stack {
1536 intf_thread_t * p_intf;
1537 input_thread_t ** p_input;
1538 playlist_t * p_playlist;
1542 static void manage_cleanup( void * args )
1544 struct manage_cleanup_stack * manage_cleanup_stack = args;
1545 intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1546 input_thread_t * p_input = *manage_cleanup_stack->p_input;
1547 id self = manage_cleanup_stack->self;
1548 playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1550 var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1551 var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1552 var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1553 var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1554 var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1556 pl_Release( p_intf );
1558 if( p_input ) vlc_object_release( p_input );
1563 playlist_t * p_playlist;
1564 input_thread_t * p_input = NULL;
1566 /* new thread requires a new pool */
1568 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1570 p_playlist = pl_Hold( p_intf );
1572 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1573 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1574 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1575 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1576 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1578 struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1579 pthread_cleanup_push(manage_cleanup, &stack);
1583 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1587 p_input = playlist_CurrentInput( p_playlist );
1589 /* Refresh the interface */
1592 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1593 p_intf->p_sys->b_input_update = true;
1596 else if( !vlc_object_alive (p_input) || p_input->b_dead )
1599 p_intf->p_sys->b_intf_update = true;
1600 p_intf->p_sys->i_play_status = END_S;
1601 msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1602 vlc_object_release( p_input );
1605 else if( cachedInputState != input_GetState( p_input ) )
1607 p_intf->p_sys->b_intf_update = true;
1610 /* Manage volume status */
1611 [self manageVolumeSlider];
1613 msleep( INTF_IDLE_SLEEP );
1618 pthread_cleanup_pop(1);
1620 msg_Dbg( p_intf, "Killing the Mac OS X module" );
1622 /* We are dead, terminate */
1623 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1626 - (void)manageVolumeSlider
1628 audio_volume_t i_volume;
1629 playlist_t * p_playlist = pl_Hold( p_intf );
1631 aout_VolumeGet( p_playlist, &i_volume );
1632 pl_Release( p_intf );
1634 if( i_volume != i_lastShownVolume )
1636 i_lastShownVolume = i_volume;
1637 p_intf->p_sys->b_volume_update = TRUE;
1641 - (void)manageIntf:(NSTimer *)o_timer
1644 playlist_t * p_playlist;
1645 input_thread_t * p_input;
1647 if( p_intf->p_sys->b_input_update )
1649 /* Called when new input is opened */
1650 p_intf->p_sys->b_current_title_update = true;
1651 p_intf->p_sys->b_intf_update = true;
1652 p_intf->p_sys->b_input_update = false;
1653 [self setupMenus]; /* Make sure input menu is up to date */
1655 /* update our info-panel to reflect the new item, if we don't show
1656 * the playlist or the selection is empty */
1657 if( [self isPlaylistCollapsed] == YES )
1659 playlist_t * p_playlist = pl_Hold( p_intf );
1661 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1664 [[self info] updatePanelWithItem: p_item->p_input];
1665 pl_Release( p_intf );
1668 if( p_intf->p_sys->b_intf_update )
1670 bool b_input = false;
1671 bool b_plmul = false;
1672 bool b_control = false;
1673 bool b_seekable = false;
1674 bool b_chapters = false;
1676 playlist_t * p_playlist = pl_Hold( p_intf );
1679 b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1682 p_input = playlist_CurrentInput( p_playlist );
1684 bool b_buffering = NO;
1686 if( ( b_input = ( p_input != NULL ) ) )
1688 /* seekable streams */
1689 cachedInputState = input_GetState( p_input );
1690 if ( cachedInputState == INIT_S ||
1691 cachedInputState == OPENING_S )
1696 /* seekable streams */
1697 b_seekable = var_GetBool( p_input, "can-seek" );
1699 /* check whether slow/fast motion is possible */
1700 b_control = var_GetBool( p_input, "can-rate" );
1702 /* chapters & titles */
1703 //b_chapters = p_input->stream.i_area_nb > 1;
1704 vlc_object_release( p_input );
1706 pl_Release( p_intf );
1710 [o_main_pgbar startAnimation:self];
1711 [o_main_pgbar setIndeterminate:YES];
1712 [o_main_pgbar setHidden:NO];
1716 [o_main_pgbar stopAnimation:self];
1717 [o_main_pgbar setHidden:YES];
1720 [o_btn_stop setEnabled: b_input];
1721 [o_embedded_window setStop: b_input];
1722 [o_btn_ff setEnabled: b_seekable];
1723 [o_btn_rewind setEnabled: b_seekable];
1724 [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1725 [o_embedded_window setPrev: (b_plmul || b_chapters)];
1726 [o_btn_next setEnabled: (b_plmul || b_chapters)];
1727 [o_embedded_window setNext: (b_plmul || b_chapters)];
1729 [o_timeslider setFloatValue: 0.0];
1730 [o_timeslider setEnabled: b_seekable];
1731 [o_timefield setStringValue: @"00:00"];
1732 [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1733 [[[self controls] fspanel] setSeekable: b_seekable];
1735 [o_embedded_window setSeekable: b_seekable];
1736 [o_embedded_window setTime:@"00:00" position:0.0];
1738 p_intf->p_sys->b_current_title_update = true;
1740 p_intf->p_sys->b_intf_update = false;
1743 if( p_intf->p_sys->b_playmode_update )
1745 [o_playlist playModeUpdated];
1746 p_intf->p_sys->b_playmode_update = false;
1748 if( p_intf->p_sys->b_playlist_update )
1750 [o_playlist playlistUpdated];
1751 p_intf->p_sys->b_playlist_update = false;
1754 if( p_intf->p_sys->b_fullscreen_update )
1756 p_intf->p_sys->b_fullscreen_update = false;
1759 if( p_intf->p_sys->b_intf_show )
1761 if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1762 [[o_controls fspanel] fadeIn];
1764 [o_window makeKeyAndOrderFront: self];
1766 p_intf->p_sys->b_intf_show = false;
1769 p_input = pl_CurrentInput( p_intf );
1770 if( p_input && vlc_object_alive (p_input) )
1774 if( p_intf->p_sys->b_current_title_update )
1777 input_item_t * p_item = input_GetItem( p_input );
1778 char * name = input_item_GetNowPlaying( p_item );
1781 name = input_item_GetName( p_item );
1783 aString = [NSString stringWithUTF8String:name];
1787 [self setScrollField: aString stopAfter:-1];
1788 [[[self controls] fspanel] setStreamTitle: aString];
1790 [[o_controls voutView] updateTitle];
1792 [o_playlist updateRowSelection];
1794 p_intf->p_sys->b_current_title_update = FALSE;
1797 if( [o_timeslider isEnabled] )
1799 /* Update the slider */
1803 char psz_time[MSTRTIME_MAX_SIZE];
1806 var_Get( p_input, "position", &pos );
1807 f_updated = 10000. * pos.f_float;
1808 [o_timeslider setFloatValue: f_updated];
1810 var_Get( p_input, "time", &time );
1812 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1813 if( b_time_remaining && dur != -1 )
1815 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1818 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1820 [o_timefield setStringValue: o_time];
1821 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1822 [o_embedded_window setTime: o_time position: f_updated];
1825 /* Manage Playing status */
1826 var_Get( p_input, "state", &val );
1827 if( p_intf->p_sys->i_play_status != val.i_int )
1829 p_intf->p_sys->i_play_status = val.i_int;
1830 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1831 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1833 vlc_object_release( p_input );
1837 vlc_object_release( p_input );
1841 p_intf->p_sys->i_play_status = END_S;
1842 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1843 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1844 [self setSubmenusEnabled: FALSE];
1847 if( p_intf->p_sys->b_volume_update )
1850 int i_volume_step = 0;
1851 o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1852 if( i_lastShownVolume != -1 )
1853 [self setScrollField:o_text stopAfter:1000000];
1854 i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1855 [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1856 [o_volumeslider setEnabled: TRUE];
1857 [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1858 [o_embedded_window setVolumeEnabled: TRUE];
1859 [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1860 p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1861 p_intf->p_sys->b_volume_update = FALSE;
1865 [self updateMessageDisplay];
1867 if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1868 [self resetScrollField];
1870 [interfaceTimer autorelease];
1872 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1873 target: self selector: @selector(manageIntf:)
1874 userInfo: nil repeats: FALSE] retain];
1878 #pragma mark Interface update
1882 playlist_t * p_playlist = pl_Hold( p_intf );
1883 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1884 if( p_input != NULL )
1886 [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1887 var: "program" selector: @selector(toggleVar:)];
1889 [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1890 var: "title" selector: @selector(toggleVar:)];
1892 [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1893 var: "chapter" selector: @selector(toggleVar:)];
1895 [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1896 var: "audio-es" selector: @selector(toggleVar:)];
1898 [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1899 var: "video-es" selector: @selector(toggleVar:)];
1901 [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1902 var: "spu-es" selector: @selector(toggleVar:)];
1904 /* special case for "Open File" inside the subtitles menu item */
1905 if( [o_mi_videotrack isEnabled] == YES )
1906 [o_mi_subtitle setEnabled: YES];
1908 aout_instance_t * p_aout = input_GetAout( p_input );
1909 if( p_aout != NULL )
1911 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1912 var: "audio-channels" selector: @selector(toggleVar:)];
1914 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1915 var: "audio-device" selector: @selector(toggleVar:)];
1917 [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1918 var: "visual" selector: @selector(toggleVar:)];
1919 vlc_object_release( (vlc_object_t *)p_aout );
1922 vout_thread_t * p_vout = input_GetVout( p_input );
1924 if( p_vout != NULL )
1926 vlc_object_t * p_dec_obj;
1928 [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1929 var: "aspect-ratio" selector: @selector(toggleVar:)];
1931 [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1932 var: "crop" selector: @selector(toggleVar:)];
1934 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1935 var: "video-device" selector: @selector(toggleVar:)];
1937 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1938 var: "deinterlace" selector: @selector(toggleVar:)];
1941 [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1942 (vlc_object_t *)p_vout var:"postprocess" selector:
1943 @selector(toggleVar:)];
1946 vlc_object_release( (vlc_object_t *)p_vout );
1948 vlc_object_release( p_input );
1950 pl_Release( p_intf );
1953 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1956 vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1962 /* clean the menu before adding new entries */
1963 if( [o_mi_screen hasSubmenu] )
1965 y = [[o_mi_screen submenu] numberOfItems] - 1;
1966 msg_Dbg( VLCIntf, "%i items in submenu", y );
1969 msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1970 [[o_mi_screen submenu] removeItemAtIndex: x];
1975 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1976 var: "video-device" selector: @selector(toggleVar:)];
1977 vlc_object_release( (vlc_object_t *)p_vout );
1980 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1983 i_end_scroll = mdate() + timeout;
1986 [o_scrollfield setStringValue: o_string];
1987 [o_embedded_window setScrollString: o_string];
1990 - (void)resetScrollField
1992 playlist_t * p_playlist = pl_Hold( p_intf );
1993 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1996 if( p_input && vlc_object_alive (p_input) )
2000 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
2001 if( input_item_GetNowPlaying( p_item->p_input ) )
2002 o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
2004 o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
2006 [self setScrollField: o_temp stopAfter:-1];
2007 [[[self controls] fspanel] setStreamTitle: o_temp];
2008 vlc_object_release( p_input );
2009 pl_Release( p_intf );
2012 pl_Release( p_intf );
2013 [self setScrollField: _NS("VLC media player") stopAfter:-1];
2016 - (void)playStatusUpdated:(int)i_status
2018 if( i_status == PLAYING_S )
2020 [[[self controls] fspanel] setPause];
2021 [o_btn_play setImage: o_img_pause];
2022 [o_btn_play setAlternateImage: o_img_pause_pressed];
2023 [o_btn_play setToolTip: _NS("Pause")];
2024 [o_mi_play setTitle: _NS("Pause")];
2025 [o_dmi_play setTitle: _NS("Pause")];
2026 [o_vmi_play setTitle: _NS("Pause")];
2030 [[[self controls] fspanel] setPlay];
2031 [o_btn_play setImage: o_img_play];
2032 [o_btn_play setAlternateImage: o_img_play_pressed];
2033 [o_btn_play setToolTip: _NS("Play")];
2034 [o_mi_play setTitle: _NS("Play")];
2035 [o_dmi_play setTitle: _NS("Play")];
2036 [o_vmi_play setTitle: _NS("Play")];
2040 - (void)setSubmenusEnabled:(BOOL)b_enabled
2042 [o_mi_program setEnabled: b_enabled];
2043 [o_mi_title setEnabled: b_enabled];
2044 [o_mi_chapter setEnabled: b_enabled];
2045 [o_mi_audiotrack setEnabled: b_enabled];
2046 [o_mi_visual setEnabled: b_enabled];
2047 [o_mi_videotrack setEnabled: b_enabled];
2048 [o_mi_subtitle setEnabled: b_enabled];
2049 [o_mi_channels setEnabled: b_enabled];
2050 [o_mi_deinterlace setEnabled: b_enabled];
2051 [o_mi_ffmpeg_pp setEnabled: b_enabled];
2052 [o_mi_device setEnabled: b_enabled];
2053 [o_mi_screen setEnabled: b_enabled];
2054 [o_mi_aspect_ratio setEnabled: b_enabled];
2055 [o_mi_crop setEnabled: b_enabled];
2056 [o_mi_teletext setEnabled: b_enabled];
2059 - (IBAction)timesliderUpdate:(id)sender
2062 playlist_t * p_playlist;
2063 input_thread_t * p_input;
2065 switch( [[NSApp currentEvent] type] )
2068 case NSLeftMouseDown:
2069 case NSLeftMouseDragged:
2070 f_updated = [sender floatValue];
2076 p_playlist = pl_Hold( p_intf );
2077 p_input = playlist_CurrentInput( p_playlist );
2078 if( p_input != NULL )
2083 char psz_time[MSTRTIME_MAX_SIZE];
2085 pos.f_float = f_updated / 10000.;
2086 var_Set( p_input, "position", pos );
2087 [o_timeslider setFloatValue: f_updated];
2089 var_Get( p_input, "time", &time );
2091 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
2092 if( b_time_remaining && dur != -1 )
2094 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
2097 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2099 [o_timefield setStringValue: o_time];
2100 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
2101 [o_embedded_window setTime: o_time position: f_updated];
2102 vlc_object_release( p_input );
2104 pl_Release( p_intf );
2107 - (IBAction)timeFieldWasClicked:(id)sender
2109 b_time_remaining = !b_time_remaining;
2114 #pragma mark Recent Items
2116 - (IBAction)clearRecentItems:(id)sender
2118 [[NSDocumentController sharedDocumentController]
2119 clearRecentDocuments: nil];
2122 - (void)openRecentItem:(id)sender
2124 [self application: nil openFile: [sender title]];
2130 - (IBAction)intfOpenFile:(id)sender
2132 if( !nib_open_loaded )
2134 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2135 [o_open awakeFromNib];
2142 - (IBAction)intfOpenFileGeneric:(id)sender
2144 if( !nib_open_loaded )
2146 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2147 [o_open awakeFromNib];
2148 [o_open openFileGeneric];
2150 [o_open openFileGeneric];
2154 - (IBAction)intfOpenDisc:(id)sender
2156 if( !nib_open_loaded )
2158 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2159 [o_open awakeFromNib];
2166 - (IBAction)intfOpenNet:(id)sender
2168 if( !nib_open_loaded )
2170 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2171 [o_open awakeFromNib];
2178 - (IBAction)intfOpenCapture:(id)sender
2180 if( !nib_open_loaded )
2182 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2183 [o_open awakeFromNib];
2184 [o_open openCapture];
2186 [o_open openCapture];
2190 - (IBAction)showWizard:(id)sender
2192 if( !nib_wizard_loaded )
2194 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2195 [o_wizard initStrings];
2196 [o_wizard resetWizard];
2197 [o_wizard showWizard];
2199 [o_wizard resetWizard];
2200 [o_wizard showWizard];
2204 - (IBAction)showVLM:(id)sender
2206 if( !nib_vlm_loaded )
2207 nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner: NSApp];
2209 [o_vlm showVLMWindow];
2212 - (IBAction)showExtended:(id)sender
2214 if( o_extended == nil )
2215 o_extended = [[VLCExtended alloc] init];
2217 if( !nib_extended_loaded )
2218 nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2220 [o_extended showPanel];
2223 - (IBAction)showBookmarks:(id)sender
2225 /* we need the wizard-nib for the bookmarks's extract functionality */
2226 if( !nib_wizard_loaded )
2228 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2229 [o_wizard initStrings];
2232 if( !nib_bookmarks_loaded )
2233 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2235 [o_bookmarks showBookmarks];
2238 - (IBAction)viewPreferences:(id)sender
2240 if( !nib_prefs_loaded )
2242 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2243 o_sprefs = [[VLCSimplePrefs alloc] init];
2244 o_prefs= [[VLCPrefs alloc] init];
2247 [o_sprefs showSimplePrefs];
2253 - (IBAction)checkForUpdate:(id)sender
2256 if( !nib_update_loaded )
2257 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
2258 [o_update showUpdateWindow];
2260 msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2261 dialog_FatalWait( VLCIntf, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2266 #pragma mark Help and Docs
2268 - (IBAction)viewAbout:(id)sender
2270 if( !nib_about_loaded )
2271 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2273 [o_about showAbout];
2276 - (IBAction)showLicense:(id)sender
2278 if( !nib_about_loaded )
2279 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2281 [o_about showGPL: sender];
2284 - (IBAction)viewHelp:(id)sender
2286 if( !nib_about_loaded )
2288 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2295 - (IBAction)openReadMe:(id)sender
2297 NSString * o_path = [[NSBundle mainBundle]
2298 pathForResource: @"README.MacOSX" ofType: @"rtf"];
2300 [[NSWorkspace sharedWorkspace] openFile: o_path
2301 withApplication: @"TextEdit"];
2304 - (IBAction)openDocumentation:(id)sender
2306 NSURL * o_url = [NSURL URLWithString:
2307 @"http://www.videolan.org/doc/"];
2309 [[NSWorkspace sharedWorkspace] openURL: o_url];
2312 - (IBAction)openWebsite:(id)sender
2314 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2316 [[NSWorkspace sharedWorkspace] openURL: o_url];
2319 - (IBAction)openForum:(id)sender
2321 NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2323 [[NSWorkspace sharedWorkspace] openURL: o_url];
2326 - (IBAction)openDonate:(id)sender
2328 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2330 [[NSWorkspace sharedWorkspace] openURL: o_url];
2334 #pragma mark Crash Log
2335 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2337 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2338 NSURL *url = [NSURL URLWithString:urlStr];
2340 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2341 [req setHTTPMethod:@"POST"];
2344 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2346 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2347 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2348 email = [emails valueAtIndex:[emails indexForIdentifier:
2349 [emails primaryIdentifier]]];
2352 email = [NSString string];
2355 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2356 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2357 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2358 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2360 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2362 /* Released from delegate */
2363 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2366 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2368 NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2369 _NS("Thanks for your report!"),
2370 _NS("OK"), nil, nil, nil);
2371 [crashLogURLConnection release];
2372 crashLogURLConnection = nil;
2375 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2377 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2378 [crashLogURLConnection release];
2379 crashLogURLConnection = nil;
2382 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2384 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2385 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2387 NSString * latestLog = nil;
2388 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2389 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2390 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
2391 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2393 while (fname = [direnum nextObject])
2395 [direnum skipDescendents];
2396 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2398 NSArray * compo = [fname componentsSeparatedByString:@"_"];
2399 if( [compo count] < 3 ) continue;
2400 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2401 if( [compo count] < 4 ) continue;
2404 if( year < [[compo objectAtIndex:0] intValue] ||
2405 (year ==[[compo objectAtIndex:0] intValue] &&
2406 (month < [[compo objectAtIndex:1] intValue] ||
2407 (month ==[[compo objectAtIndex:1] intValue] &&
2408 (day < [[compo objectAtIndex:2] intValue] ||
2409 (day ==[[compo objectAtIndex:2] intValue] &&
2410 hours < [[compo objectAtIndex:3] intValue] ))))))
2412 year = [[compo objectAtIndex:0] intValue];
2413 month = [[compo objectAtIndex:1] intValue];
2414 day = [[compo objectAtIndex:2] intValue];
2415 hours = [[compo objectAtIndex:3] intValue];
2416 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2421 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2424 if( !previouslySeen )
2426 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
2427 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2428 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
2429 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2434 - (NSString *)latestCrashLogPath
2436 return [self latestCrashLogPathPreviouslySeen:YES];
2439 - (void)lookForCrashLog
2441 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2442 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2443 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2444 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2445 if( latestLog && !areCrashLogsTooOld )
2446 [NSApp runModalForWindow: o_crashrep_win];
2450 - (IBAction)crashReporterAction:(id)sender
2452 if( sender == o_crashrep_send_btn )
2453 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2456 [o_crashrep_win orderOut: sender];
2459 - (IBAction)openCrashLog:(id)sender
2461 NSString * latestLog = [self latestCrashLogPath];
2464 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2468 NSBeginInformationalAlertSheet(_NS("No CrashLog found"), _NS("Continue"), nil, nil, o_msgs_panel, self, NULL, NULL, nil, _NS("Couldn't find any trace of a previous crash.") );
2473 #pragma mark Remove old prefs
2475 - (void)_removeOldPreferences
2477 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2478 static const int kCurrentPreferencesVersion = 1;
2479 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2480 if( version >= kCurrentPreferencesVersion ) return;
2482 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
2483 NSUserDomainMask, YES);
2484 if( !libraries || [libraries count] == 0) return;
2485 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2487 /* File not found, don't attempt anything */
2488 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2489 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2491 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2495 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2496 _NS("We just found an older version of VLC's preferences files."),
2497 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2498 if( res != NSOKButton )
2500 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2504 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2506 /* Move the file to trash so that user can find them later */
2507 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2509 /* really reset the defaults from now on */
2510 [NSUserDefaults resetStandardUserDefaults];
2512 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2513 [[NSUserDefaults standardUserDefaults] synchronize];
2516 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2518 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2524 execl(path, path, NULL);
2528 #pragma mark Errors, warnings and messages
2530 - (IBAction)viewErrorsAndWarnings:(id)sender
2532 [[[self coreDialogProvider] errorPanel] showPanel];
2535 - (IBAction)showMessagesPanel:(id)sender
2537 [o_msgs_panel makeKeyAndOrderFront: sender];
2540 - (IBAction)showInformationPanel:(id)sender
2542 if(! nib_info_loaded )
2543 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2548 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2550 if( [o_notification object] == o_msgs_panel )
2551 [self updateMessageDisplay];
2554 - (void)updateMessageDisplay
2556 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2559 NSEnumerator * o_enum;
2561 [o_messages setString: @""];
2565 o_enum = [o_msg_arr objectEnumerator];
2567 while( ( o_msg = [o_enum nextObject] ) != nil )
2569 [o_messages insertText: o_msg];
2572 b_msg_arr_changed = NO;
2573 [o_msg_lock unlock];
2577 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2579 NSColor *o_white = [NSColor whiteColor];
2580 NSColor *o_red = [NSColor redColor];
2581 NSColor *o_yellow = [NSColor yellowColor];
2582 NSColor *o_gray = [NSColor grayColor];
2584 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2585 static const char * ppsz_type[4] = { ": ", " error: ",
2586 " warning: ", " debug: " };
2589 NSDictionary *o_attr;
2590 NSAttributedString *o_msg_color;
2592 int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2596 if( [o_msg_arr count] + 2 > 600 )
2598 [o_msg_arr removeObjectAtIndex: 0];
2599 [o_msg_arr removeObjectAtIndex: 1];
2602 o_attr = [NSDictionary dictionaryWithObject: o_gray
2603 forKey: NSForegroundColorAttributeName];
2604 o_msg = [NSString stringWithFormat: @"%@%s",
2605 [[o_notification userInfo] objectForKey: @"Module"],
2607 o_msg_color = [[NSAttributedString alloc]
2608 initWithString: o_msg attributes: o_attr];
2609 [o_msg_arr addObject: [o_msg_color autorelease]];
2611 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2612 forKey: NSForegroundColorAttributeName];
2613 o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2614 o_msg_color = [[NSAttributedString alloc]
2615 initWithString: o_msg attributes: o_attr];
2616 [o_msg_arr addObject: [o_msg_color autorelease]];
2618 b_msg_arr_changed = YES;
2619 [o_msg_lock unlock];
2622 - (IBAction)saveDebugLog:(id)sender
2624 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2626 [saveFolderPanel setCanChooseDirectories: NO];
2627 [saveFolderPanel setCanChooseFiles: YES];
2628 [saveFolderPanel setCanSelectHiddenExtension: NO];
2629 [saveFolderPanel setCanCreateDirectories: YES];
2630 [saveFolderPanel setRequiredFileType: @"rtfd"];
2631 [saveFolderPanel beginSheetForDirectory:nil file: [NSString stringWithFormat: _NS("VLC Debug Log (%s).rtfd"), VLC_Version()] modalForWindow: o_msgs_panel modalDelegate:self didEndSelector:@selector(saveDebugLogAsRTF:returnCode:contextInfo:) contextInfo:nil];
2634 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2637 if( returnCode == NSOKButton )
2639 b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2641 msg_Warn( p_intf, "Error while saving the debug log" );
2646 #pragma mark Playlist toggling
2648 - (IBAction)togglePlaylist:(id)sender
2650 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2651 NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2652 /*First, check if the playlist is visible*/
2653 if( contentRect.size.height <= 169. )
2655 o_restore_rect = contentRect;
2656 b_restore_size = true;
2657 b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2660 if( o_size_with_playlist.height > 169. )
2661 o_rect.size.height = o_size_with_playlist.height;
2663 o_rect.size.height = 500.;
2665 if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2666 o_rect.size.width = o_size_with_playlist.width;
2668 o_rect.size.width = [o_window contentMinSize].width;
2670 o_rect.origin.x = contentRect.origin.x;
2671 o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2672 [o_window contentMinSize].height;
2674 o_rect = [o_window frameRectForContentRect:o_rect];
2676 NSRect screenRect = [[o_window screen] visibleFrame];
2677 if( !NSContainsRect( screenRect, o_rect ) ) {
2678 if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2679 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2680 if( NSMinY(o_rect) < NSMinY(screenRect) )
2681 o_rect.origin.y = ( NSMinY(screenRect) );
2684 [o_btn_playlist setState: YES];
2688 NSSize curSize = o_rect.size;
2689 if( b_restore_size )
2691 o_rect = o_restore_rect;
2692 if( o_rect.size.height < [o_window contentMinSize].height )
2693 o_rect.size.height = [o_window contentMinSize].height;
2694 if( o_rect.size.width < [o_window contentMinSize].width )
2695 o_rect.size.width = [o_window contentMinSize].width;
2699 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2701 o_rect.size.height = [o_window contentMinSize].height;
2702 o_rect.size.width = [o_window contentMinSize].width;
2703 o_rect.origin.x = contentRect.origin.x;
2704 /* Calculate the position of the lower right corner after resize */
2705 o_rect.origin.y = contentRect.origin.y +
2706 contentRect.size.height - [o_window contentMinSize].height;
2709 [o_playlist_view setAutoresizesSubviews: NO];
2710 [o_playlist_view removeFromSuperview];
2711 [o_btn_playlist setState: NO];
2712 b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2713 o_rect = [o_window frameRectForContentRect:o_rect];
2716 [o_window setFrame: o_rect display:YES animate: YES];
2719 - (void)updateTogglePlaylistState
2721 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2722 [o_btn_playlist setState: NO];
2724 [o_btn_playlist setState: YES];
2726 [[self playlist] outlineViewSelectionDidChange: NULL];
2729 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2732 /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2734 /*Stores the size the controller one resize, to be able to restore it when
2735 toggling the playlist*/
2736 o_size_with_playlist = proposedFrameSize;
2739 rect.size = proposedFrameSize;
2740 if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2742 if( b_small_window == NO )
2744 /* if large and going to small then hide */
2745 b_small_window = YES;
2746 [o_playlist_view setAutoresizesSubviews: NO];
2747 [o_playlist_view removeFromSuperview];
2749 return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2751 return proposedFrameSize;
2754 - (void)windowDidMove:(NSNotification *)notif
2756 b_restore_size = false;
2759 - (void)windowDidResize:(NSNotification *)notif
2761 if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2763 /* If large and coming from small then show */
2764 [o_playlist_view setAutoresizesSubviews: YES];
2765 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2766 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2767 [o_playlist_view setNeedsDisplay:YES];
2768 [[o_window contentView] addSubview: o_playlist_view];
2769 b_small_window = NO;
2771 [self updateTogglePlaylistState];
2778 @implementation VLCMain (NSMenuValidation)
2780 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2782 NSString *o_title = [o_mi title];
2783 BOOL bEnabled = TRUE;
2785 /* Recent Items Menu */
2786 if( [o_title isEqualToString: _NS("Clear Menu")] )
2788 NSMenu * o_menu = [o_mi_open_recent submenu];
2789 int i_nb_items = [o_menu numberOfItems];
2790 NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2791 recentDocumentURLs];
2792 UInt32 i_nb_docs = [o_docs count];
2794 if( i_nb_items > 1 )
2796 while( --i_nb_items )
2798 [o_menu removeItemAtIndex: 0];
2807 [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2813 o_url = [o_docs objectAtIndex: i_nb_docs];
2815 if( [o_url isFileURL] )
2817 o_doc = [o_url path];
2821 o_doc = [o_url absoluteString];
2824 [o_menu insertItemWithTitle: o_doc
2825 action: @selector(openRecentItem:)
2826 keyEquivalent: @"" atIndex: 0];
2828 if( i_nb_docs == 0 )
2844 @implementation VLCMain (Internal)
2846 - (void)handlePortMessage:(NSPortMessage *)o_msg
2851 NSInvocation * o_inv;
2852 NSConditionLock * o_lock;
2854 o_data = [[o_msg components] lastObject];
2855 o_inv = *((NSInvocation **)[o_data bytes]);
2856 [o_inv getArgument: &o_value atIndex: 2];
2857 val = (id **)[o_value pointerValue];
2858 [o_inv setArgument: val[1] atIndex: 2];
2863 [o_lock unlockWithCondition: 1];
2868 /*****************************************************************************
2869 * VLCApplication interface
2870 * exclusively used to implement media key support on Al Apple keyboards
2871 * b_justJumped is required as the keyboard send its events faster than
2872 * the user can actually jump through his media
2873 *****************************************************************************/
2875 @implementation VLCApplication
2877 - (void)awakeFromNib
2879 b_active = b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2880 b_activeInBackground = config_GetInt( VLCIntf, "macosx-mediakeys-background" );
2881 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
2882 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appGotActiveOrInactive:) name: @"NSApplicationDidBecomeActiveNotification" object: nil];
2883 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appGotActiveOrInactive:) name: @"NSApplicationWillResignActiveNotification" object: nil];
2888 [[NSNotificationCenter defaultCenter] removeObserver: self];
2892 - (void)appGotActiveOrInactive: (NSNotification *)o_notification
2894 if(( [[o_notification name] isEqualToString: @"NSApplicationWillResignActiveNotification"] && !b_activeInBackground ) || !b_mediaKeySupport)
2900 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2902 b_active = b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2903 b_activeInBackground = config_GetInt( VLCIntf, "macosx-mediakeys-background" );
2907 - (void)sendEvent: (NSEvent*)event
2911 if( [event type] == NSSystemDefined && [event subtype] == 8 )
2913 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
2914 int keyFlags = ([event data1] & 0x0000FFFF);
2915 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
2916 int keyRepeat = (keyFlags & 0x1);
2918 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
2919 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
2921 if( keyCode == NX_KEYTYPE_FAST && !b_justJumped )
2923 if( keyState == 0 && keyRepeat == 0 )
2925 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_NEXT );
2927 else if( keyRepeat == 1 )
2929 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
2931 [self performSelector:@selector(resetJump)
2937 if( keyCode == NX_KEYTYPE_REWIND && !b_justJumped )
2939 if( keyState == 0 && keyRepeat == 0 )
2941 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PREV );
2943 else if( keyRepeat == 1 )
2945 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
2947 [self performSelector:@selector(resetJump)
2954 [super sendEvent: event];