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