* src/input/input_clock.c: Fixed two long-standing (> 2 years) bugs
[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.92 2003/07/27 14:10:02 massiot 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                 vlc_mutex_unlock( &p_playlist->object_lock );
737                 playlist_Play( p_playlist );
738                 input_Seek( p_input, i_seek, INPUT_SEEK_SET );
739                 vlc_mutex_lock( &p_playlist->object_lock );
740                 vlc_mutex_lock( &p_input->stream.stream_lock );
741
742                 /* update the old value */
743                 f_slider_old = f_slider; 
744
745                 b_field_update = VLC_FALSE;
746             }
747         }
748
749         if( b_field_update )
750         {
751             NSString * o_time;
752             char psz_time[ OFFSETTOTIME_MAX_SIZE ];
753
754             input_OffsetToTime( p_input, psz_time, p_area->i_tell );
755
756             o_time = [NSString stringWithUTF8String: psz_time];
757             [o_timefield setStringValue: o_time];
758         }
759
760         /* disable screen saver */
761         UpdateSystemActivity( UsrActivity );
762     }
763
764 #undef p_area
765
766     if( p_input != NULL )
767     {
768         vlc_mutex_unlock( &p_input->stream.stream_lock );
769     }
770
771 #undef p_input
772
773     vlc_mutex_unlock( &p_playlist->object_lock );
774     vlc_object_release( p_playlist );
775
776     [self updateMessageArray];
777
778     [NSTimer scheduledTimerWithTimeInterval: 0.5
779         target: self selector: @selector(manageIntf:)
780         userInfo: nil repeats: FALSE];
781 }
782
783 - (void)setupMenus
784 {
785     intf_thread_t * p_intf = [NSApp getIntf];
786     playlist_t *p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
787                                                 FIND_ANYWHERE );
788     
789     if( p_playlist != NULL )
790     {
791 #define p_input p_playlist->p_input
792         if( p_input != NULL )
793         {
794             [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
795                 var: "program" selector: @selector(toggleVar:)];
796             
797             [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
798                 var: "title" selector: @selector(toggleVar:)];
799             
800             [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
801                 var: "chapter" selector: @selector(toggleVar:)];
802             
803             [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
804                 var: "audio-es" selector: @selector(toggleVar:)];
805             
806             [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
807                 var: "video-es" selector: @selector(toggleVar:)];
808             
809             [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
810                 var: "spu-es" selector: @selector(toggleVar:)];
811         
812             aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
813                                                         FIND_ANYWHERE );
814             if ( p_aout != NULL )
815             {
816                 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
817                     var: "audio-channels" selector: @selector(toggleVar:)];
818             
819                 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
820                     var: "audio-device" selector: @selector(toggleVar:)];
821                 vlc_object_release( (vlc_object_t *)p_aout );
822             }
823             
824             vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
825                                                                 FIND_ANYWHERE );
826             
827             if ( p_vout != NULL )
828             {
829                 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
830                     var: "video-device" selector: @selector(toggleVar:)];
831                 
832                 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
833                     var: "deinterlace" selector: @selector(toggleVar:)];
834                 vlc_object_release( (vlc_object_t *)p_vout );
835             }
836         }
837 #undef p_input
838     }
839     vlc_object_release( (vlc_object_t *)p_playlist );
840 }
841
842 - (void)updateMessageArray
843 {
844     int i_start, i_stop;
845     intf_thread_t * p_intf = [NSApp getIntf];
846
847     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
848     i_stop = *p_intf->p_sys->p_sub->pi_stop;
849     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
850
851     if( p_intf->p_sys->p_sub->i_start != i_stop )
852     {
853         NSColor *o_white = [NSColor whiteColor];
854         NSColor *o_red = [NSColor redColor];
855         NSColor *o_yellow = [NSColor yellowColor];
856         NSColor *o_gray = [NSColor grayColor];
857
858         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
859         static const char * ppsz_type[4] = { ": ", " error: ",
860                                              " warning: ", " debug: " };
861
862         for( i_start = p_intf->p_sys->p_sub->i_start;
863              i_start != i_stop;
864              i_start = (i_start+1) % VLC_MSG_QSIZE )
865         {
866             NSString *o_msg;
867             NSDictionary *o_attr;
868             NSAttributedString *o_msg_color;
869
870             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
871
872             [o_msg_lock lock];
873
874             if( [o_msg_arr count] + 2 > 400 )
875             {
876                 unsigned rid[] = { 0, 1 };
877                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
878                            numIndices: sizeof(rid)/sizeof(rid[0])];
879             }
880
881             o_attr = [NSDictionary dictionaryWithObject: o_gray
882                 forKey: NSForegroundColorAttributeName];
883             o_msg = [NSString stringWithFormat: @"%s%s",
884                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
885                 ppsz_type[i_type]];
886             o_msg_color = [[NSAttributedString alloc]
887                 initWithString: o_msg attributes: o_attr];
888             [o_msg_arr addObject: [o_msg_color autorelease]];
889
890             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
891                 forKey: NSForegroundColorAttributeName];
892             o_msg = [NSString stringWithFormat: @"%s\n",
893                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
894             o_msg_color = [[NSAttributedString alloc]
895                 initWithString: o_msg attributes: o_attr];
896             [o_msg_arr addObject: [o_msg_color autorelease]];
897
898             [o_msg_lock unlock];
899
900             if( i_type == 1 )
901             {
902                 NSString *o_my_msg = [NSString stringWithFormat: @"%s: %s\n",
903                     p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
904                     p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
905
906                 NSRange s_r = NSMakeRange( [[o_err_msg string] length], 0 );
907                 [o_err_msg setEditable: YES];
908                 [o_err_msg setSelectedRange: s_r];
909                 [o_err_msg insertText: o_my_msg];
910
911                 [o_error makeKeyAndOrderFront: self];
912                 [o_err_msg setEditable: NO];
913             }
914         }
915
916         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
917         p_intf->p_sys->p_sub->i_start = i_start;
918         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
919     }
920 }
921
922 - (void)playStatusUpdated:(BOOL)b_pause
923 {
924     if( b_pause )
925     {
926         [o_btn_play setImage: o_img_pause];
927         [o_btn_play setToolTip: _NS("Pause")];
928         [o_mi_play setTitle: _NS("Pause")];
929         [o_dmi_play setTitle: _NS("Pause")];
930     }
931     else
932     {
933         [o_btn_play setImage: o_img_play];
934         [o_btn_play setToolTip: _NS("Play")];
935         [o_mi_play setTitle: _NS("Play")];
936         [o_dmi_play setTitle: _NS("Play")];
937     }
938 }
939
940 - (void)setSubmenusEnabled:(BOOL)b_enabled
941 {
942     [o_mi_program setEnabled: b_enabled];
943     [o_mi_title setEnabled: b_enabled];
944     [o_mi_chapter setEnabled: b_enabled];
945     [o_mi_audiotrack setEnabled: b_enabled];
946     [o_mi_videotrack setEnabled: b_enabled];
947     [o_mi_subtitle setEnabled: b_enabled];
948     [o_mi_channels setEnabled: b_enabled];
949     [o_mi_deinterlace setEnabled: b_enabled];
950     [o_mi_device setEnabled: b_enabled];
951     [o_mi_screen setEnabled: b_enabled];
952 }
953
954 - (void)manageVolumeSlider
955 {
956     audio_volume_t i_volume;
957     intf_thread_t * p_intf = [NSApp getIntf];
958
959     aout_VolumeGet( p_intf, &i_volume );
960
961     [o_volumeslider setFloatValue: (float)i_volume / AOUT_VOLUME_STEP]; 
962     [o_volumeslider setEnabled: TRUE];
963
964     p_intf->p_sys->b_mute = ( i_volume == 0 );
965 }
966
967 - (IBAction)timesliderUpdate:(id)sender
968 {
969     float f_updated;
970
971     switch( [[NSApp currentEvent] type] )
972     {
973         case NSLeftMouseUp:
974         case NSLeftMouseDown:
975             f_slider = [sender floatValue];
976             return;
977
978         case NSLeftMouseDragged:
979             f_updated = [sender floatValue];
980             break;
981
982         default:
983             return;
984     }
985
986     intf_thread_t * p_intf = [NSApp getIntf];
987
988     playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
989                                                        FIND_ANYWHERE );
990
991     if( p_playlist == NULL )
992     {
993         return;
994     }
995
996     vlc_mutex_lock( &p_playlist->object_lock );
997
998     if( p_playlist->p_input != NULL )
999     {
1000         off_t i_tell;
1001         NSString * o_time;
1002         char psz_time[ OFFSETTOTIME_MAX_SIZE ];
1003
1004 #define p_area p_playlist->p_input->stream.p_selected_area
1005         vlc_mutex_lock( &p_playlist->p_input->stream.stream_lock );
1006         i_tell = f_updated / 10000. * p_area->i_size;
1007         input_OffsetToTime( p_playlist->p_input, psz_time, i_tell );
1008         vlc_mutex_unlock( &p_playlist->p_input->stream.stream_lock );
1009 #undef p_area
1010
1011         o_time = [NSString stringWithUTF8String: psz_time];
1012         [o_timefield setStringValue: o_time]; 
1013     }
1014
1015     vlc_mutex_unlock( &p_playlist->object_lock );
1016     vlc_object_release( p_playlist );
1017 }
1018
1019 - (void)terminate
1020 {
1021     NSEvent * o_event;
1022     vout_thread_t * p_vout;
1023     playlist_t * p_playlist;
1024     intf_thread_t * p_intf = [NSApp getIntf];
1025
1026     /*
1027      * Free playlists
1028      */
1029     msg_Dbg( p_intf, "removing all playlists" );
1030     while( (p_playlist = vlc_object_find( p_intf->p_vlc, VLC_OBJECT_PLAYLIST,
1031                                           FIND_CHILD )) )
1032     {
1033         vlc_object_detach( p_playlist );
1034         vlc_object_release( p_playlist );
1035         playlist_Destroy( p_playlist );
1036     }
1037
1038     /*
1039      * Free video outputs
1040      */
1041     msg_Dbg( p_intf, "removing all video outputs" );
1042     while( (p_vout = vlc_object_find( p_intf->p_vlc, 
1043                                       VLC_OBJECT_VOUT, FIND_CHILD )) )
1044     {
1045         vlc_object_detach( p_vout );
1046         vlc_object_release( p_vout );
1047         vout_Destroy( p_vout );
1048     }
1049
1050     if( o_img_pause != nil )
1051     {
1052         [o_img_pause release];
1053         o_img_pause = nil;
1054     }
1055
1056     if( o_img_play != nil )
1057     {
1058         [o_img_play release];
1059         o_img_play = nil;
1060     }
1061
1062     if( o_msg_arr != nil )
1063     {
1064         [o_msg_arr removeAllObjects];
1065         [o_msg_arr release];
1066         o_msg_arr = nil;
1067     }
1068
1069     if( o_msg_lock != nil )
1070     {
1071         [o_msg_lock release];
1072         o_msg_lock = nil;
1073     }
1074
1075     [NSApp stop: nil];
1076
1077     /* write cached user defaults to disk */
1078     [[NSUserDefaults standardUserDefaults] synchronize];
1079
1080     /* send a dummy event to break out of the event loop */
1081     o_event = [NSEvent mouseEventWithType: NSLeftMouseDown
1082                 location: NSMakePoint( 1, 1 ) modifierFlags: 0
1083                 timestamp: 1 windowNumber: [[NSApp mainWindow] windowNumber]
1084                 context: [NSGraphicsContext currentContext] eventNumber: 1
1085                 clickCount: 1 pressure: 0.0];
1086     [NSApp postEvent: o_event atStart: YES];
1087 }
1088
1089 - (IBAction)clearRecentItems:(id)sender
1090 {
1091     [[NSDocumentController sharedDocumentController]
1092                           clearRecentDocuments: nil];
1093 }
1094
1095 - (void)openRecentItem:(id)sender
1096 {
1097     [self application: nil openFile: [sender title]]; 
1098 }
1099
1100 - (IBAction)viewPreferences:(id)sender
1101 {
1102     [o_prefs showPrefs];
1103 }
1104
1105 - (IBAction)closeError:(id)sender
1106 {
1107     [o_err_msg setString: @""];
1108     [o_error performClose: self];
1109 }
1110
1111 - (IBAction)openReadMe:(id)sender
1112 {
1113     NSString * o_path = [[NSBundle mainBundle] 
1114         pathForResource: @"README.MacOSX" ofType: @"rtf"]; 
1115
1116     [[NSWorkspace sharedWorkspace] openFile: o_path 
1117                                    withApplication: @"TextEdit"];
1118 }
1119
1120 - (IBAction)openDocumentation:(id)sender
1121 {
1122     NSURL * o_url = [NSURL URLWithString: 
1123         @"http://www.videolan.org/doc/"];
1124
1125     [[NSWorkspace sharedWorkspace] openURL: o_url];
1126 }
1127
1128 - (IBAction)reportABug:(id)sender
1129 {
1130     NSURL * o_url = [NSURL URLWithString: 
1131         @"http://www.videolan.org/support/bug-reporting.html"];
1132
1133     [[NSWorkspace sharedWorkspace] openURL: o_url];
1134 }
1135
1136 - (IBAction)openWebsite:(id)sender
1137 {
1138     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org"];
1139
1140     [[NSWorkspace sharedWorkspace] openURL: o_url];
1141 }
1142
1143 - (IBAction)openLicense:(id)sender
1144 {
1145     NSString * o_path = [[NSBundle mainBundle] 
1146         pathForResource: @"COPYING" ofType: nil];
1147
1148     [[NSWorkspace sharedWorkspace] openFile: o_path 
1149                                    withApplication: @"TextEdit"];
1150 }
1151
1152 - (IBAction)openCrashLog:(id)sender
1153 {
1154     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
1155                                     stringByExpandingTildeInPath]; 
1156
1157     
1158     if ( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
1159     {
1160         [[NSWorkspace sharedWorkspace] openFile: o_path 
1161                                     withApplication: @"Console"];
1162     }
1163     else
1164     {
1165         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.") );
1166
1167     }
1168 }
1169
1170 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1171 {
1172     if( [o_notification object] == o_msgs_panel )
1173     {
1174         id o_msg;
1175         NSEnumerator * o_enum;
1176
1177         [o_messages setString: @""]; 
1178
1179         [o_msg_lock lock];
1180
1181         o_enum = [o_msg_arr objectEnumerator];
1182
1183         while( ( o_msg = [o_enum nextObject] ) != nil )
1184         {
1185             [o_messages insertText: o_msg];
1186         }
1187
1188         [o_msg_lock unlock];
1189     }
1190 }
1191
1192 @end
1193
1194 @implementation VLCMain (NSMenuValidation)
1195
1196 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
1197 {
1198     NSString *o_title = [o_mi title];
1199     BOOL bEnabled = TRUE;
1200
1201     if( [o_title isEqualToString: _NS("License")] )
1202     {
1203         /* we need to do this only once */
1204         [self setupMenus];
1205     }
1206
1207     /* Recent Items Menu */
1208     if( [o_title isEqualToString: _NS("Clear Menu")] )
1209     {
1210         NSMenu * o_menu = [o_mi_open_recent submenu];
1211         int i_nb_items = [o_menu numberOfItems];
1212         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
1213                                                        recentDocumentURLs];
1214         UInt32 i_nb_docs = [o_docs count];
1215
1216         if( i_nb_items > 1 )
1217         {
1218             while( --i_nb_items )
1219             {
1220                 [o_menu removeItemAtIndex: 0];
1221             }
1222         }
1223
1224         if( i_nb_docs > 0 )
1225         {
1226             NSURL * o_url;
1227             NSString * o_doc;
1228
1229             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
1230
1231             while( TRUE )
1232             {
1233                 i_nb_docs--;
1234
1235                 o_url = [o_docs objectAtIndex: i_nb_docs];
1236
1237                 if( [o_url isFileURL] )
1238                 {
1239                     o_doc = [o_url path];
1240                 }
1241                 else
1242                 {
1243                     o_doc = [o_url absoluteString];
1244                 }
1245
1246                 [o_menu insertItemWithTitle: o_doc
1247                     action: @selector(openRecentItem:)
1248                     keyEquivalent: @"" atIndex: 0]; 
1249
1250                 if( i_nb_docs == 0 )
1251                 {
1252                     break;
1253                 }
1254             } 
1255         }
1256         else
1257         {
1258             bEnabled = FALSE;
1259         }
1260     }
1261     return( bEnabled );
1262 }
1263
1264 @end
1265
1266 @implementation VLCMain (Internal)
1267
1268 - (void)handlePortMessage:(NSPortMessage *)o_msg
1269 {
1270     id ** val;
1271     NSData * o_data;
1272     NSValue * o_value;
1273     NSInvocation * o_inv;
1274     NSConditionLock * o_lock;
1275  
1276     o_data = [[o_msg components] lastObject];
1277     o_inv = *((NSInvocation **)[o_data bytes]); 
1278     [o_inv getArgument: &o_value atIndex: 2];
1279     val = (id **)[o_value pointerValue];
1280     [o_inv setArgument: val[1] atIndex: 2];
1281     o_lock = *(val[0]);
1282
1283     [o_lock lock];
1284     [o_inv invoke];
1285     [o_lock unlockWithCondition: 1];
1286 }
1287
1288 @end