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() */
43 #import "playlistinfo.h"
50 #import "coredialogs.h"
51 #import "embeddedwindow.h"
52 #import "AppleRemote.h"
54 #import "simple_prefs.h"
59 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
60 #import <IOKit/hidsystem/ev_keymap.h> /* for the media key support */
61 #import <Sparkle/Sparkle.h> /* we're the update delegate */
63 /*****************************************************************************
65 *****************************************************************************/
66 static void Run ( intf_thread_t *p_intf );
68 static void * ManageThread( void *user_data );
70 static unichar VLCKeyToCocoa( unsigned int i_key );
71 static unsigned int VLCModifiersToCocoa( unsigned int i_key );
73 static void updateProgressPanel (void *, const char *, float);
74 static bool checkProgressPanel (void *);
75 static void destroyProgressPanel (void *);
77 static void MsgCallback( msg_cb_data_t *, msg_item_t *, unsigned );
80 #pragma mark VLC Interface Object Callbacks
82 /*****************************************************************************
83 * OpenIntf: initialize interface
84 *****************************************************************************/
85 int OpenIntf ( vlc_object_t *p_this )
87 intf_thread_t *p_intf = (intf_thread_t*) p_this;
89 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
90 if( p_intf->p_sys == NULL )
93 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
95 /* subscribe to LibVLCCore's messages */
96 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
98 p_intf->b_should_run_on_first_thread = true;
103 /*****************************************************************************
104 * CloseIntf: destroy interface
105 *****************************************************************************/
106 void CloseIntf ( vlc_object_t *p_this )
108 intf_thread_t *p_intf = (intf_thread_t*) p_this;
110 free( p_intf->p_sys );
113 /*****************************************************************************
115 *****************************************************************************/
116 static NSLock * o_appLock = nil; // controls access to f_appExit
117 static int f_appExit = 0; // set to 1 when application termination signaled
119 static void Run( intf_thread_t *p_intf )
123 /* Do it again - for some unknown reason, vlc_thread_create() often
124 * fails to go to real-time priority with the first launched thread
126 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
128 /* Make sure the "force quit" menu item does quit instantly.
129 * VLC overrides SIGTERM which is sent by the "force quit"
130 * menu item to make sure deamon mode quits gracefully, so
131 * we un-override SIGTERM here. */
133 sigaddset( &set, SIGTERM );
134 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
136 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
138 o_appLock = [[NSLock alloc] init];
140 [VLCApplication sharedApplication];
142 [[VLCMain sharedInstance] setIntf: p_intf];
143 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
146 [[VLCMain sharedInstance] applicationWillTerminate:nil];
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 input_thread_t *getInput(void)
287 intf_thread_t *p_intf = VLCIntf;
290 return pl_CurrentInput(p_intf);
293 vout_thread_t *getVout(void)
295 input_thread_t *p_input = getInput();
298 vout_thread_t *p_vout = input_GetVout(p_input);
299 vlc_object_release(p_input);
303 aout_instance_t *getAout(void)
305 input_thread_t *p_input = getInput();
308 aout_instance_t *p_aout = input_GetAout(p_input);
309 vlc_object_release(p_input);
316 @interface VLCMain ()
317 - (void)_removeOldPreferences;
320 /*****************************************************************************
321 * VLCMain implementation
322 *****************************************************************************/
323 @implementation VLCMain
326 #pragma mark Initialization
328 static VLCMain *_o_sharedMainInstance = nil;
330 + (VLCMain *)sharedInstance
332 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
337 if( _o_sharedMainInstance)
340 return _o_sharedMainInstance;
343 _o_sharedMainInstance = [super init];
347 o_msg_lock = [[NSLock alloc] init];
348 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
349 /* subscribe to LibVLC's debug messages as early as possible (for us) */
350 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
352 o_about = [[VLAboutBox alloc] init];
354 o_open = [[VLCOpen alloc] init];
355 o_wizard = [[VLCWizard alloc] init];
357 o_vlm = [[VLCVLMController alloc] init];
360 o_bookmarks = [[VLCBookmarks alloc] init];
361 o_embedded_list = [[VLCEmbeddedList alloc] init];
362 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
363 o_info = [[VLCInfo alloc] init];
365 i_lastShownVolume = -1;
367 o_eyetv = [[VLCEyeTVController alloc] init];
369 /* announce our launch to a potential eyetv plugin */
370 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
371 object: @"VLCEyeTVSupport"
373 deliverImmediately: YES];
375 return _o_sharedMainInstance;
378 - (void)setIntf: (intf_thread_t *)p_mainintf {
382 - (intf_thread_t *)intf {
388 unsigned int i_key = 0;
389 playlist_t *p_playlist;
392 if( !p_intf ) return;
394 /* Check if we already did this once. Opening the other nibs calls it too,
395 because VLCMain is the owner */
396 if( nib_main_loaded ) return;
400 [o_window setExcludedFromWindowsMenu: YES];
401 [o_msgs_panel setExcludedFromWindowsMenu: YES];
402 [o_msgs_panel setDelegate: self];
404 /* In code and not in Nib for 10.4 compat */
405 NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"mainControllerToolbar"] autorelease];
406 [toolbar setDelegate:self];
407 [toolbar setShowsBaselineSeparator:NO];
408 [toolbar setAllowsUserCustomization:NO];
409 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
410 [toolbar setAutosavesConfiguration:YES];
411 [o_window setToolbar:toolbar];
413 i_key = config_GetInt( p_intf, "key-quit" );
414 [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
415 [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
416 i_key = config_GetInt( p_intf, "key-play-pause" );
417 [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
418 [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
419 i_key = config_GetInt( p_intf, "key-stop" );
420 [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
421 [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
422 i_key = config_GetInt( p_intf, "key-faster" );
423 [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
424 [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
425 i_key = config_GetInt( p_intf, "key-slower" );
426 [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
427 [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
428 i_key = config_GetInt( p_intf, "key-rate-normal" );
429 [o_mi_normalSpeed setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
430 [o_mi_normalSpeed setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
431 i_key = config_GetInt( p_intf, "key-prev" );
432 [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
433 [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
434 i_key = config_GetInt( p_intf, "key-next" );
435 [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
436 [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
437 i_key = config_GetInt( p_intf, "key-jump+short" );
438 [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
439 [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
440 i_key = config_GetInt( p_intf, "key-jump-short" );
441 [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
442 [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
443 i_key = config_GetInt( p_intf, "key-jump+medium" );
444 [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
445 [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
446 i_key = config_GetInt( p_intf, "key-jump-medium" );
447 [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
448 [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
449 i_key = config_GetInt( p_intf, "key-jump+long" );
450 [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
451 [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
452 i_key = config_GetInt( p_intf, "key-jump-long" );
453 [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
454 [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
455 i_key = config_GetInt( p_intf, "key-vol-up" );
456 [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
457 [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
458 i_key = config_GetInt( p_intf, "key-vol-down" );
459 [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
460 [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
461 i_key = config_GetInt( p_intf, "key-vol-mute" );
462 [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
463 [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
464 i_key = config_GetInt( p_intf, "key-fullscreen" );
465 [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
466 [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
467 i_key = config_GetInt( p_intf, "key-snapshot" );
468 [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
469 [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
470 i_key = config_GetInt( p_intf, "key-random" );
471 [o_mi_random setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
472 [o_mi_random setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
473 i_key = config_GetInt( p_intf, "key-zoom-half" );
474 [o_mi_half_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
475 [o_mi_half_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
476 i_key = config_GetInt( p_intf, "key-zoom-original" );
477 [o_mi_normal_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
478 [o_mi_normal_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
479 i_key = config_GetInt( p_intf, "key-zoom-double" );
480 [o_mi_double_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
481 [o_mi_double_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
483 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
485 [self setSubmenusEnabled: FALSE];
486 [o_volumeslider setEnabled: YES];
487 [self manageVolumeSlider];
488 [o_window setDelegate: self];
490 b_restore_size = false;
492 // Set that here as IB seems to be buggy
493 [o_window setContentMinSize:NSMakeSize(338., 30.)];
495 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
497 b_small_window = YES;
498 [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
499 [o_window frame].origin.y, [o_window frame].size.width,
500 [o_window minSize].height ) display: YES animate:YES];
501 [o_playlist_view setAutoresizesSubviews: NO];
506 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
507 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
508 [o_playlist_view setNeedsDisplay:YES];
509 [o_playlist_view setAutoresizesSubviews: YES];
510 [[o_window contentView] addSubview: o_playlist_view];
513 [self updateTogglePlaylistState];
515 o_size_with_playlist = [o_window contentRectForFrameRect:[o_window frame]].size;
517 p_playlist = pl_Hold( p_intf );
519 var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
522 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
523 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
525 pl_Release( p_intf );
527 /* load our Core Dialogs nib */
528 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
530 /* subscribe to various interactive dialogues */
531 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
532 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
533 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
534 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
535 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
536 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
537 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
538 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
539 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
540 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
541 dialog_Register( p_intf );
543 /* update the playmode stuff */
544 p_intf->p_sys->b_playmode_update = true;
546 [[NSNotificationCenter defaultCenter] addObserver: self
547 selector: @selector(refreshVoutDeviceMenu:)
548 name: NSApplicationDidChangeScreenParametersNotification
551 /* take care of tint changes during runtime */
552 o_img_play = [NSImage imageNamed: @"play"];
553 o_img_pause = [NSImage imageNamed: @"pause"];
554 [self controlTintChanged];
555 [[NSNotificationCenter defaultCenter] addObserver: self
556 selector: @selector( controlTintChanged )
557 name: NSControlTintDidChangeNotification
560 /* init Apple Remote support */
561 o_remote = [[AppleRemote alloc] init];
562 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
563 [o_remote setDelegate: _o_sharedMainInstance];
565 /* yeah, we are done */
566 nib_main_loaded = TRUE;
569 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
571 if( !p_intf ) return;
573 /* FIXME: don't poll */
574 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
575 target: self selector: @selector(manageIntf:)
576 userInfo: nil repeats: FALSE] retain];
578 /* Note: we use the pthread API to support pre-10.5 */
579 pthread_create( &manage_thread, NULL, ManageThread, self );
581 [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
582 var: "intf-add" selector: @selector(toggleVar:)];
584 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
587 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
589 if( !p_intf ) return;
591 [self _removeOldPreferences];
593 /* Handle sleep notification */
594 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
595 name:NSWorkspaceWillSleepNotification object:nil];
597 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
602 if( !p_intf ) return;
604 [o_window setTitle: _NS("VLC media player")];
605 [self setScrollField:_NS("VLC media player") stopAfter:-1];
607 /* button controls */
608 [o_btn_prev setToolTip: _NS("Previous")];
609 [o_btn_rewind setToolTip: _NS("Rewind")];
610 [o_btn_play setToolTip: _NS("Play")];
611 [o_btn_stop setToolTip: _NS("Stop")];
612 [o_btn_ff setToolTip: _NS("Fast Forward")];
613 [o_btn_next setToolTip: _NS("Next")];
614 [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
615 [o_volumeslider setToolTip: _NS("Volume")];
616 [o_timeslider setToolTip: _NS("Position")];
617 [o_btn_playlist setToolTip: _NS("Playlist")];
620 [o_msgs_panel setTitle: _NS("Messages")];
621 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
622 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
625 [o_mi_about setTitle: [_NS("About VLC media player") \
626 stringByAppendingString: @"..."]];
627 [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
628 [o_mi_prefs setTitle: _NS("Preferences...")];
629 [o_mi_add_intf setTitle: _NS("Add Interface")];
630 [o_mu_add_intf setTitle: _NS("Add Interface")];
631 [o_mi_services setTitle: _NS("Services")];
632 [o_mi_hide setTitle: _NS("Hide VLC")];
633 [o_mi_hide_others setTitle: _NS("Hide Others")];
634 [o_mi_show_all setTitle: _NS("Show All")];
635 [o_mi_quit setTitle: _NS("Quit VLC")];
637 [o_mu_file setTitle: _ANS("1:File")];
638 [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
639 [o_mi_open_file setTitle: _NS("Open File...")];
640 [o_mi_open_disc setTitle: _NS("Open Disc...")];
641 [o_mi_open_net setTitle: _NS("Open Network...")];
642 [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
643 [o_mi_open_recent setTitle: _NS("Open Recent")];
644 [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
645 [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
647 [o_mu_edit setTitle: _NS("Edit")];
648 [o_mi_cut setTitle: _NS("Cut")];
649 [o_mi_copy setTitle: _NS("Copy")];
650 [o_mi_paste setTitle: _NS("Paste")];
651 [o_mi_clear setTitle: _NS("Clear")];
652 [o_mi_select_all setTitle: _NS("Select All")];
654 [o_mu_controls setTitle: _NS("Playback")];
655 [o_mi_play setTitle: _NS("Play")];
656 [o_mi_stop setTitle: _NS("Stop")];
657 [o_mi_faster setTitle: _NS("Faster")];
658 [o_mi_slower setTitle: _NS("Slower")];
659 [o_mi_normalSpeed setTitle: _NS("Normal rate")];
660 [o_mi_previous setTitle: _NS("Previous")];
661 [o_mi_next setTitle: _NS("Next")];
662 [o_mi_random setTitle: _NS("Random")];
663 [o_mi_repeat setTitle: _NS("Repeat One")];
664 [o_mi_loop setTitle: _NS("Repeat All")];
665 [o_mi_quitAfterPB setTitle: _NS("Quit after Playback")];
666 [o_mi_fwd setTitle: _NS("Step Forward")];
667 [o_mi_bwd setTitle: _NS("Step Backward")];
669 [o_mi_program setTitle: _NS("Program")];
670 [o_mu_program setTitle: _NS("Program")];
671 [o_mi_title setTitle: _NS("Title")];
672 [o_mu_title setTitle: _NS("Title")];
673 [o_mi_chapter setTitle: _NS("Chapter")];
674 [o_mu_chapter setTitle: _NS("Chapter")];
676 [o_mu_audio setTitle: _NS("Audio")];
677 [o_mi_vol_up setTitle: _NS("Increase Volume")];
678 [o_mi_vol_down setTitle: _NS("Decrease Volume")];
679 [o_mi_mute setTitle: _NS("Mute")];
680 [o_mi_audiotrack setTitle: _NS("Audio Track")];
681 [o_mu_audiotrack setTitle: _NS("Audio Track")];
682 [o_mi_channels setTitle: _NS("Audio Channels")];
683 [o_mu_channels setTitle: _NS("Audio Channels")];
684 [o_mi_device setTitle: _NS("Audio Device")];
685 [o_mu_device setTitle: _NS("Audio Device")];
686 [o_mi_visual setTitle: _NS("Visualizations")];
687 [o_mu_visual setTitle: _NS("Visualizations")];
689 [o_mu_video setTitle: _NS("Video")];
690 [o_mi_half_window setTitle: _NS("Half Size")];
691 [o_mi_normal_window setTitle: _NS("Normal Size")];
692 [o_mi_double_window setTitle: _NS("Double Size")];
693 [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
694 [o_mi_fullscreen setTitle: _NS("Fullscreen")];
695 [o_mi_floatontop setTitle: _NS("Float on Top")];
696 [o_mi_snapshot setTitle: _NS("Snapshot")];
697 [o_mi_videotrack setTitle: _NS("Video Track")];
698 [o_mu_videotrack setTitle: _NS("Video Track")];
699 [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
700 [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
701 [o_mi_crop setTitle: _NS("Crop")];
702 [o_mu_crop setTitle: _NS("Crop")];
703 [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
704 [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
705 [o_mi_subtitle setTitle: _NS("Subtitles Track")];
706 [o_mu_subtitle setTitle: _NS("Subtitles Track")];
707 [o_mi_addSub setTitle: _NS("Open File...")];
708 [o_mi_deinterlace setTitle: _NS("Deinterlace")];
709 [o_mu_deinterlace setTitle: _NS("Deinterlace")];
710 [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
711 [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
712 [o_mi_teletext setTitle: _NS("Teletext")];
713 [o_mi_teletext_transparent setTitle: _NS("Transparent")];
714 [o_mi_teletext_index setTitle: _NS("Index")];
715 [o_mi_teletext_red setTitle: _NS("Red")];
716 [o_mi_teletext_green setTitle: _NS("Green")];
717 [o_mi_teletext_yellow setTitle: _NS("Yellow")];
718 [o_mi_teletext_blue setTitle: _NS("Blue")];
720 [o_mu_window setTitle: _NS("Window")];
721 [o_mi_minimize setTitle: _NS("Minimize Window")];
722 [o_mi_close_window setTitle: _NS("Close Window")];
723 [o_mi_player setTitle: _NS("Player...")];
724 [o_mi_controller setTitle: _NS("Controller...")];
725 [o_mi_equalizer setTitle: _NS("Equalizer...")];
726 [o_mi_extended setTitle: _NS("Extended Controls...")];
727 [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
728 [o_mi_playlist setTitle: _NS("Playlist...")];
729 [o_mi_info setTitle: _NS("Media Information...")];
730 [o_mi_messages setTitle: _NS("Messages...")];
731 [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
733 [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
735 [o_mu_help setTitle: _NS("Help")];
736 [o_mi_help setTitle: _NS("VLC media player Help...")];
737 [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
738 [o_mi_license setTitle: _NS("License")];
739 [o_mi_documentation setTitle: _NS("Online Documentation...")];
740 [o_mi_website setTitle: _NS("VideoLAN Website...")];
741 [o_mi_donation setTitle: _NS("Make a donation...")];
742 [o_mi_forum setTitle: _NS("Online Forum...")];
745 [o_dmi_play setTitle: _NS("Play")];
746 [o_dmi_stop setTitle: _NS("Stop")];
747 [o_dmi_next setTitle: _NS("Next")];
748 [o_dmi_previous setTitle: _NS("Previous")];
749 [o_dmi_mute setTitle: _NS("Mute")];
752 [o_vmi_play setTitle: _NS("Play")];
753 [o_vmi_stop setTitle: _NS("Stop")];
754 [o_vmi_prev setTitle: _NS("Previous")];
755 [o_vmi_next setTitle: _NS("Next")];
756 [o_vmi_volup setTitle: _NS("Volume Up")];
757 [o_vmi_voldown setTitle: _NS("Volume Down")];
758 [o_vmi_mute setTitle: _NS("Mute")];
759 [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
760 [o_vmi_snapshot setTitle: _NS("Snapshot")];
762 /* crash reporter panel */
763 [o_crashrep_send_btn setTitle: _NS("Send")];
764 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
765 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
766 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
767 [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, ...")];
768 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
769 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
773 #pragma mark Termination
775 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
777 if( !p_intf ) return;
779 NSArray *menuitems_array = [the_menu itemArray];
780 for( int i=0; i<[menuitems_array count]; i++ )
782 NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
783 if( [one_item hasSubmenu] )
784 [self releaseRepresentedObjects: [one_item submenu]];
786 [one_item setRepresentedObject:NULL];
790 - (void)applicationWillTerminate:(NSNotification *)notification
792 playlist_t * p_playlist;
793 vout_thread_t * p_vout;
794 int returnedValue = 0;
799 // don't allow a double termination call. If the user has
800 // already invoked the quit then simply return this time.
801 int isTerminating = false;
804 isTerminating = (f_appExit++ > 0 ? 1 : 0);
810 msg_Dbg( p_intf, "Terminating" );
812 pthread_join( manage_thread, NULL );
814 /* Make sure the intf object is getting killed */
815 vlc_object_kill( p_intf );
817 /* Make sure the interfaceTimer is destroyed */
818 [interfaceTimer invalidate];
819 [interfaceTimer release];
820 interfaceTimer = nil;
822 /* make sure that the current volume is saved */
823 config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
825 /* save the prefs if they were changed in the extended panel */
826 if(o_extended && [o_extended configChanged])
828 [o_extended savePrefs];
831 /* unsubscribe from the interactive dialogues */
832 dialog_Unregister( p_intf );
833 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
834 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
835 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
836 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
837 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
839 /* remove global observer watching for vout device changes correctly */
840 [[NSNotificationCenter defaultCenter] removeObserver: self];
842 /* release some other objects here, because it isn't sure whether dealloc
843 * will be called later on */
844 if( nib_about_loaded )
847 if( nib_prefs_loaded )
853 if( nib_open_loaded )
856 if( nib_extended_loaded )
858 [o_extended release];
861 if( nib_bookmarks_loaded )
862 [o_bookmarks release];
870 if( nib_wizard_loaded )
873 [crashLogURLConnection cancel];
874 [crashLogURLConnection release];
876 [o_embedded_list release];
877 [o_coredialogs release];
880 [o_img_pause_pressed release];
881 [o_img_play_pressed release];
882 [o_img_pause release];
883 [o_img_play release];
885 /* unsubscribe from libvlc's debug messages */
886 msg_Unsubscribe( p_intf->p_sys->p_sub );
888 [o_msg_arr removeAllObjects];
891 [o_msg_lock release];
893 /* write cached user defaults to disk */
894 [[NSUserDefaults standardUserDefaults] synchronize];
896 /* Make sure the Menu doesn't have any references to vlc objects anymore */
897 [self releaseRepresentedObjects:[NSApp mainMenu]];
899 /* Kill the playlist, so that it doesn't accept new request
900 * such as the play request from vlc.c (we are a blocking interface). */
901 p_playlist = pl_Hold( p_intf );
902 vlc_object_kill( p_playlist );
903 pl_Release( p_intf );
905 libvlc_Quit( p_intf->p_libvlc );
911 #pragma mark Sparkle delegate
912 /* received directly before the update gets installed, so let's shut down a bit */
913 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
915 [o_remote stopListening: self];
916 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
918 /* Close the window directly, because we do know that there
919 * won't be anymore video. It's currently waiting a bit. */
920 [[[o_controls voutView] window] orderOut:self];
924 #pragma mark Toolbar delegate
926 /* Our item identifiers */
927 static NSString * VLCToolbarMediaControl = @"VLCToolbarMediaControl";
929 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
931 return [NSArray arrayWithObjects:
932 // NSToolbarCustomizeToolbarItemIdentifier,
933 // NSToolbarFlexibleSpaceItemIdentifier,
934 // NSToolbarSpaceItemIdentifier,
935 // NSToolbarSeparatorItemIdentifier,
936 VLCToolbarMediaControl,
940 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
942 return [NSArray arrayWithObjects:
943 VLCToolbarMediaControl,
947 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
949 NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
951 if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
953 [toolbarItem setLabel:@"Media Controls"];
954 [toolbarItem setPaletteLabel:@"Media Controls"];
956 NSSize size = toolbarMediaControl.frame.size;
957 [toolbarItem setView:toolbarMediaControl];
958 [toolbarItem setMinSize:size];
960 [toolbarItem setMaxSize:size];
962 // Hack: For some reason we need to make sure
963 // that the those element are on top
964 // Add them again will put them frontmost
965 [toolbarMediaControl addSubview:o_scrollfield];
966 [toolbarMediaControl addSubview:o_timeslider];
967 [toolbarMediaControl addSubview:o_timefield];
968 [toolbarMediaControl addSubview:o_main_pgbar];
970 /* TODO: setup a menu */
974 /* itemIdentifier referred to a toolbar item that is not
975 * provided or supported by us or Cocoa
976 * Returning nil will inform the toolbar
977 * that this kind of item is not supported */
984 #pragma mark Other notification
986 - (void)controlTintChanged
990 if( [o_btn_play alternateImage] == o_img_play_pressed )
993 if( [NSColor currentControlTint] == NSGraphiteControlTint )
995 o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
996 o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
998 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
999 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
1000 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
1001 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
1002 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
1003 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
1004 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
1005 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
1009 o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
1010 o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
1012 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
1013 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
1014 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
1015 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
1016 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
1017 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
1018 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
1019 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
1023 [o_btn_play setAlternateImage: o_img_play_pressed];
1025 [o_btn_play setAlternateImage: o_img_pause_pressed];
1028 /* Listen to the remote in exclusive mode, only when VLC is the active
1030 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1032 if( !p_intf ) return;
1033 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
1034 [o_remote startListening: self];
1036 - (void)applicationDidResignActive:(NSNotification *)aNotification
1038 if( !p_intf ) return;
1039 [o_remote stopListening: self];
1042 /* Triggered when the computer goes to sleep */
1043 - (void)computerWillSleep: (NSNotification *)notification
1046 if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
1048 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
1053 #pragma mark File opening
1055 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
1057 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
1058 NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
1060 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
1062 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
1067 /* When user click in the Dock icon our double click in the finder */
1068 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1070 if(!hasVisibleWindows)
1071 [o_window makeKeyAndOrderFront:self];
1077 #pragma mark Apple Remote Control
1079 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1080 increase/decrease as long as the user holds the left/right, plus/minus button */
1081 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1083 if(b_remote_button_hold)
1085 switch([buttonIdentifierNumber intValue])
1087 case kRemoteButtonRight_Hold:
1088 [o_controls forward: self];
1090 case kRemoteButtonLeft_Hold:
1091 [o_controls backward: self];
1093 case kRemoteButtonVolume_Plus_Hold:
1094 [o_controls volumeUp: self];
1096 case kRemoteButtonVolume_Minus_Hold:
1097 [o_controls volumeDown: self];
1100 if(b_remote_button_hold)
1103 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1104 withObject:buttonIdentifierNumber
1110 /* Apple Remote callback */
1111 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1112 pressedDown: (BOOL) pressedDown
1113 clickCount: (unsigned int) count
1115 switch( buttonIdentifier )
1117 case kRemoteButtonPlay:
1119 [o_controls toogleFullscreen:self];
1121 [o_controls play: self];
1124 case kRemoteButtonVolume_Plus:
1125 [o_controls volumeUp: self];
1127 case kRemoteButtonVolume_Minus:
1128 [o_controls volumeDown: self];
1130 case kRemoteButtonRight:
1131 [o_controls next: self];
1133 case kRemoteButtonLeft:
1134 [o_controls prev: self];
1136 case kRemoteButtonRight_Hold:
1137 case kRemoteButtonLeft_Hold:
1138 case kRemoteButtonVolume_Plus_Hold:
1139 case kRemoteButtonVolume_Minus_Hold:
1140 /* simulate an event as long as the user holds the button */
1141 b_remote_button_hold = pressedDown;
1144 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1145 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1146 withObject:buttonIdentifierNumber];
1149 case kRemoteButtonMenu:
1150 [o_controls showPosition: self];
1153 /* Add here whatever you want other buttons to do */
1159 #pragma mark String utility
1160 // FIXME: this has nothing to do here
1162 - (NSString *)localizedString:(const char *)psz
1164 NSString * o_str = nil;
1168 o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1172 msg_Err( VLCIntf, "could not translate: %s", psz );
1178 msg_Warn( VLCIntf, "can't translate empty strings" );
1187 - (char *)delocalizeString:(NSString *)id
1189 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1190 allowLossyConversion: NO];
1195 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1196 allowLossyConversion: YES];
1197 psz_string = malloc( [o_data length] + 1 );
1198 [o_data getBytes: psz_string];
1199 psz_string[ [o_data length] ] = '\0';
1200 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1205 psz_string = malloc( [o_data length] + 1 );
1206 [o_data getBytes: psz_string];
1207 psz_string[ [o_data length] ] = '\0';
1213 /* i_width is in pixels */
1214 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1216 NSMutableString *o_wrapped;
1217 NSString *o_out_string;
1218 NSRange glyphRange, effectiveRange, charRange;
1219 NSRect lineFragmentRect;
1220 unsigned glyphIndex, breaksInserted = 0;
1222 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1223 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1224 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1225 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1226 NSTextContainer *o_container = [[NSTextContainer alloc]
1227 initWithContainerSize: NSMakeSize(i_width, 2000)];
1229 [o_layout_manager addTextContainer: o_container];
1230 [o_container release];
1231 [o_storage addLayoutManager: o_layout_manager];
1232 [o_layout_manager release];
1234 o_wrapped = [o_in_string mutableCopy];
1235 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1237 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1238 glyphIndex += effectiveRange.length) {
1239 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1240 effectiveRange: &effectiveRange];
1241 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1242 actualGlyphRange: &effectiveRange];
1243 if([o_wrapped lineRangeForRange:
1244 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1245 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1249 o_out_string = [NSString stringWithString: o_wrapped];
1250 [o_wrapped release];
1251 [o_storage release];
1253 return o_out_string;
1258 #pragma mark Key Shortcuts
1263 unsigned int i_vlckey;
1264 } nskeys_to_vlckeys[] =
1266 { NSUpArrowFunctionKey, KEY_UP },
1267 { NSDownArrowFunctionKey, KEY_DOWN },
1268 { NSLeftArrowFunctionKey, KEY_LEFT },
1269 { NSRightArrowFunctionKey, KEY_RIGHT },
1270 { NSF1FunctionKey, KEY_F1 },
1271 { NSF2FunctionKey, KEY_F2 },
1272 { NSF3FunctionKey, KEY_F3 },
1273 { NSF4FunctionKey, KEY_F4 },
1274 { NSF5FunctionKey, KEY_F5 },
1275 { NSF6FunctionKey, KEY_F6 },
1276 { NSF7FunctionKey, KEY_F7 },
1277 { NSF8FunctionKey, KEY_F8 },
1278 { NSF9FunctionKey, KEY_F9 },
1279 { NSF10FunctionKey, KEY_F10 },
1280 { NSF11FunctionKey, KEY_F11 },
1281 { NSF12FunctionKey, KEY_F12 },
1282 { NSInsertFunctionKey, KEY_INSERT },
1283 { NSHomeFunctionKey, KEY_HOME },
1284 { NSEndFunctionKey, KEY_END },
1285 { NSPageUpFunctionKey, KEY_PAGEUP },
1286 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1287 { NSMenuFunctionKey, KEY_MENU },
1288 { NSTabCharacter, KEY_TAB },
1289 { NSCarriageReturnCharacter, KEY_ENTER },
1290 { NSEnterCharacter, KEY_ENTER },
1291 { NSBackspaceCharacter, KEY_BACKSPACE },
1292 { (unichar) 0x1b, KEY_ESC },
1296 static unichar VLCKeyToCocoa( unsigned int i_key )
1300 for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1302 if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1304 return nskeys_to_vlckeys[i].i_nskey;
1307 return (unichar)(i_key & ~KEY_MODIFIER);
1310 unsigned int CocoaKeyToVLC( unichar i_key )
1314 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1316 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1318 return nskeys_to_vlckeys[i].i_vlckey;
1321 return (unsigned int)i_key;
1324 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1326 unsigned int new = 0;
1327 if( i_key & KEY_MODIFIER_COMMAND )
1328 new |= NSCommandKeyMask;
1329 if( i_key & KEY_MODIFIER_ALT )
1330 new |= NSAlternateKeyMask;
1331 if( i_key & KEY_MODIFIER_SHIFT )
1332 new |= NSShiftKeyMask;
1333 if( i_key & KEY_MODIFIER_CTRL )
1334 new |= NSControlKeyMask;
1338 /*****************************************************************************
1339 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1340 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1341 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1342 *****************************************************************************/
1343 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1347 unsigned int i_pressed_modifiers = 0;
1348 const struct hotkey *p_hotkeys;
1352 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1354 i_pressed_modifiers = [o_event modifierFlags];
1356 if( i_pressed_modifiers & NSShiftKeyMask )
1357 val.i_int |= KEY_MODIFIER_SHIFT;
1358 if( i_pressed_modifiers & NSControlKeyMask )
1359 val.i_int |= KEY_MODIFIER_CTRL;
1360 if( i_pressed_modifiers & NSAlternateKeyMask )
1361 val.i_int |= KEY_MODIFIER_ALT;
1362 if( i_pressed_modifiers & NSCommandKeyMask )
1363 val.i_int |= KEY_MODIFIER_COMMAND;
1365 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1369 case NSDeleteCharacter:
1370 case NSDeleteFunctionKey:
1371 case NSDeleteCharFunctionKey:
1372 case NSBackspaceCharacter:
1373 case NSUpArrowFunctionKey:
1374 case NSDownArrowFunctionKey:
1375 case NSRightArrowFunctionKey:
1376 case NSLeftArrowFunctionKey:
1377 case NSEnterCharacter:
1378 case NSCarriageReturnCharacter:
1382 val.i_int |= CocoaKeyToVLC( key );
1384 for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1386 if( p_hotkeys[i].i_key == val.i_int )
1388 var_Set( p_intf->p_libvlc, "key-pressed", val );
1397 #pragma mark Other objects getters
1407 - (id)simplePreferences
1412 if( !nib_prefs_loaded )
1413 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1423 if( !nib_prefs_loaded )
1424 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1437 - (BOOL)isPlaylistCollapsed
1439 return ![o_btn_playlist state];
1475 if( o_embedded_list )
1476 return o_embedded_list;
1481 - (id)coreDialogProvider
1484 return o_coredialogs;
1492 return o_main_pgbar;
1497 - (id)controllerWindow
1509 - (id)eyeTVController
1517 - (id)appleRemoteController
1523 #pragma mark Polling
1525 /*****************************************************************************
1526 * ManageThread: An ugly thread that polls
1527 *****************************************************************************/
1528 static void * ManageThread( void *user_data )
1530 id self = user_data;
1537 struct manage_cleanup_stack {
1538 intf_thread_t * p_intf;
1539 input_thread_t ** p_input;
1540 playlist_t * p_playlist;
1544 static void manage_cleanup( void * args )
1546 struct manage_cleanup_stack * manage_cleanup_stack = args;
1547 intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1548 input_thread_t * p_input = *manage_cleanup_stack->p_input;
1549 id self = manage_cleanup_stack->self;
1550 playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1552 var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1553 var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1554 var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1555 var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1556 var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1558 pl_Release( p_intf );
1560 if( p_input ) vlc_object_release( p_input );
1565 playlist_t * p_playlist;
1566 input_thread_t * p_input = NULL;
1568 /* new thread requires a new pool */
1570 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1572 p_playlist = pl_Hold( p_intf );
1574 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1575 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1576 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1577 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1578 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1580 struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1581 pthread_cleanup_push(manage_cleanup, &stack);
1583 bool exitLoop = false;
1586 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1590 p_input = playlist_CurrentInput( p_playlist );
1592 /* Refresh the interface */
1595 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1596 p_intf->p_sys->b_input_update = true;
1599 else if( !vlc_object_alive (p_input) || p_input->b_dead )
1602 p_intf->p_sys->b_intf_update = true;
1603 p_intf->p_sys->i_play_status = END_S;
1604 msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1605 vlc_object_release( p_input );
1608 else if( cachedInputState != input_GetState( p_input ) )
1610 p_intf->p_sys->b_intf_update = true;
1613 /* Manage volume status */
1614 [self manageVolumeSlider];
1616 msleep( INTF_IDLE_SLEEP );
1621 exitLoop = (f_appExit != 0 ? true : false);
1625 pthread_cleanup_pop(1);
1627 msg_Dbg( p_intf, "OS X Manage thread terminating" );
1630 - (void)manageVolumeSlider
1632 audio_volume_t i_volume;
1633 playlist_t * p_playlist = pl_Hold( p_intf );
1635 aout_VolumeGet( p_playlist, &i_volume );
1636 pl_Release( p_intf );
1638 if( i_volume != i_lastShownVolume )
1640 i_lastShownVolume = i_volume;
1641 p_intf->p_sys->b_volume_update = TRUE;
1645 - (void)manageIntf:(NSTimer *)o_timer
1648 playlist_t * p_playlist;
1649 input_thread_t * p_input;
1651 if( p_intf->p_sys->b_input_update )
1653 /* Called when new input is opened */
1654 p_intf->p_sys->b_current_title_update = true;
1655 p_intf->p_sys->b_intf_update = true;
1656 p_intf->p_sys->b_input_update = false;
1657 [self setupMenus]; /* Make sure input menu is up to date */
1659 /* update our info-panel to reflect the new item, if we don't show
1660 * the playlist or the selection is empty */
1661 if( [self isPlaylistCollapsed] == YES )
1663 playlist_t * p_playlist = pl_Hold( p_intf );
1665 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1668 [[self info] updatePanelWithItem: p_item->p_input];
1669 pl_Release( p_intf );
1672 if( p_intf->p_sys->b_intf_update )
1674 bool b_input = false;
1675 bool b_plmul = false;
1676 bool b_control = false;
1677 bool b_seekable = false;
1678 bool b_chapters = false;
1680 playlist_t * p_playlist = pl_Hold( p_intf );
1683 b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1686 p_input = playlist_CurrentInput( p_playlist );
1688 bool b_buffering = NO;
1690 if( ( b_input = ( p_input != NULL ) ) )
1692 /* seekable streams */
1693 cachedInputState = input_GetState( p_input );
1694 if ( cachedInputState == INIT_S ||
1695 cachedInputState == OPENING_S )
1700 /* seekable streams */
1701 b_seekable = var_GetBool( p_input, "can-seek" );
1703 /* check whether slow/fast motion is possible */
1704 b_control = var_GetBool( p_input, "can-rate" );
1706 /* chapters & titles */
1707 //b_chapters = p_input->stream.i_area_nb > 1;
1708 vlc_object_release( p_input );
1710 pl_Release( p_intf );
1714 [o_main_pgbar startAnimation:self];
1715 [o_main_pgbar setIndeterminate:YES];
1716 [o_main_pgbar setHidden:NO];
1720 [o_main_pgbar stopAnimation:self];
1721 [o_main_pgbar setHidden:YES];
1724 [o_btn_stop setEnabled: b_input];
1725 [o_embedded_window setStop: b_input];
1726 [o_btn_ff setEnabled: b_seekable];
1727 [o_btn_rewind setEnabled: b_seekable];
1728 [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1729 [o_embedded_window setPrev: (b_plmul || b_chapters)];
1730 [o_btn_next setEnabled: (b_plmul || b_chapters)];
1731 [o_embedded_window setNext: (b_plmul || b_chapters)];
1733 [o_timeslider setFloatValue: 0.0];
1734 [o_timeslider setEnabled: b_seekable];
1735 [o_timefield setStringValue: @"00:00"];
1736 [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1737 [[[self controls] fspanel] setSeekable: b_seekable];
1739 [o_embedded_window setSeekable: b_seekable];
1740 [o_embedded_window setTime:@"00:00" position:0.0];
1742 p_intf->p_sys->b_current_title_update = true;
1744 p_intf->p_sys->b_intf_update = false;
1747 if( p_intf->p_sys->b_playmode_update )
1749 [o_playlist playModeUpdated];
1750 p_intf->p_sys->b_playmode_update = false;
1752 if( p_intf->p_sys->b_playlist_update )
1754 [o_playlist playlistUpdated];
1755 p_intf->p_sys->b_playlist_update = false;
1758 if( p_intf->p_sys->b_fullscreen_update )
1760 p_intf->p_sys->b_fullscreen_update = false;
1763 if( p_intf->p_sys->b_intf_show )
1765 if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1766 [[o_controls fspanel] fadeIn];
1768 [o_window makeKeyAndOrderFront: self];
1770 p_intf->p_sys->b_intf_show = false;
1773 p_input = pl_CurrentInput( p_intf );
1774 if( p_input && vlc_object_alive (p_input) )
1778 if( p_intf->p_sys->b_current_title_update )
1781 input_item_t * p_item = input_GetItem( p_input );
1782 char * name = input_item_GetNowPlaying( p_item );
1785 name = input_item_GetName( p_item );
1787 aString = [NSString stringWithUTF8String:name];
1791 [self setScrollField: aString stopAfter:-1];
1792 [[[self controls] fspanel] setStreamTitle: aString];
1794 [[o_controls voutView] updateTitle];
1796 [o_playlist updateRowSelection];
1798 p_intf->p_sys->b_current_title_update = FALSE;
1801 if( [o_timeslider isEnabled] )
1803 /* Update the slider */
1807 char psz_time[MSTRTIME_MAX_SIZE];
1810 var_Get( p_input, "position", &pos );
1811 f_updated = 10000. * pos.f_float;
1812 [o_timeslider setFloatValue: f_updated];
1814 var_Get( p_input, "time", &time );
1816 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1817 if( b_time_remaining && dur != -1 )
1819 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1822 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1824 [o_timefield setStringValue: o_time];
1825 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1826 [o_embedded_window setTime: o_time position: f_updated];
1829 /* Manage Playing status */
1830 var_Get( p_input, "state", &val );
1831 if( p_intf->p_sys->i_play_status != val.i_int )
1833 p_intf->p_sys->i_play_status = val.i_int;
1834 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1835 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1837 vlc_object_release( p_input );
1841 vlc_object_release( p_input );
1845 p_intf->p_sys->i_play_status = END_S;
1846 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1847 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1848 [self setSubmenusEnabled: FALSE];
1851 if( p_intf->p_sys->b_volume_update )
1854 int i_volume_step = 0;
1855 o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1856 if( i_lastShownVolume != -1 )
1857 [self setScrollField:o_text stopAfter:1000000];
1858 i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1859 [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1860 [o_volumeslider setEnabled: TRUE];
1861 [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1862 [o_embedded_window setVolumeEnabled: TRUE];
1863 [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1864 p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1865 p_intf->p_sys->b_volume_update = FALSE;
1869 [self updateMessageDisplay];
1871 if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1872 [self resetScrollField];
1874 [interfaceTimer autorelease];
1876 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1877 target: self selector: @selector(manageIntf:)
1878 userInfo: nil repeats: FALSE] retain];
1882 #pragma mark Interface update
1886 playlist_t * p_playlist = pl_Hold( p_intf );
1887 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1888 if( p_input != NULL )
1890 [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1891 var: "program" selector: @selector(toggleVar:)];
1893 [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1894 var: "title" selector: @selector(toggleVar:)];
1896 [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1897 var: "chapter" selector: @selector(toggleVar:)];
1899 [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1900 var: "audio-es" selector: @selector(toggleVar:)];
1902 [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1903 var: "video-es" selector: @selector(toggleVar:)];
1905 [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1906 var: "spu-es" selector: @selector(toggleVar:)];
1908 /* special case for "Open File" inside the subtitles menu item */
1909 if( [o_mi_videotrack isEnabled] == YES )
1910 [o_mi_subtitle setEnabled: YES];
1912 aout_instance_t * p_aout = input_GetAout( p_input );
1913 if( p_aout != NULL )
1915 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1916 var: "audio-channels" selector: @selector(toggleVar:)];
1918 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1919 var: "audio-device" selector: @selector(toggleVar:)];
1921 [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1922 var: "visual" selector: @selector(toggleVar:)];
1923 vlc_object_release( (vlc_object_t *)p_aout );
1926 vout_thread_t * p_vout = input_GetVout( p_input );
1928 if( p_vout != NULL )
1930 vlc_object_t * p_dec_obj;
1932 [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1933 var: "aspect-ratio" selector: @selector(toggleVar:)];
1935 [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1936 var: "crop" selector: @selector(toggleVar:)];
1938 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1939 var: "video-device" selector: @selector(toggleVar:)];
1941 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1942 var: "deinterlace-mode" selector: @selector(toggleVar:)];
1945 [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1946 (vlc_object_t *)p_vout var:"postprocess" selector:
1947 @selector(toggleVar:)];
1950 vlc_object_release( (vlc_object_t *)p_vout );
1952 vlc_object_release( p_input );
1954 pl_Release( p_intf );
1957 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1960 vout_thread_t * p_vout = getVout();
1964 /* clean the menu before adding new entries */
1965 if( [o_mi_screen hasSubmenu] )
1967 y = [[o_mi_screen submenu] numberOfItems] - 1;
1968 msg_Dbg( VLCIntf, "%i items in submenu", y );
1971 msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1972 [[o_mi_screen submenu] removeItemAtIndex: x];
1977 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1978 var: "video-device" selector: @selector(toggleVar:)];
1979 vlc_object_release( (vlc_object_t *)p_vout );
1982 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1985 i_end_scroll = mdate() + timeout;
1988 [o_scrollfield setStringValue: o_string];
1989 [o_embedded_window setScrollString: o_string];
1992 - (void)resetScrollField
1994 playlist_t * p_playlist = pl_Hold( p_intf );
1995 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1998 if( p_input && vlc_object_alive (p_input) )
2002 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
2003 if( input_item_GetNowPlaying( p_item->p_input ) )
2004 o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
2006 o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
2008 [self setScrollField: o_temp stopAfter:-1];
2009 [[[self controls] fspanel] setStreamTitle: o_temp];
2010 vlc_object_release( p_input );
2011 pl_Release( p_intf );
2014 pl_Release( p_intf );
2015 [self setScrollField: _NS("VLC media player") stopAfter:-1];
2018 - (void)playStatusUpdated:(int)i_status
2020 if( i_status == PLAYING_S )
2022 [[[self controls] fspanel] setPause];
2023 [o_btn_play setImage: o_img_pause];
2024 [o_btn_play setAlternateImage: o_img_pause_pressed];
2025 [o_btn_play setToolTip: _NS("Pause")];
2026 [o_mi_play setTitle: _NS("Pause")];
2027 [o_dmi_play setTitle: _NS("Pause")];
2028 [o_vmi_play setTitle: _NS("Pause")];
2032 [[[self controls] fspanel] setPlay];
2033 [o_btn_play setImage: o_img_play];
2034 [o_btn_play setAlternateImage: o_img_play_pressed];
2035 [o_btn_play setToolTip: _NS("Play")];
2036 [o_mi_play setTitle: _NS("Play")];
2037 [o_dmi_play setTitle: _NS("Play")];
2038 [o_vmi_play setTitle: _NS("Play")];
2042 - (void)setSubmenusEnabled:(BOOL)b_enabled
2044 [o_mi_program setEnabled: b_enabled];
2045 [o_mi_title setEnabled: b_enabled];
2046 [o_mi_chapter setEnabled: b_enabled];
2047 [o_mi_audiotrack setEnabled: b_enabled];
2048 [o_mi_visual setEnabled: b_enabled];
2049 [o_mi_videotrack setEnabled: b_enabled];
2050 [o_mi_subtitle setEnabled: b_enabled];
2051 [o_mi_channels setEnabled: b_enabled];
2052 [o_mi_deinterlace setEnabled: b_enabled];
2053 [o_mi_ffmpeg_pp setEnabled: b_enabled];
2054 [o_mi_device setEnabled: b_enabled];
2055 [o_mi_screen setEnabled: b_enabled];
2056 [o_mi_aspect_ratio setEnabled: b_enabled];
2057 [o_mi_crop setEnabled: b_enabled];
2058 [o_mi_teletext setEnabled: b_enabled];
2061 - (IBAction)timesliderUpdate:(id)sender
2064 playlist_t * p_playlist;
2065 input_thread_t * p_input;
2067 switch( [[NSApp currentEvent] type] )
2070 case NSLeftMouseDown:
2071 case NSLeftMouseDragged:
2072 f_updated = [sender floatValue];
2078 p_playlist = pl_Hold( p_intf );
2079 p_input = playlist_CurrentInput( p_playlist );
2080 if( p_input != NULL )
2085 char psz_time[MSTRTIME_MAX_SIZE];
2087 pos.f_float = f_updated / 10000.;
2088 var_Set( p_input, "position", pos );
2089 [o_timeslider setFloatValue: f_updated];
2091 var_Get( p_input, "time", &time );
2093 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
2094 if( b_time_remaining && dur != -1 )
2096 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
2099 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2101 [o_timefield setStringValue: o_time];
2102 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
2103 [o_embedded_window setTime: o_time position: f_updated];
2104 vlc_object_release( p_input );
2106 pl_Release( p_intf );
2109 - (IBAction)timeFieldWasClicked:(id)sender
2111 b_time_remaining = !b_time_remaining;
2116 #pragma mark Recent Items
2118 - (IBAction)clearRecentItems:(id)sender
2120 [[NSDocumentController sharedDocumentController]
2121 clearRecentDocuments: nil];
2124 - (void)openRecentItem:(id)sender
2126 [self application: nil openFile: [sender title]];
2132 - (IBAction)intfOpenFile:(id)sender
2134 if( !nib_open_loaded )
2136 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2137 [o_open awakeFromNib];
2144 - (IBAction)intfOpenFileGeneric:(id)sender
2146 if( !nib_open_loaded )
2148 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2149 [o_open awakeFromNib];
2150 [o_open openFileGeneric];
2152 [o_open openFileGeneric];
2156 - (IBAction)intfOpenDisc:(id)sender
2158 if( !nib_open_loaded )
2160 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2161 [o_open awakeFromNib];
2168 - (IBAction)intfOpenNet:(id)sender
2170 if( !nib_open_loaded )
2172 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2173 [o_open awakeFromNib];
2180 - (IBAction)intfOpenCapture:(id)sender
2182 if( !nib_open_loaded )
2184 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2185 [o_open awakeFromNib];
2186 [o_open openCapture];
2188 [o_open openCapture];
2192 - (IBAction)showWizard:(id)sender
2194 if( !nib_wizard_loaded )
2196 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2197 [o_wizard initStrings];
2198 [o_wizard resetWizard];
2199 [o_wizard showWizard];
2201 [o_wizard resetWizard];
2202 [o_wizard showWizard];
2206 - (IBAction)showVLM:(id)sender
2209 if( !nib_vlm_loaded )
2210 nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner: NSApp];
2212 [o_vlm showVLMWindow];
2215 theAlert = [NSAlert alertWithMessageText:_NS("VLM not available") defaultButton:_NS("OK") alternateButton:nil otherButton:nil informativeTextWithFormat:_NS("The VideoLAN Manager was not enabled in this version of VLC.")];
2216 [theAlert runModal];
2220 - (IBAction)showExtended:(id)sender
2222 if( o_extended == nil )
2223 o_extended = [[VLCExtended alloc] init];
2225 if( !nib_extended_loaded )
2226 nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2228 [o_extended showPanel];
2231 - (IBAction)showBookmarks:(id)sender
2233 /* we need the wizard-nib for the bookmarks's extract functionality */
2234 if( !nib_wizard_loaded )
2236 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2237 [o_wizard initStrings];
2240 if( !nib_bookmarks_loaded )
2241 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2243 [o_bookmarks showBookmarks];
2246 - (IBAction)viewPreferences:(id)sender
2248 if( !nib_prefs_loaded )
2250 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2251 o_sprefs = [[VLCSimplePrefs alloc] init];
2252 o_prefs= [[VLCPrefs alloc] init];
2255 [o_sprefs showSimplePrefs];
2259 #pragma mark Help and Docs
2261 - (IBAction)viewAbout:(id)sender
2263 if( !nib_about_loaded )
2264 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2266 [o_about showAbout];
2269 - (IBAction)showLicense:(id)sender
2271 if( !nib_about_loaded )
2272 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2274 [o_about showGPL: sender];
2277 - (IBAction)viewHelp:(id)sender
2279 if( !nib_about_loaded )
2281 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2288 - (IBAction)openReadMe:(id)sender
2290 NSString * o_path = [[NSBundle mainBundle]
2291 pathForResource: @"README.MacOSX" ofType: @"rtf"];
2293 [[NSWorkspace sharedWorkspace] openFile: o_path
2294 withApplication: @"TextEdit"];
2297 - (IBAction)openDocumentation:(id)sender
2299 NSURL * o_url = [NSURL URLWithString:
2300 @"http://www.videolan.org/doc/"];
2302 [[NSWorkspace sharedWorkspace] openURL: o_url];
2305 - (IBAction)openWebsite:(id)sender
2307 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2309 [[NSWorkspace sharedWorkspace] openURL: o_url];
2312 - (IBAction)openForum:(id)sender
2314 NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2316 [[NSWorkspace sharedWorkspace] openURL: o_url];
2319 - (IBAction)openDonate:(id)sender
2321 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2323 [[NSWorkspace sharedWorkspace] openURL: o_url];
2327 #pragma mark Crash Log
2328 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2330 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2331 NSURL *url = [NSURL URLWithString:urlStr];
2333 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2334 [req setHTTPMethod:@"POST"];
2337 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2339 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2340 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2341 email = [emails valueAtIndex:[emails indexForIdentifier:
2342 [emails primaryIdentifier]]];
2345 email = [NSString string];
2348 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2349 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2350 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2351 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2353 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2355 /* Released from delegate */
2356 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2359 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2361 [crashLogURLConnection release];
2362 crashLogURLConnection = nil;
2365 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2367 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2368 [crashLogURLConnection release];
2369 crashLogURLConnection = nil;
2372 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2374 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2375 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2377 NSString * latestLog = nil;
2378 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2379 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2380 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
2381 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2383 while (fname = [direnum nextObject])
2385 [direnum skipDescendents];
2386 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2388 NSArray * compo = [fname componentsSeparatedByString:@"_"];
2389 if( [compo count] < 3 ) continue;
2390 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2391 if( [compo count] < 4 ) continue;
2394 if( year < [[compo objectAtIndex:0] intValue] ||
2395 (year ==[[compo objectAtIndex:0] intValue] &&
2396 (month < [[compo objectAtIndex:1] intValue] ||
2397 (month ==[[compo objectAtIndex:1] intValue] &&
2398 (day < [[compo objectAtIndex:2] intValue] ||
2399 (day ==[[compo objectAtIndex:2] intValue] &&
2400 hours < [[compo objectAtIndex:3] intValue] ))))))
2402 year = [[compo objectAtIndex:0] intValue];
2403 month = [[compo objectAtIndex:1] intValue];
2404 day = [[compo objectAtIndex:2] intValue];
2405 hours = [[compo objectAtIndex:3] intValue];
2406 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2411 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2414 if( !previouslySeen )
2416 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
2417 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2418 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
2419 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2424 - (NSString *)latestCrashLogPath
2426 return [self latestCrashLogPathPreviouslySeen:YES];
2429 - (void)lookForCrashLog
2431 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2432 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2433 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2434 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2435 if( latestLog && !areCrashLogsTooOld )
2436 [NSApp runModalForWindow: o_crashrep_win];
2440 - (IBAction)crashReporterAction:(id)sender
2442 if( sender == o_crashrep_send_btn )
2443 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2446 [o_crashrep_win orderOut: sender];
2449 - (IBAction)openCrashLog:(id)sender
2451 NSString * latestLog = [self latestCrashLogPath];
2454 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2458 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.") );
2463 #pragma mark Remove old prefs
2465 - (void)_removeOldPreferences
2467 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2468 static const int kCurrentPreferencesVersion = 1;
2469 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2470 if( version >= kCurrentPreferencesVersion ) return;
2472 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
2473 NSUserDomainMask, YES);
2474 if( !libraries || [libraries count] == 0) return;
2475 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2477 /* File not found, don't attempt anything */
2478 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2479 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2481 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2485 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2486 _NS("We just found an older version of VLC's preferences files."),
2487 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2488 if( res != NSOKButton )
2490 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2494 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2496 /* Move the file to trash so that user can find them later */
2497 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2499 /* really reset the defaults from now on */
2500 [NSUserDefaults resetStandardUserDefaults];
2502 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2503 [[NSUserDefaults standardUserDefaults] synchronize];
2506 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2508 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2514 execl(path, path, NULL);
2518 #pragma mark Errors, warnings and messages
2520 - (IBAction)viewErrorsAndWarnings:(id)sender
2522 [[[self coreDialogProvider] errorPanel] showPanel];
2525 - (IBAction)showMessagesPanel:(id)sender
2527 [o_msgs_panel makeKeyAndOrderFront: sender];
2530 - (IBAction)showInformationPanel:(id)sender
2532 if(! nib_info_loaded )
2533 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2538 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2540 if( [o_notification object] == o_msgs_panel )
2541 [self updateMessageDisplay];
2544 - (void)updateMessageDisplay
2546 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2549 NSEnumerator * o_enum;
2551 [o_messages setString: @""];
2555 o_enum = [o_msg_arr objectEnumerator];
2557 while( ( o_msg = [o_enum nextObject] ) != nil )
2559 [o_messages insertText: o_msg];
2562 b_msg_arr_changed = NO;
2563 [o_msg_lock unlock];
2567 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2569 NSColor *o_white = [NSColor whiteColor];
2570 NSColor *o_red = [NSColor redColor];
2571 NSColor *o_yellow = [NSColor yellowColor];
2572 NSColor *o_gray = [NSColor grayColor];
2574 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2575 static const char * ppsz_type[4] = { ": ", " error: ",
2576 " warning: ", " debug: " };
2579 NSDictionary *o_attr;
2580 NSAttributedString *o_msg_color;
2582 int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2586 if( [o_msg_arr count] + 2 > 600 )
2588 [o_msg_arr removeObjectAtIndex: 0];
2589 [o_msg_arr removeObjectAtIndex: 1];
2592 o_attr = [NSDictionary dictionaryWithObject: o_gray
2593 forKey: NSForegroundColorAttributeName];
2594 o_msg = [NSString stringWithFormat: @"%@%s",
2595 [[o_notification userInfo] objectForKey: @"Module"],
2597 o_msg_color = [[NSAttributedString alloc]
2598 initWithString: o_msg attributes: o_attr];
2599 [o_msg_arr addObject: [o_msg_color autorelease]];
2601 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2602 forKey: NSForegroundColorAttributeName];
2603 o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2604 o_msg_color = [[NSAttributedString alloc]
2605 initWithString: o_msg attributes: o_attr];
2606 [o_msg_arr addObject: [o_msg_color autorelease]];
2608 b_msg_arr_changed = YES;
2609 [o_msg_lock unlock];
2612 - (IBAction)saveDebugLog:(id)sender
2614 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2616 [saveFolderPanel setCanChooseDirectories: NO];
2617 [saveFolderPanel setCanChooseFiles: YES];
2618 [saveFolderPanel setCanSelectHiddenExtension: NO];
2619 [saveFolderPanel setCanCreateDirectories: YES];
2620 [saveFolderPanel setRequiredFileType: @"rtfd"];
2621 [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];
2624 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2627 if( returnCode == NSOKButton )
2629 b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2631 msg_Warn( p_intf, "Error while saving the debug log" );
2636 #pragma mark Playlist toggling
2638 - (IBAction)togglePlaylist:(id)sender
2640 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2641 NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2642 /*First, check if the playlist is visible*/
2643 if( contentRect.size.height <= 169. )
2645 o_restore_rect = contentRect;
2646 b_restore_size = true;
2647 b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2650 if( o_size_with_playlist.height > 169. )
2651 o_rect.size.height = o_size_with_playlist.height;
2653 o_rect.size.height = 500.;
2655 if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2656 o_rect.size.width = o_size_with_playlist.width;
2658 o_rect.size.width = [o_window contentMinSize].width;
2660 o_rect.origin.x = contentRect.origin.x;
2661 o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2662 [o_window contentMinSize].height;
2664 o_rect = [o_window frameRectForContentRect:o_rect];
2666 NSRect screenRect = [[o_window screen] visibleFrame];
2667 if( !NSContainsRect( screenRect, o_rect ) ) {
2668 if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2669 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2670 if( NSMinY(o_rect) < NSMinY(screenRect) )
2671 o_rect.origin.y = ( NSMinY(screenRect) );
2674 [o_btn_playlist setState: YES];
2678 NSSize curSize = o_rect.size;
2679 if( b_restore_size )
2681 o_rect = o_restore_rect;
2682 if( o_rect.size.height < [o_window contentMinSize].height )
2683 o_rect.size.height = [o_window contentMinSize].height;
2684 if( o_rect.size.width < [o_window contentMinSize].width )
2685 o_rect.size.width = [o_window contentMinSize].width;
2689 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2691 o_rect.size.height = [o_window contentMinSize].height;
2692 o_rect.size.width = [o_window contentMinSize].width;
2693 o_rect.origin.x = contentRect.origin.x;
2694 /* Calculate the position of the lower right corner after resize */
2695 o_rect.origin.y = contentRect.origin.y +
2696 contentRect.size.height - [o_window contentMinSize].height;
2699 [o_playlist_view setAutoresizesSubviews: NO];
2700 [o_playlist_view removeFromSuperview];
2701 [o_btn_playlist setState: NO];
2702 b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2703 o_rect = [o_window frameRectForContentRect:o_rect];
2706 [o_window setFrame: o_rect display:YES animate: YES];
2709 - (void)updateTogglePlaylistState
2711 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2712 [o_btn_playlist setState: NO];
2714 [o_btn_playlist setState: YES];
2716 [[self playlist] outlineViewSelectionDidChange: NULL];
2719 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2722 /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2724 /*Stores the size the controller one resize, to be able to restore it when
2725 toggling the playlist*/
2726 o_size_with_playlist = proposedFrameSize;
2729 rect.size = proposedFrameSize;
2730 if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2732 if( b_small_window == NO )
2734 /* if large and going to small then hide */
2735 b_small_window = YES;
2736 [o_playlist_view setAutoresizesSubviews: NO];
2737 [o_playlist_view removeFromSuperview];
2739 return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2741 return proposedFrameSize;
2744 - (void)windowDidMove:(NSNotification *)notif
2746 b_restore_size = false;
2749 - (void)windowDidResize:(NSNotification *)notif
2751 if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2753 /* If large and coming from small then show */
2754 [o_playlist_view setAutoresizesSubviews: YES];
2755 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2756 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2757 [o_playlist_view setNeedsDisplay:YES];
2758 [[o_window contentView] addSubview: o_playlist_view];
2759 b_small_window = NO;
2761 [self updateTogglePlaylistState];
2768 @implementation VLCMain (NSMenuValidation)
2770 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2772 NSString *o_title = [o_mi title];
2773 BOOL bEnabled = TRUE;
2775 /* Recent Items Menu */
2776 if( [o_title isEqualToString: _NS("Clear Menu")] )
2778 NSMenu * o_menu = [o_mi_open_recent submenu];
2779 int i_nb_items = [o_menu numberOfItems];
2780 NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2781 recentDocumentURLs];
2782 UInt32 i_nb_docs = [o_docs count];
2784 if( i_nb_items > 1 )
2786 while( --i_nb_items )
2788 [o_menu removeItemAtIndex: 0];
2797 [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2803 o_url = [o_docs objectAtIndex: i_nb_docs];
2805 if( [o_url isFileURL] )
2807 o_doc = [o_url path];
2811 o_doc = [o_url absoluteString];
2814 [o_menu insertItemWithTitle: o_doc
2815 action: @selector(openRecentItem:)
2816 keyEquivalent: @"" atIndex: 0];
2818 if( i_nb_docs == 0 )
2834 @implementation VLCMain (Internal)
2836 - (void)handlePortMessage:(NSPortMessage *)o_msg
2841 NSInvocation * o_inv;
2842 NSConditionLock * o_lock;
2844 o_data = [[o_msg components] lastObject];
2845 o_inv = *((NSInvocation **)[o_data bytes]);
2846 [o_inv getArgument: &o_value atIndex: 2];
2847 val = (id **)[o_value pointerValue];
2848 [o_inv setArgument: val[1] atIndex: 2];
2853 [o_lock unlockWithCondition: 1];
2858 /*****************************************************************************
2859 * VLCApplication interface
2860 * exclusively used to implement media key support on Al Apple keyboards
2861 * b_justJumped is required as the keyboard send its events faster than
2862 * the user can actually jump through his media
2863 *****************************************************************************/
2865 @implementation VLCApplication
2867 - (void)awakeFromNib
2869 b_active = b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2870 b_activeInBackground = config_GetInt( VLCIntf, "macosx-mediakeys-background" );
2871 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
2872 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appGotActiveOrInactive:) name: @"NSApplicationDidBecomeActiveNotification" object: nil];
2873 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appGotActiveOrInactive:) name: @"NSApplicationWillResignActiveNotification" object: nil];
2878 [[NSNotificationCenter defaultCenter] removeObserver: self];
2882 - (void)appGotActiveOrInactive: (NSNotification *)o_notification
2884 if(( [[o_notification name] isEqualToString: @"NSApplicationWillResignActiveNotification"] && !b_activeInBackground ) || !b_mediaKeySupport)
2890 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2892 b_active = b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2893 b_activeInBackground = config_GetInt( VLCIntf, "macosx-mediakeys-background" );
2897 - (void)sendEvent: (NSEvent*)event
2901 if( [event type] == NSSystemDefined && [event subtype] == 8 )
2903 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
2904 int keyFlags = ([event data1] & 0x0000FFFF);
2905 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
2906 int keyRepeat = (keyFlags & 0x1);
2908 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
2909 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
2911 if( keyCode == NX_KEYTYPE_FAST && !b_justJumped )
2913 if( keyState == 0 && keyRepeat == 0 )
2915 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_NEXT );
2917 else if( keyRepeat == 1 )
2919 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
2921 [self performSelector:@selector(resetJump)
2927 if( keyCode == NX_KEYTYPE_REWIND && !b_justJumped )
2929 if( keyState == 0 && keyRepeat == 0 )
2931 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PREV );
2933 else if( keyRepeat == 1 )
2935 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
2937 [self performSelector:@selector(resetJump)
2944 [super sendEvent: event];