d3d609fdcd5a484e81f35c95eb6e6f314ac25848
[vlc.git] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface plugin
3  *****************************************************************************
4  * Copyright (C) 2002-2003 VideoLAN
5  * $Id: intf.m,v 1.91 2003/06/30 01:51:10 hartman Exp $
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Christophe Massiot <massiot@via.ecp.fr>
9  *          Derk-Jan Hartman <thedj@users.sourceforge.net>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  * 
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <stdlib.h>                                      /* malloc(), free() */
30 #include <sys/param.h>                                    /* for MAXPATHLEN */
31 #include <string.h>
32
33 #include "intf.h"
34 #include "vout.h"
35 #include "prefs.h"
36 #include "playlist.h"
37 #include "info.h"
38 #include "controls.h"
39
40 /*****************************************************************************
41  * Local prototypes.
42  *****************************************************************************/
43 static void Run ( intf_thread_t *p_intf );
44
45 /*****************************************************************************
46  * OpenIntf: initialize interface
47  *****************************************************************************/
48 int E_(OpenIntf) ( vlc_object_t *p_this )
49 {   
50     intf_thread_t *p_intf = (intf_thread_t*) p_this;
51
52     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
53     if( p_intf->p_sys == NULL )
54     {
55         return( 1 );
56     }
57
58     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
59     
60     p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
61     
62     /* Put Cocoa into multithread mode as soon as possible.
63      * http://developer.apple.com/techpubs/macosx/Cocoa/
64      * TasksAndConcepts/ProgrammingTopics/Multithreading/index.html
65      * This thread does absolutely nothing at all. */
66     [NSThread detachNewThreadSelector:@selector(self) toTarget:[NSString string] withObject:nil];
67     
68     p_intf->p_sys->o_sendport = [[NSPort port] retain];
69     p_intf->p_sys->p_sub = msg_Subscribe( p_intf );
70     p_intf->pf_run = Run;
71     
72     [[VLCApplication sharedApplication] autorelease];
73     [NSApp initIntlSupport];
74     [NSApp setIntf: p_intf];
75
76     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
77
78     return( 0 );
79 }
80
81 /*****************************************************************************
82  * CloseIntf: destroy interface
83  *****************************************************************************/
84 void E_(CloseIntf) ( vlc_object_t *p_this )
85 {
86     intf_thread_t *p_intf = (intf_thread_t*) p_this;
87
88     msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
89
90     [p_intf->p_sys->o_sendport release];
91     [p_intf->p_sys->o_pool release];
92
93     free( p_intf->p_sys );
94 }
95
96 /*****************************************************************************
97  * Run: main loop
98  *****************************************************************************/
99 static void Run( intf_thread_t *p_intf )
100 {
101     /* Do it again - for some unknown reason, vlc_thread_create() often
102      * fails to go to real-time priority with the first launched thread
103      * (???) --Meuuh */
104     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
105
106     [NSApp run];
107 }
108
109 /*****************************************************************************
110  * VLCApplication implementation 
111  *****************************************************************************/
112 @implementation VLCApplication
113
114 - (id)init
115 {
116     /* default encoding: ISO-8859-1 */
117     i_encoding = NSUTF8StringEncoding;
118
119     return( [super init] );
120 }
121
122 - (void)initIntlSupport
123 {
124 }
125
126 - (NSString *)localizedString:(char *)psz
127 {
128     NSString * o_str = nil;
129
130     if( psz != NULL )
131     {
132         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
133     }
134     if ( o_str == NULL )
135     {
136         msg_Err( p_intf, "could not translate: %s", psz );
137     }
138
139     return( o_str );
140 }
141
142 - (char *)delocalizeString:(NSString *)id
143 {
144     NSData * o_data = [id dataUsingEncoding: i_encoding
145                           allowLossyConversion: NO];
146     char * psz_string;
147
148     if ( o_data == nil )
149     {
150         o_data = [id dataUsingEncoding: i_encoding
151                      allowLossyConversion: YES];
152         psz_string = malloc( [o_data length] + 1 ); 
153         [o_data getBytes: psz_string];
154         psz_string[ [o_data length] ] = '\0';
155         msg_Err( p_intf, "cannot convert to wanted encoding: %s",
156                  psz_string );
157     }
158     else
159     {
160         psz_string = malloc( [o_data length] + 1 ); 
161         [o_data getBytes: psz_string];
162         psz_string[ [o_data length] ] = '\0';
163     }
164
165     return psz_string;
166 }
167
168 - (NSStringEncoding)getEncoding
169 {
170     return i_encoding;
171 }
172
173 /* i_width is in pixels */
174 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
175 {
176     NSMutableString *o_wrapped;
177     NSString *o_out_string;
178     NSRange glyphRange, effectiveRange, charRange;
179     NSRect lineFragmentRect;
180     unsigned glyphIndex, breaksInserted = 0;
181
182     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
183         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
184         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
185     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
186     NSTextContainer *o_container = [[NSTextContainer alloc]
187         initWithContainerSize: NSMakeSize(i_width, 2000)];
188     
189     [o_layout_manager addTextContainer: o_container];
190     [o_container release];
191     [o_storage addLayoutManager: o_layout_manager];
192     [o_layout_manager release];
193         
194     o_wrapped = [o_in_string mutableCopy];
195     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
196     
197     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
198             glyphIndex += effectiveRange.length) {
199         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
200                                             effectiveRange: &effectiveRange];
201         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
202                                     actualGlyphRange: &effectiveRange];
203         if ([o_wrapped lineRangeForRange:
204                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
205             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
206             breaksInserted++;
207         }
208     }
209     o_out_string = [NSString stringWithString: o_wrapped];
210     [o_wrapped release];
211     [o_storage release];
212     
213     return o_out_string;
214 }
215
216 - (void)setIntf:(intf_thread_t *)_p_intf
217 {
218     p_intf = _p_intf;
219 }
220
221 - (intf_thread_t *)getIntf
222 {
223     return( p_intf );
224 }
225
226 - (void)terminate:(id)sender
227 {
228     p_intf->p_vlc->b_die = VLC_TRUE;
229 }
230
231 @end
232
233 int ExecuteOnMainThread( id target, SEL sel, void * p_arg )
234 {
235     int i_ret = 0;
236
237     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
238
239     if( [target respondsToSelector: @selector(performSelectorOnMainThread:
240                                              withObject:waitUntilDone:)] )
241     {
242         [target performSelectorOnMainThread: sel
243                 withObject: [NSValue valueWithPointer: p_arg]
244                 waitUntilDone: YES];
245     }
246     else if( NSApp != nil && [NSApp respondsToSelector: @selector(getIntf)] ) 
247     {
248         NSValue * o_v1;
249         NSValue * o_v2;
250         NSArray * o_array;
251         NSPort * o_recv_port;
252         NSInvocation * o_inv;
253         NSPortMessage * o_msg;
254         intf_thread_t * p_intf;
255         NSConditionLock * o_lock;
256         NSMethodSignature * o_sig;
257
258         id * val[] = { &o_lock, &o_v2 };
259
260         p_intf = (intf_thread_t *)[NSApp getIntf];
261
262         o_recv_port = [[NSPort port] retain];
263         o_v1 = [NSValue valueWithPointer: val]; 
264         o_v2 = [NSValue valueWithPointer: p_arg];
265
266         o_sig = [target methodSignatureForSelector: sel];
267         o_inv = [NSInvocation invocationWithMethodSignature: o_sig];
268         [o_inv setArgument: &o_v1 atIndex: 2];
269         [o_inv setTarget: target];
270         [o_inv setSelector: sel];
271
272         o_array = [NSArray arrayWithObject:
273             [NSData dataWithBytes: &o_inv length: sizeof(o_inv)]];
274         o_msg = [[NSPortMessage alloc]
275             initWithSendPort: p_intf->p_sys->o_sendport
276             receivePort: o_recv_port components: o_array];
277
278         o_lock = [[NSConditionLock alloc] initWithCondition: 0];
279         [o_msg sendBeforeDate: [NSDate distantPast]];
280         [o_lock lockWhenCondition: 1];
281         [o_lock unlock];
282         [o_lock release];
283
284         [o_msg release];
285         [o_recv_port release];
286     } 
287     else
288     {
289         i_ret = 1;
290     }
291
292     [o_pool release];
293
294     return( i_ret );
295 }
296
297 /*****************************************************************************
298  * playlistChanged: Callback triggered by the intf-change playlist
299  * variable, to let the intf update the playlist.
300  *****************************************************************************/
301 int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
302                      vlc_value_t old_val, vlc_value_t new_val, void *param )
303 {
304     intf_thread_t * p_intf = [NSApp getIntf];
305     p_intf->p_sys->b_playlist_update = VLC_TRUE;
306     p_intf->p_sys->b_intf_update = VLC_TRUE;
307     return VLC_SUCCESS;
308 }
309
310 /*****************************************************************************
311  * VLCMain implementation 
312  *****************************************************************************/
313 @implementation VLCMain
314
315 - (void)awakeFromNib
316 {
317     [o_window setTitle: _NS("VLC - Controller")];
318     [o_window setExcludedFromWindowsMenu: TRUE];
319
320     /* button controls */
321     [o_btn_playlist setToolTip: _NS("Playlist")];
322     [o_btn_prev setToolTip: _NS("Previous")];
323     [o_btn_slower setToolTip: _NS("Slower")];
324     [o_btn_play setToolTip: _NS("Play")];
325     [o_btn_stop setToolTip: _NS("Stop")];
326     [o_btn_faster setToolTip: _NS("Faster")];
327     [o_btn_next setToolTip: _NS("Next")];
328     [o_btn_prefs setToolTip: _NS("Preferences")];
329     [o_volumeslider setToolTip: _NS("Volume")];
330     [o_timeslider setToolTip: _NS("Position")];
331
332     /* messages panel */ 
333     [o_msgs_panel setDelegate: self];
334     [o_msgs_panel setTitle: _NS("Messages")];
335     [o_msgs_panel setExcludedFromWindowsMenu: TRUE];
336     [o_msgs_btn_crashlog setTitle: _NS("Open CrashLog")];
337
338     /* main menu */
339     [o_mi_about setTitle: _NS("About VLC media player")];
340     [o_mi_prefs setTitle: _NS("Preferences...")];
341     [o_mi_hide setTitle: _NS("Hide VLC")];
342     [o_mi_hide_others setTitle: _NS("Hide Others")];
343     [o_mi_show_all setTitle: _NS("Show All")];
344     [o_mi_quit setTitle: _NS("Quit VLC")];
345
346     [o_mu_file setTitle: _ANS("1:File")];
347     [o_mi_open_generic setTitle: _NS("Open...")];
348     [o_mi_open_file setTitle: _NS("Open File...")];
349     [o_mi_open_disc setTitle: _NS("Open Disc...")];
350     [o_mi_open_net setTitle: _NS("Open Network...")];
351     [o_mi_open_recent setTitle: _NS("Open Recent")];
352     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
353
354     [o_mu_edit setTitle: _NS("Edit")];
355     [o_mi_cut setTitle: _NS("Cut")];
356     [o_mi_copy setTitle: _NS("Copy")];
357     [o_mi_paste setTitle: _NS("Paste")];
358     [o_mi_clear setTitle: _NS("Clear")];
359     [o_mi_select_all setTitle: _NS("Select All")];
360
361     [o_mu_controls setTitle: _NS("Controls")];
362     [o_mi_play setTitle: _NS("Play")];
363     [o_mi_stop setTitle: _NS("Stop")];
364     [o_mi_faster setTitle: _NS("Faster")];
365     [o_mi_slower setTitle: _NS("Slower")];
366     [o_mi_previous setTitle: _NS("Previous")];
367     [o_mi_next setTitle: _NS("Next")];
368     [o_mi_loop setTitle: _NS("Loop")];
369     [o_mi_fwd setTitle: _NS("Step Forward")];
370     [o_mi_bwd setTitle: _NS("Step Backward")];
371     [o_mi_program setTitle: _NS("Program")];
372     [o_mu_program setTitle: _NS("Program")];
373     [o_mi_title setTitle: _NS("Title")];
374     [o_mu_title setTitle: _NS("Title")];
375     [o_mi_chapter setTitle: _NS("Chapter")];
376     [o_mu_chapter setTitle: _NS("Chapter")];
377     
378     [o_mu_audio setTitle: _NS("Audio")];
379     [o_mi_vol_up setTitle: _NS("Volume Up")];
380     [o_mi_vol_down setTitle: _NS("Volume Down")];
381     [o_mi_mute setTitle: _NS("Mute")];
382     [o_mi_audiotrack setTitle: _NS("Audio track")];
383     [o_mu_audiotrack setTitle: _NS("Audio track")];
384     [o_mi_channels setTitle: _NS("Audio channels")];
385     [o_mu_channels setTitle: _NS("Audio channels")];
386     [o_mi_device setTitle: _NS("Audio device")];
387     [o_mu_device setTitle: _NS("Audio device")];
388     
389     [o_mu_video setTitle: _NS("Video")];
390     [o_mi_half_window setTitle: _NS("Half Size")];
391     [o_mi_normal_window setTitle: _NS("Normal Size")];
392     [o_mi_double_window setTitle: _NS("Double Size")];
393     [o_mi_fittoscreen setTitle: _NS("Fit To Screen")];
394     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
395     [o_mi_floatontop setTitle: _NS("Float On Top")];
396     [o_mi_videotrack setTitle: _NS("Video track")];
397     [o_mu_videotrack setTitle: _NS("Video track")];
398     [o_mi_screen setTitle: _NS("Video device")];
399     [o_mu_screen setTitle: _NS("Video device")];
400     [o_mi_subtitle setTitle: _NS("Subtitles track")];
401     [o_mu_subtitle setTitle: _NS("Subtitles track")];
402     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
403     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
404
405     [o_mu_window setTitle: _NS("Window")];
406     [o_mi_minimize setTitle: _NS("Minimize Window")];
407     [o_mi_close_window setTitle: _NS("Close Window")];
408     [o_mi_controller setTitle: _NS("Controller")];
409     [o_mi_playlist setTitle: _NS("Playlist")];
410     [o_mi_info setTitle: _NS("Info")];
411     [o_mi_messages setTitle: _NS("Messages")];
412
413     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
414
415     [o_mu_help setTitle: _NS("Help")];
416     [o_mi_readme setTitle: _NS("ReadMe...")];
417     [o_mi_documentation setTitle: _NS("Online Documentation")];
418     [o_mi_reportabug setTitle: _NS("Report a Bug")];
419     [o_mi_website setTitle: _NS("VideoLAN Website")];
420     [o_mi_license setTitle: _NS("License")];
421
422     /* dock menu */
423     [o_dmi_play setTitle: _NS("Play")];
424     [o_dmi_stop setTitle: _NS("Stop")];
425     [o_dmi_next setTitle: _NS("Next")];
426     [o_dmi_previous setTitle: _NS("Previous")];
427
428     /* error panel */
429     [o_error setTitle: _NS("Error")];
430     [o_err_lbl setStringValue: _NS("An error has occurred which probably prevented the execution of your request:")];
431     [o_err_bug_lbl setStringValue: _NS("If you believe that it is a bug, please follow the instructions at:")]; 
432     [o_err_btn_msgs setTitle: _NS("Open Messages Window")];
433     [o_err_btn_dismiss setTitle: _NS("Dismiss")];
434
435     [o_info_window setTitle: _NS("Info")];
436
437     [self setSubmenusEnabled: FALSE];
438     [self manageVolumeSlider];
439 }
440
441 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
442 {
443     intf_thread_t * p_intf = [NSApp getIntf];
444
445     o_msg_lock = [[NSLock alloc] init];
446     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
447
448     o_img_play = [[NSImage imageNamed: @"play"] retain];
449     o_img_pause = [[NSImage imageNamed: @"pause"] retain];
450
451     [p_intf->p_sys->o_sendport setDelegate: self];
452     [[NSRunLoop currentRunLoop] 
453         addPort: p_intf->p_sys->o_sendport
454         forMode: NSDefaultRunLoopMode];
455
456     [NSTimer scheduledTimerWithTimeInterval: 0.5
457         target: self selector: @selector(manageIntf:)
458         userInfo: nil repeats: FALSE];
459
460     [NSThread detachNewThreadSelector: @selector(manage)
461         toTarget: self withObject: nil];
462
463     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
464 }
465
466 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
467 {
468     intf_thread_t * p_intf = [NSApp getIntf];
469     
470     config_PutPsz( p_intf, "sub-file", "" );
471     config_PutInt( p_intf, "sub-delay", 0 );
472     config_PutFloat( p_intf, "sub-fps", 0.0 );
473     config_PutPsz( p_intf, "sout", "" );
474     
475     [o_playlist appendArray:
476         [NSArray arrayWithObject: o_filename] atPos: -1 enqueue: NO];
477             
478     return( TRUE );
479 }
480
481 - (id)getControls
482 {
483     if ( o_controls )
484     {
485         return o_controls;
486     }
487     return nil;
488 }
489
490 - (void)manage
491 {
492     NSDate * o_sleep_date;
493     intf_thread_t * p_intf = [NSApp getIntf];
494     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
495
496     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
497
498     while( !p_intf->b_die )
499     {
500         playlist_t * p_playlist;
501
502         vlc_mutex_lock( &p_intf->change_lock );
503
504         p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
505                                               FIND_ANYWHERE );
506
507         if( p_playlist != NULL )
508         {
509             var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
510             vlc_mutex_lock( &p_playlist->object_lock );
511             
512             [self manage: p_playlist];
513             
514             vlc_mutex_unlock( &p_playlist->object_lock );
515             vlc_object_release( p_playlist );
516         }
517
518         vlc_mutex_unlock( &p_intf->change_lock );
519
520         o_sleep_date = [NSDate dateWithTimeIntervalSinceNow: .5];
521         [NSThread sleepUntilDate: o_sleep_date];
522     }
523
524     [self terminate];
525
526     [o_pool release];
527 }
528
529 - (void)manage:(playlist_t *)p_playlist
530 {
531     intf_thread_t * p_intf = [NSApp getIntf];
532
533 #define p_input p_playlist->p_input
534
535     if( p_input )
536     {
537         vlc_mutex_lock( &p_input->stream.stream_lock );
538
539         if( !p_input->b_die )
540         {
541             /* New input or stream map change */
542             if( p_input->stream.b_changed )
543             {
544                 p_intf->p_sys->b_playing = TRUE;
545                 [self manageMode: p_playlist];
546             }
547
548             vlc_value_t val;
549
550             if( var_Get( (vlc_object_t *)p_input, "intf-change", &val )
551                 >= 0 && val.b_bool )
552             {
553                 p_intf->p_sys->b_input_update = TRUE;
554             }
555         }
556         vlc_mutex_unlock( &p_input->stream.stream_lock );
557     }
558     else if( p_intf->p_sys->b_playing && !p_intf->b_die )
559     {
560         p_intf->p_sys->b_playing = FALSE;
561         [self manageMode: p_playlist];
562     }
563
564 #undef p_input
565 }
566
567 - (void)manageMode:(playlist_t *)p_playlist
568 {
569     intf_thread_t * p_intf = [NSApp getIntf];
570
571     if( p_playlist->p_input != NULL )
572     {
573         p_intf->p_sys->b_current_title_update = 1;
574         p_playlist->p_input->stream.b_changed = 0;
575         
576         msg_Dbg( p_intf, "stream has changed, refreshing interface" );
577     }
578     else
579     {
580         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
581                                                           FIND_ANYWHERE );
582         if( p_vout != NULL )
583         {
584             vlc_object_detach( p_vout );
585             vlc_object_release( p_vout );
586
587             vlc_mutex_unlock( &p_playlist->object_lock );
588             vout_Destroy( p_vout );
589             vlc_mutex_lock( &p_playlist->object_lock );
590         }
591     }
592
593     p_intf->p_sys->b_intf_update = VLC_TRUE;
594 }
595
596 - (void)manageIntf:(NSTimer *)o_timer
597 {
598     intf_thread_t * p_intf = [NSApp getIntf];
599
600     if( p_intf->p_vlc->b_die == VLC_TRUE )
601     {
602         [o_timer invalidate];
603         return;
604     }
605
606     playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
607                                                        FIND_ANYWHERE );
608
609     if( p_playlist == NULL )
610     {
611         return;
612     }
613
614     if ( p_intf->p_sys->b_playlist_update )
615     {
616         [o_playlist playlistUpdated];
617         p_intf->p_sys->b_playlist_update = VLC_FALSE;
618     }
619
620     if( p_intf->p_sys->b_current_title_update )
621     {
622         vout_thread_t   *p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
623                                               FIND_ANYWHERE );
624         if( p_vout != NULL )
625         {
626             /* We need to lock the vout here to make sure it does not disappear */
627             id o_vout_wnd;
628             NSEnumerator * o_enum = [[NSApp windows] objectEnumerator];
629             
630             while( ( o_vout_wnd = [o_enum nextObject] ) )
631             {
632                 if( [[o_vout_wnd className] isEqualToString: @"VLCWindow"] )
633                 {
634                     [o_vout_wnd updateTitle];
635                 }
636             }
637             vlc_object_release( (vlc_object_t *)p_vout );
638         }
639         [o_playlist updateRowSelection];
640         [o_info updateInfo];
641
642         p_intf->p_sys->b_current_title_update = FALSE;
643     }
644
645     vlc_mutex_lock( &p_playlist->object_lock );
646
647 #define p_input p_playlist->p_input
648
649     if( p_input != NULL )
650     {
651         vlc_mutex_lock( &p_input->stream.stream_lock );
652     }
653
654     if( p_intf->p_sys->b_intf_update )
655     {
656         vlc_bool_t b_input = VLC_FALSE;
657         vlc_bool_t b_plmul = VLC_FALSE;
658         vlc_bool_t b_control = VLC_FALSE;
659         vlc_bool_t b_seekable = VLC_FALSE;
660         vlc_bool_t b_chapters = VLC_FALSE;
661
662         b_plmul = p_playlist->i_size > 1;
663
664         if( ( b_input = ( p_input != NULL ) ) )
665         {
666             /* seekable streams */
667             b_seekable = p_input->stream.b_seekable;
668
669             /* control buttons for free pace streams */
670             b_control = p_input->stream.b_pace_control; 
671
672             /* chapters & titles */
673             b_chapters = p_input->stream.i_area_nb > 1; 
674
675             /* play status */
676             p_intf->p_sys->b_play_status = 
677                 p_input->stream.control.i_status != PAUSE_S;
678         }
679         else
680         {
681             /* play status */
682             p_intf->p_sys->b_play_status = FALSE;
683             [self setSubmenusEnabled: FALSE];
684         }
685
686         [self playStatusUpdated: p_intf->p_sys->b_play_status];
687
688         [o_btn_stop setEnabled: b_input];
689         [o_btn_faster setEnabled: b_control];
690         [o_btn_slower setEnabled: b_control];
691         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
692         [o_btn_next setEnabled: (b_plmul || b_chapters)];
693
694         [o_timeslider setFloatValue: 0.0];
695         [o_timeslider setEnabled: b_seekable];
696         [o_timefield setStringValue: @"0:00:00"];
697
698         [self manageVolumeSlider];
699
700         p_intf->p_sys->b_intf_update = VLC_FALSE;
701     }
702
703 #define p_area p_input->stream.p_selected_area
704
705     if( p_intf->p_sys->b_playing && p_input != NULL )
706     {
707         vlc_bool_t b_field_update = TRUE;
708
709         if( !p_input->b_die && ( p_intf->p_sys->b_play_status !=
710             ( p_input->stream.control.i_status != PAUSE_S ) ) ) 
711         {
712             p_intf->p_sys->b_play_status =
713                 !p_intf->p_sys->b_play_status;
714
715             [self playStatusUpdated: p_intf->p_sys->b_play_status]; 
716         }
717
718         if( p_input->stream.b_seekable )
719         {
720             if( f_slider == f_slider_old )
721             {
722                 float f_updated = ( 10000. * p_area->i_tell ) /
723                                            p_area->i_size;
724
725                 if( f_slider != f_updated )
726                 {
727                     [o_timeslider setFloatValue: f_updated];
728                 }
729             }
730             else
731             {
732                 off_t i_seek = ( f_slider * p_area->i_size ) / 10000;
733
734                 /* release the lock to be able to seek */
735                 vlc_mutex_unlock( &p_input->stream.stream_lock );
736                 input_Seek( p_input, i_seek, INPUT_SEEK_SET );
737                 vlc_mutex_lock( &p_input->stream.stream_lock );
738
739                 /* update the old value */
740                 f_slider_old = f_slider; 
741
742                 b_field_update = VLC_FALSE;
743             }
744         }
745
746         if( b_field_update )
747         {
748             NSString * o_time;
749             char psz_time[ OFFSETTOTIME_MAX_SIZE ];
750
751             input_OffsetToTime( p_input, psz_time, p_area->i_tell );
752
753             o_time = [NSString stringWithUTF8String: psz_time];
754             [o_timefield setStringValue: o_time];
755         }
756
757         /* disable screen saver */
758         UpdateSystemActivity( UsrActivity );
759     }
760
761 #undef p_area
762
763     if( p_input != NULL )
764     {
765         vlc_mutex_unlock( &p_input->stream.stream_lock );
766     }
767
768 #undef p_input
769
770     vlc_mutex_unlock( &p_playlist->object_lock );
771     vlc_object_release( p_playlist );
772
773     [self updateMessageArray];
774
775     [NSTimer scheduledTimerWithTimeInterval: 0.5
776         target: self selector: @selector(manageIntf:)
777         userInfo: nil repeats: FALSE];
778 }
779
780 - (void)setupMenus
781 {
782     intf_thread_t * p_intf = [NSApp getIntf];
783     playlist_t *p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
784                                                 FIND_ANYWHERE );
785     
786     if( p_playlist != NULL )
787     {
788 #define p_input p_playlist->p_input
789         if( p_input != NULL )
790         {
791             [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
792                 var: "program" selector: @selector(toggleVar:)];
793             
794             [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
795                 var: "title" selector: @selector(toggleVar:)];
796             
797             [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
798                 var: "chapter" selector: @selector(toggleVar:)];
799             
800             [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
801                 var: "audio-es" selector: @selector(toggleVar:)];
802             
803             [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
804                 var: "video-es" selector: @selector(toggleVar:)];
805             
806             [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
807                 var: "spu-es" selector: @selector(toggleVar:)];
808         
809             aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
810                                                         FIND_ANYWHERE );
811             if ( p_aout != NULL )
812             {
813                 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
814                     var: "audio-channels" selector: @selector(toggleVar:)];
815             
816                 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
817                     var: "audio-device" selector: @selector(toggleVar:)];
818                 vlc_object_release( (vlc_object_t *)p_aout );
819             }
820             
821             vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
822                                                                 FIND_ANYWHERE );
823             
824             if ( p_vout != NULL )
825             {
826                 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
827                     var: "video-device" selector: @selector(toggleVar:)];
828                 
829                 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
830                     var: "deinterlace" selector: @selector(toggleVar:)];
831                 vlc_object_release( (vlc_object_t *)p_vout );
832             }
833         }
834 #undef p_input
835     }
836     vlc_object_release( (vlc_object_t *)p_playlist );
837 }
838
839 - (void)updateMessageArray
840 {
841     int i_start, i_stop;
842     intf_thread_t * p_intf = [NSApp getIntf];
843
844     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
845     i_stop = *p_intf->p_sys->p_sub->pi_stop;
846     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
847
848     if( p_intf->p_sys->p_sub->i_start != i_stop )
849     {
850         NSColor *o_white = [NSColor whiteColor];
851         NSColor *o_red = [NSColor redColor];
852         NSColor *o_yellow = [NSColor yellowColor];
853         NSColor *o_gray = [NSColor grayColor];
854
855         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
856         static const char * ppsz_type[4] = { ": ", " error: ",
857                                              " warning: ", " debug: " };
858
859         for( i_start = p_intf->p_sys->p_sub->i_start;
860              i_start != i_stop;
861              i_start = (i_start+1) % VLC_MSG_QSIZE )
862         {
863             NSString *o_msg;
864             NSDictionary *o_attr;
865             NSAttributedString *o_msg_color;
866
867             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
868
869             [o_msg_lock lock];
870
871             if( [o_msg_arr count] + 2 > 400 )
872             {
873                 unsigned rid[] = { 0, 1 };
874                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
875                            numIndices: sizeof(rid)/sizeof(rid[0])];
876             }
877
878             o_attr = [NSDictionary dictionaryWithObject: o_gray
879                 forKey: NSForegroundColorAttributeName];
880             o_msg = [NSString stringWithFormat: @"%s%s",
881                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
882                 ppsz_type[i_type]];
883             o_msg_color = [[NSAttributedString alloc]
884                 initWithString: o_msg attributes: o_attr];
885             [o_msg_arr addObject: [o_msg_color autorelease]];
886
887             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
888                 forKey: NSForegroundColorAttributeName];
889             o_msg = [NSString stringWithFormat: @"%s\n",
890                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
891             o_msg_color = [[NSAttributedString alloc]
892                 initWithString: o_msg attributes: o_attr];
893             [o_msg_arr addObject: [o_msg_color autorelease]];
894
895             [o_msg_lock unlock];
896
897             if( i_type == 1 )
898             {
899                 NSString *o_my_msg = [NSString stringWithFormat: @"%s: %s\n",
900                     p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
901                     p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
902
903                 NSRange s_r = NSMakeRange( [[o_err_msg string] length], 0 );
904                 [o_err_msg setEditable: YES];
905                 [o_err_msg setSelectedRange: s_r];
906                 [o_err_msg insertText: o_my_msg];
907
908                 [o_error makeKeyAndOrderFront: self];
909                 [o_err_msg setEditable: NO];
910             }
911         }
912
913         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
914         p_intf->p_sys->p_sub->i_start = i_start;
915         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
916     }
917 }
918
919 - (void)playStatusUpdated:(BOOL)b_pause
920 {
921     if( b_pause )
922     {
923         [o_btn_play setImage: o_img_pause];
924         [o_btn_play setToolTip: _NS("Pause")];
925         [o_mi_play setTitle: _NS("Pause")];
926         [o_dmi_play setTitle: _NS("Pause")];
927     }
928     else
929     {
930         [o_btn_play setImage: o_img_play];
931         [o_btn_play setToolTip: _NS("Play")];
932         [o_mi_play setTitle: _NS("Play")];
933         [o_dmi_play setTitle: _NS("Play")];
934     }
935 }
936
937 - (void)setSubmenusEnabled:(BOOL)b_enabled
938 {
939     [o_mi_program setEnabled: b_enabled];
940     [o_mi_title setEnabled: b_enabled];
941     [o_mi_chapter setEnabled: b_enabled];
942     [o_mi_audiotrack setEnabled: b_enabled];
943     [o_mi_videotrack setEnabled: b_enabled];
944     [o_mi_subtitle setEnabled: b_enabled];
945     [o_mi_channels setEnabled: b_enabled];
946     [o_mi_deinterlace setEnabled: b_enabled];
947     [o_mi_device setEnabled: b_enabled];
948     [o_mi_screen setEnabled: b_enabled];
949 }
950
951 - (void)manageVolumeSlider
952 {
953     audio_volume_t i_volume;
954     intf_thread_t * p_intf = [NSApp getIntf];
955
956     aout_VolumeGet( p_intf, &i_volume );
957
958     [o_volumeslider setFloatValue: (float)i_volume / AOUT_VOLUME_STEP]; 
959     [o_volumeslider setEnabled: TRUE];
960
961     p_intf->p_sys->b_mute = ( i_volume == 0 );
962 }
963
964 - (IBAction)timesliderUpdate:(id)sender
965 {
966     float f_updated;
967
968     switch( [[NSApp currentEvent] type] )
969     {
970         case NSLeftMouseUp:
971         case NSLeftMouseDown:
972             f_slider = [sender floatValue];
973             return;
974
975         case NSLeftMouseDragged:
976             f_updated = [sender floatValue];
977             break;
978
979         default:
980             return;
981     }
982
983     intf_thread_t * p_intf = [NSApp getIntf];
984
985     playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
986                                                        FIND_ANYWHERE );
987
988     if( p_playlist == NULL )
989     {
990         return;
991     }
992
993     vlc_mutex_lock( &p_playlist->object_lock );
994
995     if( p_playlist->p_input != NULL )
996     {
997         off_t i_tell;
998         NSString * o_time;
999         char psz_time[ OFFSETTOTIME_MAX_SIZE ];
1000
1001 #define p_area p_playlist->p_input->stream.p_selected_area
1002         vlc_mutex_lock( &p_playlist->p_input->stream.stream_lock );
1003         i_tell = f_updated / 10000. * p_area->i_size;
1004         input_OffsetToTime( p_playlist->p_input, psz_time, i_tell );
1005         vlc_mutex_unlock( &p_playlist->p_input->stream.stream_lock );
1006 #undef p_area
1007
1008         o_time = [NSString stringWithUTF8String: psz_time];
1009         [o_timefield setStringValue: o_time]; 
1010     }
1011
1012     vlc_mutex_unlock( &p_playlist->object_lock );
1013     vlc_object_release( p_playlist );
1014 }
1015
1016 - (void)terminate
1017 {
1018     NSEvent * o_event;
1019     vout_thread_t * p_vout;
1020     playlist_t * p_playlist;
1021     intf_thread_t * p_intf = [NSApp getIntf];
1022
1023     /*
1024      * Free playlists
1025      */
1026     msg_Dbg( p_intf, "removing all playlists" );
1027     while( (p_playlist = vlc_object_find( p_intf->p_vlc, VLC_OBJECT_PLAYLIST,
1028                                           FIND_CHILD )) )
1029     {
1030         vlc_object_detach( p_playlist );
1031         vlc_object_release( p_playlist );
1032         playlist_Destroy( p_playlist );
1033     }
1034
1035     /*
1036      * Free video outputs
1037      */
1038     msg_Dbg( p_intf, "removing all video outputs" );
1039     while( (p_vout = vlc_object_find( p_intf->p_vlc, 
1040                                       VLC_OBJECT_VOUT, FIND_CHILD )) )
1041     {
1042         vlc_object_detach( p_vout );
1043         vlc_object_release( p_vout );
1044         vout_Destroy( p_vout );
1045     }
1046
1047     if( o_img_pause != nil )
1048     {
1049         [o_img_pause release];
1050         o_img_pause = nil;
1051     }
1052
1053     if( o_img_play != nil )
1054     {
1055         [o_img_play release];
1056         o_img_play = nil;
1057     }
1058
1059     if( o_msg_arr != nil )
1060     {
1061         [o_msg_arr removeAllObjects];
1062         [o_msg_arr release];
1063         o_msg_arr = nil;
1064     }
1065
1066     if( o_msg_lock != nil )
1067     {
1068         [o_msg_lock release];
1069         o_msg_lock = nil;
1070     }
1071
1072     [NSApp stop: nil];
1073
1074     /* write cached user defaults to disk */
1075     [[NSUserDefaults standardUserDefaults] synchronize];
1076
1077     /* send a dummy event to break out of the event loop */
1078     o_event = [NSEvent mouseEventWithType: NSLeftMouseDown
1079                 location: NSMakePoint( 1, 1 ) modifierFlags: 0
1080                 timestamp: 1 windowNumber: [[NSApp mainWindow] windowNumber]
1081                 context: [NSGraphicsContext currentContext] eventNumber: 1
1082                 clickCount: 1 pressure: 0.0];
1083     [NSApp postEvent: o_event atStart: YES];
1084 }
1085
1086 - (IBAction)clearRecentItems:(id)sender
1087 {
1088     [[NSDocumentController sharedDocumentController]
1089                           clearRecentDocuments: nil];
1090 }
1091
1092 - (void)openRecentItem:(id)sender
1093 {
1094     [self application: nil openFile: [sender title]]; 
1095 }
1096
1097 - (IBAction)viewPreferences:(id)sender
1098 {
1099     [o_prefs showPrefs];
1100 }
1101
1102 - (IBAction)closeError:(id)sender
1103 {
1104     [o_err_msg setString: @""];
1105     [o_error performClose: self];
1106 }
1107
1108 - (IBAction)openReadMe:(id)sender
1109 {
1110     NSString * o_path = [[NSBundle mainBundle] 
1111         pathForResource: @"README.MacOSX" ofType: @"rtf"]; 
1112
1113     [[NSWorkspace sharedWorkspace] openFile: o_path 
1114                                    withApplication: @"TextEdit"];
1115 }
1116
1117 - (IBAction)openDocumentation:(id)sender
1118 {
1119     NSURL * o_url = [NSURL URLWithString: 
1120         @"http://www.videolan.org/doc/"];
1121
1122     [[NSWorkspace sharedWorkspace] openURL: o_url];
1123 }
1124
1125 - (IBAction)reportABug:(id)sender
1126 {
1127     NSURL * o_url = [NSURL URLWithString: 
1128         @"http://www.videolan.org/support/bug-reporting.html"];
1129
1130     [[NSWorkspace sharedWorkspace] openURL: o_url];
1131 }
1132
1133 - (IBAction)openWebsite:(id)sender
1134 {
1135     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org"];
1136
1137     [[NSWorkspace sharedWorkspace] openURL: o_url];
1138 }
1139
1140 - (IBAction)openLicense:(id)sender
1141 {
1142     NSString * o_path = [[NSBundle mainBundle] 
1143         pathForResource: @"COPYING" ofType: nil];
1144
1145     [[NSWorkspace sharedWorkspace] openFile: o_path 
1146                                    withApplication: @"TextEdit"];
1147 }
1148
1149 - (IBAction)openCrashLog:(id)sender
1150 {
1151     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
1152                                     stringByExpandingTildeInPath]; 
1153
1154     
1155     if ( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
1156     {
1157         [[NSWorkspace sharedWorkspace] openFile: o_path 
1158                                     withApplication: @"Console"];
1159     }
1160     else
1161     {
1162         NSBeginInformationalAlertSheet(_NS("No CrashLog found"), @"Continue", nil, nil, o_msgs_panel, self, NULL, NULL, nil, _NS("Either you are running Mac OS X pre 10.2 or you haven't experienced any heavy crashes yet.") );
1163
1164     }
1165 }
1166
1167 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1168 {
1169     if( [o_notification object] == o_msgs_panel )
1170     {
1171         id o_msg;
1172         NSEnumerator * o_enum;
1173
1174         [o_messages setString: @""]; 
1175
1176         [o_msg_lock lock];
1177
1178         o_enum = [o_msg_arr objectEnumerator];
1179
1180         while( ( o_msg = [o_enum nextObject] ) != nil )
1181         {
1182             [o_messages insertText: o_msg];
1183         }
1184
1185         [o_msg_lock unlock];
1186     }
1187 }
1188
1189 @end
1190
1191 @implementation VLCMain (NSMenuValidation)
1192
1193 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
1194 {
1195     NSString *o_title = [o_mi title];
1196     BOOL bEnabled = TRUE;
1197
1198     if( [o_title isEqualToString: _NS("License")] )
1199     {
1200         /* we need to do this only once */
1201         [self setupMenus];
1202     }
1203
1204     /* Recent Items Menu */
1205     if( [o_title isEqualToString: _NS("Clear Menu")] )
1206     {
1207         NSMenu * o_menu = [o_mi_open_recent submenu];
1208         int i_nb_items = [o_menu numberOfItems];
1209         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
1210                                                        recentDocumentURLs];
1211         UInt32 i_nb_docs = [o_docs count];
1212
1213         if( i_nb_items > 1 )
1214         {
1215             while( --i_nb_items )
1216             {
1217                 [o_menu removeItemAtIndex: 0];
1218             }
1219         }
1220
1221         if( i_nb_docs > 0 )
1222         {
1223             NSURL * o_url;
1224             NSString * o_doc;
1225
1226             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
1227
1228             while( TRUE )
1229             {
1230                 i_nb_docs--;
1231
1232                 o_url = [o_docs objectAtIndex: i_nb_docs];
1233
1234                 if( [o_url isFileURL] )
1235                 {
1236                     o_doc = [o_url path];
1237                 }
1238                 else
1239                 {
1240                     o_doc = [o_url absoluteString];
1241                 }
1242
1243                 [o_menu insertItemWithTitle: o_doc
1244                     action: @selector(openRecentItem:)
1245                     keyEquivalent: @"" atIndex: 0]; 
1246
1247                 if( i_nb_docs == 0 )
1248                 {
1249                     break;
1250                 }
1251             } 
1252         }
1253         else
1254         {
1255             bEnabled = FALSE;
1256         }
1257     }
1258     return( bEnabled );
1259 }
1260
1261 @end
1262
1263 @implementation VLCMain (Internal)
1264
1265 - (void)handlePortMessage:(NSPortMessage *)o_msg
1266 {
1267     id ** val;
1268     NSData * o_data;
1269     NSValue * o_value;
1270     NSInvocation * o_inv;
1271     NSConditionLock * o_lock;
1272  
1273     o_data = [[o_msg components] lastObject];
1274     o_inv = *((NSInvocation **)[o_data bytes]); 
1275     [o_inv getArgument: &o_value atIndex: 2];
1276     val = (id **)[o_value pointerValue];
1277     [o_inv setArgument: val[1] atIndex: 2];
1278     o_lock = *(val[0]);
1279
1280     [o_lock lock];
1281     [o_inv invoke];
1282     [o_lock unlockWithCondition: 1];
1283 }
1284
1285 @end