]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
* include/vlc/vlc.h:
[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.96 2003/09/20 19:37:53 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_random setTitle: _NS("Shuffle")];
351     [o_mi_repeat setTitle: _NS("Repeat Item")];
352     [o_mi_loop setTitle: _NS("Repeat Playlist")];
353     [o_mi_fwd setTitle: _NS("Step Forward")];
354     [o_mi_bwd setTitle: _NS("Step Backward")];
355     [o_mi_program setTitle: _NS("Program")];
356     [o_mu_program setTitle: _NS("Program")];
357     [o_mi_title setTitle: _NS("Title")];
358     [o_mu_title setTitle: _NS("Title")];
359     [o_mi_chapter setTitle: _NS("Chapter")];
360     [o_mu_chapter setTitle: _NS("Chapter")];
361     
362     [o_mu_audio setTitle: _NS("Audio")];
363     [o_mi_vol_up setTitle: _NS("Volume Up")];
364     [o_mi_vol_down setTitle: _NS("Volume Down")];
365     [o_mi_mute setTitle: _NS("Mute")];
366     [o_mi_audiotrack setTitle: _NS("Audio track")];
367     [o_mu_audiotrack setTitle: _NS("Audio track")];
368     [o_mi_channels setTitle: _NS("Audio channels")];
369     [o_mu_channels setTitle: _NS("Audio channels")];
370     [o_mi_device setTitle: _NS("Audio device")];
371     [o_mu_device setTitle: _NS("Audio device")];
372     
373     [o_mu_video setTitle: _NS("Video")];
374     [o_mi_half_window setTitle: _NS("Half Size")];
375     [o_mi_normal_window setTitle: _NS("Normal Size")];
376     [o_mi_double_window setTitle: _NS("Double Size")];
377     [o_mi_fittoscreen setTitle: _NS("Fit To Screen")];
378     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
379     [o_mi_floatontop setTitle: _NS("Float On Top")];
380     [o_mi_videotrack setTitle: _NS("Video track")];
381     [o_mu_videotrack setTitle: _NS("Video track")];
382     [o_mi_screen setTitle: _NS("Video device")];
383     [o_mu_screen setTitle: _NS("Video device")];
384     [o_mi_subtitle setTitle: _NS("Subtitles track")];
385     [o_mu_subtitle setTitle: _NS("Subtitles track")];
386     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
387     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
388
389     [o_mu_window setTitle: _NS("Window")];
390     [o_mi_minimize setTitle: _NS("Minimize Window")];
391     [o_mi_close_window setTitle: _NS("Close Window")];
392     [o_mi_controller setTitle: _NS("Controller")];
393     [o_mi_playlist setTitle: _NS("Playlist")];
394     [o_mi_info setTitle: _NS("Info")];
395     [o_mi_messages setTitle: _NS("Messages")];
396
397     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
398
399     [o_mu_help setTitle: _NS("Help")];
400     [o_mi_readme setTitle: _NS("ReadMe...")];
401     [o_mi_documentation setTitle: _NS("Online Documentation")];
402     [o_mi_reportabug setTitle: _NS("Report a Bug")];
403     [o_mi_website setTitle: _NS("VideoLAN Website")];
404     [o_mi_license setTitle: _NS("License")];
405
406     /* dock menu */
407     [o_dmi_play setTitle: _NS("Play")];
408     [o_dmi_stop setTitle: _NS("Stop")];
409     [o_dmi_next setTitle: _NS("Next")];
410     [o_dmi_previous setTitle: _NS("Previous")];
411
412     /* error panel */
413     [o_error setTitle: _NS("Error")];
414     [o_err_lbl setStringValue: _NS("An error has occurred which probably prevented the execution of your request:")];
415     [o_err_bug_lbl setStringValue: _NS("If you believe that it is a bug, please follow the instructions at:")]; 
416     [o_err_btn_msgs setTitle: _NS("Open Messages Window")];
417     [o_err_btn_dismiss setTitle: _NS("Dismiss")];
418
419     [o_info_window setTitle: _NS("Info")];
420
421     [self setSubmenusEnabled: FALSE];
422     [self manageVolumeSlider];
423 }
424
425 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
426 {
427     intf_thread_t * p_intf = [NSApp getIntf];
428
429     o_msg_lock = [[NSLock alloc] init];
430     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
431
432     o_img_play = [[NSImage imageNamed: @"play"] retain];
433     o_img_pause = [[NSImage imageNamed: @"pause"] retain];
434
435     [p_intf->p_sys->o_sendport setDelegate: self];
436     [[NSRunLoop currentRunLoop] 
437         addPort: p_intf->p_sys->o_sendport
438         forMode: NSDefaultRunLoopMode];
439
440     [NSTimer scheduledTimerWithTimeInterval: 0.5
441         target: self selector: @selector(manageIntf:)
442         userInfo: nil repeats: FALSE];
443
444     [NSThread detachNewThreadSelector: @selector(manage)
445         toTarget: self withObject: nil];
446
447     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
448 }
449
450 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
451 {
452     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
453     [o_playlist appendArray:
454         [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
455             
456     return( TRUE );
457 }
458
459 - (id)getControls
460 {
461     if ( o_controls )
462     {
463         return o_controls;
464     }
465     return nil;
466 }
467
468 - (void)manage
469 {
470     NSDate * o_sleep_date;
471     intf_thread_t * p_intf = [NSApp getIntf];
472     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
473
474     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
475
476     while( !p_intf->b_die )
477     {
478         playlist_t * p_playlist;
479
480         vlc_mutex_lock( &p_intf->change_lock );
481
482         p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
483                                               FIND_ANYWHERE );
484
485         if( p_playlist != NULL )
486         {
487             var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
488 #define p_input p_playlist->p_input
489         
490             if( p_input )
491             {
492                 if( !p_input->b_die )
493                 {
494                     vlc_value_t val;
495
496                     /* New input or stream map change */
497                     if( p_input->stream.b_changed )
498                     {
499                         msg_Dbg( p_intf, "stream has changed, refreshing interface" );
500                         p_intf->p_sys->b_playing = TRUE;
501                         p_intf->p_sys->b_current_title_update = 1;
502                         p_input->stream.b_changed = 0;
503                         p_intf->p_sys->b_intf_update = TRUE;
504                     }
505
506                     if( var_Get( (vlc_object_t *)p_input, "intf-change", &val )
507                         >= 0 && val.b_bool )
508                     {
509                         p_intf->p_sys->b_input_update = TRUE;
510                     }
511                 }
512             }
513             else if( p_intf->p_sys->b_playing && !p_intf->b_die )
514             {
515                 p_intf->p_sys->b_playing = FALSE;
516                 p_intf->p_sys->b_intf_update = TRUE;
517             }
518             
519 #undef p_input
520             vlc_object_release( p_playlist );
521         }
522
523         vlc_mutex_unlock( &p_intf->change_lock );
524
525         o_sleep_date = [NSDate dateWithTimeIntervalSinceNow: .5];
526         [NSThread sleepUntilDate: o_sleep_date];
527     }
528
529     [self terminate];
530     [o_pool release];
531 }
532
533 - (void)manageIntf:(NSTimer *)o_timer
534 {
535     intf_thread_t * p_intf = [NSApp getIntf];
536
537     if( p_intf->p_vlc->b_die == VLC_TRUE )
538     {
539         [o_timer invalidate];
540         return;
541     }
542
543     playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
544                                                        FIND_ANYWHERE );
545
546     if( p_playlist == NULL )
547     {
548         return;
549     }
550
551     if ( p_intf->p_sys->b_playlist_update )
552     {
553         [o_playlist playlistUpdated];
554         p_intf->p_sys->b_playlist_update = VLC_FALSE;
555     }
556
557     if( p_intf->p_sys->b_current_title_update )
558     {
559         vout_thread_t   *p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
560                                               FIND_ANYWHERE );
561         if( p_vout != NULL )
562         {
563             id o_vout_wnd;
564             NSEnumerator * o_enum = [[NSApp windows] objectEnumerator];
565             
566             while( ( o_vout_wnd = [o_enum nextObject] ) )
567             {
568                 if( [[o_vout_wnd className] isEqualToString: @"VLCWindow"] )
569                 {
570                     [o_vout_wnd updateTitle];
571                 }
572             }
573             vlc_object_release( (vlc_object_t *)p_vout );
574         }
575         [o_playlist updateRowSelection];
576         [o_info updateInfo];
577
578         p_intf->p_sys->b_current_title_update = FALSE;
579     }
580
581     vlc_mutex_lock( &p_playlist->object_lock );
582
583 #define p_input p_playlist->p_input
584
585     if( p_intf->p_sys->b_intf_update )
586     {
587         vlc_bool_t b_input = VLC_FALSE;
588         vlc_bool_t b_plmul = VLC_FALSE;
589         vlc_bool_t b_control = VLC_FALSE;
590         vlc_bool_t b_seekable = VLC_FALSE;
591         vlc_bool_t b_chapters = VLC_FALSE;
592         vlc_value_t val;
593
594         b_plmul = p_playlist->i_size > 1;
595
596         if( ( b_input = ( p_input != NULL ) ) )
597         {
598             vlc_mutex_lock( &p_input->stream.stream_lock );
599
600             /* seekable streams */
601             b_seekable = p_input->stream.b_seekable;
602
603             /* control buttons for free pace streams */
604             b_control = p_input->stream.b_pace_control; 
605
606             /* chapters & titles */
607             b_chapters = p_input->stream.i_area_nb > 1; 
608  
609             vlc_mutex_unlock( &p_input->stream.stream_lock );
610
611             /* play status */
612             var_Get( p_input, "state", &val );
613             p_intf->p_sys->b_play_status = val.i_int != PAUSE_S;
614         }
615         else
616         {
617             /* play status */
618             p_intf->p_sys->b_play_status = FALSE;
619             [self setSubmenusEnabled: FALSE];
620         }
621
622         [self playStatusUpdated: p_intf->p_sys->b_play_status];
623
624         [o_btn_stop setEnabled: b_input];
625         [o_btn_faster setEnabled: b_control];
626         [o_btn_slower setEnabled: b_control];
627         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
628         [o_btn_next setEnabled: (b_plmul || b_chapters)];
629
630         [o_timeslider setFloatValue: 0.0];
631         [o_timeslider setEnabled: b_seekable];
632         [o_timefield setStringValue: @"0:00:00"];
633
634         [self manageVolumeSlider];
635
636         p_intf->p_sys->b_intf_update = VLC_FALSE;
637     }
638
639     if( p_intf->p_sys->b_playing && p_input != NULL )
640     {
641         vlc_value_t time, val;
642         NSString * o_time;
643         mtime_t i_seconds;
644         var_Get( p_input, "state", &val );
645
646         if( !p_input->b_die && ( p_intf->p_sys->b_play_status !=
647             ( val.i_int != PAUSE_S ) ) ) 
648         {
649             p_intf->p_sys->b_play_status =
650                 !p_intf->p_sys->b_play_status;
651
652             [self playStatusUpdated: p_intf->p_sys->b_play_status]; 
653         }
654
655         if( p_input->stream.b_seekable )
656         {
657             vlc_value_t pos;
658             float f_updated;
659             
660             var_Get( p_input, "position", &pos );
661             f_updated = 10000. * pos.f_float;
662
663             if( f_slider != f_updated )
664             {
665                 [o_timeslider setFloatValue: f_updated];
666             }
667         }
668             
669         var_Get( p_input, "time", &time );
670         i_seconds = time.i_time / 1000000;
671         
672         o_time = [NSString stringWithFormat: @"%d:%02d:%02d",
673                         (int) (i_seconds / (60 * 60)),
674                         (int) (i_seconds / 60 % 60),
675                         (int) (i_seconds % 60)];
676         [o_timefield setStringValue: o_time];
677
678         /* disable screen saver */
679         UpdateSystemActivity( UsrActivity );
680     }
681
682 #undef p_input
683
684     vlc_mutex_unlock( &p_playlist->object_lock );
685     vlc_object_release( p_playlist );
686
687     [self updateMessageArray];
688
689     [NSTimer scheduledTimerWithTimeInterval: 0.5
690         target: self selector: @selector(manageIntf:)
691         userInfo: nil repeats: FALSE];
692 }
693
694 - (void)setupMenus
695 {
696     intf_thread_t * p_intf = [NSApp getIntf];
697     playlist_t *p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
698                                                 FIND_ANYWHERE );
699     
700     if( p_playlist != NULL )
701     {
702 #define p_input p_playlist->p_input
703         if( p_input != NULL )
704         {
705             [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
706                 var: "program" selector: @selector(toggleVar:)];
707             
708             [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
709                 var: "title" selector: @selector(toggleVar:)];
710             
711             [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
712                 var: "chapter" selector: @selector(toggleVar:)];
713             
714             [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
715                 var: "audio-es" selector: @selector(toggleVar:)];
716             
717             [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
718                 var: "video-es" selector: @selector(toggleVar:)];
719             
720             [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
721                 var: "spu-es" selector: @selector(toggleVar:)];
722         
723             aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
724                                                         FIND_ANYWHERE );
725             if ( p_aout != NULL )
726             {
727                 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
728                     var: "audio-channels" selector: @selector(toggleVar:)];
729             
730                 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
731                     var: "audio-device" selector: @selector(toggleVar:)];
732                 vlc_object_release( (vlc_object_t *)p_aout );
733             }
734             
735             vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
736                                                                 FIND_ANYWHERE );
737             
738             if ( p_vout != NULL )
739             {
740                 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
741                     var: "video-device" selector: @selector(toggleVar:)];
742                 
743                 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
744                     var: "deinterlace" selector: @selector(toggleVar:)];
745                 vlc_object_release( (vlc_object_t *)p_vout );
746             }
747         }
748 #undef p_input
749     }
750     vlc_object_release( (vlc_object_t *)p_playlist );
751 }
752
753 - (void)updateMessageArray
754 {
755     int i_start, i_stop;
756     intf_thread_t * p_intf = [NSApp getIntf];
757
758     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
759     i_stop = *p_intf->p_sys->p_sub->pi_stop;
760     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
761
762     if( p_intf->p_sys->p_sub->i_start != i_stop )
763     {
764         NSColor *o_white = [NSColor whiteColor];
765         NSColor *o_red = [NSColor redColor];
766         NSColor *o_yellow = [NSColor yellowColor];
767         NSColor *o_gray = [NSColor grayColor];
768
769         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
770         static const char * ppsz_type[4] = { ": ", " error: ",
771                                              " warning: ", " debug: " };
772
773         for( i_start = p_intf->p_sys->p_sub->i_start;
774              i_start != i_stop;
775              i_start = (i_start+1) % VLC_MSG_QSIZE )
776         {
777             NSString *o_msg;
778             NSDictionary *o_attr;
779             NSAttributedString *o_msg_color;
780
781             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
782
783             [o_msg_lock lock];
784
785             if( [o_msg_arr count] + 2 > 400 )
786             {
787                 unsigned rid[] = { 0, 1 };
788                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
789                            numIndices: sizeof(rid)/sizeof(rid[0])];
790             }
791
792             o_attr = [NSDictionary dictionaryWithObject: o_gray
793                 forKey: NSForegroundColorAttributeName];
794             o_msg = [NSString stringWithFormat: @"%s%s",
795                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
796                 ppsz_type[i_type]];
797             o_msg_color = [[NSAttributedString alloc]
798                 initWithString: o_msg attributes: o_attr];
799             [o_msg_arr addObject: [o_msg_color autorelease]];
800
801             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
802                 forKey: NSForegroundColorAttributeName];
803             o_msg = [NSString stringWithFormat: @"%s\n",
804                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
805             o_msg_color = [[NSAttributedString alloc]
806                 initWithString: o_msg attributes: o_attr];
807             [o_msg_arr addObject: [o_msg_color autorelease]];
808
809             [o_msg_lock unlock];
810
811             if( i_type == 1 )
812             {
813                 NSString *o_my_msg = [NSString stringWithFormat: @"%s: %s\n",
814                     p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
815                     p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
816
817                 NSRange s_r = NSMakeRange( [[o_err_msg string] length], 0 );
818                 [o_err_msg setEditable: YES];
819                 [o_err_msg setSelectedRange: s_r];
820                 [o_err_msg insertText: o_my_msg];
821
822                 [o_error makeKeyAndOrderFront: self];
823                 [o_err_msg setEditable: NO];
824             }
825         }
826
827         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
828         p_intf->p_sys->p_sub->i_start = i_start;
829         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
830     }
831 }
832
833 - (void)playStatusUpdated:(BOOL)b_pause
834 {
835     if( b_pause )
836     {
837         [o_btn_play setImage: o_img_pause];
838         [o_btn_play setToolTip: _NS("Pause")];
839         [o_mi_play setTitle: _NS("Pause")];
840         [o_dmi_play setTitle: _NS("Pause")];
841     }
842     else
843     {
844         [o_btn_play setImage: o_img_play];
845         [o_btn_play setToolTip: _NS("Play")];
846         [o_mi_play setTitle: _NS("Play")];
847         [o_dmi_play setTitle: _NS("Play")];
848     }
849 }
850
851 - (void)setSubmenusEnabled:(BOOL)b_enabled
852 {
853     [o_mi_program setEnabled: b_enabled];
854     [o_mi_title setEnabled: b_enabled];
855     [o_mi_chapter setEnabled: b_enabled];
856     [o_mi_audiotrack setEnabled: b_enabled];
857     [o_mi_videotrack setEnabled: b_enabled];
858     [o_mi_subtitle setEnabled: b_enabled];
859     [o_mi_channels setEnabled: b_enabled];
860     [o_mi_deinterlace setEnabled: b_enabled];
861     [o_mi_device setEnabled: b_enabled];
862     [o_mi_screen setEnabled: b_enabled];
863 }
864
865 - (void)manageVolumeSlider
866 {
867     audio_volume_t i_volume;
868     intf_thread_t * p_intf = [NSApp getIntf];
869
870     aout_VolumeGet( p_intf, &i_volume );
871
872     [o_volumeslider setFloatValue: (float)i_volume / AOUT_VOLUME_STEP]; 
873     [o_volumeslider setEnabled: TRUE];
874
875     p_intf->p_sys->b_mute = ( i_volume == 0 );
876 }
877
878 - (IBAction)timesliderUpdate:(id)sender
879 {
880     intf_thread_t * p_intf;
881     input_thread_t * p_input;
882     float f_updated;
883
884     switch( [[NSApp currentEvent] type] )
885     {
886         case NSLeftMouseUp:
887         case NSLeftMouseDown:
888         case NSLeftMouseDragged:
889             f_updated = [sender floatValue];
890             break;
891
892         default:
893             return;
894     }
895
896     p_intf = [NSApp getIntf];
897     p_input = vlc_object_find( p_intf, VLC_OBJECT_INPUT,
898                                             FIND_ANYWHERE );
899
900     if( p_input != NULL )
901     {
902         vlc_value_t time;
903         mtime_t i_seconds;
904         NSString * o_time;
905
906         if( p_input->stream.b_seekable )
907         {
908                 vlc_value_t pos;
909                 pos.f_float = f_updated / 10000.;
910                 if( f_slider != f_updated )
911                 {
912                     var_Set( p_input, "position", pos );
913                     [o_timeslider setFloatValue: f_updated];
914                 }
915         }
916             
917         var_Get( p_input, "time", &time );
918         i_seconds = time.i_time / 1000000;
919         
920         o_time = [NSString stringWithFormat: @"%d:%02d:%02d",
921                         (int) (i_seconds / (60 * 60)),
922                         (int) (i_seconds / 60 % 60),
923                         (int) (i_seconds % 60)];
924         [o_timefield setStringValue: o_time];
925         vlc_object_release( p_input );
926     }
927 }
928
929 - (void)terminate
930 {
931     NSEvent * o_event;
932     playlist_t * p_playlist;
933     intf_thread_t * p_intf = [NSApp getIntf];
934
935     /*
936      * Free playlists
937      */
938     msg_Dbg( p_intf, "removing all playlists" );
939     while( (p_playlist = vlc_object_find( p_intf->p_vlc, VLC_OBJECT_PLAYLIST,
940                                           FIND_CHILD )) )
941     {
942         vlc_object_detach( p_playlist );
943         vlc_object_release( p_playlist );
944         playlist_Destroy( p_playlist );
945     }
946
947     if( o_img_pause != nil )
948     {
949         [o_img_pause release];
950         o_img_pause = nil;
951     }
952
953     if( o_img_play != nil )
954     {
955         [o_img_play release];
956         o_img_play = nil;
957     }
958
959     if( o_msg_arr != nil )
960     {
961         [o_msg_arr removeAllObjects];
962         [o_msg_arr release];
963         o_msg_arr = nil;
964     }
965
966     if( o_msg_lock != nil )
967     {
968         [o_msg_lock release];
969         o_msg_lock = nil;
970     }
971
972     [NSApp stop: nil];
973
974     /* write cached user defaults to disk */
975     [[NSUserDefaults standardUserDefaults] synchronize];
976
977     /* send a dummy event to break out of the event loop */
978     o_event = [NSEvent mouseEventWithType: NSLeftMouseDown
979                 location: NSMakePoint( 1, 1 ) modifierFlags: 0
980                 timestamp: 1 windowNumber: [[NSApp mainWindow] windowNumber]
981                 context: [NSGraphicsContext currentContext] eventNumber: 1
982                 clickCount: 1 pressure: 0.0];
983     [NSApp postEvent: o_event atStart: YES];
984 }
985
986 - (IBAction)clearRecentItems:(id)sender
987 {
988     [[NSDocumentController sharedDocumentController]
989                           clearRecentDocuments: nil];
990 }
991
992 - (void)openRecentItem:(id)sender
993 {
994     [self application: nil openFile: [sender title]]; 
995 }
996
997 - (IBAction)viewPreferences:(id)sender
998 {
999     [o_prefs showPrefs];
1000 }
1001
1002 - (IBAction)closeError:(id)sender
1003 {
1004     [o_err_msg setString: @""];
1005     [o_error performClose: self];
1006 }
1007
1008 - (IBAction)openReadMe:(id)sender
1009 {
1010     NSString * o_path = [[NSBundle mainBundle] 
1011         pathForResource: @"README.MacOSX" ofType: @"rtf"]; 
1012
1013     [[NSWorkspace sharedWorkspace] openFile: o_path 
1014                                    withApplication: @"TextEdit"];
1015 }
1016
1017 - (IBAction)openDocumentation:(id)sender
1018 {
1019     NSURL * o_url = [NSURL URLWithString: 
1020         @"http://www.videolan.org/doc/"];
1021
1022     [[NSWorkspace sharedWorkspace] openURL: o_url];
1023 }
1024
1025 - (IBAction)reportABug:(id)sender
1026 {
1027     NSURL * o_url = [NSURL URLWithString: 
1028         @"http://www.videolan.org/support/bug-reporting.html"];
1029
1030     [[NSWorkspace sharedWorkspace] openURL: o_url];
1031 }
1032
1033 - (IBAction)openWebsite:(id)sender
1034 {
1035     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org"];
1036
1037     [[NSWorkspace sharedWorkspace] openURL: o_url];
1038 }
1039
1040 - (IBAction)openLicense:(id)sender
1041 {
1042     NSString * o_path = [[NSBundle mainBundle] 
1043         pathForResource: @"COPYING" ofType: nil];
1044
1045     [[NSWorkspace sharedWorkspace] openFile: o_path 
1046                                    withApplication: @"TextEdit"];
1047 }
1048
1049 - (IBAction)openCrashLog:(id)sender
1050 {
1051     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
1052                                     stringByExpandingTildeInPath]; 
1053
1054     
1055     if ( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
1056     {
1057         [[NSWorkspace sharedWorkspace] openFile: o_path 
1058                                     withApplication: @"Console"];
1059     }
1060     else
1061     {
1062         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.") );
1063
1064     }
1065 }
1066
1067 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1068 {
1069     if( [o_notification object] == o_msgs_panel )
1070     {
1071         id o_msg;
1072         NSEnumerator * o_enum;
1073
1074         [o_messages setString: @""]; 
1075
1076         [o_msg_lock lock];
1077
1078         o_enum = [o_msg_arr objectEnumerator];
1079
1080         while( ( o_msg = [o_enum nextObject] ) != nil )
1081         {
1082             [o_messages insertText: o_msg];
1083         }
1084
1085         [o_msg_lock unlock];
1086     }
1087 }
1088
1089 @end
1090
1091 @implementation VLCMain (NSMenuValidation)
1092
1093 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
1094 {
1095     NSString *o_title = [o_mi title];
1096     BOOL bEnabled = TRUE;
1097
1098     if( [o_title isEqualToString: _NS("License")] )
1099     {
1100         /* we need to do this only once */
1101         [self setupMenus];
1102     }
1103
1104     /* Recent Items Menu */
1105     if( [o_title isEqualToString: _NS("Clear Menu")] )
1106     {
1107         NSMenu * o_menu = [o_mi_open_recent submenu];
1108         int i_nb_items = [o_menu numberOfItems];
1109         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
1110                                                        recentDocumentURLs];
1111         UInt32 i_nb_docs = [o_docs count];
1112
1113         if( i_nb_items > 1 )
1114         {
1115             while( --i_nb_items )
1116             {
1117                 [o_menu removeItemAtIndex: 0];
1118             }
1119         }
1120
1121         if( i_nb_docs > 0 )
1122         {
1123             NSURL * o_url;
1124             NSString * o_doc;
1125
1126             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
1127
1128             while( TRUE )
1129             {
1130                 i_nb_docs--;
1131
1132                 o_url = [o_docs objectAtIndex: i_nb_docs];
1133
1134                 if( [o_url isFileURL] )
1135                 {
1136                     o_doc = [o_url path];
1137                 }
1138                 else
1139                 {
1140                     o_doc = [o_url absoluteString];
1141                 }
1142
1143                 [o_menu insertItemWithTitle: o_doc
1144                     action: @selector(openRecentItem:)
1145                     keyEquivalent: @"" atIndex: 0]; 
1146
1147                 if( i_nb_docs == 0 )
1148                 {
1149                     break;
1150                 }
1151             } 
1152         }
1153         else
1154         {
1155             bEnabled = FALSE;
1156         }
1157     }
1158     return( bEnabled );
1159 }
1160
1161 @end
1162
1163 @implementation VLCMain (Internal)
1164
1165 - (void)handlePortMessage:(NSPortMessage *)o_msg
1166 {
1167     id ** val;
1168     NSData * o_data;
1169     NSValue * o_value;
1170     NSInvocation * o_inv;
1171     NSConditionLock * o_lock;
1172  
1173     o_data = [[o_msg components] lastObject];
1174     o_inv = *((NSInvocation **)[o_data bytes]); 
1175     [o_inv getArgument: &o_value atIndex: 2];
1176     val = (id **)[o_value pointerValue];
1177     [o_inv setArgument: val[1] atIndex: 2];
1178     o_lock = *(val[0]);
1179
1180     [o_lock lock];
1181     [o_inv invoke];
1182     [o_lock unlockWithCondition: 1];
1183 }
1184
1185 @end