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 */
62 /*****************************************************************************
64 *****************************************************************************/
65 static void Run ( intf_thread_t *p_intf );
67 static void * ManageThread( void *user_data );
69 static unichar VLCKeyToCocoa( unsigned int i_key );
70 static unsigned int VLCModifiersToCocoa( unsigned int i_key );
72 static void updateProgressPanel (void *, const char *, float);
73 static bool checkProgressPanel (void *);
74 static void destroyProgressPanel (void *);
76 static void MsgCallback( msg_cb_data_t *, msg_item_t *, unsigned );
79 #pragma mark VLC Interface Object Callbacks
81 /*****************************************************************************
82 * OpenIntf: initialize interface
83 *****************************************************************************/
84 int OpenIntf ( vlc_object_t *p_this )
86 intf_thread_t *p_intf = (intf_thread_t*) p_this;
88 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
89 if( p_intf->p_sys == NULL )
92 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
94 /* subscribe to LibVLCCore's messages */
95 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
97 p_intf->b_should_run_on_first_thread = true;
102 /*****************************************************************************
103 * CloseIntf: destroy interface
104 *****************************************************************************/
105 void CloseIntf ( vlc_object_t *p_this )
107 intf_thread_t *p_intf = (intf_thread_t*) p_this;
109 free( p_intf->p_sys );
112 /*****************************************************************************
114 *****************************************************************************/
117 static void Run( intf_thread_t *p_intf )
121 /* Do it again - for some unknown reason, vlc_thread_create() often
122 * fails to go to real-time priority with the first launched thread
124 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
126 /* Make sure the "force quit" menu item does quit instantly.
127 * VLC overrides SIGTERM which is sent by the "force quit"
128 * menu item to make sure deamon mode quits gracefully, so
129 * we un-override SIGTERM here. */
131 sigaddset( &set, SIGTERM );
132 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
134 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
136 /* Install a jmpbuffer to where we can go back before the NSApp exit
137 * see applicationWillTerminate: */
138 [VLCApplication sharedApplication];
140 [[VLCMain sharedInstance] setIntf: p_intf];
141 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
143 /* Install a jmpbuffer to where we can go back before the NSApp exit
144 * see applicationWillTerminate: */
145 if(setjmp(jmpbuffer) == 0)
152 #pragma mark Variables Callback
154 /*****************************************************************************
155 * MsgCallback: Callback triggered by the core once a new debug message is
156 * ready to be displayed. We store everything in a NSArray in our Cocoa part
157 * of this file, so we are forwarding everything through notifications.
158 *****************************************************************************/
159 static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned int i )
161 int canc = vlc_savecancel();
162 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
164 /* this may happen from time to time, let's bail out as info would be useless anyway */
165 if( !item->psz_module || !item->psz_msg )
168 NSDictionary *o_dict = [NSDictionary dictionaryWithObjectsAndKeys:
169 [NSString stringWithUTF8String: item->psz_module], @"Module",
170 [NSString stringWithUTF8String: item->psz_msg], @"Message",
171 [NSNumber numberWithInt: item->i_type], @"Type", nil];
173 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCCoreMessageReceived"
178 vlc_restorecancel( canc );
181 /*****************************************************************************
182 * playlistChanged: Callback triggered by the intf-change playlist
183 * variable, to let the intf update the playlist.
184 *****************************************************************************/
185 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
186 vlc_value_t old_val, vlc_value_t new_val, void *param )
188 intf_thread_t * p_intf = VLCIntf;
189 if( p_intf && p_intf->p_sys )
191 p_intf->p_sys->b_intf_update = true;
192 p_intf->p_sys->b_playlist_update = true;
193 p_intf->p_sys->b_playmode_update = true;
194 p_intf->p_sys->b_current_title_update = true;
199 /*****************************************************************************
200 * ShowController: Callback triggered by the show-intf playlist variable
201 * through the ShowIntf-control-intf, to let us show the controller-win;
202 * usually when in fullscreen-mode
203 *****************************************************************************/
204 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
205 vlc_value_t old_val, vlc_value_t new_val, void *param )
207 intf_thread_t * p_intf = VLCIntf;
208 if( p_intf && p_intf->p_sys )
209 p_intf->p_sys->b_intf_show = true;
213 /*****************************************************************************
214 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
215 * variable, to let the intf update the controller.
216 *****************************************************************************/
217 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
218 vlc_value_t old_val, vlc_value_t new_val, void *param )
220 intf_thread_t * p_intf = VLCIntf;
221 if( p_intf && p_intf->p_sys )
222 p_intf->p_sys->b_fullscreen_update = true;
226 /*****************************************************************************
227 * DialogCallback: Callback triggered by the "dialog-*" variables
228 * to let the intf display error and interaction dialogs
229 *****************************************************************************/
230 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
232 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
233 VLCMain *interface = (VLCMain *)data;
235 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
237 /* the progress panel needs to update itself and therefore wants special treatment within this context */
238 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
240 p_dialog->pf_update = updateProgressPanel;
241 p_dialog->pf_check = checkProgressPanel;
242 p_dialog->pf_destroy = destroyProgressPanel;
243 p_dialog->p_sys = VLCIntf->p_libvlc;
246 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
247 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewCoreDialogEventNotification" object:[interface coreDialogProvider] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: o_value, @"VLCDialogPointer", [NSString stringWithUTF8String: type], @"VLCDialogType", nil]];
253 void updateProgressPanel (void *priv, const char *text, float value)
255 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
259 o_txt = [NSString stringWithUTF8String: text];
263 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
268 void destroyProgressPanel (void *priv)
270 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
271 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
275 bool checkProgressPanel (void *priv)
277 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
278 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
285 @interface VLCMain ()
286 - (void)_removeOldPreferences;
289 /*****************************************************************************
290 * VLCMain implementation
291 *****************************************************************************/
292 @implementation VLCMain
295 #pragma mark Initialization
297 static VLCMain *_o_sharedMainInstance = nil;
299 + (VLCMain *)sharedInstance
301 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
306 if( _o_sharedMainInstance)
309 return _o_sharedMainInstance;
312 _o_sharedMainInstance = [super init];
316 o_msg_lock = [[NSLock alloc] init];
317 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
318 /* subscribe to LibVLC's debug messages as early as possible (for us) */
319 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
321 o_about = [[VLAboutBox alloc] init];
323 o_open = [[VLCOpen alloc] init];
324 o_wizard = [[VLCWizard alloc] init];
325 o_vlm = [[VLCVLMController alloc] init];
327 o_bookmarks = [[VLCBookmarks alloc] init];
328 o_embedded_list = [[VLCEmbeddedList alloc] init];
329 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
330 o_info = [[VLCInfo alloc] init];
332 o_update = [[VLCUpdate alloc] init];
335 i_lastShownVolume = -1;
337 o_remote = [[AppleRemote alloc] init];
338 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
339 [o_remote setDelegate: _o_sharedMainInstance];
341 o_eyetv = [[VLCEyeTVController alloc] init];
343 /* announce our launch to a potential eyetv plugin */
344 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
345 object: @"VLCEyeTVSupport"
347 deliverImmediately: YES];
349 return _o_sharedMainInstance;
352 - (void)setIntf: (intf_thread_t *)p_mainintf {
356 - (intf_thread_t *)intf {
362 unsigned int i_key = 0;
363 playlist_t *p_playlist;
366 if( !p_intf ) return;
368 /* Check if we already did this once. Opening the other nibs calls it too,
369 because VLCMain is the owner */
370 if( nib_main_loaded ) return;
372 /* check whether the user runs a valid version of OS X */
373 if( MACOS_VERSION < 10.5f )
378 if( MACOS_VERSION == 10.4f )
379 o_blabla = _NS("VLC's last release for your OS is the 0.9 series." );
380 else if( MACOS_VERSION == 10.3f )
381 o_blabla = _NS("VLC's last release for your OS is VLC 0.8.6i, which is prone to known security issues." );
382 else // 10.2 and 10.1, still 3% of the OS X market share
383 o_blabla = _NS("VLC's last release for your OS is VLC 0.7.2, which is highly out of date and prone to " \
384 "known security issues. We recommend you to update your Mac to a modern version of Mac OS X.");
385 ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is no longer supported")
386 defaultButton: _NS("Quit")
387 alternateButton: NULL
389 informativeTextWithFormat: _NS("VLC media player %s requires Mac OS X 10.5 or higher.\n\n%@"), VLC_Version(), o_blabla];
390 [ourAlert setAlertStyle: NSCriticalAlertStyle];
391 i_returnValue = [ourAlert runModal];
392 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
398 [o_window setExcludedFromWindowsMenu: YES];
399 [o_msgs_panel setExcludedFromWindowsMenu: YES];
400 [o_msgs_panel setDelegate: self];
402 /* In code and not in Nib for 10.4 compat */
403 NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"mainControllerToolbar"] autorelease];
404 [toolbar setDelegate:self];
405 [toolbar setShowsBaselineSeparator:NO];
406 [toolbar setAllowsUserCustomization:NO];
407 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
408 [toolbar setAutosavesConfiguration:YES];
409 [o_window setToolbar:toolbar];
411 i_key = config_GetInt( p_intf, "key-quit" );
412 [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
413 [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
414 i_key = config_GetInt( p_intf, "key-play-pause" );
415 [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
416 [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
417 i_key = config_GetInt( p_intf, "key-stop" );
418 [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
419 [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
420 i_key = config_GetInt( p_intf, "key-faster" );
421 [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
422 [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
423 i_key = config_GetInt( p_intf, "key-slower" );
424 [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
425 [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
426 i_key = config_GetInt( p_intf, "key-prev" );
427 [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
428 [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
429 i_key = config_GetInt( p_intf, "key-next" );
430 [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
431 [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
432 i_key = config_GetInt( p_intf, "key-jump+short" );
433 [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
434 [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
435 i_key = config_GetInt( p_intf, "key-jump-short" );
436 [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
437 [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
438 i_key = config_GetInt( p_intf, "key-jump+medium" );
439 [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
440 [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
441 i_key = config_GetInt( p_intf, "key-jump-medium" );
442 [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
443 [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
444 i_key = config_GetInt( p_intf, "key-jump+long" );
445 [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
446 [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
447 i_key = config_GetInt( p_intf, "key-jump-long" );
448 [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
449 [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
450 i_key = config_GetInt( p_intf, "key-vol-up" );
451 [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
452 [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
453 i_key = config_GetInt( p_intf, "key-vol-down" );
454 [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
455 [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
456 i_key = config_GetInt( p_intf, "key-vol-mute" );
457 [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
458 [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
459 i_key = config_GetInt( p_intf, "key-fullscreen" );
460 [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
461 [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
462 i_key = config_GetInt( p_intf, "key-snapshot" );
463 [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
464 [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
465 i_key = config_GetInt( p_intf, "key-random" );
466 [o_mi_random setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
467 [o_mi_random setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
468 i_key = config_GetInt( p_intf, "key-zoom-half" );
469 [o_mi_half_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
470 [o_mi_half_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
471 i_key = config_GetInt( p_intf, "key-zoom-original" );
472 [o_mi_normal_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
473 [o_mi_normal_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
474 i_key = config_GetInt( p_intf, "key-zoom-double" );
475 [o_mi_double_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
476 [o_mi_double_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
478 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
480 [self setSubmenusEnabled: FALSE];
481 [o_volumeslider setEnabled: YES];
482 [self manageVolumeSlider];
483 [o_window setDelegate: self];
485 b_restore_size = false;
487 // Set that here as IB seems to be buggy
488 [o_window setContentMinSize:NSMakeSize(338., 30.)];
490 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
492 b_small_window = YES;
493 [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
494 [o_window frame].origin.y, [o_window frame].size.width,
495 [o_window minSize].height ) display: YES animate:YES];
496 [o_playlist_view setAutoresizesSubviews: NO];
501 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
502 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
503 [o_playlist_view setNeedsDisplay:YES];
504 [o_playlist_view setAutoresizesSubviews: YES];
505 [[o_window contentView] addSubview: o_playlist_view];
508 [self updateTogglePlaylistState];
510 o_size_with_playlist = [o_window contentRectForFrameRect:[o_window frame]].size;
512 p_playlist = pl_Hold( p_intf );
514 var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
517 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
518 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
520 pl_Release( p_intf );
522 /* load our Core Dialogs nib */
523 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
525 /* subscribe to various interactive dialogues */
526 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
527 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
528 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
529 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
530 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
531 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
532 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
533 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
534 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
535 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
536 dialog_Register( p_intf );
538 /* update the playmode stuff */
539 p_intf->p_sys->b_playmode_update = true;
541 [[NSNotificationCenter defaultCenter] addObserver: self
542 selector: @selector(refreshVoutDeviceMenu:)
543 name: NSApplicationDidChangeScreenParametersNotification
546 /* take care of tint changes during runtime */
547 o_img_play = [NSImage imageNamed: @"play"];
548 o_img_pause = [NSImage imageNamed: @"pause"];
549 [self controlTintChanged];
550 [[NSNotificationCenter defaultCenter] addObserver: self
551 selector: @selector( controlTintChanged )
552 name: NSControlTintDidChangeNotification
555 /* yeah, we are done */
556 nib_main_loaded = TRUE;
559 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
561 if( !p_intf ) return;
563 /* FIXME: don't poll */
564 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
565 target: self selector: @selector(manageIntf:)
566 userInfo: nil repeats: FALSE] retain];
568 /* Note: we use the pthread API to support pre-10.5 */
569 pthread_create( &manage_thread, NULL, ManageThread, self );
571 [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
572 var: "intf-add" selector: @selector(toggleVar:)];
574 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
577 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
579 if( !p_intf ) return;
581 [self _removeOldPreferences];
584 /* Check for update silently on startup */
585 if( !nib_update_loaded )
586 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
588 if([o_update shouldCheckForUpdate])
589 [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:nil];
592 /* Handle sleep notification */
593 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
594 name:NSWorkspaceWillSleepNotification object:nil];
596 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
601 if( !p_intf ) return;
603 [o_window setTitle: _NS("VLC media player")];
604 [self setScrollField:_NS("VLC media player") stopAfter:-1];
606 /* button controls */
607 [o_btn_prev setToolTip: _NS("Previous")];
608 [o_btn_rewind setToolTip: _NS("Rewind")];
609 [o_btn_play setToolTip: _NS("Play")];
610 [o_btn_stop setToolTip: _NS("Stop")];
611 [o_btn_ff setToolTip: _NS("Fast Forward")];
612 [o_btn_next setToolTip: _NS("Next")];
613 [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
614 [o_volumeslider setToolTip: _NS("Volume")];
615 [o_timeslider setToolTip: _NS("Position")];
616 [o_btn_playlist setToolTip: _NS("Playlist")];
619 [o_msgs_panel setTitle: _NS("Messages")];
620 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
621 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
624 [o_mi_about setTitle: [_NS("About VLC media player") \
625 stringByAppendingString: @"..."]];
626 [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
627 [o_mi_prefs setTitle: _NS("Preferences...")];
628 [o_mi_add_intf setTitle: _NS("Add Interface")];
629 [o_mu_add_intf setTitle: _NS("Add Interface")];
630 [o_mi_services setTitle: _NS("Services")];
631 [o_mi_hide setTitle: _NS("Hide VLC")];
632 [o_mi_hide_others setTitle: _NS("Hide Others")];
633 [o_mi_show_all setTitle: _NS("Show All")];
634 [o_mi_quit setTitle: _NS("Quit VLC")];
636 [o_mu_file setTitle: _ANS("1:File")];
637 [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
638 [o_mi_open_file setTitle: _NS("Open File...")];
639 [o_mi_open_disc setTitle: _NS("Open Disc...")];
640 [o_mi_open_net setTitle: _NS("Open Network...")];
641 [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
642 [o_mi_open_recent setTitle: _NS("Open Recent")];
643 [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
644 [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
646 [o_mu_edit setTitle: _NS("Edit")];
647 [o_mi_cut setTitle: _NS("Cut")];
648 [o_mi_copy setTitle: _NS("Copy")];
649 [o_mi_paste setTitle: _NS("Paste")];
650 [o_mi_clear setTitle: _NS("Clear")];
651 [o_mi_select_all setTitle: _NS("Select All")];
653 [o_mu_controls setTitle: _NS("Playback")];
654 [o_mi_play setTitle: _NS("Play")];
655 [o_mi_stop setTitle: _NS("Stop")];
656 [o_mi_faster setTitle: _NS("Faster")];
657 [o_mi_slower setTitle: _NS("Slower")];
658 [o_mi_previous setTitle: _NS("Previous")];
659 [o_mi_next setTitle: _NS("Next")];
660 [o_mi_random setTitle: _NS("Random")];
661 [o_mi_repeat setTitle: _NS("Repeat One")];
662 [o_mi_loop setTitle: _NS("Repeat All")];
663 [o_mi_fwd setTitle: _NS("Step Forward")];
664 [o_mi_bwd setTitle: _NS("Step Backward")];
666 [o_mi_program setTitle: _NS("Program")];
667 [o_mu_program setTitle: _NS("Program")];
668 [o_mi_title setTitle: _NS("Title")];
669 [o_mu_title setTitle: _NS("Title")];
670 [o_mi_chapter setTitle: _NS("Chapter")];
671 [o_mu_chapter setTitle: _NS("Chapter")];
673 [o_mu_audio setTitle: _NS("Audio")];
674 [o_mi_vol_up setTitle: _NS("Increase Volume")];
675 [o_mi_vol_down setTitle: _NS("Decrease Volume")];
676 [o_mi_mute setTitle: _NS("Mute")];
677 [o_mi_audiotrack setTitle: _NS("Audio Track")];
678 [o_mu_audiotrack setTitle: _NS("Audio Track")];
679 [o_mi_channels setTitle: _NS("Audio Channels")];
680 [o_mu_channels setTitle: _NS("Audio Channels")];
681 [o_mi_device setTitle: _NS("Audio Device")];
682 [o_mu_device setTitle: _NS("Audio Device")];
683 [o_mi_visual setTitle: _NS("Visualizations")];
684 [o_mu_visual setTitle: _NS("Visualizations")];
686 [o_mu_video setTitle: _NS("Video")];
687 [o_mi_half_window setTitle: _NS("Half Size")];
688 [o_mi_normal_window setTitle: _NS("Normal Size")];
689 [o_mi_double_window setTitle: _NS("Double Size")];
690 [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
691 [o_mi_fullscreen setTitle: _NS("Fullscreen")];
692 [o_mi_floatontop setTitle: _NS("Float on Top")];
693 [o_mi_snapshot setTitle: _NS("Snapshot")];
694 [o_mi_videotrack setTitle: _NS("Video Track")];
695 [o_mu_videotrack setTitle: _NS("Video Track")];
696 [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
697 [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
698 [o_mi_crop setTitle: _NS("Crop")];
699 [o_mu_crop setTitle: _NS("Crop")];
700 [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
701 [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
702 [o_mi_subtitle setTitle: _NS("Subtitles Track")];
703 [o_mu_subtitle setTitle: _NS("Subtitles Track")];
704 [o_mi_addSub setTitle: _NS("Open File...")];
705 [o_mi_deinterlace setTitle: _NS("Deinterlace")];
706 [o_mu_deinterlace setTitle: _NS("Deinterlace")];
707 [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
708 [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
709 [o_mi_teletext setTitle: _NS("Teletext")];
710 [o_mi_teletext_transparent setTitle: _NS("Transparent")];
711 [o_mi_teletext_index setTitle: _NS("Index")];
712 [o_mi_teletext_red setTitle: _NS("Red")];
713 [o_mi_teletext_green setTitle: _NS("Green")];
714 [o_mi_teletext_yellow setTitle: _NS("Yellow")];
715 [o_mi_teletext_blue setTitle: _NS("Blue")];
717 [o_mu_window setTitle: _NS("Window")];
718 [o_mi_minimize setTitle: _NS("Minimize Window")];
719 [o_mi_close_window setTitle: _NS("Close Window")];
720 [o_mi_player setTitle: _NS("Player...")];
721 [o_mi_controller setTitle: _NS("Controller...")];
722 [o_mi_equalizer setTitle: _NS("Equalizer...")];
723 [o_mi_extended setTitle: _NS("Extended Controls...")];
724 [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
725 [o_mi_playlist setTitle: _NS("Playlist...")];
726 [o_mi_info setTitle: _NS("Media Information...")];
727 [o_mi_messages setTitle: _NS("Messages...")];
728 [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
730 [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
732 [o_mu_help setTitle: _NS("Help")];
733 [o_mi_help setTitle: _NS("VLC media player Help...")];
734 [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
735 [o_mi_license setTitle: _NS("License")];
736 [o_mi_documentation setTitle: _NS("Online Documentation...")];
737 [o_mi_website setTitle: _NS("VideoLAN Website...")];
738 [o_mi_donation setTitle: _NS("Make a donation...")];
739 [o_mi_forum setTitle: _NS("Online Forum...")];
742 [o_dmi_play setTitle: _NS("Play")];
743 [o_dmi_stop setTitle: _NS("Stop")];
744 [o_dmi_next setTitle: _NS("Next")];
745 [o_dmi_previous setTitle: _NS("Previous")];
746 [o_dmi_mute setTitle: _NS("Mute")];
749 [o_vmi_play setTitle: _NS("Play")];
750 [o_vmi_stop setTitle: _NS("Stop")];
751 [o_vmi_prev setTitle: _NS("Previous")];
752 [o_vmi_next setTitle: _NS("Next")];
753 [o_vmi_volup setTitle: _NS("Volume Up")];
754 [o_vmi_voldown setTitle: _NS("Volume Down")];
755 [o_vmi_mute setTitle: _NS("Mute")];
756 [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
757 [o_vmi_snapshot setTitle: _NS("Snapshot")];
759 /* crash reporter panel */
760 [o_crashrep_send_btn setTitle: _NS("Send")];
761 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
762 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
763 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
764 [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, ...")];
765 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
766 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
770 #pragma mark Termination
772 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
774 if( !p_intf ) return;
776 NSArray *menuitems_array = [the_menu itemArray];
777 for( int i=0; i<[menuitems_array count]; i++ )
779 NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
780 if( [one_item hasSubmenu] )
781 [self releaseRepresentedObjects: [one_item submenu]];
783 [one_item setRepresentedObject:NULL];
787 - (void)applicationWillTerminate:(NSNotification *)notification
789 playlist_t * p_playlist;
790 vout_thread_t * p_vout;
791 int returnedValue = 0;
793 if( !p_intf ) return;
795 msg_Dbg( p_intf, "Terminating" );
797 /* Make sure the manage_thread won't call -terminate: again */
798 pthread_cancel( manage_thread );
800 /* Make sure the intf object is getting killed */
801 vlc_object_kill( p_intf );
803 /* Make sure our manage_thread ends */
804 pthread_join( manage_thread, NULL );
806 /* Make sure the interfaceTimer is destroyed */
807 [interfaceTimer invalidate];
808 [interfaceTimer release];
809 interfaceTimer = nil;
811 /* make sure that the current volume is saved */
812 config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
814 /* save the prefs if they were changed in the extended panel */
815 if(o_extended && [o_extended configChanged])
817 [o_extended savePrefs];
820 /* unsubscribe from the interactive dialogues */
821 dialog_Unregister( p_intf );
822 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
823 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
824 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
825 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
826 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
828 /* remove global observer watching for vout device changes correctly */
829 [[NSNotificationCenter defaultCenter] removeObserver: self];
835 /* release some other objects here, because it isn't sure whether dealloc
836 * will be called later on */
837 if( nib_about_loaded )
840 if( nib_prefs_loaded )
846 if( nib_open_loaded )
849 if( nib_extended_loaded )
851 [o_extended release];
854 if( nib_bookmarks_loaded )
855 [o_bookmarks release];
863 if( nib_wizard_loaded )
866 [crashLogURLConnection cancel];
867 [crashLogURLConnection release];
869 [o_embedded_list release];
870 [o_coredialogs release];
873 [o_img_pause_pressed release];
874 [o_img_play_pressed release];
875 [o_img_pause release];
876 [o_img_play release];
878 /* unsubscribe from libvlc's debug messages */
879 msg_Unsubscribe( p_intf->p_sys->p_sub );
881 [o_msg_arr removeAllObjects];
884 [o_msg_lock release];
886 /* write cached user defaults to disk */
887 [[NSUserDefaults standardUserDefaults] synchronize];
889 /* Make sure the Menu doesn't have any references to vlc objects anymore */
890 [self releaseRepresentedObjects:[NSApp mainMenu]];
892 /* Kill the playlist, so that it doesn't accept new request
893 * such as the play request from vlc.c (we are a blocking interface). */
894 p_playlist = pl_Hold( p_intf );
895 vlc_object_kill( p_playlist );
896 pl_Release( p_intf );
898 libvlc_Quit( p_intf->p_libvlc );
902 /* Go back to Run() and make libvlc exit properly */
904 longjmp( jmpbuffer, 1 );
909 #pragma mark Toolbar delegate
911 /* Our item identifiers */
912 static NSString * VLCToolbarMediaControl = @"VLCToolbarMediaControl";
914 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
916 return [NSArray arrayWithObjects:
917 // NSToolbarCustomizeToolbarItemIdentifier,
918 // NSToolbarFlexibleSpaceItemIdentifier,
919 // NSToolbarSpaceItemIdentifier,
920 // NSToolbarSeparatorItemIdentifier,
921 VLCToolbarMediaControl,
925 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
927 return [NSArray arrayWithObjects:
928 VLCToolbarMediaControl,
932 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
934 NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
936 if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
938 [toolbarItem setLabel:@"Media Controls"];
939 [toolbarItem setPaletteLabel:@"Media Controls"];
941 NSSize size = toolbarMediaControl.frame.size;
942 [toolbarItem setView:toolbarMediaControl];
943 [toolbarItem setMinSize:size];
945 [toolbarItem setMaxSize:size];
947 // Hack: For some reason we need to make sure
948 // that the those element are on top
949 // Add them again will put them frontmost
950 [toolbarMediaControl addSubview:o_scrollfield];
951 [toolbarMediaControl addSubview:o_timeslider];
952 [toolbarMediaControl addSubview:o_timefield];
953 [toolbarMediaControl addSubview:o_main_pgbar];
955 /* TODO: setup a menu */
959 /* itemIdentifier referred to a toolbar item that is not
960 * provided or supported by us or Cocoa
961 * Returning nil will inform the toolbar
962 * that this kind of item is not supported */
969 #pragma mark Other notification
971 - (void)controlTintChanged
975 if( [o_btn_play alternateImage] == o_img_play_pressed )
978 if( [NSColor currentControlTint] == NSGraphiteControlTint )
980 o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
981 o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
983 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
984 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
985 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
986 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
987 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
988 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
989 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
990 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
994 o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
995 o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
997 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
998 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
999 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
1000 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
1001 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
1002 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
1003 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
1004 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
1008 [o_btn_play setAlternateImage: o_img_play_pressed];
1010 [o_btn_play setAlternateImage: o_img_pause_pressed];
1013 /* Listen to the remote in exclusive mode, only when VLC is the active
1015 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1017 if( !p_intf ) return;
1018 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
1019 [o_remote startListening: self];
1021 - (void)applicationDidResignActive:(NSNotification *)aNotification
1023 if( !p_intf ) return;
1024 [o_remote stopListening: self];
1027 /* Triggered when the computer goes to sleep */
1028 - (void)computerWillSleep: (NSNotification *)notification
1031 if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
1033 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
1038 #pragma mark File opening
1040 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
1042 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
1043 NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
1045 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
1047 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
1052 /* When user click in the Dock icon our double click in the finder */
1053 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1055 if(!hasVisibleWindows)
1056 [o_window makeKeyAndOrderFront:self];
1062 #pragma mark Apple Remote Control
1064 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1065 increase/decrease as long as the user holds the left/right, plus/minus button */
1066 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1068 if(b_remote_button_hold)
1070 switch([buttonIdentifierNumber intValue])
1072 case kRemoteButtonRight_Hold:
1073 [o_controls forward: self];
1075 case kRemoteButtonLeft_Hold:
1076 [o_controls backward: self];
1078 case kRemoteButtonVolume_Plus_Hold:
1079 [o_controls volumeUp: self];
1081 case kRemoteButtonVolume_Minus_Hold:
1082 [o_controls volumeDown: self];
1085 if(b_remote_button_hold)
1088 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1089 withObject:buttonIdentifierNumber
1095 /* Apple Remote callback */
1096 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1097 pressedDown: (BOOL) pressedDown
1098 clickCount: (unsigned int) count
1100 switch( buttonIdentifier )
1102 case kRemoteButtonPlay:
1104 [o_controls toogleFullscreen:self];
1106 [o_controls play: self];
1109 case kRemoteButtonVolume_Plus:
1110 [o_controls volumeUp: self];
1112 case kRemoteButtonVolume_Minus:
1113 [o_controls volumeDown: self];
1115 case kRemoteButtonRight:
1116 [o_controls next: self];
1118 case kRemoteButtonLeft:
1119 [o_controls prev: self];
1121 case kRemoteButtonRight_Hold:
1122 case kRemoteButtonLeft_Hold:
1123 case kRemoteButtonVolume_Plus_Hold:
1124 case kRemoteButtonVolume_Minus_Hold:
1125 /* simulate an event as long as the user holds the button */
1126 b_remote_button_hold = pressedDown;
1129 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1130 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1131 withObject:buttonIdentifierNumber];
1134 case kRemoteButtonMenu:
1135 [o_controls showPosition: self];
1138 /* Add here whatever you want other buttons to do */
1144 #pragma mark String utility
1145 // FIXME: this has nothing to do here
1147 - (NSString *)localizedString:(const char *)psz
1149 NSString * o_str = nil;
1153 o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1157 msg_Err( VLCIntf, "could not translate: %s", psz );
1163 msg_Warn( VLCIntf, "can't translate empty strings" );
1172 - (char *)delocalizeString:(NSString *)id
1174 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1175 allowLossyConversion: NO];
1180 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1181 allowLossyConversion: YES];
1182 psz_string = malloc( [o_data length] + 1 );
1183 [o_data getBytes: psz_string];
1184 psz_string[ [o_data length] ] = '\0';
1185 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1190 psz_string = malloc( [o_data length] + 1 );
1191 [o_data getBytes: psz_string];
1192 psz_string[ [o_data length] ] = '\0';
1198 /* i_width is in pixels */
1199 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1201 NSMutableString *o_wrapped;
1202 NSString *o_out_string;
1203 NSRange glyphRange, effectiveRange, charRange;
1204 NSRect lineFragmentRect;
1205 unsigned glyphIndex, breaksInserted = 0;
1207 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1208 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1209 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1210 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1211 NSTextContainer *o_container = [[NSTextContainer alloc]
1212 initWithContainerSize: NSMakeSize(i_width, 2000)];
1214 [o_layout_manager addTextContainer: o_container];
1215 [o_container release];
1216 [o_storage addLayoutManager: o_layout_manager];
1217 [o_layout_manager release];
1219 o_wrapped = [o_in_string mutableCopy];
1220 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1222 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1223 glyphIndex += effectiveRange.length) {
1224 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1225 effectiveRange: &effectiveRange];
1226 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1227 actualGlyphRange: &effectiveRange];
1228 if([o_wrapped lineRangeForRange:
1229 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1230 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1234 o_out_string = [NSString stringWithString: o_wrapped];
1235 [o_wrapped release];
1236 [o_storage release];
1238 return o_out_string;
1243 #pragma mark Key Shortcuts
1248 unsigned int i_vlckey;
1249 } nskeys_to_vlckeys[] =
1251 { NSUpArrowFunctionKey, KEY_UP },
1252 { NSDownArrowFunctionKey, KEY_DOWN },
1253 { NSLeftArrowFunctionKey, KEY_LEFT },
1254 { NSRightArrowFunctionKey, KEY_RIGHT },
1255 { NSF1FunctionKey, KEY_F1 },
1256 { NSF2FunctionKey, KEY_F2 },
1257 { NSF3FunctionKey, KEY_F3 },
1258 { NSF4FunctionKey, KEY_F4 },
1259 { NSF5FunctionKey, KEY_F5 },
1260 { NSF6FunctionKey, KEY_F6 },
1261 { NSF7FunctionKey, KEY_F7 },
1262 { NSF8FunctionKey, KEY_F8 },
1263 { NSF9FunctionKey, KEY_F9 },
1264 { NSF10FunctionKey, KEY_F10 },
1265 { NSF11FunctionKey, KEY_F11 },
1266 { NSF12FunctionKey, KEY_F12 },
1267 { NSInsertFunctionKey, KEY_INSERT },
1268 { NSHomeFunctionKey, KEY_HOME },
1269 { NSEndFunctionKey, KEY_END },
1270 { NSPageUpFunctionKey, KEY_PAGEUP },
1271 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1272 { NSMenuFunctionKey, KEY_MENU },
1273 { NSTabCharacter, KEY_TAB },
1274 { NSCarriageReturnCharacter, KEY_ENTER },
1275 { NSEnterCharacter, KEY_ENTER },
1276 { NSBackspaceCharacter, KEY_BACKSPACE },
1277 { (unichar) ' ', KEY_SPACE },
1278 { (unichar) 0x1b, KEY_ESC },
1282 static unichar VLCKeyToCocoa( unsigned int i_key )
1286 for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1288 if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1290 return nskeys_to_vlckeys[i].i_nskey;
1293 return (unichar)(i_key & ~KEY_MODIFIER);
1296 unsigned int CocoaKeyToVLC( unichar i_key )
1300 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1302 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1304 return nskeys_to_vlckeys[i].i_vlckey;
1307 return (unsigned int)i_key;
1310 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1312 unsigned int new = 0;
1313 if( i_key & KEY_MODIFIER_COMMAND )
1314 new |= NSCommandKeyMask;
1315 if( i_key & KEY_MODIFIER_ALT )
1316 new |= NSAlternateKeyMask;
1317 if( i_key & KEY_MODIFIER_SHIFT )
1318 new |= NSShiftKeyMask;
1319 if( i_key & KEY_MODIFIER_CTRL )
1320 new |= NSControlKeyMask;
1324 /*****************************************************************************
1325 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1326 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1327 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1328 *****************************************************************************/
1329 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1333 unsigned int i_pressed_modifiers = 0;
1334 const struct hotkey *p_hotkeys;
1338 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1340 i_pressed_modifiers = [o_event modifierFlags];
1342 if( i_pressed_modifiers & NSShiftKeyMask )
1343 val.i_int |= KEY_MODIFIER_SHIFT;
1344 if( i_pressed_modifiers & NSControlKeyMask )
1345 val.i_int |= KEY_MODIFIER_CTRL;
1346 if( i_pressed_modifiers & NSAlternateKeyMask )
1347 val.i_int |= KEY_MODIFIER_ALT;
1348 if( i_pressed_modifiers & NSCommandKeyMask )
1349 val.i_int |= KEY_MODIFIER_COMMAND;
1351 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1355 case NSDeleteCharacter:
1356 case NSDeleteFunctionKey:
1357 case NSDeleteCharFunctionKey:
1358 case NSBackspaceCharacter:
1359 case NSUpArrowFunctionKey:
1360 case NSDownArrowFunctionKey:
1361 case NSRightArrowFunctionKey:
1362 case NSLeftArrowFunctionKey:
1363 case NSEnterCharacter:
1364 case NSCarriageReturnCharacter:
1368 val.i_int |= CocoaKeyToVLC( key );
1370 for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1372 if( p_hotkeys[i].i_key == val.i_int )
1374 var_Set( p_intf->p_libvlc, "key-pressed", val );
1383 #pragma mark Other objects getters
1393 - (id)simplePreferences
1398 if( !nib_prefs_loaded )
1399 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1409 if( !nib_prefs_loaded )
1410 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1423 - (BOOL)isPlaylistCollapsed
1425 return ![o_btn_playlist state];
1459 if( o_embedded_list )
1460 return o_embedded_list;
1465 - (id)coreDialogProvider
1468 return o_coredialogs;
1476 return o_main_pgbar;
1481 - (id)controllerWindow
1493 - (id)eyeTVController
1501 - (id)appleRemoteController
1507 #pragma mark Polling
1509 /*****************************************************************************
1510 * ManageThread: An ugly thread that polls
1511 *****************************************************************************/
1512 static void * ManageThread( void *user_data )
1514 id self = user_data;
1521 struct manage_cleanup_stack {
1522 intf_thread_t * p_intf;
1523 input_thread_t ** p_input;
1524 playlist_t * p_playlist;
1528 static void manage_cleanup( void * args )
1530 struct manage_cleanup_stack * manage_cleanup_stack = args;
1531 intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1532 input_thread_t * p_input = *manage_cleanup_stack->p_input;
1533 id self = manage_cleanup_stack->self;
1534 playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1536 var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1537 var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1538 var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1539 var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1540 var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1542 pl_Release( p_intf );
1544 if( p_input ) vlc_object_release( p_input );
1549 playlist_t * p_playlist;
1550 input_thread_t * p_input = NULL;
1552 /* new thread requires a new pool */
1554 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1556 p_playlist = pl_Hold( p_intf );
1558 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1559 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1560 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1561 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1562 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1564 struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1565 pthread_cleanup_push(manage_cleanup, &stack);
1569 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1573 p_input = playlist_CurrentInput( p_playlist );
1575 /* Refresh the interface */
1578 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1579 p_intf->p_sys->b_input_update = true;
1582 else if( !vlc_object_alive (p_input) || p_input->b_dead )
1585 p_intf->p_sys->b_intf_update = true;
1586 p_intf->p_sys->i_play_status = END_S;
1587 msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1588 vlc_object_release( p_input );
1591 else if( cachedInputState != input_GetState( p_input ) )
1593 p_intf->p_sys->b_intf_update = true;
1596 /* Manage volume status */
1597 [self manageVolumeSlider];
1599 msleep( INTF_IDLE_SLEEP );
1604 pthread_cleanup_pop(1);
1606 msg_Dbg( p_intf, "Killing the Mac OS X module" );
1608 /* We are dead, terminate */
1609 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1612 - (void)manageVolumeSlider
1614 audio_volume_t i_volume;
1615 playlist_t * p_playlist = pl_Hold( p_intf );
1617 aout_VolumeGet( p_playlist, &i_volume );
1618 pl_Release( p_intf );
1620 if( i_volume != i_lastShownVolume )
1622 i_lastShownVolume = i_volume;
1623 p_intf->p_sys->b_volume_update = TRUE;
1627 - (void)manageIntf:(NSTimer *)o_timer
1630 playlist_t * p_playlist;
1631 input_thread_t * p_input;
1633 if( p_intf->p_sys->b_input_update )
1635 /* Called when new input is opened */
1636 p_intf->p_sys->b_current_title_update = true;
1637 p_intf->p_sys->b_intf_update = true;
1638 p_intf->p_sys->b_input_update = false;
1639 [self setupMenus]; /* Make sure input menu is up to date */
1641 /* update our info-panel to reflect the new item, if we don't show
1642 * the playlist or the selection is empty */
1643 if( [self isPlaylistCollapsed] == YES )
1645 playlist_t * p_playlist = pl_Hold( p_intf );
1647 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1650 [[self info] updatePanelWithItem: p_item->p_input];
1651 pl_Release( p_intf );
1654 if( p_intf->p_sys->b_intf_update )
1656 bool b_input = false;
1657 bool b_plmul = false;
1658 bool b_control = false;
1659 bool b_seekable = false;
1660 bool b_chapters = false;
1662 playlist_t * p_playlist = pl_Hold( p_intf );
1665 b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1668 p_input = playlist_CurrentInput( p_playlist );
1670 bool b_buffering = NO;
1672 if( ( b_input = ( p_input != NULL ) ) )
1674 /* seekable streams */
1675 cachedInputState = input_GetState( p_input );
1676 if ( cachedInputState == INIT_S ||
1677 cachedInputState == OPENING_S )
1682 /* seekable streams */
1683 b_seekable = var_GetBool( p_input, "can-seek" );
1685 /* check whether slow/fast motion is possible */
1686 b_control = var_GetBool( p_input, "can-rate" );
1688 /* chapters & titles */
1689 //b_chapters = p_input->stream.i_area_nb > 1;
1690 vlc_object_release( p_input );
1692 pl_Release( p_intf );
1696 [o_main_pgbar startAnimation:self];
1697 [o_main_pgbar setIndeterminate:YES];
1698 [o_main_pgbar setHidden:NO];
1702 [o_main_pgbar stopAnimation:self];
1703 [o_main_pgbar setHidden:YES];
1706 [o_btn_stop setEnabled: b_input];
1707 [o_embedded_window setStop: b_input];
1708 [o_btn_ff setEnabled: b_seekable];
1709 [o_btn_rewind setEnabled: b_seekable];
1710 [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1711 [o_embedded_window setPrev: (b_plmul || b_chapters)];
1712 [o_btn_next setEnabled: (b_plmul || b_chapters)];
1713 [o_embedded_window setNext: (b_plmul || b_chapters)];
1715 [o_timeslider setFloatValue: 0.0];
1716 [o_timeslider setEnabled: b_seekable];
1717 [o_timefield setStringValue: @"00:00"];
1718 [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1719 [[[self controls] fspanel] setSeekable: b_seekable];
1721 [o_embedded_window setSeekable: b_seekable];
1722 [o_embedded_window setTime:@"00:00" position:0.0];
1724 p_intf->p_sys->b_current_title_update = true;
1726 p_intf->p_sys->b_intf_update = false;
1729 if( p_intf->p_sys->b_playmode_update )
1731 [o_playlist playModeUpdated];
1732 p_intf->p_sys->b_playmode_update = false;
1734 if( p_intf->p_sys->b_playlist_update )
1736 [o_playlist playlistUpdated];
1737 p_intf->p_sys->b_playlist_update = false;
1740 if( p_intf->p_sys->b_fullscreen_update )
1742 p_intf->p_sys->b_fullscreen_update = false;
1745 if( p_intf->p_sys->b_intf_show )
1747 if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1748 [[o_controls fspanel] fadeIn];
1750 [o_window makeKeyAndOrderFront: self];
1752 p_intf->p_sys->b_intf_show = false;
1755 p_input = pl_CurrentInput( p_intf );
1756 if( p_input && vlc_object_alive (p_input) )
1760 if( p_intf->p_sys->b_current_title_update )
1763 input_item_t * p_item = input_GetItem( p_input );
1764 char * name = input_item_GetNowPlaying( p_item );
1767 name = input_item_GetName( p_item );
1769 aString = [NSString stringWithUTF8String:name];
1773 [self setScrollField: aString stopAfter:-1];
1774 [[[self controls] fspanel] setStreamTitle: aString];
1776 [[o_controls voutView] updateTitle];
1778 [o_playlist updateRowSelection];
1780 p_intf->p_sys->b_current_title_update = FALSE;
1783 if( [o_timeslider isEnabled] )
1785 /* Update the slider */
1789 char psz_time[MSTRTIME_MAX_SIZE];
1792 var_Get( p_input, "position", &pos );
1793 f_updated = 10000. * pos.f_float;
1794 [o_timeslider setFloatValue: f_updated];
1796 var_Get( p_input, "time", &time );
1798 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1799 if( b_time_remaining && dur != -1 )
1801 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1804 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1806 [o_timefield setStringValue: o_time];
1807 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1808 [o_embedded_window setTime: o_time position: f_updated];
1811 /* Manage Playing status */
1812 var_Get( p_input, "state", &val );
1813 if( p_intf->p_sys->i_play_status != val.i_int )
1815 p_intf->p_sys->i_play_status = val.i_int;
1816 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1817 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1819 vlc_object_release( p_input );
1823 vlc_object_release( p_input );
1827 p_intf->p_sys->i_play_status = END_S;
1828 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1829 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1830 [self setSubmenusEnabled: FALSE];
1833 if( p_intf->p_sys->b_volume_update )
1836 int i_volume_step = 0;
1837 o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1838 if( i_lastShownVolume != -1 )
1839 [self setScrollField:o_text stopAfter:1000000];
1840 i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1841 [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1842 [o_volumeslider setEnabled: TRUE];
1843 [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1844 [o_embedded_window setVolumeEnabled: TRUE];
1845 [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1846 p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1847 p_intf->p_sys->b_volume_update = FALSE;
1851 [self updateMessageDisplay];
1853 if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1854 [self resetScrollField];
1856 [interfaceTimer autorelease];
1858 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1859 target: self selector: @selector(manageIntf:)
1860 userInfo: nil repeats: FALSE] retain];
1864 #pragma mark Interface update
1868 playlist_t * p_playlist = pl_Hold( p_intf );
1869 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1870 if( p_input != NULL )
1872 [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1873 var: "program" selector: @selector(toggleVar:)];
1875 [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1876 var: "title" selector: @selector(toggleVar:)];
1878 [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1879 var: "chapter" selector: @selector(toggleVar:)];
1881 [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1882 var: "audio-es" selector: @selector(toggleVar:)];
1884 [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1885 var: "video-es" selector: @selector(toggleVar:)];
1887 [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1888 var: "spu-es" selector: @selector(toggleVar:)];
1890 /* special case for "Open File" inside the subtitles menu item */
1891 if( [o_mi_videotrack isEnabled] == YES )
1892 [o_mi_subtitle setEnabled: YES];
1894 aout_instance_t * p_aout = input_GetAout( p_input );
1895 if( p_aout != NULL )
1897 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1898 var: "audio-channels" selector: @selector(toggleVar:)];
1900 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1901 var: "audio-device" selector: @selector(toggleVar:)];
1903 [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1904 var: "visual" selector: @selector(toggleVar:)];
1905 vlc_object_release( (vlc_object_t *)p_aout );
1908 vout_thread_t * p_vout = input_GetVout( p_input );
1910 if( p_vout != NULL )
1912 vlc_object_t * p_dec_obj;
1914 [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1915 var: "aspect-ratio" selector: @selector(toggleVar:)];
1917 [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1918 var: "crop" selector: @selector(toggleVar:)];
1920 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1921 var: "video-device" selector: @selector(toggleVar:)];
1923 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1924 var: "deinterlace" selector: @selector(toggleVar:)];
1927 [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1928 (vlc_object_t *)p_vout var:"postprocess" selector:
1929 @selector(toggleVar:)];
1932 vlc_object_release( (vlc_object_t *)p_vout );
1934 vlc_object_release( p_input );
1936 pl_Release( p_intf );
1939 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1942 vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1948 /* clean the menu before adding new entries */
1949 if( [o_mi_screen hasSubmenu] )
1951 y = [[o_mi_screen submenu] numberOfItems] - 1;
1952 msg_Dbg( VLCIntf, "%i items in submenu", y );
1955 msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1956 [[o_mi_screen submenu] removeItemAtIndex: x];
1961 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1962 var: "video-device" selector: @selector(toggleVar:)];
1963 vlc_object_release( (vlc_object_t *)p_vout );
1966 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1969 i_end_scroll = mdate() + timeout;
1972 [o_scrollfield setStringValue: o_string];
1973 [o_embedded_window setScrollString: o_string];
1976 - (void)resetScrollField
1978 playlist_t * p_playlist = pl_Hold( p_intf );
1979 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1982 if( p_input && vlc_object_alive (p_input) )
1986 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1987 if( input_item_GetNowPlaying( p_item->p_input ) )
1988 o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
1990 o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
1992 [self setScrollField: o_temp stopAfter:-1];
1993 [[[self controls] fspanel] setStreamTitle: o_temp];
1994 vlc_object_release( p_input );
1995 pl_Release( p_intf );
1998 pl_Release( p_intf );
1999 [self setScrollField: _NS("VLC media player") stopAfter:-1];
2002 - (void)playStatusUpdated:(int)i_status
2004 if( i_status == PLAYING_S )
2006 [[[self controls] fspanel] setPause];
2007 [o_btn_play setImage: o_img_pause];
2008 [o_btn_play setAlternateImage: o_img_pause_pressed];
2009 [o_btn_play setToolTip: _NS("Pause")];
2010 [o_mi_play setTitle: _NS("Pause")];
2011 [o_dmi_play setTitle: _NS("Pause")];
2012 [o_vmi_play setTitle: _NS("Pause")];
2016 [[[self controls] fspanel] setPlay];
2017 [o_btn_play setImage: o_img_play];
2018 [o_btn_play setAlternateImage: o_img_play_pressed];
2019 [o_btn_play setToolTip: _NS("Play")];
2020 [o_mi_play setTitle: _NS("Play")];
2021 [o_dmi_play setTitle: _NS("Play")];
2022 [o_vmi_play setTitle: _NS("Play")];
2026 - (void)setSubmenusEnabled:(BOOL)b_enabled
2028 [o_mi_program setEnabled: b_enabled];
2029 [o_mi_title setEnabled: b_enabled];
2030 [o_mi_chapter setEnabled: b_enabled];
2031 [o_mi_audiotrack setEnabled: b_enabled];
2032 [o_mi_visual setEnabled: b_enabled];
2033 [o_mi_videotrack setEnabled: b_enabled];
2034 [o_mi_subtitle setEnabled: b_enabled];
2035 [o_mi_channels setEnabled: b_enabled];
2036 [o_mi_deinterlace setEnabled: b_enabled];
2037 [o_mi_ffmpeg_pp setEnabled: b_enabled];
2038 [o_mi_device setEnabled: b_enabled];
2039 [o_mi_screen setEnabled: b_enabled];
2040 [o_mi_aspect_ratio setEnabled: b_enabled];
2041 [o_mi_crop setEnabled: b_enabled];
2042 [o_mi_teletext setEnabled: b_enabled];
2045 - (IBAction)timesliderUpdate:(id)sender
2048 playlist_t * p_playlist;
2049 input_thread_t * p_input;
2051 switch( [[NSApp currentEvent] type] )
2054 case NSLeftMouseDown:
2055 case NSLeftMouseDragged:
2056 f_updated = [sender floatValue];
2062 p_playlist = pl_Hold( p_intf );
2063 p_input = playlist_CurrentInput( p_playlist );
2064 if( p_input != NULL )
2069 char psz_time[MSTRTIME_MAX_SIZE];
2071 pos.f_float = f_updated / 10000.;
2072 var_Set( p_input, "position", pos );
2073 [o_timeslider setFloatValue: f_updated];
2075 var_Get( p_input, "time", &time );
2077 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
2078 if( b_time_remaining && dur != -1 )
2080 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
2083 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2085 [o_timefield setStringValue: o_time];
2086 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
2087 [o_embedded_window setTime: o_time position: f_updated];
2088 vlc_object_release( p_input );
2090 pl_Release( p_intf );
2093 - (IBAction)timeFieldWasClicked:(id)sender
2095 b_time_remaining = !b_time_remaining;
2100 #pragma mark Recent Items
2102 - (IBAction)clearRecentItems:(id)sender
2104 [[NSDocumentController sharedDocumentController]
2105 clearRecentDocuments: nil];
2108 - (void)openRecentItem:(id)sender
2110 [self application: nil openFile: [sender title]];
2116 - (IBAction)intfOpenFile:(id)sender
2118 if( !nib_open_loaded )
2120 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2121 [o_open awakeFromNib];
2128 - (IBAction)intfOpenFileGeneric:(id)sender
2130 if( !nib_open_loaded )
2132 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2133 [o_open awakeFromNib];
2134 [o_open openFileGeneric];
2136 [o_open openFileGeneric];
2140 - (IBAction)intfOpenDisc:(id)sender
2142 if( !nib_open_loaded )
2144 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2145 [o_open awakeFromNib];
2152 - (IBAction)intfOpenNet:(id)sender
2154 if( !nib_open_loaded )
2156 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2157 [o_open awakeFromNib];
2164 - (IBAction)intfOpenCapture:(id)sender
2166 if( !nib_open_loaded )
2168 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2169 [o_open awakeFromNib];
2170 [o_open openCapture];
2172 [o_open openCapture];
2176 - (IBAction)showWizard:(id)sender
2178 if( !nib_wizard_loaded )
2180 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2181 [o_wizard initStrings];
2182 [o_wizard resetWizard];
2183 [o_wizard showWizard];
2185 [o_wizard resetWizard];
2186 [o_wizard showWizard];
2190 - (IBAction)showVLM:(id)sender
2192 if( !nib_vlm_loaded )
2193 nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner: NSApp];
2195 [o_vlm showVLMWindow];
2198 - (IBAction)showExtended:(id)sender
2200 if( o_extended == nil )
2201 o_extended = [[VLCExtended alloc] init];
2203 if( !nib_extended_loaded )
2204 nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2206 [o_extended showPanel];
2209 - (IBAction)showBookmarks:(id)sender
2211 /* we need the wizard-nib for the bookmarks's extract functionality */
2212 if( !nib_wizard_loaded )
2214 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2215 [o_wizard initStrings];
2218 if( !nib_bookmarks_loaded )
2219 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2221 [o_bookmarks showBookmarks];
2224 - (IBAction)viewPreferences:(id)sender
2226 if( !nib_prefs_loaded )
2228 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2229 o_sprefs = [[VLCSimplePrefs alloc] init];
2230 o_prefs= [[VLCPrefs alloc] init];
2233 [o_sprefs showSimplePrefs];
2239 - (IBAction)checkForUpdate:(id)sender
2242 if( !nib_update_loaded )
2243 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
2244 [o_update showUpdateWindow];
2246 msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2247 dialog_FatalWait( VLCIntf, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2252 #pragma mark Help and Docs
2254 - (IBAction)viewAbout:(id)sender
2256 if( !nib_about_loaded )
2257 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2259 [o_about showAbout];
2262 - (IBAction)showLicense:(id)sender
2264 if( !nib_about_loaded )
2265 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2267 [o_about showGPL: sender];
2270 - (IBAction)viewHelp:(id)sender
2272 if( !nib_about_loaded )
2274 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2281 - (IBAction)openReadMe:(id)sender
2283 NSString * o_path = [[NSBundle mainBundle]
2284 pathForResource: @"README.MacOSX" ofType: @"rtf"];
2286 [[NSWorkspace sharedWorkspace] openFile: o_path
2287 withApplication: @"TextEdit"];
2290 - (IBAction)openDocumentation:(id)sender
2292 NSURL * o_url = [NSURL URLWithString:
2293 @"http://www.videolan.org/doc/"];
2295 [[NSWorkspace sharedWorkspace] openURL: o_url];
2298 - (IBAction)openWebsite:(id)sender
2300 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2302 [[NSWorkspace sharedWorkspace] openURL: o_url];
2305 - (IBAction)openForum:(id)sender
2307 NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2309 [[NSWorkspace sharedWorkspace] openURL: o_url];
2312 - (IBAction)openDonate:(id)sender
2314 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2316 [[NSWorkspace sharedWorkspace] openURL: o_url];
2320 #pragma mark Crash Log
2321 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2323 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2324 NSURL *url = [NSURL URLWithString:urlStr];
2326 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2327 [req setHTTPMethod:@"POST"];
2330 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2332 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2333 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2334 email = [emails valueAtIndex:[emails indexForIdentifier:
2335 [emails primaryIdentifier]]];
2338 email = [NSString string];
2341 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2342 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2343 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2344 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2346 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2348 /* Released from delegate */
2349 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2352 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2354 NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2355 _NS("Thanks for your report!"),
2356 _NS("OK"), nil, nil, nil);
2357 [crashLogURLConnection release];
2358 crashLogURLConnection = nil;
2361 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2363 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2364 [crashLogURLConnection release];
2365 crashLogURLConnection = nil;
2368 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2370 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2371 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2373 NSString * latestLog = nil;
2374 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2375 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2376 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
2377 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2379 while (fname = [direnum nextObject])
2381 [direnum skipDescendents];
2382 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2384 NSArray * compo = [fname componentsSeparatedByString:@"_"];
2385 if( [compo count] < 3 ) continue;
2386 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2387 if( [compo count] < 4 ) continue;
2390 if( year < [[compo objectAtIndex:0] intValue] ||
2391 (year ==[[compo objectAtIndex:0] intValue] &&
2392 (month < [[compo objectAtIndex:1] intValue] ||
2393 (month ==[[compo objectAtIndex:1] intValue] &&
2394 (day < [[compo objectAtIndex:2] intValue] ||
2395 (day ==[[compo objectAtIndex:2] intValue] &&
2396 hours < [[compo objectAtIndex:3] intValue] ))))))
2398 year = [[compo objectAtIndex:0] intValue];
2399 month = [[compo objectAtIndex:1] intValue];
2400 day = [[compo objectAtIndex:2] intValue];
2401 hours = [[compo objectAtIndex:3] intValue];
2402 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2407 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2410 if( !previouslySeen )
2412 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
2413 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2414 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
2415 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2420 - (NSString *)latestCrashLogPath
2422 return [self latestCrashLogPathPreviouslySeen:YES];
2425 - (void)lookForCrashLog
2427 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2428 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2429 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2430 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2431 if( latestLog && !areCrashLogsTooOld )
2432 [NSApp runModalForWindow: o_crashrep_win];
2436 - (IBAction)crashReporterAction:(id)sender
2438 if( sender == o_crashrep_send_btn )
2439 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2442 [o_crashrep_win orderOut: sender];
2445 - (IBAction)openCrashLog:(id)sender
2447 NSString * latestLog = [self latestCrashLogPath];
2450 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2454 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.") );
2459 #pragma mark Remove old prefs
2461 - (void)_removeOldPreferences
2463 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2464 static const int kCurrentPreferencesVersion = 1;
2465 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2466 if( version >= kCurrentPreferencesVersion ) return;
2468 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
2469 NSUserDomainMask, YES);
2470 if( !libraries || [libraries count] == 0) return;
2471 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2473 /* File not found, don't attempt anything */
2474 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2475 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2477 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2481 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2482 _NS("We just found an older version of VLC's preferences files."),
2483 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2484 if( res != NSOKButton )
2486 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2490 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2492 /* Move the file to trash so that user can find them later */
2493 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2495 /* really reset the defaults from now on */
2496 [NSUserDefaults resetStandardUserDefaults];
2498 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2499 [[NSUserDefaults standardUserDefaults] synchronize];
2502 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2504 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2510 execl(path, path, NULL);
2514 #pragma mark Errors, warnings and messages
2516 - (IBAction)viewErrorsAndWarnings:(id)sender
2518 [[[self coreDialogProvider] errorPanel] showPanel];
2521 - (IBAction)showMessagesPanel:(id)sender
2523 [o_msgs_panel makeKeyAndOrderFront: sender];
2526 - (IBAction)showInformationPanel:(id)sender
2528 if(! nib_info_loaded )
2529 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2534 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2536 if( [o_notification object] == o_msgs_panel )
2537 [self updateMessageDisplay];
2540 - (void)updateMessageDisplay
2542 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2545 NSEnumerator * o_enum;
2547 [o_messages setString: @""];
2551 o_enum = [o_msg_arr objectEnumerator];
2553 while( ( o_msg = [o_enum nextObject] ) != nil )
2555 [o_messages insertText: o_msg];
2558 b_msg_arr_changed = NO;
2559 [o_msg_lock unlock];
2563 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2565 NSColor *o_white = [NSColor whiteColor];
2566 NSColor *o_red = [NSColor redColor];
2567 NSColor *o_yellow = [NSColor yellowColor];
2568 NSColor *o_gray = [NSColor grayColor];
2570 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2571 static const char * ppsz_type[4] = { ": ", " error: ",
2572 " warning: ", " debug: " };
2575 NSDictionary *o_attr;
2576 NSAttributedString *o_msg_color;
2578 int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2582 if( [o_msg_arr count] + 2 > 600 )
2584 [o_msg_arr removeObjectAtIndex: 0];
2585 [o_msg_arr removeObjectAtIndex: 1];
2588 o_attr = [NSDictionary dictionaryWithObject: o_gray
2589 forKey: NSForegroundColorAttributeName];
2590 o_msg = [NSString stringWithFormat: @"%@%s",
2591 [[o_notification userInfo] objectForKey: @"Module"],
2593 o_msg_color = [[NSAttributedString alloc]
2594 initWithString: o_msg attributes: o_attr];
2595 [o_msg_arr addObject: [o_msg_color autorelease]];
2597 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2598 forKey: NSForegroundColorAttributeName];
2599 o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2600 o_msg_color = [[NSAttributedString alloc]
2601 initWithString: o_msg attributes: o_attr];
2602 [o_msg_arr addObject: [o_msg_color autorelease]];
2604 b_msg_arr_changed = YES;
2605 [o_msg_lock unlock];
2608 - (IBAction)saveDebugLog:(id)sender
2610 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2612 [saveFolderPanel setCanChooseDirectories: NO];
2613 [saveFolderPanel setCanChooseFiles: YES];
2614 [saveFolderPanel setCanSelectHiddenExtension: NO];
2615 [saveFolderPanel setCanCreateDirectories: YES];
2616 [saveFolderPanel setRequiredFileType: @"rtfd"];
2617 [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];
2620 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2623 if( returnCode == NSOKButton )
2625 b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2627 msg_Warn( p_intf, "Error while saving the debug log" );
2632 #pragma mark Playlist toggling
2634 - (IBAction)togglePlaylist:(id)sender
2636 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2637 NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2638 /*First, check if the playlist is visible*/
2639 if( contentRect.size.height <= 169. )
2641 o_restore_rect = contentRect;
2642 b_restore_size = true;
2643 b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2646 if( o_size_with_playlist.height > 169. )
2647 o_rect.size.height = o_size_with_playlist.height;
2649 o_rect.size.height = 500.;
2651 if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2652 o_rect.size.width = o_size_with_playlist.width;
2654 o_rect.size.width = [o_window contentMinSize].width;
2656 o_rect.origin.x = contentRect.origin.x;
2657 o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2658 [o_window contentMinSize].height;
2660 o_rect = [o_window frameRectForContentRect:o_rect];
2662 NSRect screenRect = [[o_window screen] visibleFrame];
2663 if( !NSContainsRect( screenRect, o_rect ) ) {
2664 if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2665 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2666 if( NSMinY(o_rect) < NSMinY(screenRect) )
2667 o_rect.origin.y = ( NSMinY(screenRect) );
2670 [o_btn_playlist setState: YES];
2674 NSSize curSize = o_rect.size;
2675 if( b_restore_size )
2677 o_rect = o_restore_rect;
2678 if( o_rect.size.height < [o_window contentMinSize].height )
2679 o_rect.size.height = [o_window contentMinSize].height;
2680 if( o_rect.size.width < [o_window contentMinSize].width )
2681 o_rect.size.width = [o_window contentMinSize].width;
2685 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2687 o_rect.size.height = [o_window contentMinSize].height;
2688 o_rect.size.width = [o_window contentMinSize].width;
2689 o_rect.origin.x = contentRect.origin.x;
2690 /* Calculate the position of the lower right corner after resize */
2691 o_rect.origin.y = contentRect.origin.y +
2692 contentRect.size.height - [o_window contentMinSize].height;
2695 [o_playlist_view setAutoresizesSubviews: NO];
2696 [o_playlist_view removeFromSuperview];
2697 [o_btn_playlist setState: NO];
2698 b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2699 o_rect = [o_window frameRectForContentRect:o_rect];
2702 [o_window setFrame: o_rect display:YES animate: YES];
2705 - (void)updateTogglePlaylistState
2707 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2708 [o_btn_playlist setState: NO];
2710 [o_btn_playlist setState: YES];
2712 [[self playlist] outlineViewSelectionDidChange: NULL];
2715 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2718 /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2720 /*Stores the size the controller one resize, to be able to restore it when
2721 toggling the playlist*/
2722 o_size_with_playlist = proposedFrameSize;
2725 rect.size = proposedFrameSize;
2726 if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2728 if( b_small_window == NO )
2730 /* if large and going to small then hide */
2731 b_small_window = YES;
2732 [o_playlist_view setAutoresizesSubviews: NO];
2733 [o_playlist_view removeFromSuperview];
2735 return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2737 return proposedFrameSize;
2740 - (void)windowDidMove:(NSNotification *)notif
2742 b_restore_size = false;
2745 - (void)windowDidResize:(NSNotification *)notif
2747 if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2749 /* If large and coming from small then show */
2750 [o_playlist_view setAutoresizesSubviews: YES];
2751 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2752 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2753 [o_playlist_view setNeedsDisplay:YES];
2754 [[o_window contentView] addSubview: o_playlist_view];
2755 b_small_window = NO;
2757 [self updateTogglePlaylistState];
2764 @implementation VLCMain (NSMenuValidation)
2766 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2768 NSString *o_title = [o_mi title];
2769 BOOL bEnabled = TRUE;
2771 /* Recent Items Menu */
2772 if( [o_title isEqualToString: _NS("Clear Menu")] )
2774 NSMenu * o_menu = [o_mi_open_recent submenu];
2775 int i_nb_items = [o_menu numberOfItems];
2776 NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2777 recentDocumentURLs];
2778 UInt32 i_nb_docs = [o_docs count];
2780 if( i_nb_items > 1 )
2782 while( --i_nb_items )
2784 [o_menu removeItemAtIndex: 0];
2793 [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2799 o_url = [o_docs objectAtIndex: i_nb_docs];
2801 if( [o_url isFileURL] )
2803 o_doc = [o_url path];
2807 o_doc = [o_url absoluteString];
2810 [o_menu insertItemWithTitle: o_doc
2811 action: @selector(openRecentItem:)
2812 keyEquivalent: @"" atIndex: 0];
2814 if( i_nb_docs == 0 )
2830 @implementation VLCMain (Internal)
2832 - (void)handlePortMessage:(NSPortMessage *)o_msg
2837 NSInvocation * o_inv;
2838 NSConditionLock * o_lock;
2840 o_data = [[o_msg components] lastObject];
2841 o_inv = *((NSInvocation **)[o_data bytes]);
2842 [o_inv getArgument: &o_value atIndex: 2];
2843 val = (id **)[o_value pointerValue];
2844 [o_inv setArgument: val[1] atIndex: 2];
2849 [o_lock unlockWithCondition: 1];
2854 /*****************************************************************************
2855 * VLCApplication interface
2856 * exclusively used to implement media key support on Al Apple keyboards
2857 * b_justJumped is required as the keyboard send its events faster than
2858 * the user can actually jump through his media
2859 *****************************************************************************/
2861 @implementation VLCApplication
2863 - (void)awakeFromNib
2865 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2866 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
2871 [[NSNotificationCenter defaultCenter] removeObserver: self];
2875 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2877 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2880 - (void)sendEvent: (NSEvent*)event
2882 if( b_mediaKeySupport )
2884 if( [event type] == NSSystemDefined && [event subtype] == 8 )
2886 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
2887 int keyFlags = ([event data1] & 0x0000FFFF);
2888 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
2889 int keyRepeat = (keyFlags & 0x1);
2891 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
2892 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
2894 if( keyCode == NX_KEYTYPE_FAST && !b_justJumped )
2896 if( keyState == 0 && keyRepeat == 0 )
2898 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_NEXT );
2900 else if( keyRepeat == 1 )
2902 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
2904 [self performSelector:@selector(resetJump)
2910 if( keyCode == NX_KEYTYPE_REWIND && !b_justJumped )
2912 if( keyState == 0 && keyRepeat == 0 )
2914 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PREV );
2916 else if( keyRepeat == 1 )
2918 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
2920 [self performSelector:@selector(resetJump)
2927 [super sendEvent: event];