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: 200] 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-fatal", VLC_VAR_ADDRESS );
527 var_AddCallback( p_intf, "dialog-fatal", DialogCallback, self );
528 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
529 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
530 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
531 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
532 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
533 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
534 dialog_Register( p_intf );
536 /* update the playmode stuff */
537 p_intf->p_sys->b_playmode_update = true;
539 [[NSNotificationCenter defaultCenter] addObserver: self
540 selector: @selector(refreshVoutDeviceMenu:)
541 name: NSApplicationDidChangeScreenParametersNotification
544 /* take care of tint changes during runtime */
545 o_img_play = [NSImage imageNamed: @"play"];
546 o_img_pause = [NSImage imageNamed: @"pause"];
547 [self controlTintChanged];
548 [[NSNotificationCenter defaultCenter] addObserver: self
549 selector: @selector( controlTintChanged )
550 name: NSControlTintDidChangeNotification
553 /* yeah, we are done */
554 nib_main_loaded = TRUE;
557 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
559 if( !p_intf ) return;
561 /* FIXME: don't poll */
562 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
563 target: self selector: @selector(manageIntf:)
564 userInfo: nil repeats: FALSE] retain];
566 /* Note: we use the pthread API to support pre-10.5 */
567 pthread_create( &manage_thread, NULL, ManageThread, self );
569 [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
570 var: "intf-add" selector: @selector(toggleVar:)];
572 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
575 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
577 if( !p_intf ) return;
579 [self _removeOldPreferences];
582 /* Check for update silently on startup */
583 if( !nib_update_loaded )
584 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
586 if([o_update shouldCheckForUpdate])
587 [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:nil];
590 /* Handle sleep notification */
591 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
592 name:NSWorkspaceWillSleepNotification object:nil];
594 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
599 if( !p_intf ) return;
601 [o_window setTitle: _NS("VLC media player")];
602 [self setScrollField:_NS("VLC media player") stopAfter:-1];
604 /* button controls */
605 [o_btn_prev setToolTip: _NS("Previous")];
606 [o_btn_rewind setToolTip: _NS("Rewind")];
607 [o_btn_play setToolTip: _NS("Play")];
608 [o_btn_stop setToolTip: _NS("Stop")];
609 [o_btn_ff setToolTip: _NS("Fast Forward")];
610 [o_btn_next setToolTip: _NS("Next")];
611 [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
612 [o_volumeslider setToolTip: _NS("Volume")];
613 [o_timeslider setToolTip: _NS("Position")];
614 [o_btn_playlist setToolTip: _NS("Playlist")];
617 [o_msgs_panel setTitle: _NS("Messages")];
618 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
619 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
622 [o_mi_about setTitle: [_NS("About VLC media player") \
623 stringByAppendingString: @"..."]];
624 [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
625 [o_mi_prefs setTitle: _NS("Preferences...")];
626 [o_mi_add_intf setTitle: _NS("Add Interface")];
627 [o_mu_add_intf setTitle: _NS("Add Interface")];
628 [o_mi_services setTitle: _NS("Services")];
629 [o_mi_hide setTitle: _NS("Hide VLC")];
630 [o_mi_hide_others setTitle: _NS("Hide Others")];
631 [o_mi_show_all setTitle: _NS("Show All")];
632 [o_mi_quit setTitle: _NS("Quit VLC")];
634 [o_mu_file setTitle: _ANS("1:File")];
635 [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
636 [o_mi_open_file setTitle: _NS("Open File...")];
637 [o_mi_open_disc setTitle: _NS("Open Disc...")];
638 [o_mi_open_net setTitle: _NS("Open Network...")];
639 [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
640 [o_mi_open_recent setTitle: _NS("Open Recent")];
641 [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
642 [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
644 [o_mu_edit setTitle: _NS("Edit")];
645 [o_mi_cut setTitle: _NS("Cut")];
646 [o_mi_copy setTitle: _NS("Copy")];
647 [o_mi_paste setTitle: _NS("Paste")];
648 [o_mi_clear setTitle: _NS("Clear")];
649 [o_mi_select_all setTitle: _NS("Select All")];
651 [o_mu_controls setTitle: _NS("Playback")];
652 [o_mi_play setTitle: _NS("Play")];
653 [o_mi_stop setTitle: _NS("Stop")];
654 [o_mi_faster setTitle: _NS("Faster")];
655 [o_mi_slower setTitle: _NS("Slower")];
656 [o_mi_previous setTitle: _NS("Previous")];
657 [o_mi_next setTitle: _NS("Next")];
658 [o_mi_random setTitle: _NS("Random")];
659 [o_mi_repeat setTitle: _NS("Repeat One")];
660 [o_mi_loop setTitle: _NS("Repeat All")];
661 [o_mi_fwd setTitle: _NS("Step Forward")];
662 [o_mi_bwd setTitle: _NS("Step Backward")];
664 [o_mi_program setTitle: _NS("Program")];
665 [o_mu_program setTitle: _NS("Program")];
666 [o_mi_title setTitle: _NS("Title")];
667 [o_mu_title setTitle: _NS("Title")];
668 [o_mi_chapter setTitle: _NS("Chapter")];
669 [o_mu_chapter setTitle: _NS("Chapter")];
671 [o_mu_audio setTitle: _NS("Audio")];
672 [o_mi_vol_up setTitle: _NS("Increase Volume")];
673 [o_mi_vol_down setTitle: _NS("Decrease Volume")];
674 [o_mi_mute setTitle: _NS("Mute")];
675 [o_mi_audiotrack setTitle: _NS("Audio Track")];
676 [o_mu_audiotrack setTitle: _NS("Audio Track")];
677 [o_mi_channels setTitle: _NS("Audio Channels")];
678 [o_mu_channels setTitle: _NS("Audio Channels")];
679 [o_mi_device setTitle: _NS("Audio Device")];
680 [o_mu_device setTitle: _NS("Audio Device")];
681 [o_mi_visual setTitle: _NS("Visualizations")];
682 [o_mu_visual setTitle: _NS("Visualizations")];
684 [o_mu_video setTitle: _NS("Video")];
685 [o_mi_half_window setTitle: _NS("Half Size")];
686 [o_mi_normal_window setTitle: _NS("Normal Size")];
687 [o_mi_double_window setTitle: _NS("Double Size")];
688 [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
689 [o_mi_fullscreen setTitle: _NS("Fullscreen")];
690 [o_mi_floatontop setTitle: _NS("Float on Top")];
691 [o_mi_snapshot setTitle: _NS("Snapshot")];
692 [o_mi_videotrack setTitle: _NS("Video Track")];
693 [o_mu_videotrack setTitle: _NS("Video Track")];
694 [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
695 [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
696 [o_mi_crop setTitle: _NS("Crop")];
697 [o_mu_crop setTitle: _NS("Crop")];
698 [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
699 [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
700 [o_mi_subtitle setTitle: _NS("Subtitles Track")];
701 [o_mu_subtitle setTitle: _NS("Subtitles Track")];
702 [o_mi_addSub setTitle: _NS("Open File...")];
703 [o_mi_deinterlace setTitle: _NS("Deinterlace")];
704 [o_mu_deinterlace setTitle: _NS("Deinterlace")];
705 [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
706 [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
707 [o_mi_teletext setTitle: _NS("Teletext")];
708 [o_mi_teletext_transparent setTitle: _NS("Transparent")];
709 [o_mi_teletext_index setTitle: _NS("Index")];
710 [o_mi_teletext_red setTitle: _NS("Red")];
711 [o_mi_teletext_green setTitle: _NS("Green")];
712 [o_mi_teletext_yellow setTitle: _NS("Yellow")];
713 [o_mi_teletext_blue setTitle: _NS("Blue")];
715 [o_mu_window setTitle: _NS("Window")];
716 [o_mi_minimize setTitle: _NS("Minimize Window")];
717 [o_mi_close_window setTitle: _NS("Close Window")];
718 [o_mi_player setTitle: _NS("Player...")];
719 [o_mi_controller setTitle: _NS("Controller...")];
720 [o_mi_equalizer setTitle: _NS("Equalizer...")];
721 [o_mi_extended setTitle: _NS("Extended Controls...")];
722 [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
723 [o_mi_playlist setTitle: _NS("Playlist...")];
724 [o_mi_info setTitle: _NS("Media Information...")];
725 [o_mi_messages setTitle: _NS("Messages...")];
726 [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
728 [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
730 [o_mu_help setTitle: _NS("Help")];
731 [o_mi_help setTitle: _NS("VLC media player Help...")];
732 [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
733 [o_mi_license setTitle: _NS("License")];
734 [o_mi_documentation setTitle: _NS("Online Documentation...")];
735 [o_mi_website setTitle: _NS("VideoLAN Website...")];
736 [o_mi_donation setTitle: _NS("Make a donation...")];
737 [o_mi_forum setTitle: _NS("Online Forum...")];
740 [o_dmi_play setTitle: _NS("Play")];
741 [o_dmi_stop setTitle: _NS("Stop")];
742 [o_dmi_next setTitle: _NS("Next")];
743 [o_dmi_previous setTitle: _NS("Previous")];
744 [o_dmi_mute setTitle: _NS("Mute")];
747 [o_vmi_play setTitle: _NS("Play")];
748 [o_vmi_stop setTitle: _NS("Stop")];
749 [o_vmi_prev setTitle: _NS("Previous")];
750 [o_vmi_next setTitle: _NS("Next")];
751 [o_vmi_volup setTitle: _NS("Volume Up")];
752 [o_vmi_voldown setTitle: _NS("Volume Down")];
753 [o_vmi_mute setTitle: _NS("Mute")];
754 [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
755 [o_vmi_snapshot setTitle: _NS("Snapshot")];
757 /* crash reporter panel */
758 [o_crashrep_send_btn setTitle: _NS("Send")];
759 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
760 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
761 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
762 [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, ...")];
763 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
764 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
768 #pragma mark Termination
770 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
772 if( !p_intf ) return;
774 NSArray *menuitems_array = [the_menu itemArray];
775 for( int i=0; i<[menuitems_array count]; i++ )
777 NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
778 if( [one_item hasSubmenu] )
779 [self releaseRepresentedObjects: [one_item submenu]];
781 [one_item setRepresentedObject:NULL];
785 - (void)applicationWillTerminate:(NSNotification *)notification
787 playlist_t * p_playlist;
788 vout_thread_t * p_vout;
789 int returnedValue = 0;
791 if( !p_intf ) return;
793 msg_Dbg( p_intf, "Terminating" );
795 /* Make sure the manage_thread won't call -terminate: again */
796 pthread_cancel( manage_thread );
798 /* Make sure the intf object is getting killed */
799 vlc_object_kill( p_intf );
801 /* Make sure our manage_thread ends */
802 pthread_join( manage_thread, NULL );
804 /* Make sure the interfaceTimer is destroyed */
805 [interfaceTimer invalidate];
806 [interfaceTimer release];
807 interfaceTimer = nil;
809 /* make sure that the current volume is saved */
810 config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
812 /* save the prefs if they were changed in the extended panel */
813 if(o_extended && [o_extended configChanged])
815 [o_extended savePrefs];
818 /* unsubscribe from the interactive dialogues */
819 dialog_Unregister( p_intf );
820 var_DelCallback( p_intf, "dialog-fatal", DialogCallback, self );
821 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
822 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
823 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
825 /* remove global observer watching for vout device changes correctly */
826 [[NSNotificationCenter defaultCenter] removeObserver: self];
832 /* release some other objects here, because it isn't sure whether dealloc
833 * will be called later on */
834 if( nib_about_loaded )
837 if( nib_prefs_loaded )
843 if( nib_open_loaded )
846 if( nib_extended_loaded )
848 [o_extended release];
851 if( nib_bookmarks_loaded )
852 [o_bookmarks release];
860 if( nib_wizard_loaded )
863 [crashLogURLConnection cancel];
864 [crashLogURLConnection release];
866 [o_embedded_list release];
867 [o_coredialogs release];
870 [o_img_pause_pressed release];
871 [o_img_play_pressed release];
872 [o_img_pause release];
873 [o_img_play release];
875 /* unsubscribe from libvlc's debug messages */
876 msg_Unsubscribe( p_intf->p_sys->p_sub );
878 [o_msg_arr removeAllObjects];
881 [o_msg_lock release];
883 /* write cached user defaults to disk */
884 [[NSUserDefaults standardUserDefaults] synchronize];
886 /* Make sure the Menu doesn't have any references to vlc objects anymore */
887 [self releaseRepresentedObjects:[NSApp mainMenu]];
889 /* Kill the playlist, so that it doesn't accept new request
890 * such as the play request from vlc.c (we are a blocking interface). */
891 p_playlist = pl_Hold( p_intf );
892 vlc_object_kill( p_playlist );
893 pl_Release( p_intf );
895 libvlc_Quit( p_intf->p_libvlc );
899 /* Go back to Run() and make libvlc exit properly */
901 longjmp( jmpbuffer, 1 );
906 #pragma mark Toolbar delegate
908 /* Our item identifiers */
909 static NSString * VLCToolbarMediaControl = @"VLCToolbarMediaControl";
911 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
913 return [NSArray arrayWithObjects:
914 // NSToolbarCustomizeToolbarItemIdentifier,
915 // NSToolbarFlexibleSpaceItemIdentifier,
916 // NSToolbarSpaceItemIdentifier,
917 // NSToolbarSeparatorItemIdentifier,
918 VLCToolbarMediaControl,
922 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
924 return [NSArray arrayWithObjects:
925 VLCToolbarMediaControl,
929 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
931 NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
933 if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
935 [toolbarItem setLabel:@"Media Controls"];
936 [toolbarItem setPaletteLabel:@"Media Controls"];
938 NSSize size = toolbarMediaControl.frame.size;
939 [toolbarItem setView:toolbarMediaControl];
940 [toolbarItem setMinSize:size];
942 [toolbarItem setMaxSize:size];
944 // Hack: For some reason we need to make sure
945 // that the those element are on top
946 // Add them again will put them frontmost
947 [toolbarMediaControl addSubview:o_scrollfield];
948 [toolbarMediaControl addSubview:o_timeslider];
949 [toolbarMediaControl addSubview:o_timefield];
950 [toolbarMediaControl addSubview:o_main_pgbar];
952 /* TODO: setup a menu */
956 /* itemIdentifier referred to a toolbar item that is not
957 * provided or supported by us or Cocoa
958 * Returning nil will inform the toolbar
959 * that this kind of item is not supported */
966 #pragma mark Other notification
968 - (void)controlTintChanged
972 if( [o_btn_play alternateImage] == o_img_play_pressed )
975 if( [NSColor currentControlTint] == NSGraphiteControlTint )
977 o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
978 o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
980 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
981 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
982 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
983 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
984 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
985 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
986 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
987 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
991 o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
992 o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
994 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
995 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
996 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
997 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
998 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
999 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
1000 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
1001 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
1005 [o_btn_play setAlternateImage: o_img_play_pressed];
1007 [o_btn_play setAlternateImage: o_img_pause_pressed];
1010 /* Listen to the remote in exclusive mode, only when VLC is the active
1012 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1014 if( !p_intf ) return;
1015 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
1016 [o_remote startListening: self];
1018 - (void)applicationDidResignActive:(NSNotification *)aNotification
1020 if( !p_intf ) return;
1021 [o_remote stopListening: self];
1024 /* Triggered when the computer goes to sleep */
1025 - (void)computerWillSleep: (NSNotification *)notification
1028 if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
1030 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
1035 #pragma mark File opening
1037 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
1039 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
1040 NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
1042 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
1044 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
1049 /* When user click in the Dock icon our double click in the finder */
1050 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1052 if(!hasVisibleWindows)
1053 [o_window makeKeyAndOrderFront:self];
1059 #pragma mark Apple Remote Control
1061 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1062 increase/decrease as long as the user holds the left/right, plus/minus button */
1063 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1065 if(b_remote_button_hold)
1067 switch([buttonIdentifierNumber intValue])
1069 case kRemoteButtonRight_Hold:
1070 [o_controls forward: self];
1072 case kRemoteButtonLeft_Hold:
1073 [o_controls backward: self];
1075 case kRemoteButtonVolume_Plus_Hold:
1076 [o_controls volumeUp: self];
1078 case kRemoteButtonVolume_Minus_Hold:
1079 [o_controls volumeDown: self];
1082 if(b_remote_button_hold)
1085 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1086 withObject:buttonIdentifierNumber
1092 /* Apple Remote callback */
1093 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1094 pressedDown: (BOOL) pressedDown
1095 clickCount: (unsigned int) count
1097 switch( buttonIdentifier )
1099 case kRemoteButtonPlay:
1101 [o_controls toogleFullscreen:self];
1103 [o_controls play: self];
1106 case kRemoteButtonVolume_Plus:
1107 [o_controls volumeUp: self];
1109 case kRemoteButtonVolume_Minus:
1110 [o_controls volumeDown: self];
1112 case kRemoteButtonRight:
1113 [o_controls next: self];
1115 case kRemoteButtonLeft:
1116 [o_controls prev: self];
1118 case kRemoteButtonRight_Hold:
1119 case kRemoteButtonLeft_Hold:
1120 case kRemoteButtonVolume_Plus_Hold:
1121 case kRemoteButtonVolume_Minus_Hold:
1122 /* simulate an event as long as the user holds the button */
1123 b_remote_button_hold = pressedDown;
1126 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1127 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1128 withObject:buttonIdentifierNumber];
1131 case kRemoteButtonMenu:
1132 [o_controls showPosition: self];
1135 /* Add here whatever you want other buttons to do */
1141 #pragma mark String utility
1142 // FIXME: this has nothing to do here
1144 - (NSString *)localizedString:(const char *)psz
1146 NSString * o_str = nil;
1150 o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1154 msg_Err( VLCIntf, "could not translate: %s", psz );
1160 msg_Warn( VLCIntf, "can't translate empty strings" );
1169 - (char *)delocalizeString:(NSString *)id
1171 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1172 allowLossyConversion: NO];
1177 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1178 allowLossyConversion: YES];
1179 psz_string = malloc( [o_data length] + 1 );
1180 [o_data getBytes: psz_string];
1181 psz_string[ [o_data length] ] = '\0';
1182 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1187 psz_string = malloc( [o_data length] + 1 );
1188 [o_data getBytes: psz_string];
1189 psz_string[ [o_data length] ] = '\0';
1195 /* i_width is in pixels */
1196 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1198 NSMutableString *o_wrapped;
1199 NSString *o_out_string;
1200 NSRange glyphRange, effectiveRange, charRange;
1201 NSRect lineFragmentRect;
1202 unsigned glyphIndex, breaksInserted = 0;
1204 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1205 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1206 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1207 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1208 NSTextContainer *o_container = [[NSTextContainer alloc]
1209 initWithContainerSize: NSMakeSize(i_width, 2000)];
1211 [o_layout_manager addTextContainer: o_container];
1212 [o_container release];
1213 [o_storage addLayoutManager: o_layout_manager];
1214 [o_layout_manager release];
1216 o_wrapped = [o_in_string mutableCopy];
1217 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1219 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1220 glyphIndex += effectiveRange.length) {
1221 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1222 effectiveRange: &effectiveRange];
1223 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1224 actualGlyphRange: &effectiveRange];
1225 if([o_wrapped lineRangeForRange:
1226 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1227 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1231 o_out_string = [NSString stringWithString: o_wrapped];
1232 [o_wrapped release];
1233 [o_storage release];
1235 return o_out_string;
1240 #pragma mark Key Shortcuts
1245 unsigned int i_vlckey;
1246 } nskeys_to_vlckeys[] =
1248 { NSUpArrowFunctionKey, KEY_UP },
1249 { NSDownArrowFunctionKey, KEY_DOWN },
1250 { NSLeftArrowFunctionKey, KEY_LEFT },
1251 { NSRightArrowFunctionKey, KEY_RIGHT },
1252 { NSF1FunctionKey, KEY_F1 },
1253 { NSF2FunctionKey, KEY_F2 },
1254 { NSF3FunctionKey, KEY_F3 },
1255 { NSF4FunctionKey, KEY_F4 },
1256 { NSF5FunctionKey, KEY_F5 },
1257 { NSF6FunctionKey, KEY_F6 },
1258 { NSF7FunctionKey, KEY_F7 },
1259 { NSF8FunctionKey, KEY_F8 },
1260 { NSF9FunctionKey, KEY_F9 },
1261 { NSF10FunctionKey, KEY_F10 },
1262 { NSF11FunctionKey, KEY_F11 },
1263 { NSF12FunctionKey, KEY_F12 },
1264 { NSInsertFunctionKey, KEY_INSERT },
1265 { NSHomeFunctionKey, KEY_HOME },
1266 { NSEndFunctionKey, KEY_END },
1267 { NSPageUpFunctionKey, KEY_PAGEUP },
1268 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1269 { NSMenuFunctionKey, KEY_MENU },
1270 { NSTabCharacter, KEY_TAB },
1271 { NSCarriageReturnCharacter, KEY_ENTER },
1272 { NSEnterCharacter, KEY_ENTER },
1273 { NSBackspaceCharacter, KEY_BACKSPACE },
1274 { (unichar) ' ', KEY_SPACE },
1275 { (unichar) 0x1b, KEY_ESC },
1279 static unichar VLCKeyToCocoa( unsigned int i_key )
1283 for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1285 if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1287 return nskeys_to_vlckeys[i].i_nskey;
1290 return (unichar)(i_key & ~KEY_MODIFIER);
1293 unsigned int CocoaKeyToVLC( unichar i_key )
1297 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1299 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1301 return nskeys_to_vlckeys[i].i_vlckey;
1304 return (unsigned int)i_key;
1307 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1309 unsigned int new = 0;
1310 if( i_key & KEY_MODIFIER_COMMAND )
1311 new |= NSCommandKeyMask;
1312 if( i_key & KEY_MODIFIER_ALT )
1313 new |= NSAlternateKeyMask;
1314 if( i_key & KEY_MODIFIER_SHIFT )
1315 new |= NSShiftKeyMask;
1316 if( i_key & KEY_MODIFIER_CTRL )
1317 new |= NSControlKeyMask;
1321 /*****************************************************************************
1322 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1323 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1324 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1325 *****************************************************************************/
1326 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1330 unsigned int i_pressed_modifiers = 0;
1331 const struct hotkey *p_hotkeys;
1335 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1337 i_pressed_modifiers = [o_event modifierFlags];
1339 if( i_pressed_modifiers & NSShiftKeyMask )
1340 val.i_int |= KEY_MODIFIER_SHIFT;
1341 if( i_pressed_modifiers & NSControlKeyMask )
1342 val.i_int |= KEY_MODIFIER_CTRL;
1343 if( i_pressed_modifiers & NSAlternateKeyMask )
1344 val.i_int |= KEY_MODIFIER_ALT;
1345 if( i_pressed_modifiers & NSCommandKeyMask )
1346 val.i_int |= KEY_MODIFIER_COMMAND;
1348 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1352 case NSDeleteCharacter:
1353 case NSDeleteFunctionKey:
1354 case NSDeleteCharFunctionKey:
1355 case NSBackspaceCharacter:
1356 case NSUpArrowFunctionKey:
1357 case NSDownArrowFunctionKey:
1358 case NSRightArrowFunctionKey:
1359 case NSLeftArrowFunctionKey:
1360 case NSEnterCharacter:
1361 case NSCarriageReturnCharacter:
1365 val.i_int |= CocoaKeyToVLC( key );
1367 for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1369 if( p_hotkeys[i].i_key == val.i_int )
1371 var_Set( p_intf->p_libvlc, "key-pressed", val );
1380 #pragma mark Other objects getters
1390 - (id)simplePreferences
1395 if( !nib_prefs_loaded )
1396 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1406 if( !nib_prefs_loaded )
1407 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1420 - (BOOL)isPlaylistCollapsed
1422 return ![o_btn_playlist state];
1456 if( o_embedded_list )
1457 return o_embedded_list;
1462 - (id)coreDialogProvider
1465 return o_coredialogs;
1473 return o_main_pgbar;
1478 - (id)controllerWindow
1490 - (id)eyeTVController
1498 - (id)appleRemoteController
1504 #pragma mark Polling
1506 /*****************************************************************************
1507 * ManageThread: An ugly thread that polls
1508 *****************************************************************************/
1509 static void * ManageThread( void *user_data )
1511 id self = user_data;
1518 struct manage_cleanup_stack {
1519 intf_thread_t * p_intf;
1520 input_thread_t ** p_input;
1521 playlist_t * p_playlist;
1525 static void manage_cleanup( void * args )
1527 struct manage_cleanup_stack * manage_cleanup_stack = args;
1528 intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1529 input_thread_t * p_input = *manage_cleanup_stack->p_input;
1530 id self = manage_cleanup_stack->self;
1531 playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1533 var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1534 var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1535 var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1536 var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1537 var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1539 pl_Release( p_intf );
1541 if( p_input ) vlc_object_release( p_input );
1546 playlist_t * p_playlist;
1547 input_thread_t * p_input = NULL;
1549 /* new thread requires a new pool */
1551 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1553 p_playlist = pl_Hold( p_intf );
1555 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1556 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1557 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1558 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1559 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1561 struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1562 pthread_cleanup_push(manage_cleanup, &stack);
1566 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1570 p_input = playlist_CurrentInput( p_playlist );
1572 /* Refresh the interface */
1575 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1576 p_intf->p_sys->b_input_update = true;
1579 else if( !vlc_object_alive (p_input) || p_input->b_dead )
1582 p_intf->p_sys->b_intf_update = true;
1583 p_intf->p_sys->i_play_status = END_S;
1584 msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1585 vlc_object_release( p_input );
1588 else if( cachedInputState != input_GetState( p_input ) )
1590 p_intf->p_sys->b_intf_update = true;
1593 /* Manage volume status */
1594 [self manageVolumeSlider];
1596 msleep( INTF_IDLE_SLEEP );
1601 pthread_cleanup_pop(1);
1603 msg_Dbg( p_intf, "Killing the Mac OS X module" );
1605 /* We are dead, terminate */
1606 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1609 - (void)manageVolumeSlider
1611 audio_volume_t i_volume;
1612 aout_VolumeGet( p_intf, &i_volume );
1614 if( i_volume != i_lastShownVolume )
1616 i_lastShownVolume = i_volume;
1617 p_intf->p_sys->b_volume_update = TRUE;
1621 - (void)manageIntf:(NSTimer *)o_timer
1624 playlist_t * p_playlist;
1625 input_thread_t * p_input;
1627 if( p_intf->p_sys->b_input_update )
1629 /* Called when new input is opened */
1630 p_intf->p_sys->b_current_title_update = true;
1631 p_intf->p_sys->b_intf_update = true;
1632 p_intf->p_sys->b_input_update = false;
1633 [self setupMenus]; /* Make sure input menu is up to date */
1635 /* update our info-panel to reflect the new item, if we don't show
1636 * the playlist or the selection is empty */
1637 if( [self isPlaylistCollapsed] == YES )
1639 playlist_t * p_playlist = pl_Hold( p_intf );
1641 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1644 [[self info] updatePanelWithItem: p_item->p_input];
1645 pl_Release( p_intf );
1648 if( p_intf->p_sys->b_intf_update )
1650 bool b_input = false;
1651 bool b_plmul = false;
1652 bool b_control = false;
1653 bool b_seekable = false;
1654 bool b_chapters = false;
1656 playlist_t * p_playlist = pl_Hold( p_intf );
1659 b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1662 p_input = playlist_CurrentInput( p_playlist );
1664 bool b_buffering = NO;
1666 if( ( b_input = ( p_input != NULL ) ) )
1668 /* seekable streams */
1669 cachedInputState = input_GetState( p_input );
1670 if ( cachedInputState == INIT_S ||
1671 cachedInputState == OPENING_S )
1676 /* seekable streams */
1677 b_seekable = var_GetBool( p_input, "can-seek" );
1679 /* check whether slow/fast motion is possible */
1680 b_control = var_GetBool( p_input, "can-rate" );
1682 /* chapters & titles */
1683 //b_chapters = p_input->stream.i_area_nb > 1;
1684 vlc_object_release( p_input );
1686 pl_Release( p_intf );
1690 [o_main_pgbar startAnimation:self];
1691 [o_main_pgbar setIndeterminate:YES];
1692 [o_main_pgbar setHidden:NO];
1696 [o_main_pgbar stopAnimation:self];
1697 [o_main_pgbar setHidden:YES];
1700 [o_btn_stop setEnabled: b_input];
1701 [o_embedded_window setStop: b_input];
1702 [o_btn_ff setEnabled: b_seekable];
1703 [o_btn_rewind setEnabled: b_seekable];
1704 [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1705 [o_embedded_window setPrev: (b_plmul || b_chapters)];
1706 [o_btn_next setEnabled: (b_plmul || b_chapters)];
1707 [o_embedded_window setNext: (b_plmul || b_chapters)];
1709 [o_timeslider setFloatValue: 0.0];
1710 [o_timeslider setEnabled: b_seekable];
1711 [o_timefield setStringValue: @"00:00"];
1712 [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1713 [[[self controls] fspanel] setSeekable: b_seekable];
1715 [o_embedded_window setSeekable: b_seekable];
1716 [o_embedded_window setTime:@"00:00" position:0.0];
1718 p_intf->p_sys->b_current_title_update = true;
1720 p_intf->p_sys->b_intf_update = false;
1723 if( p_intf->p_sys->b_playmode_update )
1725 [o_playlist playModeUpdated];
1726 p_intf->p_sys->b_playmode_update = false;
1728 if( p_intf->p_sys->b_playlist_update )
1730 [o_playlist playlistUpdated];
1731 p_intf->p_sys->b_playlist_update = false;
1734 if( p_intf->p_sys->b_fullscreen_update )
1736 p_intf->p_sys->b_fullscreen_update = false;
1739 if( p_intf->p_sys->b_intf_show )
1741 if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1742 [[o_controls fspanel] fadeIn];
1744 [o_window makeKeyAndOrderFront: self];
1746 p_intf->p_sys->b_intf_show = false;
1749 p_input = pl_CurrentInput( p_intf );
1750 if( p_input && vlc_object_alive (p_input) )
1754 if( p_intf->p_sys->b_current_title_update )
1757 input_item_t * p_item = input_GetItem( p_input );
1758 char * name = input_item_GetNowPlaying( p_item );
1761 name = input_item_GetName( p_item );
1763 aString = [NSString stringWithUTF8String:name];
1767 [self setScrollField: aString stopAfter:-1];
1768 [[[self controls] fspanel] setStreamTitle: aString];
1770 [[o_controls voutView] updateTitle];
1772 [o_playlist updateRowSelection];
1774 p_intf->p_sys->b_current_title_update = FALSE;
1777 if( [o_timeslider isEnabled] )
1779 /* Update the slider */
1783 char psz_time[MSTRTIME_MAX_SIZE];
1786 var_Get( p_input, "position", &pos );
1787 f_updated = 10000. * pos.f_float;
1788 [o_timeslider setFloatValue: f_updated];
1790 var_Get( p_input, "time", &time );
1792 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1793 if( b_time_remaining && dur != -1 )
1795 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1798 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1800 [o_timefield setStringValue: o_time];
1801 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1802 [o_embedded_window setTime: o_time position: f_updated];
1805 /* Manage Playing status */
1806 var_Get( p_input, "state", &val );
1807 if( p_intf->p_sys->i_play_status != val.i_int )
1809 p_intf->p_sys->i_play_status = val.i_int;
1810 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1811 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1813 vlc_object_release( p_input );
1817 vlc_object_release( p_input );
1821 p_intf->p_sys->i_play_status = END_S;
1822 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1823 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1824 [self setSubmenusEnabled: FALSE];
1827 if( p_intf->p_sys->b_volume_update )
1830 int i_volume_step = 0;
1831 o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1832 if( i_lastShownVolume != -1 )
1833 [self setScrollField:o_text stopAfter:1000000];
1834 i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1835 [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1836 [o_volumeslider setEnabled: TRUE];
1837 [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1838 [o_embedded_window setVolumeEnabled: TRUE];
1839 [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1840 p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1841 p_intf->p_sys->b_volume_update = FALSE;
1845 [self updateMessageDisplay];
1847 if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1848 [self resetScrollField];
1850 [interfaceTimer autorelease];
1852 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1853 target: self selector: @selector(manageIntf:)
1854 userInfo: nil repeats: FALSE] retain];
1858 #pragma mark Interface update
1862 playlist_t * p_playlist = pl_Hold( p_intf );
1863 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1864 if( p_input != NULL )
1866 [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1867 var: "program" selector: @selector(toggleVar:)];
1869 [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1870 var: "title" selector: @selector(toggleVar:)];
1872 [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1873 var: "chapter" selector: @selector(toggleVar:)];
1875 [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1876 var: "audio-es" selector: @selector(toggleVar:)];
1878 [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1879 var: "video-es" selector: @selector(toggleVar:)];
1881 [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1882 var: "spu-es" selector: @selector(toggleVar:)];
1884 /* special case for "Open File" inside the subtitles menu item */
1885 if( [o_mi_videotrack isEnabled] == YES )
1886 [o_mi_subtitle setEnabled: YES];
1888 aout_instance_t * p_aout = input_GetAout( p_input );
1889 if( p_aout != NULL )
1891 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1892 var: "audio-channels" selector: @selector(toggleVar:)];
1894 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1895 var: "audio-device" selector: @selector(toggleVar:)];
1897 [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1898 var: "visual" selector: @selector(toggleVar:)];
1899 vlc_object_release( (vlc_object_t *)p_aout );
1902 vout_thread_t * p_vout = input_GetVout( p_input );
1904 if( p_vout != NULL )
1906 vlc_object_t * p_dec_obj;
1908 [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1909 var: "aspect-ratio" selector: @selector(toggleVar:)];
1911 [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1912 var: "crop" selector: @selector(toggleVar:)];
1914 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1915 var: "video-device" selector: @selector(toggleVar:)];
1917 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1918 var: "deinterlace" selector: @selector(toggleVar:)];
1921 [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1922 (vlc_object_t *)p_vout var:"postprocess" selector:
1923 @selector(toggleVar:)];
1926 vlc_object_release( (vlc_object_t *)p_vout );
1928 vlc_object_release( p_input );
1930 pl_Release( p_intf );
1933 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1936 vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1942 /* clean the menu before adding new entries */
1943 if( [o_mi_screen hasSubmenu] )
1945 y = [[o_mi_screen submenu] numberOfItems] - 1;
1946 msg_Dbg( VLCIntf, "%i items in submenu", y );
1949 msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1950 [[o_mi_screen submenu] removeItemAtIndex: x];
1955 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1956 var: "video-device" selector: @selector(toggleVar:)];
1957 vlc_object_release( (vlc_object_t *)p_vout );
1960 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1963 i_end_scroll = mdate() + timeout;
1966 [o_scrollfield setStringValue: o_string];
1967 [o_embedded_window setScrollString: o_string];
1970 - (void)resetScrollField
1972 playlist_t * p_playlist = pl_Hold( p_intf );
1973 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1976 if( p_input && vlc_object_alive (p_input) )
1980 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1981 if( input_item_GetNowPlaying( p_item->p_input ) )
1982 o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
1984 o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
1986 [self setScrollField: o_temp stopAfter:-1];
1987 [[[self controls] fspanel] setStreamTitle: o_temp];
1988 vlc_object_release( p_input );
1989 pl_Release( p_intf );
1992 pl_Release( p_intf );
1993 [self setScrollField: _NS("VLC media player") stopAfter:-1];
1996 - (void)playStatusUpdated:(int)i_status
1998 if( i_status == PLAYING_S )
2000 [[[self controls] fspanel] setPause];
2001 [o_btn_play setImage: o_img_pause];
2002 [o_btn_play setAlternateImage: o_img_pause_pressed];
2003 [o_btn_play setToolTip: _NS("Pause")];
2004 [o_mi_play setTitle: _NS("Pause")];
2005 [o_dmi_play setTitle: _NS("Pause")];
2006 [o_vmi_play setTitle: _NS("Pause")];
2010 [[[self controls] fspanel] setPlay];
2011 [o_btn_play setImage: o_img_play];
2012 [o_btn_play setAlternateImage: o_img_play_pressed];
2013 [o_btn_play setToolTip: _NS("Play")];
2014 [o_mi_play setTitle: _NS("Play")];
2015 [o_dmi_play setTitle: _NS("Play")];
2016 [o_vmi_play setTitle: _NS("Play")];
2020 - (void)setSubmenusEnabled:(BOOL)b_enabled
2022 [o_mi_program setEnabled: b_enabled];
2023 [o_mi_title setEnabled: b_enabled];
2024 [o_mi_chapter setEnabled: b_enabled];
2025 [o_mi_audiotrack setEnabled: b_enabled];
2026 [o_mi_visual setEnabled: b_enabled];
2027 [o_mi_videotrack setEnabled: b_enabled];
2028 [o_mi_subtitle setEnabled: b_enabled];
2029 [o_mi_channels setEnabled: b_enabled];
2030 [o_mi_deinterlace setEnabled: b_enabled];
2031 [o_mi_ffmpeg_pp setEnabled: b_enabled];
2032 [o_mi_device setEnabled: b_enabled];
2033 [o_mi_screen setEnabled: b_enabled];
2034 [o_mi_aspect_ratio setEnabled: b_enabled];
2035 [o_mi_crop setEnabled: b_enabled];
2036 [o_mi_teletext setEnabled: b_enabled];
2039 - (IBAction)timesliderUpdate:(id)sender
2042 playlist_t * p_playlist;
2043 input_thread_t * p_input;
2045 switch( [[NSApp currentEvent] type] )
2048 case NSLeftMouseDown:
2049 case NSLeftMouseDragged:
2050 f_updated = [sender floatValue];
2056 p_playlist = pl_Hold( p_intf );
2057 p_input = playlist_CurrentInput( p_playlist );
2058 if( p_input != NULL )
2063 char psz_time[MSTRTIME_MAX_SIZE];
2065 pos.f_float = f_updated / 10000.;
2066 var_Set( p_input, "position", pos );
2067 [o_timeslider setFloatValue: f_updated];
2069 var_Get( p_input, "time", &time );
2071 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
2072 if( b_time_remaining && dur != -1 )
2074 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
2077 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2079 [o_timefield setStringValue: o_time];
2080 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
2081 [o_embedded_window setTime: o_time position: f_updated];
2082 vlc_object_release( p_input );
2084 pl_Release( p_intf );
2087 - (IBAction)timeFieldWasClicked:(id)sender
2089 b_time_remaining = !b_time_remaining;
2094 #pragma mark Recent Items
2096 - (IBAction)clearRecentItems:(id)sender
2098 [[NSDocumentController sharedDocumentController]
2099 clearRecentDocuments: nil];
2102 - (void)openRecentItem:(id)sender
2104 [self application: nil openFile: [sender title]];
2110 - (IBAction)intfOpenFile:(id)sender
2112 if( !nib_open_loaded )
2114 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2115 [o_open awakeFromNib];
2122 - (IBAction)intfOpenFileGeneric:(id)sender
2124 if( !nib_open_loaded )
2126 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2127 [o_open awakeFromNib];
2128 [o_open openFileGeneric];
2130 [o_open openFileGeneric];
2134 - (IBAction)intfOpenDisc:(id)sender
2136 if( !nib_open_loaded )
2138 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2139 [o_open awakeFromNib];
2146 - (IBAction)intfOpenNet:(id)sender
2148 if( !nib_open_loaded )
2150 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2151 [o_open awakeFromNib];
2158 - (IBAction)intfOpenCapture:(id)sender
2160 if( !nib_open_loaded )
2162 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2163 [o_open awakeFromNib];
2164 [o_open openCapture];
2166 [o_open openCapture];
2170 - (IBAction)showWizard:(id)sender
2172 if( !nib_wizard_loaded )
2174 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2175 [o_wizard initStrings];
2176 [o_wizard resetWizard];
2177 [o_wizard showWizard];
2179 [o_wizard resetWizard];
2180 [o_wizard showWizard];
2184 - (IBAction)showVLM:(id)sender
2186 if( !nib_vlm_loaded )
2187 nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner: NSApp];
2189 [o_vlm showVLMWindow];
2192 - (IBAction)showExtended:(id)sender
2194 if( o_extended == nil )
2195 o_extended = [[VLCExtended alloc] init];
2197 if( !nib_extended_loaded )
2198 nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2200 [o_extended showPanel];
2203 - (IBAction)showBookmarks:(id)sender
2205 /* we need the wizard-nib for the bookmarks's extract functionality */
2206 if( !nib_wizard_loaded )
2208 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2209 [o_wizard initStrings];
2212 if( !nib_bookmarks_loaded )
2213 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2215 [o_bookmarks showBookmarks];
2218 - (IBAction)viewPreferences:(id)sender
2220 if( !nib_prefs_loaded )
2222 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2223 o_sprefs = [[VLCSimplePrefs alloc] init];
2224 o_prefs= [[VLCPrefs alloc] init];
2227 [o_sprefs showSimplePrefs];
2233 - (IBAction)checkForUpdate:(id)sender
2236 if( !nib_update_loaded )
2237 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
2238 [o_update showUpdateWindow];
2240 msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2241 dialog_FatalWait( VLCIntf, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2246 #pragma mark Help and Docs
2248 - (IBAction)viewAbout:(id)sender
2250 if( !nib_about_loaded )
2251 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2253 [o_about showAbout];
2256 - (IBAction)showLicense:(id)sender
2258 if( !nib_about_loaded )
2259 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2261 [o_about showGPL: sender];
2264 - (IBAction)viewHelp:(id)sender
2266 if( !nib_about_loaded )
2268 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2275 - (IBAction)openReadMe:(id)sender
2277 NSString * o_path = [[NSBundle mainBundle]
2278 pathForResource: @"README.MacOSX" ofType: @"rtf"];
2280 [[NSWorkspace sharedWorkspace] openFile: o_path
2281 withApplication: @"TextEdit"];
2284 - (IBAction)openDocumentation:(id)sender
2286 NSURL * o_url = [NSURL URLWithString:
2287 @"http://www.videolan.org/doc/"];
2289 [[NSWorkspace sharedWorkspace] openURL: o_url];
2292 - (IBAction)openWebsite:(id)sender
2294 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2296 [[NSWorkspace sharedWorkspace] openURL: o_url];
2299 - (IBAction)openForum:(id)sender
2301 NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2303 [[NSWorkspace sharedWorkspace] openURL: o_url];
2306 - (IBAction)openDonate:(id)sender
2308 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2310 [[NSWorkspace sharedWorkspace] openURL: o_url];
2314 #pragma mark Crash Log
2315 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2317 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2318 NSURL *url = [NSURL URLWithString:urlStr];
2320 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2321 [req setHTTPMethod:@"POST"];
2324 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2326 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2327 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2328 email = [emails valueAtIndex:[emails indexForIdentifier:
2329 [emails primaryIdentifier]]];
2332 email = [NSString string];
2335 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2336 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2337 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2338 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2340 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2342 /* Released from delegate */
2343 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2346 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2348 NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2349 _NS("Thanks for your report!"),
2350 _NS("OK"), nil, nil, nil);
2351 [crashLogURLConnection release];
2352 crashLogURLConnection = nil;
2355 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2357 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2358 [crashLogURLConnection release];
2359 crashLogURLConnection = nil;
2362 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2364 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2365 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2367 NSString * latestLog = nil;
2368 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2369 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2370 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
2371 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2373 while (fname = [direnum nextObject])
2375 [direnum skipDescendents];
2376 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2378 NSArray * compo = [fname componentsSeparatedByString:@"_"];
2379 if( [compo count] < 3 ) continue;
2380 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2381 if( [compo count] < 4 ) continue;
2384 if( year < [[compo objectAtIndex:0] intValue] ||
2385 (year ==[[compo objectAtIndex:0] intValue] &&
2386 (month < [[compo objectAtIndex:1] intValue] ||
2387 (month ==[[compo objectAtIndex:1] intValue] &&
2388 (day < [[compo objectAtIndex:2] intValue] ||
2389 (day ==[[compo objectAtIndex:2] intValue] &&
2390 hours < [[compo objectAtIndex:3] intValue] ))))))
2392 year = [[compo objectAtIndex:0] intValue];
2393 month = [[compo objectAtIndex:1] intValue];
2394 day = [[compo objectAtIndex:2] intValue];
2395 hours = [[compo objectAtIndex:3] intValue];
2396 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2401 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2404 if( !previouslySeen )
2406 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
2407 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2408 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
2409 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2414 - (NSString *)latestCrashLogPath
2416 return [self latestCrashLogPathPreviouslySeen:YES];
2419 - (void)lookForCrashLog
2421 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2422 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2423 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2424 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2425 if( latestLog && !areCrashLogsTooOld )
2426 [NSApp runModalForWindow: o_crashrep_win];
2430 - (IBAction)crashReporterAction:(id)sender
2432 if( sender == o_crashrep_send_btn )
2433 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2436 [o_crashrep_win orderOut: sender];
2439 - (IBAction)openCrashLog:(id)sender
2441 NSString * latestLog = [self latestCrashLogPath];
2444 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2448 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.") );
2453 #pragma mark Remove old prefs
2455 - (void)_removeOldPreferences
2457 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2458 static const int kCurrentPreferencesVersion = 1;
2459 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2460 if( version >= kCurrentPreferencesVersion ) return;
2462 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
2463 NSUserDomainMask, YES);
2464 if( !libraries || [libraries count] == 0) return;
2465 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2467 /* File not found, don't attempt anything */
2468 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2469 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2471 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2475 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2476 _NS("We just found an older version of VLC's preferences files."),
2477 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2478 if( res != NSOKButton )
2480 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2484 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2486 /* Move the file to trash so that user can find them later */
2487 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2489 /* really reset the defaults from now on */
2490 [NSUserDefaults resetStandardUserDefaults];
2492 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2493 [[NSUserDefaults standardUserDefaults] synchronize];
2496 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2498 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2504 execl(path, path, NULL);
2508 #pragma mark Errors, warnings and messages
2510 - (IBAction)viewErrorsAndWarnings:(id)sender
2512 [[[self coreDialogProvider] errorPanel] showPanel];
2515 - (IBAction)showMessagesPanel:(id)sender
2517 [o_msgs_panel makeKeyAndOrderFront: sender];
2520 - (IBAction)showInformationPanel:(id)sender
2522 if(! nib_info_loaded )
2523 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2528 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2530 if( [o_notification object] == o_msgs_panel )
2531 [self updateMessageDisplay];
2534 - (void)updateMessageDisplay
2536 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2539 NSEnumerator * o_enum;
2541 [o_messages setString: @""];
2545 o_enum = [o_msg_arr objectEnumerator];
2547 while( ( o_msg = [o_enum nextObject] ) != nil )
2549 [o_messages insertText: o_msg];
2552 b_msg_arr_changed = NO;
2553 [o_msg_lock unlock];
2557 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2559 NSColor *o_white = [NSColor whiteColor];
2560 NSColor *o_red = [NSColor redColor];
2561 NSColor *o_yellow = [NSColor yellowColor];
2562 NSColor *o_gray = [NSColor grayColor];
2564 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2565 static const char * ppsz_type[4] = { ": ", " error: ",
2566 " warning: ", " debug: " };
2569 NSDictionary *o_attr;
2570 NSAttributedString *o_msg_color;
2572 int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2576 if( [o_msg_arr count] + 2 > 600 )
2578 [o_msg_arr removeObjectAtIndex: 0];
2579 [o_msg_arr removeObjectAtIndex: 1];
2582 o_attr = [NSDictionary dictionaryWithObject: o_gray
2583 forKey: NSForegroundColorAttributeName];
2584 o_msg = [NSString stringWithFormat: @"%@%s",
2585 [[o_notification userInfo] objectForKey: @"Module"],
2587 o_msg_color = [[NSAttributedString alloc]
2588 initWithString: o_msg attributes: o_attr];
2589 [o_msg_arr addObject: [o_msg_color autorelease]];
2591 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2592 forKey: NSForegroundColorAttributeName];
2593 o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2594 o_msg_color = [[NSAttributedString alloc]
2595 initWithString: o_msg attributes: o_attr];
2596 [o_msg_arr addObject: [o_msg_color autorelease]];
2598 b_msg_arr_changed = YES;
2599 [o_msg_lock unlock];
2602 - (IBAction)saveDebugLog:(id)sender
2604 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2606 [saveFolderPanel setCanChooseDirectories: NO];
2607 [saveFolderPanel setCanChooseFiles: YES];
2608 [saveFolderPanel setCanSelectHiddenExtension: NO];
2609 [saveFolderPanel setCanCreateDirectories: YES];
2610 [saveFolderPanel setRequiredFileType: @"rtfd"];
2611 [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];
2614 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2617 if( returnCode == NSOKButton )
2619 b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2621 msg_Warn( p_intf, "Error while saving the debug log" );
2626 #pragma mark Playlist toggling
2628 - (IBAction)togglePlaylist:(id)sender
2630 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2631 NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2632 /*First, check if the playlist is visible*/
2633 if( contentRect.size.height <= 169. )
2635 o_restore_rect = contentRect;
2636 b_restore_size = true;
2637 b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2640 if( o_size_with_playlist.height > 169. )
2641 o_rect.size.height = o_size_with_playlist.height;
2643 o_rect.size.height = 500.;
2645 if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2646 o_rect.size.width = o_size_with_playlist.width;
2648 o_rect.size.width = [o_window contentMinSize].width;
2650 o_rect.origin.x = contentRect.origin.x;
2651 o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2652 [o_window contentMinSize].height;
2654 o_rect = [o_window frameRectForContentRect:o_rect];
2656 NSRect screenRect = [[o_window screen] visibleFrame];
2657 if( !NSContainsRect( screenRect, o_rect ) ) {
2658 if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2659 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2660 if( NSMinY(o_rect) < NSMinY(screenRect) )
2661 o_rect.origin.y = ( NSMinY(screenRect) );
2664 [o_btn_playlist setState: YES];
2668 NSSize curSize = o_rect.size;
2669 if( b_restore_size )
2671 o_rect = o_restore_rect;
2672 if( o_rect.size.height < [o_window contentMinSize].height )
2673 o_rect.size.height = [o_window contentMinSize].height;
2674 if( o_rect.size.width < [o_window contentMinSize].width )
2675 o_rect.size.width = [o_window contentMinSize].width;
2679 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2681 o_rect.size.height = [o_window contentMinSize].height;
2682 o_rect.size.width = [o_window contentMinSize].width;
2683 o_rect.origin.x = contentRect.origin.x;
2684 /* Calculate the position of the lower right corner after resize */
2685 o_rect.origin.y = contentRect.origin.y +
2686 contentRect.size.height - [o_window contentMinSize].height;
2689 [o_playlist_view setAutoresizesSubviews: NO];
2690 [o_playlist_view removeFromSuperview];
2691 [o_btn_playlist setState: NO];
2692 b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2693 o_rect = [o_window frameRectForContentRect:o_rect];
2696 [o_window setFrame: o_rect display:YES animate: YES];
2699 - (void)updateTogglePlaylistState
2701 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2702 [o_btn_playlist setState: NO];
2704 [o_btn_playlist setState: YES];
2706 [[self playlist] outlineViewSelectionDidChange: NULL];
2709 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2712 /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2714 /*Stores the size the controller one resize, to be able to restore it when
2715 toggling the playlist*/
2716 o_size_with_playlist = proposedFrameSize;
2719 rect.size = proposedFrameSize;
2720 if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2722 if( b_small_window == NO )
2724 /* if large and going to small then hide */
2725 b_small_window = YES;
2726 [o_playlist_view setAutoresizesSubviews: NO];
2727 [o_playlist_view removeFromSuperview];
2729 return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2731 return proposedFrameSize;
2734 - (void)windowDidMove:(NSNotification *)notif
2736 b_restore_size = false;
2739 - (void)windowDidResize:(NSNotification *)notif
2741 if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2743 /* If large and coming from small then show */
2744 [o_playlist_view setAutoresizesSubviews: YES];
2745 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2746 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2747 [o_playlist_view setNeedsDisplay:YES];
2748 [[o_window contentView] addSubview: o_playlist_view];
2749 b_small_window = NO;
2751 [self updateTogglePlaylistState];
2758 @implementation VLCMain (NSMenuValidation)
2760 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2762 NSString *o_title = [o_mi title];
2763 BOOL bEnabled = TRUE;
2765 /* Recent Items Menu */
2766 if( [o_title isEqualToString: _NS("Clear Menu")] )
2768 NSMenu * o_menu = [o_mi_open_recent submenu];
2769 int i_nb_items = [o_menu numberOfItems];
2770 NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2771 recentDocumentURLs];
2772 UInt32 i_nb_docs = [o_docs count];
2774 if( i_nb_items > 1 )
2776 while( --i_nb_items )
2778 [o_menu removeItemAtIndex: 0];
2787 [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2793 o_url = [o_docs objectAtIndex: i_nb_docs];
2795 if( [o_url isFileURL] )
2797 o_doc = [o_url path];
2801 o_doc = [o_url absoluteString];
2804 [o_menu insertItemWithTitle: o_doc
2805 action: @selector(openRecentItem:)
2806 keyEquivalent: @"" atIndex: 0];
2808 if( i_nb_docs == 0 )
2824 @implementation VLCMain (Internal)
2826 - (void)handlePortMessage:(NSPortMessage *)o_msg
2831 NSInvocation * o_inv;
2832 NSConditionLock * o_lock;
2834 o_data = [[o_msg components] lastObject];
2835 o_inv = *((NSInvocation **)[o_data bytes]);
2836 [o_inv getArgument: &o_value atIndex: 2];
2837 val = (id **)[o_value pointerValue];
2838 [o_inv setArgument: val[1] atIndex: 2];
2843 [o_lock unlockWithCondition: 1];
2848 /*****************************************************************************
2849 * VLCApplication interface
2850 * exclusively used to implement media key support on Al Apple keyboards
2851 * b_justJumped is required as the keyboard send its events faster than
2852 * the user can actually jump through his media
2853 *****************************************************************************/
2855 @implementation VLCApplication
2857 - (void)awakeFromNib
2859 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2862 - (void)enableMediaKeySupport:(BOOL)b_value
2864 b_mediaKeySupport = b_value;
2867 - (void)sendEvent: (NSEvent*)event
2869 if( b_mediaKeySupport )
2871 if( [event type] == NSSystemDefined && [event subtype] == 8 )
2873 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
2874 int keyFlags = ([event data1] & 0x0000FFFF);
2875 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
2876 int keyRepeat = (keyFlags & 0x1);
2878 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
2879 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
2881 if( keyCode == NX_KEYTYPE_FAST && !b_justJumped )
2883 if( keyState == 0 && keyRepeat == 0 )
2885 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_NEXT );
2887 else if( keyRepeat == 1 )
2889 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
2891 [self performSelector:@selector(resetJump)
2897 if( keyCode == NX_KEYTYPE_REWIND && !b_justJumped )
2899 if( keyState == 0 && keyRepeat == 0 )
2901 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PREV );
2903 else if( keyRepeat == 1 )
2905 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
2907 [self performSelector:@selector(resetJump)
2914 [super sendEvent: event];