]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
2b70749219523e91c223a43793428707f63d199c
[vlc] / 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.93 2003/07/27 23:05:41 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     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
469     [o_playlist appendArray:
470         [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
471             
472     return( TRUE );
473 }
474
475 - (id)getControls
476 {
477     if ( o_controls )
478     {
479         return o_controls;
480     }
481     return nil;
482 }
483
484 - (void)manage
485 {
486     NSDate * o_sleep_date;
487     intf_thread_t * p_intf = [NSApp getIntf];
488     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
489
490     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
491
492     while( !p_intf->b_die )
493     {
494         playlist_t * p_playlist;
495
496         vlc_mutex_lock( &p_intf->change_lock );
497
498         p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
499                                               FIND_ANYWHERE );
500
501         if( p_playlist != NULL )
502         {
503             var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
504             vlc_mutex_lock( &p_playlist->object_lock );
505             
506             [self manage: p_playlist];
507             
508             vlc_mutex_unlock( &p_playlist->object_lock );
509             vlc_object_release( p_playlist );
510         }
511
512         vlc_mutex_unlock( &p_intf->change_lock );
513
514         o_sleep_date = [NSDate dateWithTimeIntervalSinceNow: .5];
515         [NSThread sleepUntilDate: o_sleep_date];
516     }
517
518     [self terminate];
519
520     [o_pool release];
521 }
522
523 - (void)manage:(playlist_t *)p_playlist
524 {
525     intf_thread_t * p_intf = [NSApp getIntf];
526
527 #define p_input p_playlist->p_input
528
529     if( p_input )
530     {
531         vlc_mutex_lock( &p_input->stream.stream_lock );
532
533         if( !p_input->b_die )
534         {
535             /* New input or stream map change */
536             if( p_input->stream.b_changed )
537             {
538                 p_intf->p_sys->b_playing = TRUE;
539                 [self manageMode: p_playlist];
540             }
541
542             vlc_value_t val;
543
544             if( var_Get( (vlc_object_t *)p_input, "intf-change", &val )
545                 >= 0 && val.b_bool )
546             {
547                 p_intf->p_sys->b_input_update = TRUE;
548             }
549         }
550         vlc_mutex_unlock( &p_input->stream.stream_lock );
551     }
552     else if( p_intf->p_sys->b_playing && !p_intf->b_die )
553     {
554         p_intf->p_sys->b_playing = FALSE;
555         [self manageMode: p_playlist];
556     }
557
558 #undef p_input
559 }
560
561 - (void)manageMode:(playlist_t *)p_playlist
562 {
563     intf_thread_t * p_intf = [NSApp getIntf];
564
565     if( p_playlist->p_input != NULL )
566     {
567         p_intf->p_sys->b_current_title_update = 1;
568         p_playlist->p_input->stream.b_changed = 0;
569         
570         msg_Dbg( p_intf, "stream has changed, refreshing interface" );
571     }
572     else
573     {
574         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
575                                                           FIND_ANYWHERE );
576         if( p_vout != NULL )
577         {
578             vlc_object_detach( p_vout );
579             vlc_object_release( p_vout );
580
581             vlc_mutex_unlock( &p_playlist->object_lock );
582             vout_Destroy( p_vout );
583             vlc_mutex_lock( &p_playlist->object_lock );
584         }
585     }
586
587     p_intf->p_sys->b_intf_update = VLC_TRUE;
588 }
589
590 - (void)manageIntf:(NSTimer *)o_timer
591 {
592     intf_thread_t * p_intf = [NSApp getIntf];
593
594     if( p_intf->p_vlc->b_die == VLC_TRUE )
595     {
596         [o_timer invalidate];
597         return;
598     }
599
600     playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
601                                                        FIND_ANYWHERE );
602
603     if( p_playlist == NULL )
604     {
605         return;
606     }
607
608     if ( p_intf->p_sys->b_playlist_update )
609     {
610         [o_playlist playlistUpdated];
611         p_intf->p_sys->b_playlist_update = VLC_FALSE;
612     }
613
614     if( p_intf->p_sys->b_current_title_update )
615     {
616         vout_thread_t   *p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
617                                               FIND_ANYWHERE );
618         if( p_vout != NULL )
619         {
620             /* We need to lock the vout here to make sure it does not disappear */
621             id o_vout_wnd;
622             NSEnumerator * o_enum = [[NSApp windows] objectEnumerator];
623             
624             while( ( o_vout_wnd = [o_enum nextObject] ) )
625             {
626                 if( [[o_vout_wnd className] isEqualToString: @"VLCWindow"] )
627                 {
628                     [o_vout_wnd updateTitle];
629                 }
630             }
631             vlc_object_release( (vlc_object_t *)p_vout );
632         }
633         [o_playlist updateRowSelection];
634         [o_info updateInfo];
635
636         p_intf->p_sys->b_current_title_update = FALSE;
637     }
638
639     vlc_mutex_lock( &p_playlist->object_lock );
640
641 #define p_input p_playlist->p_input
642
643     if( p_input != NULL )
644     {
645         vlc_mutex_lock( &p_input->stream.stream_lock );
646     }
647
648     if( p_intf->p_sys->b_intf_update )
649     {
650         vlc_bool_t b_input = VLC_FALSE;
651         vlc_bool_t b_plmul = VLC_FALSE;
652         vlc_bool_t b_control = VLC_FALSE;
653         vlc_bool_t b_seekable = VLC_FALSE;
654         vlc_bool_t b_chapters = VLC_FALSE;
655
656         b_plmul = p_playlist->i_size > 1;
657
658         if( ( b_input = ( p_input != NULL ) ) )
659         {
660             /* seekable streams */
661             b_seekable = p_input->stream.b_seekable;
662
663             /* control buttons for free pace streams */
664             b_control = p_input->stream.b_pace_control; 
665
666             /* chapters & titles */
667             b_chapters = p_input->stream.i_area_nb > 1; 
668
669             /* play status */
670             p_intf->p_sys->b_play_status = 
671                 p_input->stream.control.i_status != PAUSE_S;
672         }
673         else
674         {
675             /* play status */
676             p_intf->p_sys->b_play_status = FALSE;
677             [self setSubmenusEnabled: FALSE];
678         }
679
680         [self playStatusUpdated: p_intf->p_sys->b_play_status];
681
682         [o_btn_stop setEnabled: b_input];
683         [o_btn_faster setEnabled: b_control];
684         [o_btn_slower setEnabled: b_control];
685         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
686         [o_btn_next setEnabled: (b_plmul || b_chapters)];
687
688         [o_timeslider setFloatValue: 0.0];
689         [o_timeslider setEnabled: b_seekable];
690         [o_timefield setStringValue: @"0:00:00"];
691
692         [self manageVolumeSlider];
693
694         p_intf->p_sys->b_intf_update = VLC_FALSE;
695     }
696
697 #define p_area p_input->stream.p_selected_area
698
699     if( p_intf->p_sys->b_playing && p_input != NULL )
700     {
701         vlc_bool_t b_field_update = TRUE;
702
703         if( !p_input->b_die && ( p_intf->p_sys->b_play_status !=
704             ( p_input->stream.control.i_status != PAUSE_S ) ) ) 
705         {
706             p_intf->p_sys->b_play_status =
707                 !p_intf->p_sys->b_play_status;
708
709             [self playStatusUpdated: p_intf->p_sys->b_play_status]; 
710         }
711
712         if( p_input->stream.b_seekable )
713         {
714             if( f_slider == f_slider_old )
715             {
716                 float f_updated = ( 10000. * p_area->i_tell ) /
717                                            p_area->i_size;
718
719                 if( f_slider != f_updated )
720                 {
721                     [o_timeslider setFloatValue: f_updated];
722                 }
723             }
724             else
725             {
726                 off_t i_seek = ( f_slider * p_area->i_size ) / 10000;
727
728                 /* release the lock to be able to seek */
729                 vlc_mutex_unlock( &p_input->stream.stream_lock );
730                 vlc_mutex_unlock( &p_playlist->object_lock );
731                 playlist_Play( p_playlist );
732                 input_Seek( p_input, i_seek, INPUT_SEEK_SET );
733                 vlc_mutex_lock( &p_playlist->object_lock );
734                 vlc_mutex_lock( &p_input->stream.stream_lock );
735
736                 /* update the old value */
737                 f_slider_old = f_slider; 
738
739                 b_field_update = VLC_FALSE;
740             }
741         }
742
743         if( b_field_update )
744         {
745             NSString * o_time;
746             char psz_time[ OFFSETTOTIME_MAX_SIZE ];
747
748             input_OffsetToTime( p_input, psz_time, p_area->i_tell );
749
750             o_time = [NSString stringWithUTF8String: psz_time];
751             [o_timefield setStringValue: o_time];
752         }
753
754         /* disable screen saver */
755         UpdateSystemActivity( UsrActivity );
756     }
757
758 #undef p_area
759
760     if( p_input != NULL )
761     {
762         vlc_mutex_unlock( &p_input->stream.stream_lock );
763     }
764
765 #undef p_input
766
767     vlc_mutex_unlock( &p_playlist->object_lock );
768     vlc_object_release( p_playlist );
769
770     [self updateMessageArray];
771
772     [NSTimer scheduledTimerWithTimeInterval: 0.5
773         target: self selector: @selector(manageIntf:)
774         userInfo: nil repeats: FALSE];
775 }
776
777 - (void)setupMenus
778 {
779     intf_thread_t * p_intf = [NSApp getIntf];
780     playlist_t *p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
781                                                 FIND_ANYWHERE );
782     
783     if( p_playlist != NULL )
784     {
785 #define p_input p_playlist->p_input
786         if( p_input != NULL )
787         {
788             [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
789                 var: "program" selector: @selector(toggleVar:)];
790             
791             [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
792                 var: "title" selector: @selector(toggleVar:)];
793             
794             [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
795                 var: "chapter" selector: @selector(toggleVar:)];
796             
797             [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
798                 var: "audio-es" selector: @selector(toggleVar:)];
799             
800             [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
801                 var: "video-es" selector: @selector(toggleVar:)];
802             
803             [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
804                 var: "spu-es" selector: @selector(toggleVar:)];
805         
806             aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
807                                                         FIND_ANYWHERE );
808             if ( p_aout != NULL )
809             {
810                 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
811                     var: "audio-channels" selector: @selector(toggleVar:)];
812             
813                 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
814                     var: "audio-device" selector: @selector(toggleVar:)];
815                 vlc_object_release( (vlc_object_t *)p_aout );
816             }
817             
818             vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
819                                                                 FIND_ANYWHERE );
820             
821             if ( p_vout != NULL )
822             {
823                 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
824                     var: "video-device" selector: @selector(toggleVar:)];
825                 
826                 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
827                     var: "deinterlace" selector: @selector(toggleVar:)];
828                 vlc_object_release( (vlc_object_t *)p_vout );
829             }
830         }
831 #undef p_input
832     }
833     vlc_object_release( (vlc_object_t *)p_playlist );
834 }
835
836 - (void)updateMessageArray
837 {
838     int i_start, i_stop;
839     intf_thread_t * p_intf = [NSApp getIntf];
840
841     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
842     i_stop = *p_intf->p_sys->p_sub->pi_stop;
843     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
844
845     if( p_intf->p_sys->p_sub->i_start != i_stop )
846     {
847         NSColor *o_white = [NSColor whiteColor];
848         NSColor *o_red = [NSColor redColor];
849         NSColor *o_yellow = [NSColor yellowColor];
850         NSColor *o_gray = [NSColor grayColor];
851
852         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
853         static const char * ppsz_type[4] = { ": ", " error: ",
854                                              " warning: ", " debug: " };
855
856         for( i_start = p_intf->p_sys->p_sub->i_start;
857              i_start != i_stop;
858              i_start = (i_start+1) % VLC_MSG_QSIZE )
859         {
860             NSString *o_msg;
861             NSDictionary *o_attr;
862             NSAttributedString *o_msg_color;
863
864             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
865
866             [o_msg_lock lock];
867
868             if( [o_msg_arr count] + 2 > 400 )
869             {
870                 unsigned rid[] = { 0, 1 };
871                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
872                            numIndices: sizeof(rid)/sizeof(rid[0])];
873             }
874
875             o_attr = [NSDictionary dictionaryWithObject: o_gray
876                 forKey: NSForegroundColorAttributeName];
877             o_msg = [NSString stringWithFormat: @"%s%s",
878                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
879                 ppsz_type[i_type]];
880             o_msg_color = [[NSAttributedString alloc]
881                 initWithString: o_msg attributes: o_attr];
882             [o_msg_arr addObject: [o_msg_color autorelease]];
883
884             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
885                 forKey: NSForegroundColorAttributeName];
886             o_msg = [NSString stringWithFormat: @"%s\n",
887                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
888             o_msg_color = [[NSAttributedString alloc]
889                 initWithString: o_msg attributes: o_attr];
890             [o_msg_arr addObject: [o_msg_color autorelease]];
891
892             [o_msg_lock unlock];
893
894             if( i_type == 1 )
895             {
896                 NSString *o_my_msg = [NSString stringWithFormat: @"%s: %s\n",
897                     p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
898                     p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
899
900                 NSRange s_r = NSMakeRange( [[o_err_msg string] length], 0 );
901                 [o_err_msg setEditable: YES];
902                 [o_err_msg setSelectedRange: s_r];
903                 [o_err_msg insertText: o_my_msg];
904
905                 [o_error makeKeyAndOrderFront: self];
906                 [o_err_msg setEditable: NO];
907             }
908         }
909
910         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
911         p_intf->p_sys->p_sub->i_start = i_start;
912         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
913     }
914 }
915
916 - (void)playStatusUpdated:(BOOL)b_pause
917 {
918     if( b_pause )
919     {
920         [o_btn_play setImage: o_img_pause];
921         [o_btn_play setToolTip: _NS("Pause")];
922         [o_mi_play setTitle: _NS("Pause")];
923         [o_dmi_play setTitle: _NS("Pause")];
924     }
925     else
926     {
927         [o_btn_play setImage: o_img_play];
928         [o_btn_play setToolTip: _NS("Play")];
929         [o_mi_play setTitle: _NS("Play")];
930         [o_dmi_play setTitle: _NS("Play")];
931     }
932 }
933
934 - (void)setSubmenusEnabled:(BOOL)b_enabled
935 {
936     [o_mi_program setEnabled: b_enabled];
937     [o_mi_title setEnabled: b_enabled];
938     [o_mi_chapter setEnabled: b_enabled];
939     [o_mi_audiotrack setEnabled: b_enabled];
940     [o_mi_videotrack setEnabled: b_enabled];
941     [o_mi_subtitle setEnabled: b_enabled];
942     [o_mi_channels setEnabled: b_enabled];
943     [o_mi_deinterlace setEnabled: b_enabled];
944     [o_mi_device setEnabled: b_enabled];
945     [o_mi_screen setEnabled: b_enabled];
946 }
947
948 - (void)manageVolumeSlider
949 {
950     audio_volume_t i_volume;
951     intf_thread_t * p_intf = [NSApp getIntf];
952
953     aout_VolumeGet( p_intf, &i_volume );
954
955     [o_volumeslider setFloatValue: (float)i_volume / AOUT_VOLUME_STEP]; 
956     [o_volumeslider setEnabled: TRUE];
957
958     p_intf->p_sys->b_mute = ( i_volume == 0 );
959 }
960
961 - (IBAction)timesliderUpdate:(id)sender
962 {
963     float f_updated;
964
965     switch( [[NSApp currentEvent] type] )
966     {
967         case NSLeftMouseUp:
968         case NSLeftMouseDown:
969             f_slider = [sender floatValue];
970             return;
971
972         case NSLeftMouseDragged:
973             f_updated = [sender floatValue];
974             break;
975
976         default:
977             return;
978     }
979
980     intf_thread_t * p_intf = [NSApp getIntf];
981
982     playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
983                                                        FIND_ANYWHERE );
984
985     if( p_playlist == NULL )
986     {
987         return;
988     }
989
990     vlc_mutex_lock( &p_playlist->object_lock );
991
992     if( p_playlist->p_input != NULL )
993     {
994         off_t i_tell;
995         NSString * o_time;
996         char psz_time[ OFFSETTOTIME_MAX_SIZE ];
997
998 #define p_area p_playlist->p_input->stream.p_selected_area
999         vlc_mutex_lock( &p_playlist->p_input->stream.stream_lock );
1000         i_tell = f_updated / 10000. * p_area->i_size;
1001         input_OffsetToTime( p_playlist->p_input, psz_time, i_tell );
1002         vlc_mutex_unlock( &p_playlist->p_input->stream.stream_lock );
1003 #undef p_area
1004
1005         o_time = [NSString stringWithUTF8String: psz_time];
1006         [o_timefield setStringValue: o_time]; 
1007     }
1008
1009     vlc_mutex_unlock( &p_playlist->object_lock );
1010     vlc_object_release( p_playlist );
1011 }
1012
1013 - (void)terminate
1014 {
1015     NSEvent * o_event;
1016     vout_thread_t * p_vout;
1017     playlist_t * p_playlist;
1018     intf_thread_t * p_intf = [NSApp getIntf];
1019
1020     /*
1021      * Free playlists
1022      */
1023     msg_Dbg( p_intf, "removing all playlists" );
1024     while( (p_playlist = vlc_object_find( p_intf->p_vlc, VLC_OBJECT_PLAYLIST,
1025                                           FIND_CHILD )) )
1026     {
1027         vlc_object_detach( p_playlist );
1028         vlc_object_release( p_playlist );
1029         playlist_Destroy( p_playlist );
1030     }
1031
1032     /*
1033      * Free video outputs
1034      */
1035     msg_Dbg( p_intf, "removing all video outputs" );
1036     while( (p_vout = vlc_object_find( p_intf->p_vlc, 
1037                                       VLC_OBJECT_VOUT, FIND_CHILD )) )
1038     {
1039         vlc_object_detach( p_vout );
1040         vlc_object_release( p_vout );
1041         vout_Destroy( p_vout );
1042     }
1043
1044     if( o_img_pause != nil )
1045     {
1046         [o_img_pause release];
1047         o_img_pause = nil;
1048     }
1049
1050     if( o_img_play != nil )
1051     {
1052         [o_img_play release];
1053         o_img_play = nil;
1054     }
1055
1056     if( o_msg_arr != nil )
1057     {
1058         [o_msg_arr removeAllObjects];
1059         [o_msg_arr release];
1060         o_msg_arr = nil;
1061     }
1062
1063     if( o_msg_lock != nil )
1064     {
1065         [o_msg_lock release];
1066         o_msg_lock = nil;
1067     }
1068
1069     [NSApp stop: nil];
1070
1071     /* write cached user defaults to disk */
1072     [[NSUserDefaults standardUserDefaults] synchronize];
1073
1074     /* send a dummy event to break out of the event loop */
1075     o_event = [NSEvent mouseEventWithType: NSLeftMouseDown
1076                 location: NSMakePoint( 1, 1 ) modifierFlags: 0
1077                 timestamp: 1 windowNumber: [[NSApp mainWindow] windowNumber]
1078                 context: [NSGraphicsContext currentContext] eventNumber: 1
1079                 clickCount: 1 pressure: 0.0];
1080     [NSApp postEvent: o_event atStart: YES];
1081 }
1082
1083 - (IBAction)clearRecentItems:(id)sender
1084 {
1085     [[NSDocumentController sharedDocumentController]
1086                           clearRecentDocuments: nil];
1087 }
1088
1089 - (void)openRecentItem:(id)sender
1090 {
1091     [self application: nil openFile: [sender title]]; 
1092 }
1093
1094 - (IBAction)viewPreferences:(id)sender
1095 {
1096     [o_prefs showPrefs];
1097 }
1098
1099 - (IBAction)closeError:(id)sender
1100 {
1101     [o_err_msg setString: @""];
1102     [o_error performClose: self];
1103 }
1104
1105 - (IBAction)openReadMe:(id)sender
1106 {
1107     NSString * o_path = [[NSBundle mainBundle] 
1108         pathForResource: @"README.MacOSX" ofType: @"rtf"]; 
1109
1110     [[NSWorkspace sharedWorkspace] openFile: o_path 
1111                                    withApplication: @"TextEdit"];
1112 }
1113
1114 - (IBAction)openDocumentation:(id)sender
1115 {
1116     NSURL * o_url = [NSURL URLWithString: 
1117         @"http://www.videolan.org/doc/"];
1118
1119     [[NSWorkspace sharedWorkspace] openURL: o_url];
1120 }
1121
1122 - (IBAction)reportABug:(id)sender
1123 {
1124     NSURL * o_url = [NSURL URLWithString: 
1125         @"http://www.videolan.org/support/bug-reporting.html"];
1126
1127     [[NSWorkspace sharedWorkspace] openURL: o_url];
1128 }
1129
1130 - (IBAction)openWebsite:(id)sender
1131 {
1132     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org"];
1133
1134     [[NSWorkspace sharedWorkspace] openURL: o_url];
1135 }
1136
1137 - (IBAction)openLicense:(id)sender
1138 {
1139     NSString * o_path = [[NSBundle mainBundle] 
1140         pathForResource: @"COPYING" ofType: nil];
1141
1142     [[NSWorkspace sharedWorkspace] openFile: o_path 
1143                                    withApplication: @"TextEdit"];
1144 }
1145
1146 - (IBAction)openCrashLog:(id)sender
1147 {
1148     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
1149                                     stringByExpandingTildeInPath]; 
1150
1151     
1152     if ( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
1153     {
1154         [[NSWorkspace sharedWorkspace] openFile: o_path 
1155                                     withApplication: @"Console"];
1156     }
1157     else
1158     {
1159         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.") );
1160
1161     }
1162 }
1163
1164 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1165 {
1166     if( [o_notification object] == o_msgs_panel )
1167     {
1168         id o_msg;
1169         NSEnumerator * o_enum;
1170
1171         [o_messages setString: @""]; 
1172
1173         [o_msg_lock lock];
1174
1175         o_enum = [o_msg_arr objectEnumerator];
1176
1177         while( ( o_msg = [o_enum nextObject] ) != nil )
1178         {
1179             [o_messages insertText: o_msg];
1180         }
1181
1182         [o_msg_lock unlock];
1183     }
1184 }
1185
1186 @end
1187
1188 @implementation VLCMain (NSMenuValidation)
1189
1190 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
1191 {
1192     NSString *o_title = [o_mi title];
1193     BOOL bEnabled = TRUE;
1194
1195     if( [o_title isEqualToString: _NS("License")] )
1196     {
1197         /* we need to do this only once */
1198         [self setupMenus];
1199     }
1200
1201     /* Recent Items Menu */
1202     if( [o_title isEqualToString: _NS("Clear Menu")] )
1203     {
1204         NSMenu * o_menu = [o_mi_open_recent submenu];
1205         int i_nb_items = [o_menu numberOfItems];
1206         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
1207                                                        recentDocumentURLs];
1208         UInt32 i_nb_docs = [o_docs count];
1209
1210         if( i_nb_items > 1 )
1211         {
1212             while( --i_nb_items )
1213             {
1214                 [o_menu removeItemAtIndex: 0];
1215             }
1216         }
1217
1218         if( i_nb_docs > 0 )
1219         {
1220             NSURL * o_url;
1221             NSString * o_doc;
1222
1223             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
1224
1225             while( TRUE )
1226             {
1227                 i_nb_docs--;
1228
1229                 o_url = [o_docs objectAtIndex: i_nb_docs];
1230
1231                 if( [o_url isFileURL] )
1232                 {
1233                     o_doc = [o_url path];
1234                 }
1235                 else
1236                 {
1237                     o_doc = [o_url absoluteString];
1238                 }
1239
1240                 [o_menu insertItemWithTitle: o_doc
1241                     action: @selector(openRecentItem:)
1242                     keyEquivalent: @"" atIndex: 0]; 
1243
1244                 if( i_nb_docs == 0 )
1245                 {
1246                     break;
1247                 }
1248             } 
1249         }
1250         else
1251         {
1252             bEnabled = FALSE;
1253         }
1254     }
1255     return( bEnabled );
1256 }
1257
1258 @end
1259
1260 @implementation VLCMain (Internal)
1261
1262 - (void)handlePortMessage:(NSPortMessage *)o_msg
1263 {
1264     id ** val;
1265     NSData * o_data;
1266     NSValue * o_value;
1267     NSInvocation * o_inv;
1268     NSConditionLock * o_lock;
1269  
1270     o_data = [[o_msg components] lastObject];
1271     o_inv = *((NSInvocation **)[o_data bytes]); 
1272     [o_inv getArgument: &o_value atIndex: 2];
1273     val = (id **)[o_value pointerValue];
1274     [o_inv setArgument: val[1] atIndex: 2];
1275     o_lock = *(val[0]);
1276
1277     [o_lock lock];
1278     [o_inv invoke];
1279     [o_lock unlockWithCondition: 1];
1280 }
1281
1282 @end