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"
57 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
58 #import <IOKit/hidsystem/ev_keymap.h> /* for the media key support */
59 #import <Sparkle/Sparkle.h> /* we're the update delegate */
61 /*****************************************************************************
63 *****************************************************************************/
64 static void Run ( intf_thread_t *p_intf );
66 static void * ManageThread( void *user_data );
68 static unichar VLCKeyToCocoa( unsigned int i_key );
69 static unsigned int VLCModifiersToCocoa( unsigned int i_key );
71 static void updateProgressPanel (void *, const char *, float);
72 static bool checkProgressPanel (void *);
73 static void destroyProgressPanel (void *);
75 static void MsgCallback( msg_cb_data_t *, msg_item_t *, unsigned );
78 #pragma mark VLC Interface Object Callbacks
80 /*****************************************************************************
81 * OpenIntf: initialize interface
82 *****************************************************************************/
83 int OpenIntf ( vlc_object_t *p_this )
85 intf_thread_t *p_intf = (intf_thread_t*) p_this;
87 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
88 if( p_intf->p_sys == NULL )
91 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
93 /* subscribe to LibVLCCore's messages */
94 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
96 p_intf->b_should_run_on_first_thread = true;
101 /*****************************************************************************
102 * CloseIntf: destroy interface
103 *****************************************************************************/
104 void CloseIntf ( vlc_object_t *p_this )
106 intf_thread_t *p_intf = (intf_thread_t*) p_this;
108 free( p_intf->p_sys );
111 /*****************************************************************************
113 *****************************************************************************/
116 static void Run( intf_thread_t *p_intf )
120 /* Do it again - for some unknown reason, vlc_thread_create() often
121 * fails to go to real-time priority with the first launched thread
123 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
125 /* Make sure the "force quit" menu item does quit instantly.
126 * VLC overrides SIGTERM which is sent by the "force quit"
127 * menu item to make sure deamon mode quits gracefully, so
128 * we un-override SIGTERM here. */
130 sigaddset( &set, SIGTERM );
131 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
133 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
135 /* Install a jmpbuffer to where we can go back before the NSApp exit
136 * see applicationWillTerminate: */
137 [VLCApplication sharedApplication];
139 [[VLCMain sharedInstance] setIntf: p_intf];
140 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
142 /* Install a jmpbuffer to where we can go back before the NSApp exit
143 * see applicationWillTerminate: */
144 if(setjmp(jmpbuffer) == 0)
151 #pragma mark Variables Callback
153 /*****************************************************************************
154 * MsgCallback: Callback triggered by the core once a new debug message is
155 * ready to be displayed. We store everything in a NSArray in our Cocoa part
156 * of this file, so we are forwarding everything through notifications.
157 *****************************************************************************/
158 static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned int i )
160 int canc = vlc_savecancel();
161 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
163 /* this may happen from time to time, let's bail out as info would be useless anyway */
164 if( !item->psz_module || !item->psz_msg )
167 NSDictionary *o_dict = [NSDictionary dictionaryWithObjectsAndKeys:
168 [NSString stringWithUTF8String: item->psz_module], @"Module",
169 [NSString stringWithUTF8String: item->psz_msg], @"Message",
170 [NSNumber numberWithInt: item->i_type], @"Type", nil];
172 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCCoreMessageReceived"
177 vlc_restorecancel( canc );
180 /*****************************************************************************
181 * playlistChanged: Callback triggered by the intf-change playlist
182 * variable, to let the intf update the playlist.
183 *****************************************************************************/
184 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
185 vlc_value_t old_val, vlc_value_t new_val, void *param )
187 intf_thread_t * p_intf = VLCIntf;
188 if( p_intf && p_intf->p_sys )
190 p_intf->p_sys->b_intf_update = true;
191 p_intf->p_sys->b_playlist_update = true;
192 p_intf->p_sys->b_playmode_update = true;
193 p_intf->p_sys->b_current_title_update = true;
198 /*****************************************************************************
199 * ShowController: Callback triggered by the show-intf playlist variable
200 * through the ShowIntf-control-intf, to let us show the controller-win;
201 * usually when in fullscreen-mode
202 *****************************************************************************/
203 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
204 vlc_value_t old_val, vlc_value_t new_val, void *param )
206 intf_thread_t * p_intf = VLCIntf;
207 if( p_intf && p_intf->p_sys )
208 p_intf->p_sys->b_intf_show = true;
212 /*****************************************************************************
213 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
214 * variable, to let the intf update the controller.
215 *****************************************************************************/
216 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
217 vlc_value_t old_val, vlc_value_t new_val, void *param )
219 intf_thread_t * p_intf = VLCIntf;
220 if( p_intf && p_intf->p_sys )
221 p_intf->p_sys->b_fullscreen_update = true;
225 /*****************************************************************************
226 * DialogCallback: Callback triggered by the "dialog-*" variables
227 * to let the intf display error and interaction dialogs
228 *****************************************************************************/
229 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
231 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
232 VLCMain *interface = (VLCMain *)data;
234 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
236 /* the progress panel needs to update itself and therefore wants special treatment within this context */
237 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
239 p_dialog->pf_update = updateProgressPanel;
240 p_dialog->pf_check = checkProgressPanel;
241 p_dialog->pf_destroy = destroyProgressPanel;
242 p_dialog->p_sys = VLCIntf->p_libvlc;
245 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
246 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewCoreDialogEventNotification" object:[interface coreDialogProvider] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: o_value, @"VLCDialogPointer", [NSString stringWithUTF8String: type], @"VLCDialogType", nil]];
252 void updateProgressPanel (void *priv, const char *text, float value)
254 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
258 o_txt = [NSString stringWithUTF8String: text];
262 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
267 void destroyProgressPanel (void *priv)
269 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
270 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
274 bool checkProgressPanel (void *priv)
276 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
277 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
284 @interface VLCMain ()
285 - (void)_removeOldPreferences;
288 /*****************************************************************************
289 * VLCMain implementation
290 *****************************************************************************/
291 @implementation VLCMain
294 #pragma mark Initialization
296 static VLCMain *_o_sharedMainInstance = nil;
298 + (VLCMain *)sharedInstance
300 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
305 if( _o_sharedMainInstance)
308 return _o_sharedMainInstance;
311 _o_sharedMainInstance = [super init];
315 o_msg_lock = [[NSLock alloc] init];
316 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
317 /* subscribe to LibVLC's debug messages as early as possible (for us) */
318 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
320 o_about = [[VLAboutBox alloc] init];
322 o_open = [[VLCOpen alloc] init];
323 o_wizard = [[VLCWizard alloc] init];
324 o_vlm = [[VLCVLMController alloc] init];
326 o_bookmarks = [[VLCBookmarks alloc] init];
327 o_embedded_list = [[VLCEmbeddedList alloc] init];
328 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
329 o_info = [[VLCInfo alloc] init];
331 i_lastShownVolume = -1;
333 o_remote = [[AppleRemote alloc] init];
334 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
335 [o_remote setDelegate: _o_sharedMainInstance];
337 o_eyetv = [[VLCEyeTVController alloc] init];
339 /* announce our launch to a potential eyetv plugin */
340 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
341 object: @"VLCEyeTVSupport"
343 deliverImmediately: YES];
345 return _o_sharedMainInstance;
348 - (void)setIntf: (intf_thread_t *)p_mainintf {
352 - (intf_thread_t *)intf {
358 unsigned int i_key = 0;
359 playlist_t *p_playlist;
362 if( !p_intf ) return;
364 /* Check if we already did this once. Opening the other nibs calls it too,
365 because VLCMain is the owner */
366 if( nib_main_loaded ) return;
368 /* check whether the user runs a valid version of OS X */
369 if( MACOS_VERSION < 10.5f )
374 if( MACOS_VERSION == 10.4f )
375 o_blabla = _NS("VLC's last release for your OS is the 0.9 series." );
376 else if( MACOS_VERSION == 10.3f )
377 o_blabla = _NS("VLC's last release for your OS is VLC 0.8.6i, which is prone to known security issues." );
378 else // 10.2 and 10.1, still 3% of the OS X market share
379 o_blabla = _NS("VLC's last release for your OS is VLC 0.7.2, which is highly out of date and prone to " \
380 "known security issues. We recommend you to update your Mac to a modern version of Mac OS X.");
381 ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is no longer supported")
382 defaultButton: _NS("Quit")
383 alternateButton: NULL
385 informativeTextWithFormat: _NS("VLC media player %s requires Mac OS X 10.5 or higher.\n\n%@"), VLC_Version(), o_blabla];
386 [ourAlert setAlertStyle: NSCriticalAlertStyle];
387 i_returnValue = [ourAlert runModal];
388 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
394 [o_window setExcludedFromWindowsMenu: YES];
395 [o_msgs_panel setExcludedFromWindowsMenu: YES];
396 [o_msgs_panel setDelegate: self];
398 /* In code and not in Nib for 10.4 compat */
399 NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"mainControllerToolbar"] autorelease];
400 [toolbar setDelegate:self];
401 [toolbar setShowsBaselineSeparator:NO];
402 [toolbar setAllowsUserCustomization:NO];
403 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
404 [toolbar setAutosavesConfiguration:YES];
405 [o_window setToolbar:toolbar];
407 i_key = config_GetInt( p_intf, "key-quit" );
408 [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
409 [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
410 i_key = config_GetInt( p_intf, "key-play-pause" );
411 [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
412 [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
413 i_key = config_GetInt( p_intf, "key-stop" );
414 [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
415 [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
416 i_key = config_GetInt( p_intf, "key-faster" );
417 [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
418 [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
419 i_key = config_GetInt( p_intf, "key-slower" );
420 [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
421 [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
422 i_key = config_GetInt( p_intf, "key-prev" );
423 [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
424 [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
425 i_key = config_GetInt( p_intf, "key-next" );
426 [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
427 [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
428 i_key = config_GetInt( p_intf, "key-jump+short" );
429 [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
430 [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
431 i_key = config_GetInt( p_intf, "key-jump-short" );
432 [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
433 [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
434 i_key = config_GetInt( p_intf, "key-jump+medium" );
435 [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
436 [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
437 i_key = config_GetInt( p_intf, "key-jump-medium" );
438 [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
439 [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
440 i_key = config_GetInt( p_intf, "key-jump+long" );
441 [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
442 [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
443 i_key = config_GetInt( p_intf, "key-jump-long" );
444 [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
445 [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
446 i_key = config_GetInt( p_intf, "key-vol-up" );
447 [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
448 [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
449 i_key = config_GetInt( p_intf, "key-vol-down" );
450 [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
451 [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
452 i_key = config_GetInt( p_intf, "key-vol-mute" );
453 [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
454 [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
455 i_key = config_GetInt( p_intf, "key-fullscreen" );
456 [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
457 [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
458 i_key = config_GetInt( p_intf, "key-snapshot" );
459 [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
460 [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
461 i_key = config_GetInt( p_intf, "key-random" );
462 [o_mi_random setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
463 [o_mi_random setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
464 i_key = config_GetInt( p_intf, "key-zoom-half" );
465 [o_mi_half_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
466 [o_mi_half_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
467 i_key = config_GetInt( p_intf, "key-zoom-original" );
468 [o_mi_normal_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
469 [o_mi_normal_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
470 i_key = config_GetInt( p_intf, "key-zoom-double" );
471 [o_mi_double_window setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
472 [o_mi_double_window setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
474 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
476 [self setSubmenusEnabled: FALSE];
477 [o_volumeslider setEnabled: YES];
478 [self manageVolumeSlider];
479 [o_window setDelegate: self];
481 b_restore_size = false;
483 // Set that here as IB seems to be buggy
484 [o_window setContentMinSize:NSMakeSize(338., 30.)];
486 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
488 b_small_window = YES;
489 [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
490 [o_window frame].origin.y, [o_window frame].size.width,
491 [o_window minSize].height ) display: YES animate:YES];
492 [o_playlist_view setAutoresizesSubviews: NO];
497 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
498 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
499 [o_playlist_view setNeedsDisplay:YES];
500 [o_playlist_view setAutoresizesSubviews: YES];
501 [[o_window contentView] addSubview: o_playlist_view];
504 [self updateTogglePlaylistState];
506 o_size_with_playlist = [o_window contentRectForFrameRect:[o_window frame]].size;
508 p_playlist = pl_Hold( p_intf );
510 var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
513 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
514 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
516 pl_Release( p_intf );
518 /* load our Core Dialogs nib */
519 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
521 /* subscribe to various interactive dialogues */
522 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
523 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
524 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
525 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
526 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
527 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
528 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
529 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
530 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
531 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
532 dialog_Register( p_intf );
534 /* update the playmode stuff */
535 p_intf->p_sys->b_playmode_update = true;
537 [[NSNotificationCenter defaultCenter] addObserver: self
538 selector: @selector(refreshVoutDeviceMenu:)
539 name: NSApplicationDidChangeScreenParametersNotification
542 /* take care of tint changes during runtime */
543 o_img_play = [NSImage imageNamed: @"play"];
544 o_img_pause = [NSImage imageNamed: @"pause"];
545 [self controlTintChanged];
546 [[NSNotificationCenter defaultCenter] addObserver: self
547 selector: @selector( controlTintChanged )
548 name: NSControlTintDidChangeNotification
551 /* yeah, we are done */
552 nib_main_loaded = TRUE;
555 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
557 if( !p_intf ) return;
559 /* FIXME: don't poll */
560 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
561 target: self selector: @selector(manageIntf:)
562 userInfo: nil repeats: FALSE] retain];
564 /* Note: we use the pthread API to support pre-10.5 */
565 pthread_create( &manage_thread, NULL, ManageThread, self );
567 [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
568 var: "intf-add" selector: @selector(toggleVar:)];
570 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
573 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
575 if( !p_intf ) return;
577 [self _removeOldPreferences];
579 /* Handle sleep notification */
580 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
581 name:NSWorkspaceWillSleepNotification object:nil];
583 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
588 if( !p_intf ) return;
590 [o_window setTitle: _NS("VLC media player")];
591 [self setScrollField:_NS("VLC media player") stopAfter:-1];
593 /* button controls */
594 [o_btn_prev setToolTip: _NS("Previous")];
595 [o_btn_rewind setToolTip: _NS("Rewind")];
596 [o_btn_play setToolTip: _NS("Play")];
597 [o_btn_stop setToolTip: _NS("Stop")];
598 [o_btn_ff setToolTip: _NS("Fast Forward")];
599 [o_btn_next setToolTip: _NS("Next")];
600 [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
601 [o_volumeslider setToolTip: _NS("Volume")];
602 [o_timeslider setToolTip: _NS("Position")];
603 [o_btn_playlist setToolTip: _NS("Playlist")];
606 [o_msgs_panel setTitle: _NS("Messages")];
607 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
608 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
611 [o_mi_about setTitle: [_NS("About VLC media player") \
612 stringByAppendingString: @"..."]];
613 [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
614 [o_mi_prefs setTitle: _NS("Preferences...")];
615 [o_mi_add_intf setTitle: _NS("Add Interface")];
616 [o_mu_add_intf setTitle: _NS("Add Interface")];
617 [o_mi_services setTitle: _NS("Services")];
618 [o_mi_hide setTitle: _NS("Hide VLC")];
619 [o_mi_hide_others setTitle: _NS("Hide Others")];
620 [o_mi_show_all setTitle: _NS("Show All")];
621 [o_mi_quit setTitle: _NS("Quit VLC")];
623 [o_mu_file setTitle: _ANS("1:File")];
624 [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
625 [o_mi_open_file setTitle: _NS("Open File...")];
626 [o_mi_open_disc setTitle: _NS("Open Disc...")];
627 [o_mi_open_net setTitle: _NS("Open Network...")];
628 [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
629 [o_mi_open_recent setTitle: _NS("Open Recent")];
630 [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
631 [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
633 [o_mu_edit setTitle: _NS("Edit")];
634 [o_mi_cut setTitle: _NS("Cut")];
635 [o_mi_copy setTitle: _NS("Copy")];
636 [o_mi_paste setTitle: _NS("Paste")];
637 [o_mi_clear setTitle: _NS("Clear")];
638 [o_mi_select_all setTitle: _NS("Select All")];
640 [o_mu_controls setTitle: _NS("Playback")];
641 [o_mi_play setTitle: _NS("Play")];
642 [o_mi_stop setTitle: _NS("Stop")];
643 [o_mi_faster setTitle: _NS("Faster")];
644 [o_mi_slower setTitle: _NS("Slower")];
645 [o_mi_previous setTitle: _NS("Previous")];
646 [o_mi_next setTitle: _NS("Next")];
647 [o_mi_random setTitle: _NS("Random")];
648 [o_mi_repeat setTitle: _NS("Repeat One")];
649 [o_mi_loop setTitle: _NS("Repeat All")];
650 [o_mi_quitAfterPB setTitle: _NS("Quit after Playback")];
651 [o_mi_fwd setTitle: _NS("Step Forward")];
652 [o_mi_bwd setTitle: _NS("Step Backward")];
654 [o_mi_program setTitle: _NS("Program")];
655 [o_mu_program setTitle: _NS("Program")];
656 [o_mi_title setTitle: _NS("Title")];
657 [o_mu_title setTitle: _NS("Title")];
658 [o_mi_chapter setTitle: _NS("Chapter")];
659 [o_mu_chapter setTitle: _NS("Chapter")];
661 [o_mu_audio setTitle: _NS("Audio")];
662 [o_mi_vol_up setTitle: _NS("Increase Volume")];
663 [o_mi_vol_down setTitle: _NS("Decrease Volume")];
664 [o_mi_mute setTitle: _NS("Mute")];
665 [o_mi_audiotrack setTitle: _NS("Audio Track")];
666 [o_mu_audiotrack setTitle: _NS("Audio Track")];
667 [o_mi_channels setTitle: _NS("Audio Channels")];
668 [o_mu_channels setTitle: _NS("Audio Channels")];
669 [o_mi_device setTitle: _NS("Audio Device")];
670 [o_mu_device setTitle: _NS("Audio Device")];
671 [o_mi_visual setTitle: _NS("Visualizations")];
672 [o_mu_visual setTitle: _NS("Visualizations")];
674 [o_mu_video setTitle: _NS("Video")];
675 [o_mi_half_window setTitle: _NS("Half Size")];
676 [o_mi_normal_window setTitle: _NS("Normal Size")];
677 [o_mi_double_window setTitle: _NS("Double Size")];
678 [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
679 [o_mi_fullscreen setTitle: _NS("Fullscreen")];
680 [o_mi_floatontop setTitle: _NS("Float on Top")];
681 [o_mi_snapshot setTitle: _NS("Snapshot")];
682 [o_mi_videotrack setTitle: _NS("Video Track")];
683 [o_mu_videotrack setTitle: _NS("Video Track")];
684 [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
685 [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
686 [o_mi_crop setTitle: _NS("Crop")];
687 [o_mu_crop setTitle: _NS("Crop")];
688 [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
689 [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
690 [o_mi_subtitle setTitle: _NS("Subtitles Track")];
691 [o_mu_subtitle setTitle: _NS("Subtitles Track")];
692 [o_mi_addSub setTitle: _NS("Open File...")];
693 [o_mi_deinterlace setTitle: _NS("Deinterlace")];
694 [o_mu_deinterlace setTitle: _NS("Deinterlace")];
695 [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
696 [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
697 [o_mi_teletext setTitle: _NS("Teletext")];
698 [o_mi_teletext_transparent setTitle: _NS("Transparent")];
699 [o_mi_teletext_index setTitle: _NS("Index")];
700 [o_mi_teletext_red setTitle: _NS("Red")];
701 [o_mi_teletext_green setTitle: _NS("Green")];
702 [o_mi_teletext_yellow setTitle: _NS("Yellow")];
703 [o_mi_teletext_blue setTitle: _NS("Blue")];
705 [o_mu_window setTitle: _NS("Window")];
706 [o_mi_minimize setTitle: _NS("Minimize Window")];
707 [o_mi_close_window setTitle: _NS("Close Window")];
708 [o_mi_player setTitle: _NS("Player...")];
709 [o_mi_controller setTitle: _NS("Controller...")];
710 [o_mi_equalizer setTitle: _NS("Equalizer...")];
711 [o_mi_extended setTitle: _NS("Extended Controls...")];
712 [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
713 [o_mi_playlist setTitle: _NS("Playlist...")];
714 [o_mi_info setTitle: _NS("Media Information...")];
715 [o_mi_messages setTitle: _NS("Messages...")];
716 [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
718 [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
720 [o_mu_help setTitle: _NS("Help")];
721 [o_mi_help setTitle: _NS("VLC media player Help...")];
722 [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
723 [o_mi_license setTitle: _NS("License")];
724 [o_mi_documentation setTitle: _NS("Online Documentation...")];
725 [o_mi_website setTitle: _NS("VideoLAN Website...")];
726 [o_mi_donation setTitle: _NS("Make a donation...")];
727 [o_mi_forum setTitle: _NS("Online Forum...")];
730 [o_dmi_play setTitle: _NS("Play")];
731 [o_dmi_stop setTitle: _NS("Stop")];
732 [o_dmi_next setTitle: _NS("Next")];
733 [o_dmi_previous setTitle: _NS("Previous")];
734 [o_dmi_mute setTitle: _NS("Mute")];
737 [o_vmi_play setTitle: _NS("Play")];
738 [o_vmi_stop setTitle: _NS("Stop")];
739 [o_vmi_prev setTitle: _NS("Previous")];
740 [o_vmi_next setTitle: _NS("Next")];
741 [o_vmi_volup setTitle: _NS("Volume Up")];
742 [o_vmi_voldown setTitle: _NS("Volume Down")];
743 [o_vmi_mute setTitle: _NS("Mute")];
744 [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
745 [o_vmi_snapshot setTitle: _NS("Snapshot")];
747 /* crash reporter panel */
748 [o_crashrep_send_btn setTitle: _NS("Send")];
749 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
750 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
751 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
752 [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, ...")];
753 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
754 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
758 #pragma mark Termination
760 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
762 if( !p_intf ) return;
764 NSArray *menuitems_array = [the_menu itemArray];
765 for( int i=0; i<[menuitems_array count]; i++ )
767 NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
768 if( [one_item hasSubmenu] )
769 [self releaseRepresentedObjects: [one_item submenu]];
771 [one_item setRepresentedObject:NULL];
775 - (void)applicationWillTerminate:(NSNotification *)notification
777 playlist_t * p_playlist;
778 vout_thread_t * p_vout;
779 int returnedValue = 0;
781 if( !p_intf ) return;
783 msg_Dbg( p_intf, "Terminating" );
785 /* Make sure the manage_thread won't call -terminate: again */
786 pthread_cancel( manage_thread );
788 /* Make sure the intf object is getting killed */
789 vlc_object_kill( p_intf );
791 /* Make sure our manage_thread ends */
792 pthread_join( manage_thread, NULL );
794 /* Make sure the interfaceTimer is destroyed */
795 [interfaceTimer invalidate];
796 [interfaceTimer release];
797 interfaceTimer = nil;
799 /* make sure that the current volume is saved */
800 config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
802 /* save the prefs if they were changed in the extended panel */
803 if(o_extended && [o_extended configChanged])
805 [o_extended savePrefs];
808 /* unsubscribe from the interactive dialogues */
809 dialog_Unregister( p_intf );
810 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
811 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
812 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
813 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
814 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
816 /* remove global observer watching for vout device changes correctly */
817 [[NSNotificationCenter defaultCenter] removeObserver: self];
819 /* release some other objects here, because it isn't sure whether dealloc
820 * will be called later on */
821 if( nib_about_loaded )
824 if( nib_prefs_loaded )
830 if( nib_open_loaded )
833 if( nib_extended_loaded )
835 [o_extended release];
838 if( nib_bookmarks_loaded )
839 [o_bookmarks release];
847 if( nib_wizard_loaded )
850 [crashLogURLConnection cancel];
851 [crashLogURLConnection release];
853 [o_embedded_list release];
854 [o_coredialogs release];
857 [o_img_pause_pressed release];
858 [o_img_play_pressed release];
859 [o_img_pause release];
860 [o_img_play release];
862 /* unsubscribe from libvlc's debug messages */
863 msg_Unsubscribe( p_intf->p_sys->p_sub );
865 [o_msg_arr removeAllObjects];
868 [o_msg_lock release];
870 /* write cached user defaults to disk */
871 [[NSUserDefaults standardUserDefaults] synchronize];
873 /* Make sure the Menu doesn't have any references to vlc objects anymore */
874 [self releaseRepresentedObjects:[NSApp mainMenu]];
876 /* Kill the playlist, so that it doesn't accept new request
877 * such as the play request from vlc.c (we are a blocking interface). */
878 p_playlist = pl_Hold( p_intf );
879 vlc_object_kill( p_playlist );
880 pl_Release( p_intf );
882 libvlc_Quit( p_intf->p_libvlc );
886 /* Go back to Run() and make libvlc exit properly */
888 longjmp( jmpbuffer, 1 );
893 #pragma mark Sparkle delegate
894 /* received directly before the update gets installed, so let's shut down a bit */
895 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
897 [o_remote stopListening: self];
898 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
900 /* Close the window directly, because we do know that there
901 * won't be anymore video. It's currently waiting a bit. */
902 [[[o_controls voutView] window] orderOut:self];
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 playlist_t * p_playlist = pl_Hold( p_intf );
1614 aout_VolumeGet( p_playlist, &i_volume );
1615 pl_Release( p_intf );
1617 if( i_volume != i_lastShownVolume )
1619 i_lastShownVolume = i_volume;
1620 p_intf->p_sys->b_volume_update = TRUE;
1624 - (void)manageIntf:(NSTimer *)o_timer
1627 playlist_t * p_playlist;
1628 input_thread_t * p_input;
1630 if( p_intf->p_sys->b_input_update )
1632 /* Called when new input is opened */
1633 p_intf->p_sys->b_current_title_update = true;
1634 p_intf->p_sys->b_intf_update = true;
1635 p_intf->p_sys->b_input_update = false;
1636 [self setupMenus]; /* Make sure input menu is up to date */
1638 /* update our info-panel to reflect the new item, if we don't show
1639 * the playlist or the selection is empty */
1640 if( [self isPlaylistCollapsed] == YES )
1642 playlist_t * p_playlist = pl_Hold( p_intf );
1644 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1647 [[self info] updatePanelWithItem: p_item->p_input];
1648 pl_Release( p_intf );
1651 if( p_intf->p_sys->b_intf_update )
1653 bool b_input = false;
1654 bool b_plmul = false;
1655 bool b_control = false;
1656 bool b_seekable = false;
1657 bool b_chapters = false;
1659 playlist_t * p_playlist = pl_Hold( p_intf );
1662 b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1665 p_input = playlist_CurrentInput( p_playlist );
1667 bool b_buffering = NO;
1669 if( ( b_input = ( p_input != NULL ) ) )
1671 /* seekable streams */
1672 cachedInputState = input_GetState( p_input );
1673 if ( cachedInputState == INIT_S ||
1674 cachedInputState == OPENING_S )
1679 /* seekable streams */
1680 b_seekable = var_GetBool( p_input, "can-seek" );
1682 /* check whether slow/fast motion is possible */
1683 b_control = var_GetBool( p_input, "can-rate" );
1685 /* chapters & titles */
1686 //b_chapters = p_input->stream.i_area_nb > 1;
1687 vlc_object_release( p_input );
1689 pl_Release( p_intf );
1693 [o_main_pgbar startAnimation:self];
1694 [o_main_pgbar setIndeterminate:YES];
1695 [o_main_pgbar setHidden:NO];
1699 [o_main_pgbar stopAnimation:self];
1700 [o_main_pgbar setHidden:YES];
1703 [o_btn_stop setEnabled: b_input];
1704 [o_embedded_window setStop: b_input];
1705 [o_btn_ff setEnabled: b_seekable];
1706 [o_btn_rewind setEnabled: b_seekable];
1707 [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1708 [o_embedded_window setPrev: (b_plmul || b_chapters)];
1709 [o_btn_next setEnabled: (b_plmul || b_chapters)];
1710 [o_embedded_window setNext: (b_plmul || b_chapters)];
1712 [o_timeslider setFloatValue: 0.0];
1713 [o_timeslider setEnabled: b_seekable];
1714 [o_timefield setStringValue: @"00:00"];
1715 [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1716 [[[self controls] fspanel] setSeekable: b_seekable];
1718 [o_embedded_window setSeekable: b_seekable];
1719 [o_embedded_window setTime:@"00:00" position:0.0];
1721 p_intf->p_sys->b_current_title_update = true;
1723 p_intf->p_sys->b_intf_update = false;
1726 if( p_intf->p_sys->b_playmode_update )
1728 [o_playlist playModeUpdated];
1729 p_intf->p_sys->b_playmode_update = false;
1731 if( p_intf->p_sys->b_playlist_update )
1733 [o_playlist playlistUpdated];
1734 p_intf->p_sys->b_playlist_update = false;
1737 if( p_intf->p_sys->b_fullscreen_update )
1739 p_intf->p_sys->b_fullscreen_update = false;
1742 if( p_intf->p_sys->b_intf_show )
1744 if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1745 [[o_controls fspanel] fadeIn];
1747 [o_window makeKeyAndOrderFront: self];
1749 p_intf->p_sys->b_intf_show = false;
1752 p_input = pl_CurrentInput( p_intf );
1753 if( p_input && vlc_object_alive (p_input) )
1757 if( p_intf->p_sys->b_current_title_update )
1760 input_item_t * p_item = input_GetItem( p_input );
1761 char * name = input_item_GetNowPlaying( p_item );
1764 name = input_item_GetName( p_item );
1766 aString = [NSString stringWithUTF8String:name];
1770 [self setScrollField: aString stopAfter:-1];
1771 [[[self controls] fspanel] setStreamTitle: aString];
1773 [[o_controls voutView] updateTitle];
1775 [o_playlist updateRowSelection];
1777 p_intf->p_sys->b_current_title_update = FALSE;
1780 if( [o_timeslider isEnabled] )
1782 /* Update the slider */
1786 char psz_time[MSTRTIME_MAX_SIZE];
1789 var_Get( p_input, "position", &pos );
1790 f_updated = 10000. * pos.f_float;
1791 [o_timeslider setFloatValue: f_updated];
1793 var_Get( p_input, "time", &time );
1795 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1796 if( b_time_remaining && dur != -1 )
1798 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1801 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1803 [o_timefield setStringValue: o_time];
1804 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1805 [o_embedded_window setTime: o_time position: f_updated];
1808 /* Manage Playing status */
1809 var_Get( p_input, "state", &val );
1810 if( p_intf->p_sys->i_play_status != val.i_int )
1812 p_intf->p_sys->i_play_status = val.i_int;
1813 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1814 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1816 vlc_object_release( p_input );
1820 vlc_object_release( p_input );
1824 p_intf->p_sys->i_play_status = END_S;
1825 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1826 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1827 [self setSubmenusEnabled: FALSE];
1830 if( p_intf->p_sys->b_volume_update )
1833 int i_volume_step = 0;
1834 o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1835 if( i_lastShownVolume != -1 )
1836 [self setScrollField:o_text stopAfter:1000000];
1837 i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1838 [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1839 [o_volumeslider setEnabled: TRUE];
1840 [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1841 [o_embedded_window setVolumeEnabled: TRUE];
1842 [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1843 p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1844 p_intf->p_sys->b_volume_update = FALSE;
1848 [self updateMessageDisplay];
1850 if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1851 [self resetScrollField];
1853 [interfaceTimer autorelease];
1855 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1856 target: self selector: @selector(manageIntf:)
1857 userInfo: nil repeats: FALSE] retain];
1861 #pragma mark Interface update
1865 playlist_t * p_playlist = pl_Hold( p_intf );
1866 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1867 if( p_input != NULL )
1869 [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1870 var: "program" selector: @selector(toggleVar:)];
1872 [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1873 var: "title" selector: @selector(toggleVar:)];
1875 [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1876 var: "chapter" selector: @selector(toggleVar:)];
1878 [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1879 var: "audio-es" selector: @selector(toggleVar:)];
1881 [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1882 var: "video-es" selector: @selector(toggleVar:)];
1884 [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1885 var: "spu-es" selector: @selector(toggleVar:)];
1887 /* special case for "Open File" inside the subtitles menu item */
1888 if( [o_mi_videotrack isEnabled] == YES )
1889 [o_mi_subtitle setEnabled: YES];
1891 aout_instance_t * p_aout = input_GetAout( p_input );
1892 if( p_aout != NULL )
1894 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1895 var: "audio-channels" selector: @selector(toggleVar:)];
1897 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1898 var: "audio-device" selector: @selector(toggleVar:)];
1900 [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1901 var: "visual" selector: @selector(toggleVar:)];
1902 vlc_object_release( (vlc_object_t *)p_aout );
1905 vout_thread_t * p_vout = input_GetVout( p_input );
1907 if( p_vout != NULL )
1909 vlc_object_t * p_dec_obj;
1911 [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1912 var: "aspect-ratio" selector: @selector(toggleVar:)];
1914 [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1915 var: "crop" selector: @selector(toggleVar:)];
1917 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1918 var: "video-device" selector: @selector(toggleVar:)];
1920 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1921 var: "deinterlace" selector: @selector(toggleVar:)];
1924 [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1925 (vlc_object_t *)p_vout var:"postprocess" selector:
1926 @selector(toggleVar:)];
1929 vlc_object_release( (vlc_object_t *)p_vout );
1931 vlc_object_release( p_input );
1933 pl_Release( p_intf );
1936 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1939 vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1945 /* clean the menu before adding new entries */
1946 if( [o_mi_screen hasSubmenu] )
1948 y = [[o_mi_screen submenu] numberOfItems] - 1;
1949 msg_Dbg( VLCIntf, "%i items in submenu", y );
1952 msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1953 [[o_mi_screen submenu] removeItemAtIndex: x];
1958 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1959 var: "video-device" selector: @selector(toggleVar:)];
1960 vlc_object_release( (vlc_object_t *)p_vout );
1963 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1966 i_end_scroll = mdate() + timeout;
1969 [o_scrollfield setStringValue: o_string];
1970 [o_embedded_window setScrollString: o_string];
1973 - (void)resetScrollField
1975 playlist_t * p_playlist = pl_Hold( p_intf );
1976 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1979 if( p_input && vlc_object_alive (p_input) )
1983 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1984 if( input_item_GetNowPlaying( p_item->p_input ) )
1985 o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
1987 o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
1989 [self setScrollField: o_temp stopAfter:-1];
1990 [[[self controls] fspanel] setStreamTitle: o_temp];
1991 vlc_object_release( p_input );
1992 pl_Release( p_intf );
1995 pl_Release( p_intf );
1996 [self setScrollField: _NS("VLC media player") stopAfter:-1];
1999 - (void)playStatusUpdated:(int)i_status
2001 if( i_status == PLAYING_S )
2003 [[[self controls] fspanel] setPause];
2004 [o_btn_play setImage: o_img_pause];
2005 [o_btn_play setAlternateImage: o_img_pause_pressed];
2006 [o_btn_play setToolTip: _NS("Pause")];
2007 [o_mi_play setTitle: _NS("Pause")];
2008 [o_dmi_play setTitle: _NS("Pause")];
2009 [o_vmi_play setTitle: _NS("Pause")];
2013 [[[self controls] fspanel] setPlay];
2014 [o_btn_play setImage: o_img_play];
2015 [o_btn_play setAlternateImage: o_img_play_pressed];
2016 [o_btn_play setToolTip: _NS("Play")];
2017 [o_mi_play setTitle: _NS("Play")];
2018 [o_dmi_play setTitle: _NS("Play")];
2019 [o_vmi_play setTitle: _NS("Play")];
2023 - (void)setSubmenusEnabled:(BOOL)b_enabled
2025 [o_mi_program setEnabled: b_enabled];
2026 [o_mi_title setEnabled: b_enabled];
2027 [o_mi_chapter setEnabled: b_enabled];
2028 [o_mi_audiotrack setEnabled: b_enabled];
2029 [o_mi_visual setEnabled: b_enabled];
2030 [o_mi_videotrack setEnabled: b_enabled];
2031 [o_mi_subtitle setEnabled: b_enabled];
2032 [o_mi_channels setEnabled: b_enabled];
2033 [o_mi_deinterlace setEnabled: b_enabled];
2034 [o_mi_ffmpeg_pp setEnabled: b_enabled];
2035 [o_mi_device setEnabled: b_enabled];
2036 [o_mi_screen setEnabled: b_enabled];
2037 [o_mi_aspect_ratio setEnabled: b_enabled];
2038 [o_mi_crop setEnabled: b_enabled];
2039 [o_mi_teletext setEnabled: b_enabled];
2042 - (IBAction)timesliderUpdate:(id)sender
2045 playlist_t * p_playlist;
2046 input_thread_t * p_input;
2048 switch( [[NSApp currentEvent] type] )
2051 case NSLeftMouseDown:
2052 case NSLeftMouseDragged:
2053 f_updated = [sender floatValue];
2059 p_playlist = pl_Hold( p_intf );
2060 p_input = playlist_CurrentInput( p_playlist );
2061 if( p_input != NULL )
2066 char psz_time[MSTRTIME_MAX_SIZE];
2068 pos.f_float = f_updated / 10000.;
2069 var_Set( p_input, "position", pos );
2070 [o_timeslider setFloatValue: f_updated];
2072 var_Get( p_input, "time", &time );
2074 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
2075 if( b_time_remaining && dur != -1 )
2077 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
2080 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2082 [o_timefield setStringValue: o_time];
2083 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
2084 [o_embedded_window setTime: o_time position: f_updated];
2085 vlc_object_release( p_input );
2087 pl_Release( p_intf );
2090 - (IBAction)timeFieldWasClicked:(id)sender
2092 b_time_remaining = !b_time_remaining;
2097 #pragma mark Recent Items
2099 - (IBAction)clearRecentItems:(id)sender
2101 [[NSDocumentController sharedDocumentController]
2102 clearRecentDocuments: nil];
2105 - (void)openRecentItem:(id)sender
2107 [self application: nil openFile: [sender title]];
2113 - (IBAction)intfOpenFile:(id)sender
2115 if( !nib_open_loaded )
2117 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2118 [o_open awakeFromNib];
2125 - (IBAction)intfOpenFileGeneric:(id)sender
2127 if( !nib_open_loaded )
2129 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2130 [o_open awakeFromNib];
2131 [o_open openFileGeneric];
2133 [o_open openFileGeneric];
2137 - (IBAction)intfOpenDisc:(id)sender
2139 if( !nib_open_loaded )
2141 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2142 [o_open awakeFromNib];
2149 - (IBAction)intfOpenNet:(id)sender
2151 if( !nib_open_loaded )
2153 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2154 [o_open awakeFromNib];
2161 - (IBAction)intfOpenCapture:(id)sender
2163 if( !nib_open_loaded )
2165 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2166 [o_open awakeFromNib];
2167 [o_open openCapture];
2169 [o_open openCapture];
2173 - (IBAction)showWizard:(id)sender
2175 if( !nib_wizard_loaded )
2177 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2178 [o_wizard initStrings];
2179 [o_wizard resetWizard];
2180 [o_wizard showWizard];
2182 [o_wizard resetWizard];
2183 [o_wizard showWizard];
2187 - (IBAction)showVLM:(id)sender
2189 if( !nib_vlm_loaded )
2190 nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner: NSApp];
2192 [o_vlm showVLMWindow];
2195 - (IBAction)showExtended:(id)sender
2197 if( o_extended == nil )
2198 o_extended = [[VLCExtended alloc] init];
2200 if( !nib_extended_loaded )
2201 nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2203 [o_extended showPanel];
2206 - (IBAction)showBookmarks:(id)sender
2208 /* we need the wizard-nib for the bookmarks's extract functionality */
2209 if( !nib_wizard_loaded )
2211 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2212 [o_wizard initStrings];
2215 if( !nib_bookmarks_loaded )
2216 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2218 [o_bookmarks showBookmarks];
2221 - (IBAction)viewPreferences:(id)sender
2223 if( !nib_prefs_loaded )
2225 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2226 o_sprefs = [[VLCSimplePrefs alloc] init];
2227 o_prefs= [[VLCPrefs alloc] init];
2230 [o_sprefs showSimplePrefs];
2234 #pragma mark Help and Docs
2236 - (IBAction)viewAbout:(id)sender
2238 if( !nib_about_loaded )
2239 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2241 [o_about showAbout];
2244 - (IBAction)showLicense:(id)sender
2246 if( !nib_about_loaded )
2247 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2249 [o_about showGPL: sender];
2252 - (IBAction)viewHelp:(id)sender
2254 if( !nib_about_loaded )
2256 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2263 - (IBAction)openReadMe:(id)sender
2265 NSString * o_path = [[NSBundle mainBundle]
2266 pathForResource: @"README.MacOSX" ofType: @"rtf"];
2268 [[NSWorkspace sharedWorkspace] openFile: o_path
2269 withApplication: @"TextEdit"];
2272 - (IBAction)openDocumentation:(id)sender
2274 NSURL * o_url = [NSURL URLWithString:
2275 @"http://www.videolan.org/doc/"];
2277 [[NSWorkspace sharedWorkspace] openURL: o_url];
2280 - (IBAction)openWebsite:(id)sender
2282 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2284 [[NSWorkspace sharedWorkspace] openURL: o_url];
2287 - (IBAction)openForum:(id)sender
2289 NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2291 [[NSWorkspace sharedWorkspace] openURL: o_url];
2294 - (IBAction)openDonate:(id)sender
2296 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2298 [[NSWorkspace sharedWorkspace] openURL: o_url];
2302 #pragma mark Crash Log
2303 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2305 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2306 NSURL *url = [NSURL URLWithString:urlStr];
2308 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2309 [req setHTTPMethod:@"POST"];
2312 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2314 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2315 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2316 email = [emails valueAtIndex:[emails indexForIdentifier:
2317 [emails primaryIdentifier]]];
2320 email = [NSString string];
2323 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2324 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2325 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2326 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2328 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2330 /* Released from delegate */
2331 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2334 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2336 NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2337 _NS("Thanks for your report!"),
2338 _NS("OK"), nil, nil, nil);
2339 [crashLogURLConnection release];
2340 crashLogURLConnection = nil;
2343 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2345 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2346 [crashLogURLConnection release];
2347 crashLogURLConnection = nil;
2350 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2352 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2353 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2355 NSString * latestLog = nil;
2356 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2357 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2358 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
2359 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2361 while (fname = [direnum nextObject])
2363 [direnum skipDescendents];
2364 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2366 NSArray * compo = [fname componentsSeparatedByString:@"_"];
2367 if( [compo count] < 3 ) continue;
2368 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2369 if( [compo count] < 4 ) continue;
2372 if( year < [[compo objectAtIndex:0] intValue] ||
2373 (year ==[[compo objectAtIndex:0] intValue] &&
2374 (month < [[compo objectAtIndex:1] intValue] ||
2375 (month ==[[compo objectAtIndex:1] intValue] &&
2376 (day < [[compo objectAtIndex:2] intValue] ||
2377 (day ==[[compo objectAtIndex:2] intValue] &&
2378 hours < [[compo objectAtIndex:3] intValue] ))))))
2380 year = [[compo objectAtIndex:0] intValue];
2381 month = [[compo objectAtIndex:1] intValue];
2382 day = [[compo objectAtIndex:2] intValue];
2383 hours = [[compo objectAtIndex:3] intValue];
2384 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2389 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2392 if( !previouslySeen )
2394 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
2395 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2396 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
2397 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2402 - (NSString *)latestCrashLogPath
2404 return [self latestCrashLogPathPreviouslySeen:YES];
2407 - (void)lookForCrashLog
2409 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2410 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2411 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2412 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2413 if( latestLog && !areCrashLogsTooOld )
2414 [NSApp runModalForWindow: o_crashrep_win];
2418 - (IBAction)crashReporterAction:(id)sender
2420 if( sender == o_crashrep_send_btn )
2421 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2424 [o_crashrep_win orderOut: sender];
2427 - (IBAction)openCrashLog:(id)sender
2429 NSString * latestLog = [self latestCrashLogPath];
2432 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2436 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.") );
2441 #pragma mark Remove old prefs
2443 - (void)_removeOldPreferences
2445 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2446 static const int kCurrentPreferencesVersion = 1;
2447 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2448 if( version >= kCurrentPreferencesVersion ) return;
2450 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
2451 NSUserDomainMask, YES);
2452 if( !libraries || [libraries count] == 0) return;
2453 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2455 /* File not found, don't attempt anything */
2456 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2457 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2459 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2463 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2464 _NS("We just found an older version of VLC's preferences files."),
2465 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2466 if( res != NSOKButton )
2468 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2472 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2474 /* Move the file to trash so that user can find them later */
2475 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2477 /* really reset the defaults from now on */
2478 [NSUserDefaults resetStandardUserDefaults];
2480 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2481 [[NSUserDefaults standardUserDefaults] synchronize];
2484 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2486 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2492 execl(path, path, NULL);
2496 #pragma mark Errors, warnings and messages
2498 - (IBAction)viewErrorsAndWarnings:(id)sender
2500 [[[self coreDialogProvider] errorPanel] showPanel];
2503 - (IBAction)showMessagesPanel:(id)sender
2505 [o_msgs_panel makeKeyAndOrderFront: sender];
2508 - (IBAction)showInformationPanel:(id)sender
2510 if(! nib_info_loaded )
2511 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2516 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2518 if( [o_notification object] == o_msgs_panel )
2519 [self updateMessageDisplay];
2522 - (void)updateMessageDisplay
2524 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2527 NSEnumerator * o_enum;
2529 [o_messages setString: @""];
2533 o_enum = [o_msg_arr objectEnumerator];
2535 while( ( o_msg = [o_enum nextObject] ) != nil )
2537 [o_messages insertText: o_msg];
2540 b_msg_arr_changed = NO;
2541 [o_msg_lock unlock];
2545 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2547 NSColor *o_white = [NSColor whiteColor];
2548 NSColor *o_red = [NSColor redColor];
2549 NSColor *o_yellow = [NSColor yellowColor];
2550 NSColor *o_gray = [NSColor grayColor];
2552 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2553 static const char * ppsz_type[4] = { ": ", " error: ",
2554 " warning: ", " debug: " };
2557 NSDictionary *o_attr;
2558 NSAttributedString *o_msg_color;
2560 int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2564 if( [o_msg_arr count] + 2 > 600 )
2566 [o_msg_arr removeObjectAtIndex: 0];
2567 [o_msg_arr removeObjectAtIndex: 1];
2570 o_attr = [NSDictionary dictionaryWithObject: o_gray
2571 forKey: NSForegroundColorAttributeName];
2572 o_msg = [NSString stringWithFormat: @"%@%s",
2573 [[o_notification userInfo] objectForKey: @"Module"],
2575 o_msg_color = [[NSAttributedString alloc]
2576 initWithString: o_msg attributes: o_attr];
2577 [o_msg_arr addObject: [o_msg_color autorelease]];
2579 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2580 forKey: NSForegroundColorAttributeName];
2581 o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2582 o_msg_color = [[NSAttributedString alloc]
2583 initWithString: o_msg attributes: o_attr];
2584 [o_msg_arr addObject: [o_msg_color autorelease]];
2586 b_msg_arr_changed = YES;
2587 [o_msg_lock unlock];
2590 - (IBAction)saveDebugLog:(id)sender
2592 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2594 [saveFolderPanel setCanChooseDirectories: NO];
2595 [saveFolderPanel setCanChooseFiles: YES];
2596 [saveFolderPanel setCanSelectHiddenExtension: NO];
2597 [saveFolderPanel setCanCreateDirectories: YES];
2598 [saveFolderPanel setRequiredFileType: @"rtfd"];
2599 [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];
2602 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2605 if( returnCode == NSOKButton )
2607 b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2609 msg_Warn( p_intf, "Error while saving the debug log" );
2614 #pragma mark Playlist toggling
2616 - (IBAction)togglePlaylist:(id)sender
2618 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2619 NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2620 /*First, check if the playlist is visible*/
2621 if( contentRect.size.height <= 169. )
2623 o_restore_rect = contentRect;
2624 b_restore_size = true;
2625 b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2628 if( o_size_with_playlist.height > 169. )
2629 o_rect.size.height = o_size_with_playlist.height;
2631 o_rect.size.height = 500.;
2633 if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2634 o_rect.size.width = o_size_with_playlist.width;
2636 o_rect.size.width = [o_window contentMinSize].width;
2638 o_rect.origin.x = contentRect.origin.x;
2639 o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2640 [o_window contentMinSize].height;
2642 o_rect = [o_window frameRectForContentRect:o_rect];
2644 NSRect screenRect = [[o_window screen] visibleFrame];
2645 if( !NSContainsRect( screenRect, o_rect ) ) {
2646 if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2647 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2648 if( NSMinY(o_rect) < NSMinY(screenRect) )
2649 o_rect.origin.y = ( NSMinY(screenRect) );
2652 [o_btn_playlist setState: YES];
2656 NSSize curSize = o_rect.size;
2657 if( b_restore_size )
2659 o_rect = o_restore_rect;
2660 if( o_rect.size.height < [o_window contentMinSize].height )
2661 o_rect.size.height = [o_window contentMinSize].height;
2662 if( o_rect.size.width < [o_window contentMinSize].width )
2663 o_rect.size.width = [o_window contentMinSize].width;
2667 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2669 o_rect.size.height = [o_window contentMinSize].height;
2670 o_rect.size.width = [o_window contentMinSize].width;
2671 o_rect.origin.x = contentRect.origin.x;
2672 /* Calculate the position of the lower right corner after resize */
2673 o_rect.origin.y = contentRect.origin.y +
2674 contentRect.size.height - [o_window contentMinSize].height;
2677 [o_playlist_view setAutoresizesSubviews: NO];
2678 [o_playlist_view removeFromSuperview];
2679 [o_btn_playlist setState: NO];
2680 b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2681 o_rect = [o_window frameRectForContentRect:o_rect];
2684 [o_window setFrame: o_rect display:YES animate: YES];
2687 - (void)updateTogglePlaylistState
2689 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2690 [o_btn_playlist setState: NO];
2692 [o_btn_playlist setState: YES];
2694 [[self playlist] outlineViewSelectionDidChange: NULL];
2697 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2700 /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2702 /*Stores the size the controller one resize, to be able to restore it when
2703 toggling the playlist*/
2704 o_size_with_playlist = proposedFrameSize;
2707 rect.size = proposedFrameSize;
2708 if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2710 if( b_small_window == NO )
2712 /* if large and going to small then hide */
2713 b_small_window = YES;
2714 [o_playlist_view setAutoresizesSubviews: NO];
2715 [o_playlist_view removeFromSuperview];
2717 return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2719 return proposedFrameSize;
2722 - (void)windowDidMove:(NSNotification *)notif
2724 b_restore_size = false;
2727 - (void)windowDidResize:(NSNotification *)notif
2729 if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2731 /* If large and coming from small then show */
2732 [o_playlist_view setAutoresizesSubviews: YES];
2733 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2734 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2735 [o_playlist_view setNeedsDisplay:YES];
2736 [[o_window contentView] addSubview: o_playlist_view];
2737 b_small_window = NO;
2739 [self updateTogglePlaylistState];
2746 @implementation VLCMain (NSMenuValidation)
2748 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2750 NSString *o_title = [o_mi title];
2751 BOOL bEnabled = TRUE;
2753 /* Recent Items Menu */
2754 if( [o_title isEqualToString: _NS("Clear Menu")] )
2756 NSMenu * o_menu = [o_mi_open_recent submenu];
2757 int i_nb_items = [o_menu numberOfItems];
2758 NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2759 recentDocumentURLs];
2760 UInt32 i_nb_docs = [o_docs count];
2762 if( i_nb_items > 1 )
2764 while( --i_nb_items )
2766 [o_menu removeItemAtIndex: 0];
2775 [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2781 o_url = [o_docs objectAtIndex: i_nb_docs];
2783 if( [o_url isFileURL] )
2785 o_doc = [o_url path];
2789 o_doc = [o_url absoluteString];
2792 [o_menu insertItemWithTitle: o_doc
2793 action: @selector(openRecentItem:)
2794 keyEquivalent: @"" atIndex: 0];
2796 if( i_nb_docs == 0 )
2812 @implementation VLCMain (Internal)
2814 - (void)handlePortMessage:(NSPortMessage *)o_msg
2819 NSInvocation * o_inv;
2820 NSConditionLock * o_lock;
2822 o_data = [[o_msg components] lastObject];
2823 o_inv = *((NSInvocation **)[o_data bytes]);
2824 [o_inv getArgument: &o_value atIndex: 2];
2825 val = (id **)[o_value pointerValue];
2826 [o_inv setArgument: val[1] atIndex: 2];
2831 [o_lock unlockWithCondition: 1];
2836 /*****************************************************************************
2837 * VLCApplication interface
2838 * exclusively used to implement media key support on Al Apple keyboards
2839 * b_justJumped is required as the keyboard send its events faster than
2840 * the user can actually jump through his media
2841 *****************************************************************************/
2843 @implementation VLCApplication
2845 - (void)awakeFromNib
2847 b_active = b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2848 b_activeInBackground = config_GetInt( VLCIntf, "macosx-mediakeys-background" );
2849 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
2850 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appGotActiveOrInactive:) name: @"NSApplicationDidBecomeActiveNotification" object: nil];
2851 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appGotActiveOrInactive:) name: @"NSApplicationWillResignActiveNotification" object: nil];
2856 [[NSNotificationCenter defaultCenter] removeObserver: self];
2860 - (void)appGotActiveOrInactive: (NSNotification *)o_notification
2862 if(( [[o_notification name] isEqualToString: @"NSApplicationWillResignActiveNotification"] && !b_activeInBackground ) || !b_mediaKeySupport)
2868 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2870 b_active = b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2871 b_activeInBackground = config_GetInt( VLCIntf, "macosx-mediakeys-background" );
2875 - (void)sendEvent: (NSEvent*)event
2879 if( [event type] == NSSystemDefined && [event subtype] == 8 )
2881 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
2882 int keyFlags = ([event data1] & 0x0000FFFF);
2883 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
2884 int keyRepeat = (keyFlags & 0x1);
2886 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
2887 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
2889 if( keyCode == NX_KEYTYPE_FAST && !b_justJumped )
2891 if( keyState == 0 && keyRepeat == 0 )
2893 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_NEXT );
2895 else if( keyRepeat == 1 )
2897 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
2899 [self performSelector:@selector(resetJump)
2905 if( keyCode == NX_KEYTYPE_REWIND && !b_justJumped )
2907 if( keyState == 0 && keyRepeat == 0 )
2909 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_PREV );
2911 else if( keyRepeat == 1 )
2913 var_SetInteger( VLCIntf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
2915 [self performSelector:@selector(resetJump)
2922 [super sendEvent: event];