1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2009 the VideoLAN team
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
30 #include <stdlib.h> /* malloc(), free() */
31 #include <sys/param.h> /* for MAXPATHLEN */
33 #include <vlc_common.h>
35 #include <vlc_dialog.h>
36 #include <unistd.h> /* execl() */
37 #import <vlc_dialog.h>
44 #import "playlistinfo.h"
51 #import "interaction.h"
52 #import "embeddedwindow.h"
54 #import "AppleRemote.h"
56 #import "simple_prefs.h"
59 #import <AddressBook/AddressBook.h>
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 );
72 #pragma mark VLC Interface Object Callbacks
74 /*****************************************************************************
75 * OpenIntf: initialize interface
76 *****************************************************************************/
77 int OpenIntf ( vlc_object_t *p_this )
79 intf_thread_t *p_intf = (intf_thread_t*) p_this;
81 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
82 if( p_intf->p_sys == NULL )
85 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
87 p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
89 /* subscribe to LibVLCCore's messages */
90 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
92 p_intf->b_should_run_on_first_thread = true;
97 /*****************************************************************************
98 * CloseIntf: destroy interface
99 *****************************************************************************/
100 void CloseIntf ( vlc_object_t *p_this )
102 intf_thread_t *p_intf = (intf_thread_t*) p_this;
104 [p_intf->p_sys->o_pool release];
106 free( p_intf->p_sys );
109 /*****************************************************************************
111 *****************************************************************************/
114 static void Run( intf_thread_t *p_intf )
118 /* Do it again - for some unknown reason, vlc_thread_create() often
119 * fails to go to real-time priority with the first launched thread
121 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
123 /* Make sure the "force quit" menu item does quit instantly.
124 * VLC overrides SIGTERM which is sent by the "force quit"
125 * menu item to make sure deamon mode quits gracefully, so
126 * we un-override SIGTERM here. */
128 sigaddset( &set, SIGTERM );
129 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
131 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
133 /* Install a jmpbuffer to where we can go back before the NSApp exit
134 * see applicationWillTerminate: */
135 [NSApplication sharedApplication];
137 [[VLCMain sharedInstance] setIntf: p_intf];
138 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
140 /* Install a jmpbuffer to where we can go back before the NSApp exit
141 * see applicationWillTerminate: */
142 if(setjmp(jmpbuffer) == 0)
149 #pragma mark Variables Callback
151 /*****************************************************************************
152 * MsgCallback: Callback triggered by the core once a new debug message is
153 * ready to be displayed. We store everything in a NSArray in our Cocoa part
154 * of this file, so we are forwarding everything through notifications.
155 *****************************************************************************/
156 static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned int i )
158 int canc = vlc_savecancel();
159 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
161 NSDictionary *o_dict = [NSDictionary dictionaryWithObjects:
162 [NSArray arrayWithObjects:
163 [NSString stringWithUTF8String: item->psz_module],
164 [NSString stringWithUTF8String: item->psz_msg],
165 [NSNumber numberWithInt: item->i_type], nil]
167 [NSArray arrayWithObjects: @"Module", @"Message", @"Type", nil]];
169 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCCoreMessageReceived"
174 vlc_restorecancel( canc );
178 /*****************************************************************************
179 * playlistChanged: Callback triggered by the intf-change playlist
180 * variable, to let the intf update the playlist.
181 *****************************************************************************/
182 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
183 vlc_value_t old_val, vlc_value_t new_val, void *param )
185 intf_thread_t * p_intf = VLCIntf;
186 if( p_intf && p_intf->p_sys )
188 p_intf->p_sys->b_intf_update = true;
189 p_intf->p_sys->b_playlist_update = true;
190 p_intf->p_sys->b_playmode_update = true;
191 p_intf->p_sys->b_current_title_update = true;
196 /*****************************************************************************
197 * ShowController: Callback triggered by the show-intf playlist variable
198 * through the ShowIntf-control-intf, to let us show the controller-win;
199 * usually when in fullscreen-mode
200 *****************************************************************************/
201 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
202 vlc_value_t old_val, vlc_value_t new_val, void *param )
204 intf_thread_t * p_intf = VLCIntf;
205 if( p_intf && p_intf->p_sys )
206 p_intf->p_sys->b_intf_show = true;
210 /*****************************************************************************
211 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
212 * variable, to let the intf update the controller.
213 *****************************************************************************/
214 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
215 vlc_value_t old_val, vlc_value_t new_val, void *param )
217 intf_thread_t * p_intf = VLCIntf;
218 if( p_intf && p_intf->p_sys )
219 p_intf->p_sys->b_fullscreen_update = true;
223 /*****************************************************************************
224 * DialogCallback: Callback triggered by the "dialog-*" variables
225 * to let the intf display error and interaction dialogs
226 *****************************************************************************/
227 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
229 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
230 VLCMain *interface = (VLCMain *)data;
232 const dialog_fatal_t *p_dialog = (const dialog_fatal_t *)value.p_address;
234 NSLog( @"dialog callback triggered; type of dialogue is '%s'", type );
236 NSValue *o_value = [NSValue valueWithPointer:p_dialog];
237 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewCoreDialogEventNotification" object:[interface getCoreDialogProvider] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: o_value, @"VLCDialogPointer", [NSString stringWithUTF8String: type], @"VLCDialogType", nil]];
246 @interface VLCMain ()
247 - (void)_removeOldPreferences;
250 /*****************************************************************************
251 * VLCMain implementation
252 *****************************************************************************/
253 @implementation VLCMain
256 #pragma mark Initialization
258 static VLCMain *_o_sharedMainInstance = nil;
260 + (VLCMain *)sharedInstance
262 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
267 if( _o_sharedMainInstance)
270 return _o_sharedMainInstance;
273 _o_sharedMainInstance = [super init];
275 o_msg_lock = [[NSLock alloc] init];
276 o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
277 /* subscribe to LibVLC's debug messages as early as possible (for us) */
278 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
280 o_about = [[VLAboutBox alloc] init];
282 o_open = [[VLCOpen alloc] init];
283 o_wizard = [[VLCWizard alloc] init];
284 o_vlm = [[VLCVLMController alloc] init];
286 o_bookmarks = [[VLCBookmarks alloc] init];
287 o_embedded_list = [[VLCEmbeddedList alloc] init];
288 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
289 o_info = [[VLCInfo alloc] init];
291 o_update = [[VLCUpdate alloc] init];
294 i_lastShownVolume = -1;
296 o_remote = [[AppleRemote alloc] init];
297 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
298 [o_remote setDelegate: _o_sharedMainInstance];
300 o_eyetv = [[VLCEyeTVController alloc] init];
302 /* announce our launch to a potential eyetv plugin */
303 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
304 object: @"VLCEyeTVSupport"
306 deliverImmediately: YES];
308 return _o_sharedMainInstance;
311 - (void)setIntf: (intf_thread_t *)p_mainintf {
315 - (intf_thread_t *)getIntf {
321 unsigned int i_key = 0;
322 playlist_t *p_playlist;
325 /* Check if we already did this once. Opening the other nibs calls it too, because VLCMain is the owner */
326 if( nib_main_loaded ) return;
328 /* check whether the user runs a valid version of OS X */
329 if( MACOS_VERSION < 10.5f )
334 if( MACOS_VERSION == 10.4f )
335 o_blabla = _NS("VLC's last release for your OS is the 0.9 series." );
336 else if( MACOS_VERSION == 10.3f )
337 o_blabla = _NS("VLC's last release for your OS is VLC 0.8.6i, which is prone to known security issues." );
338 else // 10.2 and 10.1, still 3% of the OS X market share
339 o_blabla = _NS("VLC's last release for your OS is VLC 0.7.2, which is highly out of date and prone to " \
340 "known security issues. We recommend you to update your Mac to a modern version of Mac OS X.");
341 ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is no longer supported")
342 defaultButton: _NS("Quit")
343 alternateButton: NULL
345 informativeTextWithFormat: _NS("VLC media player %s requires Mac OS X 10.5 or higher.\n\n%@"), VLC_Version(), o_blabla];
346 [ourAlert setAlertStyle: NSCriticalAlertStyle];
347 i_returnValue = [ourAlert runModal];
348 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
354 [o_window setExcludedFromWindowsMenu: YES];
355 [o_msgs_panel setExcludedFromWindowsMenu: YES];
356 [o_msgs_panel setDelegate: self];
358 /* In code and not in Nib for 10.4 compat */
359 NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"mainControllerToolbar"] autorelease];
360 [toolbar setDelegate:self];
361 [toolbar setShowsBaselineSeparator:NO];
362 [toolbar setAllowsUserCustomization:NO];
363 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
364 [toolbar setAutosavesConfiguration:YES];
365 [o_window setToolbar:toolbar];
367 i_key = config_GetInt( p_intf, "key-quit" );
368 [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
369 [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
370 i_key = config_GetInt( p_intf, "key-play-pause" );
371 [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
372 [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
373 i_key = config_GetInt( p_intf, "key-stop" );
374 [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
375 [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
376 i_key = config_GetInt( p_intf, "key-faster" );
377 [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
378 [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
379 i_key = config_GetInt( p_intf, "key-slower" );
380 [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
381 [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
382 i_key = config_GetInt( p_intf, "key-prev" );
383 [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
384 [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
385 i_key = config_GetInt( p_intf, "key-next" );
386 [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
387 [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
388 i_key = config_GetInt( p_intf, "key-jump+short" );
389 [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
390 [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
391 i_key = config_GetInt( p_intf, "key-jump-short" );
392 [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
393 [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
394 i_key = config_GetInt( p_intf, "key-jump+medium" );
395 [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
396 [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
397 i_key = config_GetInt( p_intf, "key-jump-medium" );
398 [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
399 [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
400 i_key = config_GetInt( p_intf, "key-jump+long" );
401 [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
402 [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
403 i_key = config_GetInt( p_intf, "key-jump-long" );
404 [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
405 [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
406 i_key = config_GetInt( p_intf, "key-vol-up" );
407 [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
408 [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
409 i_key = config_GetInt( p_intf, "key-vol-down" );
410 [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
411 [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
412 i_key = config_GetInt( p_intf, "key-vol-mute" );
413 [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
414 [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
415 i_key = config_GetInt( p_intf, "key-fullscreen" );
416 [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
417 [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
418 i_key = config_GetInt( p_intf, "key-snapshot" );
419 [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
420 [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
422 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
424 [self setSubmenusEnabled: FALSE];
425 [o_volumeslider setEnabled: YES];
426 [self manageVolumeSlider];
427 [o_window setDelegate: self];
429 b_restore_size = false;
431 // Set that here as IB seems to be buggy
432 [o_window setContentMinSize:NSMakeSize(338., 30.)];
434 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
436 b_small_window = YES;
437 [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
438 [o_window frame].origin.y, [o_window frame].size.width,
439 [o_window minSize].height ) display: YES animate:YES];
440 [o_playlist_view setAutoresizesSubviews: NO];
445 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
446 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
447 [o_playlist_view setNeedsDisplay:YES];
448 [o_playlist_view setAutoresizesSubviews: YES];
449 [[o_window contentView] addSubview: o_playlist_view];
452 [self updateTogglePlaylistState];
454 o_size_with_playlist = [o_window contentRectForFrameRect:[o_window frame]].size;
456 p_playlist = pl_Hold( p_intf );
458 var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
461 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
462 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
464 pl_Release( p_intf );
466 /* load our Core Dialogs nib */
467 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
469 /* subscribe to various interactive dialogues */
470 var_Create( p_intf, "dialog-fatal", VLC_VAR_ADDRESS );
471 var_AddCallback( p_intf, "dialog-fatal", DialogCallback, self );
472 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
473 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
474 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
475 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
476 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
477 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
478 dialog_Register( p_intf );
480 /* update the playmode stuff */
481 p_intf->p_sys->b_playmode_update = true;
483 [[NSNotificationCenter defaultCenter] addObserver: self
484 selector: @selector(refreshVoutDeviceMenu:)
485 name: NSApplicationDidChangeScreenParametersNotification
488 /* take care of tint changes during runtime */
489 o_img_play = [NSImage imageNamed: @"play"];
490 o_img_pause = [NSImage imageNamed: @"pause"];
491 [self controlTintChanged];
492 [[NSNotificationCenter defaultCenter] addObserver: self
493 selector: @selector( controlTintChanged )
494 name: NSControlTintDidChangeNotification
497 /* yeah, we are done */
498 nib_main_loaded = TRUE;
501 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
503 /* FIXME: don't poll */
504 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
505 target: self selector: @selector(manageIntf:)
506 userInfo: nil repeats: FALSE] retain];
508 /* Note: we use the pthread API to support pre-10.5 */
509 pthread_create( &manage_thread, NULL, ManageThread, self );
511 [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
512 var: "intf-add" selector: @selector(toggleVar:)];
514 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
517 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
519 [self _removeOldPreferences];
522 /* Check for update silently on startup */
523 if( !nib_update_loaded )
524 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
526 if([o_update shouldCheckForUpdate])
527 [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:nil];
530 /* Handle sleep notification */
531 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
532 name:NSWorkspaceWillSleepNotification object:nil];
534 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
539 [o_window setTitle: _NS("VLC media player")];
540 [self setScrollField:_NS("VLC media player") stopAfter:-1];
542 /* button controls */
543 [o_btn_prev setToolTip: _NS("Previous")];
544 [o_btn_rewind setToolTip: _NS("Rewind")];
545 [o_btn_play setToolTip: _NS("Play")];
546 [o_btn_stop setToolTip: _NS("Stop")];
547 [o_btn_ff setToolTip: _NS("Fast Forward")];
548 [o_btn_next setToolTip: _NS("Next")];
549 [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
550 [o_volumeslider setToolTip: _NS("Volume")];
551 [o_timeslider setToolTip: _NS("Position")];
552 [o_btn_playlist setToolTip: _NS("Playlist")];
555 [o_msgs_panel setTitle: _NS("Messages")];
556 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
557 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
560 [o_mi_about setTitle: [_NS("About VLC media player") \
561 stringByAppendingString: @"..."]];
562 [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
563 [o_mi_prefs setTitle: _NS("Preferences...")];
564 [o_mi_add_intf setTitle: _NS("Add Interface")];
565 [o_mu_add_intf setTitle: _NS("Add Interface")];
566 [o_mi_services setTitle: _NS("Services")];
567 [o_mi_hide setTitle: _NS("Hide VLC")];
568 [o_mi_hide_others setTitle: _NS("Hide Others")];
569 [o_mi_show_all setTitle: _NS("Show All")];
570 [o_mi_quit setTitle: _NS("Quit VLC")];
572 [o_mu_file setTitle: _ANS("1:File")];
573 [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
574 [o_mi_open_file setTitle: _NS("Open File...")];
575 [o_mi_open_disc setTitle: _NS("Open Disc...")];
576 [o_mi_open_net setTitle: _NS("Open Network...")];
577 [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
578 [o_mi_open_recent setTitle: _NS("Open Recent")];
579 [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
580 [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
582 [o_mu_edit setTitle: _NS("Edit")];
583 [o_mi_cut setTitle: _NS("Cut")];
584 [o_mi_copy setTitle: _NS("Copy")];
585 [o_mi_paste setTitle: _NS("Paste")];
586 [o_mi_clear setTitle: _NS("Clear")];
587 [o_mi_select_all setTitle: _NS("Select All")];
589 [o_mu_controls setTitle: _NS("Playback")];
590 [o_mi_play setTitle: _NS("Play")];
591 [o_mi_stop setTitle: _NS("Stop")];
592 [o_mi_faster setTitle: _NS("Faster")];
593 [o_mi_slower setTitle: _NS("Slower")];
594 [o_mi_previous setTitle: _NS("Previous")];
595 [o_mi_next setTitle: _NS("Next")];
596 [o_mi_random setTitle: _NS("Random")];
597 [o_mi_repeat setTitle: _NS("Repeat One")];
598 [o_mi_loop setTitle: _NS("Repeat All")];
599 [o_mi_fwd setTitle: _NS("Step Forward")];
600 [o_mi_bwd setTitle: _NS("Step Backward")];
602 [o_mi_program setTitle: _NS("Program")];
603 [o_mu_program setTitle: _NS("Program")];
604 [o_mi_title setTitle: _NS("Title")];
605 [o_mu_title setTitle: _NS("Title")];
606 [o_mi_chapter setTitle: _NS("Chapter")];
607 [o_mu_chapter setTitle: _NS("Chapter")];
609 [o_mu_audio setTitle: _NS("Audio")];
610 [o_mi_vol_up setTitle: _NS("Increase Volume")];
611 [o_mi_vol_down setTitle: _NS("Decrease Volume")];
612 [o_mi_mute setTitle: _NS("Mute")];
613 [o_mi_audiotrack setTitle: _NS("Audio Track")];
614 [o_mu_audiotrack setTitle: _NS("Audio Track")];
615 [o_mi_channels setTitle: _NS("Audio Channels")];
616 [o_mu_channels setTitle: _NS("Audio Channels")];
617 [o_mi_device setTitle: _NS("Audio Device")];
618 [o_mu_device setTitle: _NS("Audio Device")];
619 [o_mi_visual setTitle: _NS("Visualizations")];
620 [o_mu_visual setTitle: _NS("Visualizations")];
622 [o_mu_video setTitle: _NS("Video")];
623 [o_mi_half_window setTitle: _NS("Half Size")];
624 [o_mi_normal_window setTitle: _NS("Normal Size")];
625 [o_mi_double_window setTitle: _NS("Double Size")];
626 [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
627 [o_mi_fullscreen setTitle: _NS("Fullscreen")];
628 [o_mi_floatontop setTitle: _NS("Float on Top")];
629 [o_mi_snapshot setTitle: _NS("Snapshot")];
630 [o_mi_videotrack setTitle: _NS("Video Track")];
631 [o_mu_videotrack setTitle: _NS("Video Track")];
632 [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
633 [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
634 [o_mi_crop setTitle: _NS("Crop")];
635 [o_mu_crop setTitle: _NS("Crop")];
636 [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
637 [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
638 [o_mi_subtitle setTitle: _NS("Subtitles Track")];
639 [o_mu_subtitle setTitle: _NS("Subtitles Track")];
640 [o_mi_addSub setTitle: _NS("Open File...")];
641 [o_mi_deinterlace setTitle: _NS("Deinterlace")];
642 [o_mu_deinterlace setTitle: _NS("Deinterlace")];
643 [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
644 [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
645 [o_mi_teletext setTitle: _NS("Teletext")];
646 [o_mi_teletext_transparent setTitle: _NS("Transparent")];
647 [o_mi_teletext_index setTitle: _NS("Index")];
648 [o_mi_teletext_red setTitle: _NS("Red")];
649 [o_mi_teletext_green setTitle: _NS("Green")];
650 [o_mi_teletext_yellow setTitle: _NS("Yellow")];
651 [o_mi_teletext_blue setTitle: _NS("Blue")];
653 [o_mu_window setTitle: _NS("Window")];
654 [o_mi_minimize setTitle: _NS("Minimize Window")];
655 [o_mi_close_window setTitle: _NS("Close Window")];
656 [o_mi_controller setTitle: _NS("Controller...")];
657 [o_mi_equalizer setTitle: _NS("Equalizer...")];
658 [o_mi_extended setTitle: _NS("Extended Controls...")];
659 [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
660 [o_mi_playlist setTitle: _NS("Playlist...")];
661 [o_mi_info setTitle: _NS("Media Information...")];
662 [o_mi_messages setTitle: _NS("Messages...")];
663 [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
665 [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
667 [o_mu_help setTitle: _NS("Help")];
668 [o_mi_help setTitle: _NS("VLC media player Help...")];
669 [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
670 [o_mi_license setTitle: _NS("License")];
671 [o_mi_documentation setTitle: _NS("Online Documentation...")];
672 [o_mi_website setTitle: _NS("VideoLAN Website...")];
673 [o_mi_donation setTitle: _NS("Make a donation...")];
674 [o_mi_forum setTitle: _NS("Online Forum...")];
677 [o_dmi_play setTitle: _NS("Play")];
678 [o_dmi_stop setTitle: _NS("Stop")];
679 [o_dmi_next setTitle: _NS("Next")];
680 [o_dmi_previous setTitle: _NS("Previous")];
681 [o_dmi_mute setTitle: _NS("Mute")];
684 [o_vmi_play setTitle: _NS("Play")];
685 [o_vmi_stop setTitle: _NS("Stop")];
686 [o_vmi_prev setTitle: _NS("Previous")];
687 [o_vmi_next setTitle: _NS("Next")];
688 [o_vmi_volup setTitle: _NS("Volume Up")];
689 [o_vmi_voldown setTitle: _NS("Volume Down")];
690 [o_vmi_mute setTitle: _NS("Mute")];
691 [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
692 [o_vmi_snapshot setTitle: _NS("Snapshot")];
694 /* crash reporter panel */
695 [o_crashrep_send_btn setTitle: _NS("Send")];
696 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
697 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
698 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
699 [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, ...")];
700 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
701 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
705 #pragma mark Termination
707 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
709 NSArray *menuitems_array = [the_menu itemArray];
710 for( int i=0; i<[menuitems_array count]; i++ )
712 NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
713 if( [one_item hasSubmenu] )
714 [self releaseRepresentedObjects: [one_item submenu]];
716 [one_item setRepresentedObject:NULL];
720 - (void)applicationWillTerminate:(NSNotification *)notification
722 playlist_t * p_playlist;
723 vout_thread_t * p_vout;
724 int returnedValue = 0;
726 msg_Dbg( p_intf, "Terminating" );
728 /* Make sure the manage_thread won't call -terminate: again */
729 pthread_cancel( manage_thread );
731 /* Make sure the intf object is getting killed */
732 vlc_object_kill( p_intf );
734 /* Make sure our manage_thread ends */
735 pthread_join( manage_thread, NULL );
737 /* Make sure the interfaceTimer is destroyed */
738 [interfaceTimer invalidate];
739 [interfaceTimer release];
740 interfaceTimer = nil;
742 /* make sure that the current volume is saved */
743 config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
745 /* save the prefs if they were changed in the extended panel */
746 if(o_extended && [o_extended getConfigChanged])
748 [o_extended savePrefs];
751 /* unsubscribe from the interactive dialogues */
752 dialog_Unregister( p_intf );
753 var_DelCallback( p_intf, "dialog-fatal", DialogCallback, self );
754 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
755 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
756 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
758 /* remove global observer watching for vout device changes correctly */
759 [[NSNotificationCenter defaultCenter] removeObserver: self];
763 /* release some other objects here, because it isn't sure whether dealloc
764 * will be called later on */
765 if( nib_about_loaded )
768 if( nib_prefs_loaded )
774 if( nib_open_loaded )
777 if( nib_extended_loaded )
779 [o_extended release];
782 if( nib_bookmarks_loaded )
783 [o_bookmarks release];
791 if( nib_wizard_loaded )
794 [crashLogURLConnection cancel];
795 [crashLogURLConnection release];
797 [o_embedded_list release];
798 [o_coredialogs release];
801 [o_img_pause_pressed release];
802 [o_img_play_pressed release];
803 [o_img_pause release];
804 [o_img_play release];
806 /* unsubscribe from libvlc's debug messages */
807 msg_Unsubscribe( p_intf->p_sys->p_sub );
809 [o_msg_arr removeAllObjects];
812 [o_msg_lock release];
814 /* write cached user defaults to disk */
815 [[NSUserDefaults standardUserDefaults] synchronize];
817 /* Make sure the Menu doesn't have any references to vlc objects anymore */
818 [self releaseRepresentedObjects:[NSApp mainMenu]];
820 /* Kill the playlist, so that it doesn't accept new request
821 * such as the play request from vlc.c (we are a blocking interface). */
822 p_playlist = pl_Hold( p_intf );
823 vlc_object_kill( p_playlist );
824 pl_Release( p_intf );
826 libvlc_Quit( p_intf->p_libvlc );
830 /* Go back to Run() and make libvlc exit properly */
832 longjmp( jmpbuffer, 1 );
837 #pragma mark Toolbar delegate
839 /* Our item identifiers */
840 static NSString * VLCToolbarMediaControl = @"VLCToolbarMediaControl";
842 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
844 return [NSArray arrayWithObjects:
845 // NSToolbarCustomizeToolbarItemIdentifier,
846 // NSToolbarFlexibleSpaceItemIdentifier,
847 // NSToolbarSpaceItemIdentifier,
848 // NSToolbarSeparatorItemIdentifier,
849 VLCToolbarMediaControl,
853 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
855 return [NSArray arrayWithObjects:
856 VLCToolbarMediaControl,
860 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
862 NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
865 if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
867 [toolbarItem setLabel:@"Media Controls"];
868 [toolbarItem setPaletteLabel:@"Media Controls"];
870 NSSize size = toolbarMediaControl.frame.size;
871 [toolbarItem setView:toolbarMediaControl];
872 [toolbarItem setMinSize:size];
874 [toolbarItem setMaxSize:size];
876 // Hack: For some reason we need to make sure
877 // that the those element are on top
878 // Add them again will put them frontmost
879 [toolbarMediaControl addSubview:o_scrollfield];
880 [toolbarMediaControl addSubview:o_timeslider];
881 [toolbarMediaControl addSubview:o_timefield];
882 [toolbarMediaControl addSubview:o_main_pgbar];
884 /* TODO: setup a menu */
888 /* itemIdentifier referred to a toolbar item that is not
889 * provided or supported by us or Cocoa
890 * Returning nil will inform the toolbar
891 * that this kind of item is not supported */
898 #pragma mark Other notification
900 - (void)controlTintChanged
904 if( [o_btn_play alternateImage] == o_img_play_pressed )
907 if( [NSColor currentControlTint] == NSGraphiteControlTint )
909 o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
910 o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
912 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
913 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
914 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
915 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
916 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
917 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
918 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
919 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
923 o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
924 o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
926 [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
927 [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
928 [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
929 [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
930 [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
931 [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
932 [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
933 [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
937 [o_btn_play setAlternateImage: o_img_play_pressed];
939 [o_btn_play setAlternateImage: o_img_pause_pressed];
942 /* Listen to the remote in exclusive mode, only when VLC is the active
944 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
946 [o_remote startListening: self];
948 - (void)applicationDidResignActive:(NSNotification *)aNotification
950 [o_remote stopListening: self];
953 /* Triggered when the computer goes to sleep */
954 - (void)computerWillSleep: (NSNotification *)notification
957 if( p_intf->p_sys->i_play_status == PLAYING_S )
960 val.i_int = config_GetInt( p_intf, "key-play-pause" );
961 var_Set( p_intf->p_libvlc, "key-pressed", val );
966 #pragma mark File opening
968 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
970 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
971 NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
973 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
975 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
980 /* When user click in the Dock icon our double click in the finder */
981 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
983 if(!hasVisibleWindows)
984 [o_window makeKeyAndOrderFront:self];
990 #pragma mark Apple Remote Control
992 /* Helper method for the remote control interface in order to trigger forward/backward and volume
993 increase/decrease as long as the user holds the left/right, plus/minus button */
994 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
996 if(b_remote_button_hold)
998 switch([buttonIdentifierNumber intValue])
1000 case kRemoteButtonRight_Hold:
1001 [o_controls forward: self];
1003 case kRemoteButtonLeft_Hold:
1004 [o_controls backward: self];
1006 case kRemoteButtonVolume_Plus_Hold:
1007 [o_controls volumeUp: self];
1009 case kRemoteButtonVolume_Minus_Hold:
1010 [o_controls volumeDown: self];
1013 if(b_remote_button_hold)
1016 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1017 withObject:buttonIdentifierNumber
1023 /* Apple Remote callback */
1024 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1025 pressedDown: (BOOL) pressedDown
1026 clickCount: (unsigned int) count
1028 switch( buttonIdentifier )
1030 case kRemoteButtonPlay:
1032 [o_controls toogleFullscreen:self];
1034 [o_controls play: self];
1037 case kRemoteButtonVolume_Plus:
1038 [o_controls volumeUp: self];
1040 case kRemoteButtonVolume_Minus:
1041 [o_controls volumeDown: self];
1043 case kRemoteButtonRight:
1044 [o_controls next: self];
1046 case kRemoteButtonLeft:
1047 [o_controls prev: self];
1049 case kRemoteButtonRight_Hold:
1050 case kRemoteButtonLeft_Hold:
1051 case kRemoteButtonVolume_Plus_Hold:
1052 case kRemoteButtonVolume_Minus_Hold:
1053 /* simulate an event as long as the user holds the button */
1054 b_remote_button_hold = pressedDown;
1057 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1058 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1059 withObject:buttonIdentifierNumber];
1062 case kRemoteButtonMenu:
1063 [o_controls showPosition: self];
1066 /* Add here whatever you want other buttons to do */
1072 #pragma mark String utility
1073 // FIXME: this has nothing to do here
1075 - (NSString *)localizedString:(const char *)psz
1077 NSString * o_str = nil;
1081 o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1085 msg_Err( VLCIntf, "could not translate: %s", psz );
1091 msg_Warn( VLCIntf, "can't translate empty strings" );
1100 - (char *)delocalizeString:(NSString *)id
1102 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1103 allowLossyConversion: NO];
1108 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1109 allowLossyConversion: YES];
1110 psz_string = malloc( [o_data length] + 1 );
1111 [o_data getBytes: psz_string];
1112 psz_string[ [o_data length] ] = '\0';
1113 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1118 psz_string = malloc( [o_data length] + 1 );
1119 [o_data getBytes: psz_string];
1120 psz_string[ [o_data length] ] = '\0';
1126 /* i_width is in pixels */
1127 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1129 NSMutableString *o_wrapped;
1130 NSString *o_out_string;
1131 NSRange glyphRange, effectiveRange, charRange;
1132 NSRect lineFragmentRect;
1133 unsigned glyphIndex, breaksInserted = 0;
1135 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1136 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1137 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1138 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1139 NSTextContainer *o_container = [[NSTextContainer alloc]
1140 initWithContainerSize: NSMakeSize(i_width, 2000)];
1142 [o_layout_manager addTextContainer: o_container];
1143 [o_container release];
1144 [o_storage addLayoutManager: o_layout_manager];
1145 [o_layout_manager release];
1147 o_wrapped = [o_in_string mutableCopy];
1148 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1150 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1151 glyphIndex += effectiveRange.length) {
1152 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1153 effectiveRange: &effectiveRange];
1154 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1155 actualGlyphRange: &effectiveRange];
1156 if([o_wrapped lineRangeForRange:
1157 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1158 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1162 o_out_string = [NSString stringWithString: o_wrapped];
1163 [o_wrapped release];
1164 [o_storage release];
1166 return o_out_string;
1171 #pragma mark Key Shortcuts
1176 unsigned int i_vlckey;
1177 } nskeys_to_vlckeys[] =
1179 { NSUpArrowFunctionKey, KEY_UP },
1180 { NSDownArrowFunctionKey, KEY_DOWN },
1181 { NSLeftArrowFunctionKey, KEY_LEFT },
1182 { NSRightArrowFunctionKey, KEY_RIGHT },
1183 { NSF1FunctionKey, KEY_F1 },
1184 { NSF2FunctionKey, KEY_F2 },
1185 { NSF3FunctionKey, KEY_F3 },
1186 { NSF4FunctionKey, KEY_F4 },
1187 { NSF5FunctionKey, KEY_F5 },
1188 { NSF6FunctionKey, KEY_F6 },
1189 { NSF7FunctionKey, KEY_F7 },
1190 { NSF8FunctionKey, KEY_F8 },
1191 { NSF9FunctionKey, KEY_F9 },
1192 { NSF10FunctionKey, KEY_F10 },
1193 { NSF11FunctionKey, KEY_F11 },
1194 { NSF12FunctionKey, KEY_F12 },
1195 { NSInsertFunctionKey, KEY_INSERT },
1196 { NSHomeFunctionKey, KEY_HOME },
1197 { NSEndFunctionKey, KEY_END },
1198 { NSPageUpFunctionKey, KEY_PAGEUP },
1199 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1200 { NSMenuFunctionKey, KEY_MENU },
1201 { NSTabCharacter, KEY_TAB },
1202 { NSCarriageReturnCharacter, KEY_ENTER },
1203 { NSEnterCharacter, KEY_ENTER },
1204 { NSBackspaceCharacter, KEY_BACKSPACE },
1205 { (unichar) ' ', KEY_SPACE },
1206 { (unichar) 0x1b, KEY_ESC },
1210 static unichar VLCKeyToCocoa( unsigned int i_key )
1214 for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1216 if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1218 return nskeys_to_vlckeys[i].i_nskey;
1221 return (unichar)(i_key & ~KEY_MODIFIER);
1224 unsigned int CocoaKeyToVLC( unichar i_key )
1228 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1230 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1232 return nskeys_to_vlckeys[i].i_vlckey;
1235 return (unsigned int)i_key;
1238 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1240 unsigned int new = 0;
1241 if( i_key & KEY_MODIFIER_COMMAND )
1242 new |= NSCommandKeyMask;
1243 if( i_key & KEY_MODIFIER_ALT )
1244 new |= NSAlternateKeyMask;
1245 if( i_key & KEY_MODIFIER_SHIFT )
1246 new |= NSShiftKeyMask;
1247 if( i_key & KEY_MODIFIER_CTRL )
1248 new |= NSControlKeyMask;
1252 /*****************************************************************************
1253 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1254 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1255 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1256 *****************************************************************************/
1257 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1261 unsigned int i_pressed_modifiers = 0;
1262 struct hotkey *p_hotkeys;
1266 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1268 i_pressed_modifiers = [o_event modifierFlags];
1270 if( i_pressed_modifiers & NSShiftKeyMask )
1271 val.i_int |= KEY_MODIFIER_SHIFT;
1272 if( i_pressed_modifiers & NSControlKeyMask )
1273 val.i_int |= KEY_MODIFIER_CTRL;
1274 if( i_pressed_modifiers & NSAlternateKeyMask )
1275 val.i_int |= KEY_MODIFIER_ALT;
1276 if( i_pressed_modifiers & NSCommandKeyMask )
1277 val.i_int |= KEY_MODIFIER_COMMAND;
1279 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1283 case NSDeleteCharacter:
1284 case NSDeleteFunctionKey:
1285 case NSDeleteCharFunctionKey:
1286 case NSBackspaceCharacter:
1287 case NSUpArrowFunctionKey:
1288 case NSDownArrowFunctionKey:
1289 case NSRightArrowFunctionKey:
1290 case NSLeftArrowFunctionKey:
1291 case NSEnterCharacter:
1292 case NSCarriageReturnCharacter:
1296 val.i_int |= CocoaKeyToVLC( key );
1298 for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1300 if( p_hotkeys[i].i_key == val.i_int )
1302 var_Set( p_intf->p_libvlc, "key-pressed", val );
1311 #pragma mark Other objects getters
1312 // FIXME: this is ugly and does not respect cocoa naming scheme
1322 - (id)getSimplePreferences
1327 if( !nib_prefs_loaded )
1328 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1333 - (id)getPreferences
1338 if( !nib_prefs_loaded )
1339 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1352 - (BOOL)isPlaylistCollapsed
1354 return ![o_btn_playlist state];
1386 - (id)getEmbeddedList
1388 if( o_embedded_list )
1389 return o_embedded_list;
1394 - (id)getCoreDialogProvider
1397 return o_coredialogs;
1402 - (id)getMainIntfPgbar
1405 return o_main_pgbar;
1410 - (id)getControllerWindow
1422 - (id)getEyeTVController
1431 #pragma mark Polling
1433 /*****************************************************************************
1434 * ManageThread: An ugly thread that polls
1435 *****************************************************************************/
1436 static void * ManageThread( void *user_data )
1438 id self = user_data;
1445 struct manage_cleanup_stack {
1446 intf_thread_t * p_intf;
1447 input_thread_t ** p_input;
1448 playlist_t * p_playlist;
1452 static void manage_cleanup( void * args )
1454 struct manage_cleanup_stack * manage_cleanup_stack = args;
1455 intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1456 input_thread_t * p_input = *manage_cleanup_stack->p_input;
1457 id self = manage_cleanup_stack->self;
1458 playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1460 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1461 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1462 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1463 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1464 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1466 pl_Release( p_intf );
1468 if( p_input ) vlc_object_release( p_input );
1473 playlist_t * p_playlist;
1474 input_thread_t * p_input = NULL;
1476 /* new thread requires a new pool */
1478 vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1480 p_playlist = pl_Hold( p_intf );
1482 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1483 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1484 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1485 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1486 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1488 struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1489 pthread_cleanup_push(manage_cleanup, &stack);
1493 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1497 p_input = playlist_CurrentInput( p_playlist );
1499 /* Refresh the interface */
1502 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1503 p_intf->p_sys->b_input_update = true;
1506 else if( !vlc_object_alive (p_input) || p_input->b_dead )
1509 p_intf->p_sys->b_intf_update = true;
1510 p_intf->p_sys->i_play_status = END_S;
1511 msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1512 vlc_object_release( p_input );
1515 else if( cachedInputState != input_GetState( p_input ) )
1517 p_intf->p_sys->b_intf_update = true;
1520 /* Manage volume status */
1521 [self manageVolumeSlider];
1523 msleep( INTF_IDLE_SLEEP );
1528 pthread_cleanup_pop(1);
1530 msg_Dbg( p_intf, "Killing the Mac OS X module" );
1532 /* We are dead, terminate */
1533 [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1536 - (void)manageVolumeSlider
1538 audio_volume_t i_volume;
1539 aout_VolumeGet( p_intf, &i_volume );
1541 if( i_volume != i_lastShownVolume )
1543 i_lastShownVolume = i_volume;
1544 p_intf->p_sys->b_volume_update = TRUE;
1548 - (void)manageIntf:(NSTimer *)o_timer
1551 playlist_t * p_playlist;
1552 input_thread_t * p_input;
1554 if( p_intf->p_sys->b_input_update )
1556 /* Called when new input is opened */
1557 p_intf->p_sys->b_current_title_update = true;
1558 p_intf->p_sys->b_intf_update = true;
1559 p_intf->p_sys->b_input_update = false;
1560 [self setupMenus]; /* Make sure input menu is up to date */
1562 if( p_intf->p_sys->b_intf_update )
1564 bool b_input = false;
1565 bool b_plmul = false;
1566 bool b_control = false;
1567 bool b_seekable = false;
1568 bool b_chapters = false;
1570 playlist_t * p_playlist = pl_Hold( p_intf );
1572 /* TODO: fix i_size use */
1573 b_plmul = p_playlist->items.i_size > 1;
1575 p_input = playlist_CurrentInput( p_playlist );
1576 bool b_buffering = NO;
1578 if( ( b_input = ( p_input != NULL ) ) )
1580 /* seekable streams */
1581 cachedInputState = input_GetState( p_input );
1582 if ( cachedInputState == INIT_S ||
1583 cachedInputState == OPENING_S )
1588 /* update our info-panel to reflect the new item, if we don't show
1589 * the playlist or the selection is empty */
1590 if( [self isPlaylistCollapsed] == YES )
1593 [[self getInfo] updatePanelWithItem: playlist_CurrentPlayingItem( p_playlist )->p_input];
1597 /* seekable streams */
1598 b_seekable = var_GetBool( p_input, "can-seek" );
1600 /* check whether slow/fast motion is possible */
1601 b_control = var_GetBool( p_input, "can-rate" );
1603 /* chapters & titles */
1604 //b_chapters = p_input->stream.i_area_nb > 1;
1605 vlc_object_release( p_input );
1607 pl_Release( p_intf );
1611 [o_main_pgbar startAnimation:self];
1612 [o_main_pgbar setIndeterminate:YES];
1613 [o_main_pgbar setHidden:NO];
1617 [o_main_pgbar stopAnimation:self];
1618 [o_main_pgbar setHidden:YES];
1621 [o_btn_stop setEnabled: b_input];
1622 [o_btn_ff setEnabled: b_seekable];
1623 [o_btn_rewind setEnabled: b_seekable];
1624 [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1625 [o_btn_next setEnabled: (b_plmul || b_chapters)];
1627 [o_timeslider setFloatValue: 0.0];
1628 [o_timeslider setEnabled: b_seekable];
1629 [o_timefield setStringValue: @"00:00"];
1630 [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1631 [[[self getControls] getFSPanel] setSeekable: b_seekable];
1633 [o_embedded_window setSeekable: b_seekable];
1635 p_intf->p_sys->b_current_title_update = true;
1637 p_intf->p_sys->b_intf_update = false;
1640 if( p_intf->p_sys->b_playmode_update )
1642 [o_playlist playModeUpdated];
1643 p_intf->p_sys->b_playmode_update = false;
1645 if( p_intf->p_sys->b_playlist_update )
1647 [o_playlist playlistUpdated];
1648 p_intf->p_sys->b_playlist_update = false;
1651 if( p_intf->p_sys->b_fullscreen_update )
1653 p_intf->p_sys->b_fullscreen_update = false;
1656 if( p_intf->p_sys->b_intf_show )
1658 if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1659 [[o_controls getFSPanel] fadeIn];
1661 [o_window makeKeyAndOrderFront: self];
1663 p_intf->p_sys->b_intf_show = false;
1666 p_input = pl_CurrentInput( p_intf );
1667 if( p_input && vlc_object_alive (p_input) )
1671 if( p_intf->p_sys->b_current_title_update )
1674 input_item_t * p_item = input_GetItem( p_input );
1675 char * name = input_item_GetNowPlaying( p_item );
1678 name = input_item_GetName( p_item );
1680 aString = [NSString stringWithUTF8String:name];
1684 [self setScrollField: aString stopAfter:-1];
1685 [[[self getControls] getFSPanel] setStreamTitle: aString];
1687 [[o_controls voutView] updateTitle];
1689 [o_playlist updateRowSelection];
1690 p_intf->p_sys->b_current_title_update = FALSE;
1693 if( [o_timeslider isEnabled] )
1695 /* Update the slider */
1699 char psz_time[MSTRTIME_MAX_SIZE];
1702 var_Get( p_input, "position", &pos );
1703 f_updated = 10000. * pos.f_float;
1704 [o_timeslider setFloatValue: f_updated];
1706 var_Get( p_input, "time", &time );
1708 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1709 if( b_time_remaining && dur != -1 )
1711 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1714 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1716 [o_timefield setStringValue: o_time];
1717 [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1718 [o_embedded_window setTime: o_time position: f_updated];
1721 /* Manage Playing status */
1722 var_Get( p_input, "state", &val );
1723 if( p_intf->p_sys->i_play_status != val.i_int )
1725 p_intf->p_sys->i_play_status = val.i_int;
1726 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1727 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1729 vlc_object_release( p_input );
1733 vlc_object_release( p_input );
1737 p_intf->p_sys->i_play_status = END_S;
1738 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1739 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1740 [self setSubmenusEnabled: FALSE];
1743 if( p_intf->p_sys->b_volume_update )
1746 int i_volume_step = 0;
1747 o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1748 if( i_lastShownVolume != -1 )
1749 [self setScrollField:o_text stopAfter:1000000];
1750 i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1751 [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1752 [o_volumeslider setEnabled: TRUE];
1753 [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1754 p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1755 p_intf->p_sys->b_volume_update = FALSE;
1759 [self updateMessageDisplay];
1761 if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1762 [self resetScrollField];
1764 [interfaceTimer autorelease];
1766 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1767 target: self selector: @selector(manageIntf:)
1768 userInfo: nil repeats: FALSE] retain];
1772 #pragma mark Interface update
1776 playlist_t * p_playlist = pl_Hold( p_intf );
1777 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1778 if( p_input != NULL )
1780 [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1781 var: "program" selector: @selector(toggleVar:)];
1783 [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1784 var: "title" selector: @selector(toggleVar:)];
1786 [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1787 var: "chapter" selector: @selector(toggleVar:)];
1789 [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1790 var: "audio-es" selector: @selector(toggleVar:)];
1792 [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1793 var: "video-es" selector: @selector(toggleVar:)];
1795 [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1796 var: "spu-es" selector: @selector(toggleVar:)];
1798 /* special case for "Open File" inside the subtitles menu item */
1799 if( [o_mi_videotrack isEnabled] == YES )
1800 [o_mi_subtitle setEnabled: YES];
1802 aout_instance_t * p_aout = input_GetAout( p_input );
1803 if( p_aout != NULL )
1805 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1806 var: "audio-channels" selector: @selector(toggleVar:)];
1808 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1809 var: "audio-device" selector: @selector(toggleVar:)];
1811 [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1812 var: "visual" selector: @selector(toggleVar:)];
1813 vlc_object_release( (vlc_object_t *)p_aout );
1816 vout_thread_t * p_vout = input_GetVout( p_input );
1818 if( p_vout != NULL )
1820 vlc_object_t * p_dec_obj;
1822 [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1823 var: "aspect-ratio" selector: @selector(toggleVar:)];
1825 [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1826 var: "crop" selector: @selector(toggleVar:)];
1828 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1829 var: "video-device" selector: @selector(toggleVar:)];
1831 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1832 var: "deinterlace" selector: @selector(toggleVar:)];
1835 /* FIXME Post processing. */
1836 p_dec_obj = (vlc_object_t *)vlc_object_find(
1837 (vlc_object_t *)p_vout,
1840 if( p_dec_obj != NULL )
1842 [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1843 (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1844 @selector(toggleVar:)];
1846 vlc_object_release(p_dec_obj);
1849 vlc_object_release( (vlc_object_t *)p_vout );
1851 vlc_object_release( p_input );
1853 pl_Release( p_intf );
1856 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1859 vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1865 /* clean the menu before adding new entries */
1866 if( [o_mi_screen hasSubmenu] )
1868 y = [[o_mi_screen submenu] numberOfItems] - 1;
1869 msg_Dbg( VLCIntf, "%i items in submenu", y );
1872 msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1873 [[o_mi_screen submenu] removeItemAtIndex: x];
1878 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1879 var: "video-device" selector: @selector(toggleVar:)];
1880 vlc_object_release( (vlc_object_t *)p_vout );
1883 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1886 i_end_scroll = mdate() + timeout;
1889 [o_scrollfield setStringValue: o_string];
1892 - (void)resetScrollField
1894 playlist_t * p_playlist = pl_Hold( p_intf );
1895 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1898 if( p_input && vlc_object_alive (p_input) )
1902 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1903 if( input_item_GetNowPlaying( p_item->p_input ) )
1904 o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
1906 o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
1908 [self setScrollField: o_temp stopAfter:-1];
1909 [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1910 vlc_object_release( p_input );
1911 pl_Release( p_intf );
1914 pl_Release( p_intf );
1915 [self setScrollField: _NS("VLC media player") stopAfter:-1];
1918 - (void)playStatusUpdated:(int)i_status
1920 if( i_status == PLAYING_S )
1922 [[[self getControls] getFSPanel] setPause];
1923 [o_btn_play setImage: o_img_pause];
1924 [o_btn_play setAlternateImage: o_img_pause_pressed];
1925 [o_btn_play setToolTip: _NS("Pause")];
1926 [o_mi_play setTitle: _NS("Pause")];
1927 [o_dmi_play setTitle: _NS("Pause")];
1928 [o_vmi_play setTitle: _NS("Pause")];
1932 [[[self getControls] getFSPanel] setPlay];
1933 [o_btn_play setImage: o_img_play];
1934 [o_btn_play setAlternateImage: o_img_play_pressed];
1935 [o_btn_play setToolTip: _NS("Play")];
1936 [o_mi_play setTitle: _NS("Play")];
1937 [o_dmi_play setTitle: _NS("Play")];
1938 [o_vmi_play setTitle: _NS("Play")];
1942 - (void)setSubmenusEnabled:(BOOL)b_enabled
1944 [o_mi_program setEnabled: b_enabled];
1945 [o_mi_title setEnabled: b_enabled];
1946 [o_mi_chapter setEnabled: b_enabled];
1947 [o_mi_audiotrack setEnabled: b_enabled];
1948 [o_mi_visual setEnabled: b_enabled];
1949 [o_mi_videotrack setEnabled: b_enabled];
1950 [o_mi_subtitle setEnabled: b_enabled];
1951 [o_mi_channels setEnabled: b_enabled];
1952 [o_mi_deinterlace setEnabled: b_enabled];
1953 [o_mi_ffmpeg_pp setEnabled: b_enabled];
1954 [o_mi_device setEnabled: b_enabled];
1955 [o_mi_screen setEnabled: b_enabled];
1956 [o_mi_aspect_ratio setEnabled: b_enabled];
1957 [o_mi_crop setEnabled: b_enabled];
1958 [o_mi_teletext setEnabled: b_enabled];
1961 - (IBAction)timesliderUpdate:(id)sender
1964 playlist_t * p_playlist;
1965 input_thread_t * p_input;
1967 switch( [[NSApp currentEvent] type] )
1970 case NSLeftMouseDown:
1971 case NSLeftMouseDragged:
1972 f_updated = [sender floatValue];
1978 p_playlist = pl_Hold( p_intf );
1979 p_input = playlist_CurrentInput( p_playlist );
1980 if( p_input != NULL )
1985 char psz_time[MSTRTIME_MAX_SIZE];
1987 pos.f_float = f_updated / 10000.;
1988 var_Set( p_input, "position", pos );
1989 [o_timeslider setFloatValue: f_updated];
1991 var_Get( p_input, "time", &time );
1993 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1994 if( b_time_remaining && dur != -1 )
1996 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
1999 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2001 [o_timefield setStringValue: o_time];
2002 [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
2003 [o_embedded_window setTime: o_time position: f_updated];
2004 vlc_object_release( p_input );
2006 pl_Release( p_intf );
2009 - (IBAction)timeFieldWasClicked:(id)sender
2011 b_time_remaining = !b_time_remaining;
2016 #pragma mark Recent Items
2018 - (IBAction)clearRecentItems:(id)sender
2020 [[NSDocumentController sharedDocumentController]
2021 clearRecentDocuments: nil];
2024 - (void)openRecentItem:(id)sender
2026 [self application: nil openFile: [sender title]];
2032 - (IBAction)intfOpenFile:(id)sender
2034 if( !nib_open_loaded )
2036 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2037 [o_open awakeFromNib];
2044 - (IBAction)intfOpenFileGeneric:(id)sender
2046 if( !nib_open_loaded )
2048 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2049 [o_open awakeFromNib];
2050 [o_open openFileGeneric];
2052 [o_open openFileGeneric];
2056 - (IBAction)intfOpenDisc:(id)sender
2058 if( !nib_open_loaded )
2060 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2061 [o_open awakeFromNib];
2068 - (IBAction)intfOpenNet:(id)sender
2070 if( !nib_open_loaded )
2072 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2073 [o_open awakeFromNib];
2080 - (IBAction)intfOpenCapture:(id)sender
2082 if( !nib_open_loaded )
2084 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2085 [o_open awakeFromNib];
2086 [o_open openCapture];
2088 [o_open openCapture];
2092 - (IBAction)showWizard:(id)sender
2094 if( !nib_wizard_loaded )
2096 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2097 [o_wizard initStrings];
2098 [o_wizard resetWizard];
2099 [o_wizard showWizard];
2101 [o_wizard resetWizard];
2102 [o_wizard showWizard];
2106 - (IBAction)showVLM:(id)sender
2108 if( !nib_vlm_loaded )
2109 nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner: NSApp];
2111 [o_vlm showVLMWindow];
2114 - (IBAction)showExtended:(id)sender
2116 if( o_extended == nil )
2117 o_extended = [[VLCExtended alloc] init];
2119 if( !nib_extended_loaded )
2120 nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2122 [o_extended showPanel];
2125 - (IBAction)showBookmarks:(id)sender
2127 dialog_Fatal( p_intf, "Title", "Message" );
2129 /* we need the wizard-nib for the bookmarks's extract functionality */
2130 if( !nib_wizard_loaded )
2132 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2133 [o_wizard initStrings];
2136 if( !nib_bookmarks_loaded )
2137 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2139 [o_bookmarks showBookmarks];
2142 - (IBAction)viewPreferences:(id)sender
2144 if( !nib_prefs_loaded )
2146 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2147 o_sprefs = [[VLCSimplePrefs alloc] init];
2148 o_prefs= [[VLCPrefs alloc] init];
2151 [o_sprefs showSimplePrefs];
2157 - (IBAction)checkForUpdate:(id)sender
2160 if( !nib_update_loaded )
2161 nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner: NSApp];
2162 [o_update showUpdateWindow];
2164 msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2165 dialog_FatalWait( VLCIntf, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2170 #pragma mark Help and Docs
2172 - (IBAction)viewAbout:(id)sender
2174 if( !nib_about_loaded )
2175 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2177 [o_about showAbout];
2180 - (IBAction)showLicense:(id)sender
2182 if( !nib_about_loaded )
2183 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2185 [o_about showGPL: sender];
2188 - (IBAction)viewHelp:(id)sender
2190 if( !nib_about_loaded )
2192 nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2199 - (IBAction)openReadMe:(id)sender
2201 NSString * o_path = [[NSBundle mainBundle]
2202 pathForResource: @"README.MacOSX" ofType: @"rtf"];
2204 [[NSWorkspace sharedWorkspace] openFile: o_path
2205 withApplication: @"TextEdit"];
2208 - (IBAction)openDocumentation:(id)sender
2210 NSURL * o_url = [NSURL URLWithString:
2211 @"http://www.videolan.org/doc/"];
2213 [[NSWorkspace sharedWorkspace] openURL: o_url];
2216 - (IBAction)openWebsite:(id)sender
2218 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2220 [[NSWorkspace sharedWorkspace] openURL: o_url];
2223 - (IBAction)openForum:(id)sender
2225 NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2227 [[NSWorkspace sharedWorkspace] openURL: o_url];
2230 - (IBAction)openDonate:(id)sender
2232 NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2234 [[NSWorkspace sharedWorkspace] openURL: o_url];
2238 #pragma mark Crash Log
2239 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2241 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2242 NSURL *url = [NSURL URLWithString:urlStr];
2244 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2245 [req setHTTPMethod:@"POST"];
2248 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2250 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2251 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2252 email = [emails valueAtIndex:[emails indexForIdentifier:
2253 [emails primaryIdentifier]]];
2256 email = [NSString string];
2259 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2260 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2261 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2262 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2264 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2266 /* Released from delegate */
2267 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2270 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2272 NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2273 _NS("Thanks for your report!"),
2274 _NS("OK"), nil, nil, nil);
2275 [crashLogURLConnection release];
2276 crashLogURLConnection = nil;
2279 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2281 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2282 [crashLogURLConnection release];
2283 crashLogURLConnection = nil;
2286 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2288 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2289 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2291 NSString * latestLog = nil;
2292 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2293 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2294 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
2295 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2297 while (fname = [direnum nextObject])
2299 [direnum skipDescendents];
2300 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2302 NSArray * compo = [fname componentsSeparatedByString:@"_"];
2303 if( [compo count] < 3 ) continue;
2304 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2305 if( [compo count] < 4 ) continue;
2308 if( year < [[compo objectAtIndex:0] intValue] ||
2309 (year ==[[compo objectAtIndex:0] intValue] &&
2310 (month < [[compo objectAtIndex:1] intValue] ||
2311 (month ==[[compo objectAtIndex:1] intValue] &&
2312 (day < [[compo objectAtIndex:2] intValue] ||
2313 (day ==[[compo objectAtIndex:2] intValue] &&
2314 hours < [[compo objectAtIndex:3] intValue] ))))))
2316 year = [[compo objectAtIndex:0] intValue];
2317 month = [[compo objectAtIndex:1] intValue];
2318 day = [[compo objectAtIndex:2] intValue];
2319 hours = [[compo objectAtIndex:3] intValue];
2320 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2325 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2328 if( !previouslySeen )
2330 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
2331 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2332 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
2333 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2338 - (NSString *)latestCrashLogPath
2340 return [self latestCrashLogPathPreviouslySeen:YES];
2343 - (void)lookForCrashLog
2345 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2346 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2347 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2348 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2349 if( latestLog && !areCrashLogsTooOld )
2350 [NSApp runModalForWindow: o_crashrep_win];
2354 - (IBAction)crashReporterAction:(id)sender
2356 if( sender == o_crashrep_send_btn )
2357 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2360 [o_crashrep_win orderOut: sender];
2363 - (IBAction)openCrashLog:(id)sender
2365 NSString * latestLog = [self latestCrashLogPath];
2368 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2372 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.") );
2377 #pragma mark Remove old prefs
2379 - (void)_removeOldPreferences
2381 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2382 static const int kCurrentPreferencesVersion = 1;
2383 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2384 if( version >= kCurrentPreferencesVersion ) return;
2386 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
2387 NSUserDomainMask, YES);
2388 if( !libraries || [libraries count] == 0) return;
2389 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2391 /* File not found, don't attempt anything */
2392 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2393 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2395 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2399 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2400 _NS("We just found an older version of VLC's preferences files."),
2401 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2402 if( res != NSOKButton )
2404 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2408 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2410 /* Move the file to trash so that user can find them later */
2411 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2413 /* really reset the defaults from now on */
2414 [NSUserDefaults resetStandardUserDefaults];
2416 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2417 [[NSUserDefaults standardUserDefaults] synchronize];
2420 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2422 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2428 execl(path, path, NULL);
2432 #pragma mark Errors, warnings and messages
2434 - (IBAction)viewErrorsAndWarnings:(id)sender
2436 [[[self getCoreDialogProvider] getErrorPanel] showPanel];
2439 - (IBAction)showMessagesPanel:(id)sender
2441 [o_msgs_panel makeKeyAndOrderFront: sender];
2444 - (IBAction)showInformationPanel:(id)sender
2446 if(! nib_info_loaded )
2447 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2452 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2454 if( [o_notification object] == o_msgs_panel )
2455 [self updateMessageDisplay];
2458 - (void)updateMessageDisplay
2460 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2463 NSEnumerator * o_enum;
2465 [o_messages setString: @""];
2469 o_enum = [o_msg_arr objectEnumerator];
2471 while( ( o_msg = [o_enum nextObject] ) != nil )
2473 [o_messages insertText: o_msg];
2476 b_msg_arr_changed = NO;
2477 [o_msg_lock unlock];
2481 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2483 NSColor *o_white = [NSColor whiteColor];
2484 NSColor *o_red = [NSColor redColor];
2485 NSColor *o_yellow = [NSColor yellowColor];
2486 NSColor *o_gray = [NSColor grayColor];
2488 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2489 static const char * ppsz_type[4] = { ": ", " error: ",
2490 " warning: ", " debug: " };
2493 NSDictionary *o_attr;
2494 NSAttributedString *o_msg_color;
2496 int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2500 if( [o_msg_arr count] + 2 > 400 )
2502 unsigned rid[] = { 0, 1 };
2503 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
2504 numIndices: sizeof(rid)/sizeof(rid[0])];
2507 o_attr = [NSDictionary dictionaryWithObject: o_gray
2508 forKey: NSForegroundColorAttributeName];
2509 o_msg = [NSString stringWithFormat: @"%@%s",
2510 [[o_notification userInfo] objectForKey: @"Module"],
2512 o_msg_color = [[NSAttributedString alloc]
2513 initWithString: o_msg attributes: o_attr];
2514 [o_msg_arr addObject: [o_msg_color autorelease]];
2516 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2517 forKey: NSForegroundColorAttributeName];
2518 o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2519 o_msg_color = [[NSAttributedString alloc]
2520 initWithString: o_msg attributes: o_attr];
2521 [o_msg_arr addObject: [o_msg_color autorelease]];
2523 b_msg_arr_changed = YES;
2524 [o_msg_lock unlock];
2527 - (IBAction)saveDebugLog:(id)sender
2529 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2531 [saveFolderPanel setCanChooseDirectories: NO];
2532 [saveFolderPanel setCanChooseFiles: YES];
2533 [saveFolderPanel setCanSelectHiddenExtension: NO];
2534 [saveFolderPanel setCanCreateDirectories: YES];
2535 [saveFolderPanel setRequiredFileType: @"rtfd"];
2536 [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];
2539 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2542 if( returnCode == NSOKButton )
2544 b_returned = [o_messages writeRTFDToFile: [sheet filename] atomically: YES];
2546 msg_Warn( p_intf, "Error while saving the debug log" );
2551 #pragma mark Playlist toggling
2553 - (IBAction)togglePlaylist:(id)sender
2555 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2556 NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2557 /*First, check if the playlist is visible*/
2558 if( contentRect.size.height <= 169. )
2560 o_restore_rect = contentRect;
2561 b_restore_size = true;
2562 b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2565 if( o_size_with_playlist.height > 169. )
2566 o_rect.size.height = o_size_with_playlist.height;
2568 o_rect.size.height = 500.;
2570 if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2571 o_rect.size.width = o_size_with_playlist.width;
2573 o_rect.size.width = [o_window contentMinSize].width;
2575 o_rect.origin.x = contentRect.origin.x;
2576 o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2577 [o_window contentMinSize].height;
2579 o_rect = [o_window frameRectForContentRect:o_rect];
2581 NSRect screenRect = [[o_window screen] visibleFrame];
2582 if( !NSContainsRect( screenRect, o_rect ) ) {
2583 if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2584 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2585 if( NSMinY(o_rect) < NSMinY(screenRect) )
2586 o_rect.origin.y = ( NSMinY(screenRect) );
2589 [o_btn_playlist setState: YES];
2593 NSSize curSize = o_rect.size;
2594 if( b_restore_size )
2596 o_rect = o_restore_rect;
2597 if( o_rect.size.height < [o_window contentMinSize].height )
2598 o_rect.size.height = [o_window contentMinSize].height;
2599 if( o_rect.size.width < [o_window contentMinSize].width )
2600 o_rect.size.width = [o_window contentMinSize].width;
2604 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2606 o_rect.size.height = [o_window contentMinSize].height;
2607 o_rect.size.width = [o_window contentMinSize].width;
2608 o_rect.origin.x = contentRect.origin.x;
2609 /* Calculate the position of the lower right corner after resize */
2610 o_rect.origin.y = contentRect.origin.y +
2611 contentRect.size.height - [o_window contentMinSize].height;
2614 [o_playlist_view setAutoresizesSubviews: NO];
2615 [o_playlist_view removeFromSuperview];
2616 [o_btn_playlist setState: NO];
2617 b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2618 o_rect = [o_window frameRectForContentRect:o_rect];
2621 [o_window setFrame: o_rect display:YES animate: YES];
2624 - (void)updateTogglePlaylistState
2626 if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2627 [o_btn_playlist setState: NO];
2629 [o_btn_playlist setState: YES];
2631 [[self getPlaylist] outlineViewSelectionDidChange: NULL];
2634 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2637 /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2639 /*Stores the size the controller one resize, to be able to restore it when
2640 toggling the playlist*/
2641 o_size_with_playlist = proposedFrameSize;
2644 rect.size = proposedFrameSize;
2645 if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2647 if( b_small_window == NO )
2649 /* if large and going to small then hide */
2650 b_small_window = YES;
2651 [o_playlist_view setAutoresizesSubviews: NO];
2652 [o_playlist_view removeFromSuperview];
2654 return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2656 return proposedFrameSize;
2659 - (void)windowDidMove:(NSNotification *)notif
2661 b_restore_size = false;
2664 - (void)windowDidResize:(NSNotification *)notif
2666 if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2668 /* If large and coming from small then show */
2669 [o_playlist_view setAutoresizesSubviews: YES];
2670 NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2671 [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2672 [o_playlist_view setNeedsDisplay:YES];
2673 [[o_window contentView] addSubview: o_playlist_view];
2674 b_small_window = NO;
2676 [self updateTogglePlaylistState];
2683 @implementation VLCMain (NSMenuValidation)
2685 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2687 NSString *o_title = [o_mi title];
2688 BOOL bEnabled = TRUE;
2690 /* Recent Items Menu */
2691 if( [o_title isEqualToString: _NS("Clear Menu")] )
2693 NSMenu * o_menu = [o_mi_open_recent submenu];
2694 int i_nb_items = [o_menu numberOfItems];
2695 NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2696 recentDocumentURLs];
2697 UInt32 i_nb_docs = [o_docs count];
2699 if( i_nb_items > 1 )
2701 while( --i_nb_items )
2703 [o_menu removeItemAtIndex: 0];
2712 [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2718 o_url = [o_docs objectAtIndex: i_nb_docs];
2720 if( [o_url isFileURL] )
2722 o_doc = [o_url path];
2726 o_doc = [o_url absoluteString];
2729 [o_menu insertItemWithTitle: o_doc
2730 action: @selector(openRecentItem:)
2731 keyEquivalent: @"" atIndex: 0];
2733 if( i_nb_docs == 0 )
2749 @implementation VLCMain (Internal)
2751 - (void)handlePortMessage:(NSPortMessage *)o_msg
2756 NSInvocation * o_inv;
2757 NSConditionLock * o_lock;
2759 o_data = [[o_msg components] lastObject];
2760 o_inv = *((NSInvocation **)[o_data bytes]);
2761 [o_inv getArgument: &o_value atIndex: 2];
2762 val = (id **)[o_value pointerValue];
2763 [o_inv setArgument: val[1] atIndex: 2];
2768 [o_lock unlockWithCondition: 1];