osx/framework: added wrapper methods for snapshots and deinterlacing
[vlc.git] / modules / video_output / msw / events.c
1 /*****************************************************************************
2  * events.c: Windows DirectX video output events handler
3  *****************************************************************************
4  * Copyright (C) 2001-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24
25 /*****************************************************************************
26  * Preamble: This file contains the functions related to the creation of
27  *             a window and the handling of its messages (events).
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <errno.h>                                                 /* ENOMEM */
34 #include <ctype.h>                                              /* tolower() */
35
36 #ifndef _WIN32_WINNT
37 #   define _WIN32_WINNT 0x0500
38 #endif
39
40 #include <vlc_common.h>
41 #include <vlc_interface.h>
42 #include <vlc_playlist.h>
43 #include <vlc_vout.h>
44 #include <vlc_vout_window.h>
45
46 #include <windows.h>
47 #include <tchar.h>
48 #include <windowsx.h>
49 #include <shellapi.h>
50
51 #ifdef MODULE_NAME_IS_directx
52 #include <ddraw.h>
53 #endif
54 #ifdef MODULE_NAME_IS_direct3d
55 #include <d3d9.h>
56 #endif
57 #ifdef MODULE_NAME_IS_glwin32
58 #include <GL/gl.h>
59 #endif
60
61 #include <vlc_keys.h>
62 #include "vout.h"
63
64 #ifdef UNDER_CE
65 #include <aygshell.h>
66     //WINSHELLAPI BOOL WINAPI SHFullScreen(HWND hwndRequester, DWORD dwState);
67 #endif
68
69 /*#if defined(UNDER_CE) && !defined(__PLUGIN__) --FIXME*/
70 /*#   define SHFS_SHOWSIPBUTTON 0x0004
71 #   define SHFS_HIDESIPBUTTON 0x0008
72 #   define MENU_HEIGHT 26
73     BOOL SHFullScreen(HWND hwndRequester, DWORD dwState);
74 #endif*/
75
76 /*****************************************************************************
77  * Local prototypes.
78  *****************************************************************************/
79 #define WM_VLC_HIDE_MOUSE   (WM_APP + 0)
80 #define WM_VLC_SHOW_MOUSE   (WM_APP + 1)
81 #define WM_VLC_CHANGE_TEXT  (WM_APP + 2)
82
83 struct event_thread_t
84 {
85     vout_thread_t *p_vout;
86
87     /* */
88     vlc_thread_t thread;
89     vlc_mutex_t  lock;
90     vlc_cond_t   wait;
91     bool         b_ready;
92     bool         b_done;
93     bool         b_error;
94
95     /* */
96     bool use_desktop;
97     bool use_overlay;
98
99     /* Mouse */
100     volatile bool    b_cursor_hidden;
101     volatile mtime_t i_lastmoved;
102     mtime_t          i_mouse_hide_timeout;
103
104     /* Title */
105     char *psz_title;
106
107     int               i_window_style;
108     vout_window_cfg_t wnd_cfg;
109
110     /* */
111     unsigned i_changes;
112
113     /* */
114     vout_window_t *parent_window;
115     HWND hparent;
116     HWND hwnd;
117     HWND hvideownd;
118     HWND hfswnd;
119 };
120
121 static int  DirectXCreateWindow( event_thread_t * );
122 static void DirectXCloseWindow ( event_thread_t * );
123 static long FAR PASCAL DirectXEventProc( HWND, UINT, WPARAM, LPARAM );
124
125 static void DirectXPopupMenu( event_thread_t *p_event, bool b_open )
126 {
127     var_SetBool( p_event->p_vout->p_libvlc, "intf-popupmenu", b_open );
128 }
129
130 static int DirectXConvertKey( int i_key );
131
132 /*****************************************************************************
133  * EventThread: Create video window & handle its messages
134  *****************************************************************************
135  * This function creates a video window and then enters an infinite loop
136  * that handles the messages sent to that window.
137  * The main goal of this thread is to isolate the Win32 PeekMessage function
138  * because this one can block for a long time.
139  *****************************************************************************/
140 static void *EventThread( void *p_this )
141 {
142     event_thread_t *p_event = (event_thread_t *)p_this;
143     vout_thread_t *p_vout = p_event->p_vout;
144     MSG msg;
145     POINT old_mouse_pos = {0,0}, mouse_pos;
146     vlc_value_t val;
147     unsigned int i_width, i_height, i_x, i_y;
148     HMODULE hkernel32;
149     int canc = vlc_savecancel ();
150
151     vlc_mutex_lock( &p_event->lock );
152     /* Create a window for the video */
153     /* Creating a window under Windows also initializes the thread's event
154      * message queue */
155     if( DirectXCreateWindow( p_event ) )
156         p_event->b_error = true;
157
158     p_event->b_ready = true;
159     vlc_cond_signal( &p_event->wait );
160
161     const bool b_error = p_event->b_error;
162     vlc_mutex_unlock( &p_event->lock );
163
164     if( b_error )
165     {
166         vlc_restorecancel( canc );
167         return NULL;
168     }
169
170 #ifndef UNDER_CE
171     /* Set power management stuff */
172     if( (hkernel32 = GetModuleHandle( _T("KERNEL32") ) ) )
173     {
174         ULONG (WINAPI* OurSetThreadExecutionState)( ULONG );
175
176         OurSetThreadExecutionState = (ULONG (WINAPI*)( ULONG ))
177             GetProcAddress( hkernel32, _T("SetThreadExecutionState") );
178
179         if( OurSetThreadExecutionState )
180             /* Prevent monitor from powering off */
181             OurSetThreadExecutionState( ES_DISPLAY_REQUIRED | ES_CONTINUOUS );
182         else
183             msg_Dbg( p_vout, "no support for SetThreadExecutionState()" );
184     }
185 #endif
186
187     /* Main loop */
188     /* GetMessage will sleep if there's no message in the queue */
189     for( ;; )
190     {
191         if( !GetMessage( &msg, 0, 0, 0 ) )
192         {
193             vlc_mutex_lock( &p_event->lock );
194             p_event->b_done = true;
195             vlc_mutex_unlock( &p_event->lock );
196             break;
197         }
198
199         /* Check if we are asked to exit */
200         vlc_mutex_lock( &p_event->lock );
201         const bool b_done = p_event->b_done;
202         vlc_mutex_unlock( &p_event->lock );
203         if( b_done )
204             break;
205
206         /* */
207         switch( msg.message )
208         {
209
210         case WM_MOUSEMOVE:
211             vlc_mutex_lock( &p_event->lock );
212             vout_PlacePicture( p_event->p_vout,
213                                p_event->wnd_cfg.width,
214                                p_event->wnd_cfg.height,
215                                &i_x, &i_y, &i_width, &i_height );
216             vlc_mutex_unlock( &p_event->lock );
217
218             if( msg.hwnd == p_event->hvideownd )
219             {
220                 /* Child window */
221                 i_x = i_y = 0;
222             }
223
224             if( i_width && i_height )
225             {
226                 val.i_int = ( GET_X_LPARAM(msg.lParam) - i_x ) *
227                     p_event->p_vout->fmt_in.i_visible_width / i_width +
228                     p_event->p_vout->fmt_in.i_x_offset;
229                 var_Set( p_event->p_vout, "mouse-x", val );
230                 val.i_int = ( GET_Y_LPARAM(msg.lParam) - i_y ) *
231                     p_event->p_vout->fmt_in.i_visible_height / i_height +
232                     p_event->p_vout->fmt_in.i_y_offset;
233                 var_Set( p_event->p_vout, "mouse-y", val );
234
235                 var_SetBool( p_event->p_vout, "mouse-moved", true );
236             }
237
238         case WM_NCMOUSEMOVE:
239             GetCursorPos( &mouse_pos );
240             if( (abs(mouse_pos.x - old_mouse_pos.x) > 2 ||
241                 (abs(mouse_pos.y - old_mouse_pos.y)) > 2 ) )
242             {
243                 GetCursorPos( &old_mouse_pos );
244                 p_event->i_lastmoved = mdate();
245
246                 if( p_event->b_cursor_hidden )
247                 {
248                     p_event->b_cursor_hidden = 0;
249                     ShowCursor( TRUE );
250                 }
251             }
252             break;
253
254         case WM_VLC_HIDE_MOUSE:
255             if( p_event->b_cursor_hidden ) break;
256             p_event->b_cursor_hidden = true;
257             GetCursorPos( &old_mouse_pos );
258             ShowCursor( FALSE );
259             break;
260
261         case WM_VLC_SHOW_MOUSE:
262             if( !p_event->b_cursor_hidden ) break;
263             p_event->b_cursor_hidden = false;
264             GetCursorPos( &old_mouse_pos );
265             ShowCursor( TRUE );
266             break;
267
268         case WM_LBUTTONDOWN:
269             var_Get( p_event->p_vout, "mouse-button-down", &val );
270             val.i_int |= 1;
271             var_Set( p_event->p_vout, "mouse-button-down", val );
272             DirectXPopupMenu( p_event, false );
273             break;
274
275         case WM_LBUTTONUP:
276             var_Get( p_event->p_vout, "mouse-button-down", &val );
277             val.i_int &= ~1;
278             var_Set( p_event->p_vout, "mouse-button-down", val );
279
280             var_SetBool( p_event->p_vout, "mouse-clicked", true );
281             break;
282
283         case WM_LBUTTONDBLCLK:
284             vlc_mutex_lock( &p_event->lock );
285             p_event->i_changes |= VOUT_FULLSCREEN_CHANGE;
286             vlc_mutex_unlock( &p_event->lock );
287             break;
288
289         case WM_MBUTTONDOWN:
290             var_Get( p_event->p_vout, "mouse-button-down", &val );
291             val.i_int |= 2;
292             var_Set( p_event->p_vout, "mouse-button-down", val );
293             DirectXPopupMenu( p_event, false );
294             break;
295
296         case WM_MBUTTONUP:
297             var_Get( p_event->p_vout, "mouse-button-down", &val );
298             val.i_int &= ~2;
299             var_Set( p_event->p_vout, "mouse-button-down", val );
300             break;
301
302         case WM_RBUTTONDOWN:
303             var_Get( p_event->p_vout, "mouse-button-down", &val );
304             val.i_int |= 4;
305             var_Set( p_event->p_vout, "mouse-button-down", val );
306             DirectXPopupMenu( p_event, false );
307             break;
308
309         case WM_RBUTTONUP:
310             var_Get( p_event->p_vout, "mouse-button-down", &val );
311             val.i_int &= ~4;
312             var_Set( p_event->p_vout, "mouse-button-down", val );
313             DirectXPopupMenu( p_event, true );
314             break;
315
316         case WM_KEYDOWN:
317         case WM_SYSKEYDOWN:
318             /* The key events are first processed here and not translated
319              * into WM_CHAR events because we need to know the status of the
320              * modifier keys. */
321             val.i_int = DirectXConvertKey( msg.wParam );
322             if( !val.i_int )
323             {
324                 /* This appears to be a "normal" (ascii) key */
325                 val.i_int = tolower( MapVirtualKey( msg.wParam, 2 ) );
326             }
327
328             if( val.i_int )
329             {
330                 if( GetKeyState(VK_CONTROL) & 0x8000 )
331                 {
332                     val.i_int |= KEY_MODIFIER_CTRL;
333                 }
334                 if( GetKeyState(VK_SHIFT) & 0x8000 )
335                 {
336                     val.i_int |= KEY_MODIFIER_SHIFT;
337                 }
338                 if( GetKeyState(VK_MENU) & 0x8000 )
339                 {
340                     val.i_int |= KEY_MODIFIER_ALT;
341                 }
342
343                 var_Set( p_vout->p_libvlc, "key-pressed", val );
344             }
345             break;
346
347         case WM_MOUSEWHEEL:
348             if( GET_WHEEL_DELTA_WPARAM( msg.wParam ) > 0 )
349             {
350                 val.i_int = KEY_MOUSEWHEELUP;
351             }
352             else
353             {
354                 val.i_int = KEY_MOUSEWHEELDOWN;
355             }
356             if( val.i_int )
357             {
358                 if( GetKeyState(VK_CONTROL) & 0x8000 )
359                 {
360                     val.i_int |= KEY_MODIFIER_CTRL;
361                 }
362                 if( GetKeyState(VK_SHIFT) & 0x8000 )
363                 {
364                     val.i_int |= KEY_MODIFIER_SHIFT;
365                 }
366                 if( GetKeyState(VK_MENU) & 0x8000 )
367                 {
368                     val.i_int |= KEY_MODIFIER_ALT;
369                 }
370
371                 var_Set( p_vout->p_libvlc, "key-pressed", val );
372             }
373             break;
374
375         case WM_VLC_CHANGE_TEXT:
376         {
377             vlc_mutex_lock( &p_event->lock );
378             wchar_t *pwz_title = NULL;
379             if( p_event->psz_title )
380             {
381                 const size_t i_length = strlen(p_event->psz_title);
382                 pwz_title = malloc( 2 * (i_length + 1) );
383                 if( pwz_title )
384                 {
385                     mbstowcs( pwz_title, p_event->psz_title, 2 * i_length );
386                     pwz_title[i_length] = 0;
387                 }
388             }
389             vlc_mutex_unlock( &p_event->lock );
390
391             if( pwz_title )
392             {
393                 SetWindowText( p_event->hwnd, (LPCTSTR)pwz_title );
394                 if( p_event->hfswnd )
395                     SetWindowText( p_event->hfswnd, (LPCTSTR)pwz_title );
396                 free( pwz_title );
397             }
398             break;
399         }
400
401         default:
402             /* Messages we don't handle directly are dispatched to the
403              * window procedure */
404             TranslateMessage(&msg);
405             DispatchMessage(&msg);
406             break;
407
408         } /* End Switch */
409
410     } /* End Main loop */
411
412     /* Check for WM_QUIT if we created the window */
413     if( !p_event->hparent && msg.message == WM_QUIT )
414     {
415         msg_Warn( p_vout, "WM_QUIT... should not happen!!" );
416         p_event->hwnd = NULL; /* Window already destroyed */
417     }
418
419     msg_Dbg( p_vout, "DirectXEventThread terminating" );
420
421     DirectXCloseWindow( p_event );
422     vlc_restorecancel(canc);
423     return NULL;
424 }
425
426
427 /* following functions are local */
428
429 /*****************************************************************************
430  * DirectXCreateWindow: create a window for the video.
431  *****************************************************************************
432  * Before creating a direct draw surface, we need to create a window in which
433  * the video will be displayed. This window will also allow us to capture the
434  * events.
435  *****************************************************************************/
436 static int DirectXCreateWindow( event_thread_t *p_event )
437 {
438     vout_thread_t *p_vout = p_event->p_vout;
439     HINSTANCE  hInstance;
440     HMENU      hMenu;
441     RECT       rect_window;
442     WNDCLASS   wc;                            /* window class components */
443     HICON      vlc_icon;
444     char       vlc_path[MAX_PATH+1];
445     int        i_style, i_stylex;
446
447     msg_Dbg( p_vout, "DirectXCreateWindow" );
448
449     /* Get this module's instance */
450     hInstance = GetModuleHandle(NULL);
451
452     #ifdef MODULE_NAME_IS_direct3d
453     if( !p_event->use_desktop )
454     {
455     #endif
456         /* If an external window was specified, we'll draw in it. */
457         p_event->parent_window = vout_window_New( VLC_OBJECT(p_vout), NULL, &p_event->wnd_cfg );
458         if( p_event->parent_window )
459             p_event->hparent = p_event->parent_window->handle.hwnd;
460     #ifdef MODULE_NAME_IS_direct3d
461     }
462     else
463     {
464         /* Find Program Manager */
465         HWND hwnd = FindWindow( _T("Progman"), NULL );
466         if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SHELLDLL_DefView"), NULL );
467         if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SysListView32"), NULL );
468         if( !hwnd )
469             msg_Err( p_vout, "Couldn't find desktop icon window. Desktop mode can't be established." );
470         p_event->hparent = hwnd;
471     }
472     #endif
473
474     /* Get the Icon from the main app */
475     vlc_icon = NULL;
476 #ifndef UNDER_CE
477     if( GetModuleFileName( NULL, vlc_path, MAX_PATH ) )
478     {
479         vlc_icon = ExtractIcon( hInstance, vlc_path, 0 );
480     }
481 #endif
482
483     /* Fill in the window class structure */
484     wc.style         = CS_OWNDC|CS_DBLCLKS;          /* style: dbl click */
485     wc.lpfnWndProc   = (WNDPROC)DirectXEventProc;       /* event handler */
486     wc.cbClsExtra    = 0;                         /* no extra class data */
487     wc.cbWndExtra    = 0;                        /* no extra window data */
488     wc.hInstance     = hInstance;                            /* instance */
489     wc.hIcon         = vlc_icon;                /* load the vlc big icon */
490     wc.hCursor       = LoadCursor(NULL, IDC_ARROW);    /* default cursor */
491     wc.hbrBackground = GetStockObject(BLACK_BRUSH);  /* background color */
492     wc.lpszMenuName  = NULL;                                  /* no menu */
493     wc.lpszClassName = _T("VLC DirectX");         /* use a special class */
494
495     /* Register the window class */
496     if( !RegisterClass(&wc) )
497     {
498         WNDCLASS wndclass;
499
500         if( vlc_icon ) DestroyIcon( vlc_icon );
501
502         /* Check why it failed. If it's because one already exists
503          * then fine, otherwise return with an error. */
504         if( !GetClassInfo( hInstance, _T("VLC DirectX"), &wndclass ) )
505         {
506             msg_Err( p_vout, "DirectXCreateWindow RegisterClass FAILED (err=%lu)", GetLastError() );
507             return VLC_EGENERIC;
508         }
509     }
510
511     /* Register the video sub-window class */
512     wc.lpszClassName = _T("VLC DirectX video"); wc.hIcon = 0;
513     wc.hbrBackground = NULL; /* no background color */
514     if( !RegisterClass(&wc) )
515     {
516         WNDCLASS wndclass;
517
518         /* Check why it failed. If it's because one already exists
519          * then fine, otherwise return with an error. */
520         if( !GetClassInfo( hInstance, _T("VLC DirectX video"), &wndclass ) )
521         {
522             msg_Err( p_vout, "DirectXCreateWindow RegisterClass FAILED (err=%lu)", GetLastError() );
523             return VLC_EGENERIC;
524         }
525     }
526
527     /* When you create a window you give the dimensions you wish it to
528      * have. Unfortunatly these dimensions will include the borders and
529      * titlebar. We use the following function to find out the size of
530      * the window corresponding to the useable surface we want */
531     rect_window.top    = 10;
532     rect_window.left   = 10;
533     rect_window.right  = rect_window.left + p_event->wnd_cfg.width;
534     rect_window.bottom = rect_window.top  + p_event->wnd_cfg.height;
535
536     if( var_GetBool( p_vout, "video-deco" ) )
537     {
538         /* Open with window decoration */
539         AdjustWindowRect( &rect_window, WS_OVERLAPPEDWINDOW|WS_SIZEBOX, 0 );
540         i_style = WS_OVERLAPPEDWINDOW|WS_SIZEBOX|WS_VISIBLE|WS_CLIPCHILDREN;
541         i_stylex = 0;
542     }
543     else
544     {
545         /* No window decoration */
546         AdjustWindowRect( &rect_window, WS_POPUP, 0 );
547         i_style = WS_POPUP|WS_VISIBLE|WS_CLIPCHILDREN;
548         i_stylex = 0; // WS_EX_TOOLWINDOW; Is TOOLWINDOW really needed ?
549                       // It messes up the fullscreen window.
550     }
551
552     if( p_event->hparent )
553     {
554         i_style = WS_VISIBLE|WS_CLIPCHILDREN|WS_CHILD;
555         i_stylex = 0;
556     }
557
558     p_event->i_window_style = i_style;
559
560     /* Create the window */
561     p_event->hwnd =
562         CreateWindowEx( WS_EX_NOPARENTNOTIFY | i_stylex,
563                     _T("VLC DirectX"),               /* name of window class */
564                     _T(VOUT_TITLE) _T(" (DirectX Output)"),  /* window title */
565                     i_style,                                 /* window style */
566                     (p_event->wnd_cfg.x < 0) ? CW_USEDEFAULT :
567                         (UINT)p_event->wnd_cfg.x,   /* default X coordinate */
568                     (p_event->wnd_cfg.y < 0) ? CW_USEDEFAULT :
569                         (UINT)p_event->wnd_cfg.y,   /* default Y coordinate */
570                     rect_window.right - rect_window.left,    /* window width */
571                     rect_window.bottom - rect_window.top,   /* window height */
572                     p_event->hparent,                       /* parent window */
573                     NULL,                          /* no menu in this window */
574                     hInstance,            /* handle of this program instance */
575                     (LPVOID)p_event );           /* send p_vout to WM_CREATE */
576
577     if( !p_event->hwnd )
578     {
579         msg_Warn( p_vout, "DirectXCreateWindow create window FAILED (err=%lu)", GetLastError() );
580         return VLC_EGENERIC;
581     }
582
583     if( p_event->hparent )
584     {
585         LONG i_style;
586
587         /* We don't want the window owner to overwrite our client area */
588         i_style = GetWindowLong( p_event->hparent, GWL_STYLE );
589
590         if( !(i_style & WS_CLIPCHILDREN) )
591             /* Hmmm, apparently this is a blocking call... */
592             SetWindowLong( p_event->hparent, GWL_STYLE,
593                            i_style | WS_CLIPCHILDREN );
594
595         /* Create our fullscreen window */
596         p_event->hfswnd =
597             CreateWindowEx( WS_EX_APPWINDOW, _T("VLC DirectX"),
598                             _T(VOUT_TITLE) _T(" (DirectX Output)"),
599                             WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN|WS_SIZEBOX,
600                             CW_USEDEFAULT, CW_USEDEFAULT,
601                             CW_USEDEFAULT, CW_USEDEFAULT,
602                             NULL, NULL, hInstance, NULL );
603     }
604
605     /* Append a "Always On Top" entry in the system menu */
606     hMenu = GetSystemMenu( p_event->hwnd, FALSE );
607     AppendMenu( hMenu, MF_SEPARATOR, 0, _T("") );
608     AppendMenu( hMenu, MF_STRING | MF_UNCHECKED,
609                        IDM_TOGGLE_ON_TOP, _T("Always on &Top") );
610
611     /* Create video sub-window. This sub window will always exactly match
612      * the size of the video, which allows us to use crazy overlay colorkeys
613      * without having them shown outside of the video area. */
614     p_event->hvideownd =
615     CreateWindow( _T("VLC DirectX video"), _T(""),   /* window class */
616         WS_CHILD,                   /* window style, not visible initially */
617         0, 0,
618         p_vout->render.i_width,          /* default width */
619         p_vout->render.i_height,        /* default height */
620         p_event->hwnd,                   /* parent window */
621         NULL, hInstance,
622         (LPVOID)p_event );    /* send p_vout to WM_CREATE */
623
624     if( !p_event->hvideownd )
625         msg_Warn( p_vout, "can't create video sub-window" );
626     else
627         msg_Dbg( p_vout, "created video sub-window" );
628
629     /* Now display the window */
630     ShowWindow( p_event->hwnd, SW_SHOW );
631
632     return VLC_SUCCESS;
633 }
634
635 /*****************************************************************************
636  * DirectXCloseWindow: close the window created by DirectXCreateWindow
637  *****************************************************************************
638  * This function returns all resources allocated by DirectXCreateWindow.
639  *****************************************************************************/
640 static void DirectXCloseWindow( event_thread_t *p_event )
641 {
642     vout_thread_t *p_vout = p_event->p_vout;
643     msg_Dbg( p_vout, "DirectXCloseWindow" );
644
645     DestroyWindow( p_event->hwnd );
646     if( p_event->hfswnd ) DestroyWindow( p_event->hfswnd );
647
648     #ifdef MODULE_NAME_IS_direct3d
649     if( !p_event->use_desktop )
650     #endif
651         vout_window_Delete( p_event->parent_window );
652     p_event->hwnd = NULL;
653
654     /* We don't unregister the Window Class because it could lead to race
655      * conditions and it will be done anyway by the system when the app will
656      * exit */
657 }
658
659 /*****************************************************************************
660  * DirectXEventProc: This is the window event processing function.
661  *****************************************************************************
662  * On Windows, when you create a window you have to attach an event processing
663  * function to it. The aim of this function is to manage "Queued Messages" and
664  * "Nonqueued Messages".
665  * Queued Messages are those picked up and retransmitted by vout_Manage
666  * (using the GetMessage and DispatchMessage functions).
667  * Nonqueued Messages are those that Windows will send directly to this
668  * procedure (like WM_DESTROY, WM_WINDOWPOSCHANGED...)
669  *****************************************************************************/
670 static long FAR PASCAL DirectXEventProc( HWND hwnd, UINT message,
671                                          WPARAM wParam, LPARAM lParam )
672 {
673     event_thread_t *p_event;
674
675     if( message == WM_CREATE )
676     {
677         /* Store p_vout for future use */
678         p_event = (event_thread_t *)((CREATESTRUCT *)lParam)->lpCreateParams;
679         SetWindowLongPtr( hwnd, GWLP_USERDATA, (LONG_PTR)p_event );
680         return TRUE;
681     }
682     else
683     {
684         LONG_PTR p_user_data = GetWindowLongPtr( hwnd, GWLP_USERDATA );
685         p_event = (event_thread_t *)p_user_data;
686         if( !p_event )
687         {
688             /* Hmmm mozilla does manage somehow to save the pointer to our
689              * windowproc and still calls it after the vout has been closed. */
690             return DefWindowProc(hwnd, message, wParam, lParam);
691         }
692     }
693     vout_thread_t *p_vout = p_event->p_vout;
694
695 #ifndef UNDER_CE
696     /* Catch the screensaver and the monitor turn-off */
697     if( message == WM_SYSCOMMAND &&
698         ( (wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER ) )
699     {
700         //if( p_vout ) msg_Dbg( p_vout, "WinProc WM_SYSCOMMAND screensaver" );
701         return 0; /* this stops them from happening */
702     }
703 #endif
704
705     if( hwnd == p_event->hvideownd )
706     {
707         switch( message )
708         {
709 #ifdef MODULE_NAME_IS_directx
710         case WM_ERASEBKGND:
711         /* For overlay, we need to erase background */
712             return !p_event->use_overlay ?
713                 1 : DefWindowProc(hwnd, message, wParam, lParam);
714         case WM_PAINT:
715         /*
716         ** For overlay, DefWindowProc() will erase dirty regions
717         ** with colorkey.
718         ** For non-overlay, vout will paint the whole window at
719         ** regular interval, therefore dirty regions can be ignored
720         ** to minimize repaint.
721         */
722             if( !p_event->use_overlay )
723             {
724                 ValidateRect(hwnd, NULL);
725             }
726             // fall through to default
727 #else
728         /*
729         ** For OpenGL and Direct3D, vout will update the whole
730         ** window at regular interval, therefore dirty region
731         ** can be ignored to minimize repaint.
732         */
733         case WM_ERASEBKGND:
734             /* nothing to erase */
735             return 1;
736         case WM_PAINT:
737             /* nothing to repaint */
738             ValidateRect(hwnd, NULL);
739             // fall through
740 #endif
741         default:
742             return DefWindowProc(hwnd, message, wParam, lParam);
743         }
744     }
745
746     switch( message )
747     {
748
749     case WM_WINDOWPOSCHANGED:
750         UpdateRects( p_vout, true );
751         return 0;
752
753     /* the user wants to close the window */
754     case WM_CLOSE:
755     {
756         playlist_t * p_playlist = pl_Hold( p_vout );
757         if( p_playlist )
758         {
759             playlist_Stop( p_playlist );
760             pl_Release( p_vout );
761         }
762         return 0;
763     }
764
765     /* the window has been closed so shut down everything now */
766     case WM_DESTROY:
767         msg_Dbg( p_vout, "WinProc WM_DESTROY" );
768         /* just destroy the window */
769         PostQuitMessage( 0 );
770         return 0;
771
772     case WM_SYSCOMMAND:
773         switch (wParam)
774         {
775             case IDM_TOGGLE_ON_TOP:            /* toggle the "on top" status */
776             {
777                 msg_Dbg( p_vout, "WinProc WM_SYSCOMMAND: IDM_TOGGLE_ON_TOP");
778
779                 /* Change the current value */
780                 var_ToggleBool( p_vout, "video-on-top" );
781                 return 0;
782             }
783         }
784         break;
785
786     case WM_PAINT:
787     case WM_NCPAINT:
788     case WM_ERASEBKGND:
789         return DefWindowProc(hwnd, message, wParam, lParam);
790
791     case WM_KILLFOCUS:
792 #ifdef MODULE_NAME_IS_wingapi
793         GXSuspend();
794 #endif
795 #ifdef UNDER_CE
796         if( hwnd == p_event->hfswnd )
797         {
798             HWND htbar = FindWindow( _T("HHTaskbar"), NULL );
799             ShowWindow( htbar, SW_SHOW );
800         }
801
802         if( !p_event->hparent ||
803             hwnd == p_event->hfswnd )
804         {
805             SHFullScreen( hwnd, SHFS_SHOWSIPBUTTON );
806         }
807 #endif
808         return 0;
809
810     case WM_SETFOCUS:
811 #ifdef MODULE_NAME_IS_wingapi
812         GXResume();
813 #endif
814 #ifdef UNDER_CE
815         if( p_event->hparent &&
816             hwnd != p_event->hfswnd && p_vout->b_fullscreen )
817         {
818             vlc_mutex_lock( &p_event->lock );
819             p_event->i_changes |= VOUT_FULLSCREEN_CHANGE;
820             vlc_mutex_unlock( &p_event->lock );
821         }
822
823         if( hwnd == p_event->hfswnd )
824         {
825             HWND htbar = FindWindow( _T("HHTaskbar"), NULL );
826             ShowWindow( htbar, SW_HIDE );
827         }
828
829         if( !p_event->hparent ||
830             hwnd == p_event->hfswnd )
831         {
832             SHFullScreen( hwnd, SHFS_HIDESIPBUTTON );
833         }
834 #endif
835         return 0;
836
837     default:
838         //msg_Dbg( p_vout, "WinProc WM Default %i", message );
839         break;
840     }
841
842     /* Let windows handle the message */
843     return DefWindowProc(hwnd, message, wParam, lParam);
844 }
845
846 static struct
847 {
848     int i_dxkey;
849     int i_vlckey;
850
851 } dxkeys_to_vlckeys[] =
852 {
853     { VK_F1, KEY_F1 }, { VK_F2, KEY_F2 }, { VK_F3, KEY_F3 }, { VK_F4, KEY_F4 },
854     { VK_F5, KEY_F5 }, { VK_F6, KEY_F6 }, { VK_F7, KEY_F7 }, { VK_F8, KEY_F8 },
855     { VK_F9, KEY_F9 }, { VK_F10, KEY_F10 }, { VK_F11, KEY_F11 },
856     { VK_F12, KEY_F12 },
857
858     { VK_RETURN, KEY_ENTER },
859     { VK_SPACE, ' ' },
860     { VK_ESCAPE, KEY_ESC },
861
862     { VK_LEFT, KEY_LEFT },
863     { VK_RIGHT, KEY_RIGHT },
864     { VK_UP, KEY_UP },
865     { VK_DOWN, KEY_DOWN },
866
867     { VK_HOME, KEY_HOME },
868     { VK_END, KEY_END },
869     { VK_PRIOR, KEY_PAGEUP },
870     { VK_NEXT, KEY_PAGEDOWN },
871
872     { VK_INSERT, KEY_INSERT },
873     { VK_DELETE, KEY_DELETE },
874
875     { VK_CONTROL, 0 },
876     { VK_SHIFT, 0 },
877     { VK_MENU, 0 },
878
879     { VK_BROWSER_BACK, KEY_BROWSER_BACK },
880     { VK_BROWSER_FORWARD, KEY_BROWSER_FORWARD },
881     { VK_BROWSER_REFRESH, KEY_BROWSER_REFRESH },
882     { VK_BROWSER_STOP, KEY_BROWSER_STOP },
883     { VK_BROWSER_SEARCH, KEY_BROWSER_SEARCH },
884     { VK_BROWSER_FAVORITES, KEY_BROWSER_FAVORITES },
885     { VK_BROWSER_HOME, KEY_BROWSER_HOME },
886     { VK_VOLUME_MUTE, KEY_VOLUME_MUTE },
887     { VK_VOLUME_DOWN, KEY_VOLUME_DOWN },
888     { VK_VOLUME_UP, KEY_VOLUME_UP },
889     { VK_MEDIA_NEXT_TRACK, KEY_MEDIA_NEXT_TRACK },
890     { VK_MEDIA_PREV_TRACK, KEY_MEDIA_PREV_TRACK },
891     { VK_MEDIA_STOP, KEY_MEDIA_STOP },
892     { VK_MEDIA_PLAY_PAUSE, KEY_MEDIA_PLAY_PAUSE },
893
894     { 0, 0 }
895 };
896
897 static int DirectXConvertKey( int i_key )
898 {
899     int i;
900
901     for( i = 0; dxkeys_to_vlckeys[i].i_dxkey != 0; i++ )
902     {
903         if( dxkeys_to_vlckeys[i].i_dxkey == i_key )
904         {
905             return dxkeys_to_vlckeys[i].i_vlckey;
906         }
907     }
908
909     return 0;
910 }
911
912 void EventThreadMouseAutoHide( event_thread_t *p_event )
913 {
914     vout_thread_t *p_vout = p_event->p_vout;
915
916     if( p_vout->b_fullscreen &&
917         !p_event->b_cursor_hidden &&
918         (mdate() - p_event->i_lastmoved) > p_event->i_mouse_hide_timeout )
919     {
920         /* Hide the cursor only if it is inside our window */
921         POINT point;
922         GetCursorPos( &point );
923
924         HWND hwnd = WindowFromPoint(point);
925         if( hwnd == p_event->hwnd || hwnd == p_event->hvideownd )
926         {
927             PostMessage( p_event->hwnd, WM_VLC_HIDE_MOUSE, 0, 0 );
928         }
929         else
930         {
931             p_event->i_lastmoved = mdate();
932         }
933     }
934 }
935 void EventThreadMouseShow( event_thread_t *p_event )
936 {
937     PostMessage( p_event->hwnd, WM_VLC_SHOW_MOUSE, 0, 0 );
938 }
939 void EventThreadUpdateTitle( event_thread_t *p_event, const char *psz_fallback )
940 {
941     char *psz_title = var_GetNonEmptyString( p_event->p_vout, "video-title" );
942     if( !psz_title )
943         psz_title = strdup( psz_fallback );
944     if( !psz_title )
945         return;
946
947     vlc_mutex_lock( &p_event->lock );
948     free( p_event->psz_title );
949     p_event->psz_title = psz_title;
950     vlc_mutex_unlock( &p_event->lock );
951
952     PostMessage( p_event->hwnd, WM_VLC_CHANGE_TEXT, 0, 0 );
953 }
954 unsigned EventThreadRetreiveChanges( event_thread_t *p_event )
955 {
956     vlc_mutex_lock( &p_event->lock );
957     unsigned i_changes = p_event->i_changes;
958     p_event->i_changes = 0;
959     vlc_mutex_unlock( &p_event->lock );
960
961     return i_changes;
962 }
963 int EventThreadGetWindowStyle( event_thread_t *p_event )
964 {
965     /* No need to lock, it is serialized by EventThreadStart */
966     return p_event->i_window_style;
967 }
968
969 void EventThreadUpdateWindowPosition( event_thread_t *p_event, bool *pb_changed,
970                                       int x, int y, int w, int h )
971 {
972     vlc_mutex_lock( &p_event->lock );
973     *pb_changed = x != p_event->wnd_cfg.x ||
974                   y != p_event->wnd_cfg.y ||
975                   w != p_event->wnd_cfg.width ||
976                   h != p_event->wnd_cfg.height;
977
978     p_event->wnd_cfg.x      = x;
979     p_event->wnd_cfg.y      = y;
980     p_event->wnd_cfg.width  = y;
981     p_event->wnd_cfg.height = h;
982     vlc_mutex_unlock( &p_event->lock );
983 }
984 event_thread_t *EventThreadCreate( vout_thread_t *p_vout, const vout_window_cfg_t *p_wnd_cfg )
985 {
986      /* Create the Vout EventThread, this thread is created by us to isolate
987      * the Win32 PeekMessage function calls. We want to do this because
988      * Windows can stay blocked inside this call for a long time, and when
989      * this happens it thus blocks vlc's video_output thread.
990      * Vout EventThread will take care of the creation of the video
991      * window (because PeekMessage has to be called from the same thread which
992      * created the window). */
993     msg_Dbg( p_vout, "creating Vout EventThread" );
994     event_thread_t *p_event = malloc( sizeof(*p_event) );
995     if( !p_event )
996         return NULL;
997
998     p_event->p_vout = p_vout;
999     vlc_mutex_init( &p_event->lock );
1000     vlc_cond_init( &p_event->wait );
1001
1002     p_event->b_cursor_hidden      = false;
1003     p_event->i_lastmoved          = mdate();
1004     p_event->i_mouse_hide_timeout =
1005         var_GetInteger(p_vout, "mouse-hide-timeout") * 1000;
1006     p_event->psz_title = NULL;
1007     p_event->wnd_cfg = *p_wnd_cfg;
1008    
1009     return p_event;
1010 }
1011
1012 void EventThreadDestroy( event_thread_t *p_event )
1013 {
1014     free( p_event->psz_title );
1015     vlc_cond_destroy( &p_event->wait );
1016     vlc_mutex_destroy( &p_event->lock );
1017     free( p_event );
1018 }
1019
1020 int EventThreadStart( event_thread_t *p_event, event_hwnd_t *p_hwnd, const event_cfg_t *p_cfg )
1021 {
1022     p_event->use_desktop = p_cfg->use_desktop;
1023     p_event->use_overlay = p_cfg->use_overlay;
1024
1025     p_event->i_changes = 0;
1026
1027     p_event->b_ready = false;
1028     p_event->b_done  = false;
1029     p_event->b_error = false;
1030
1031     if( vlc_clone( &p_event->thread, EventThread, p_event,
1032                    VLC_THREAD_PRIORITY_LOW ) )
1033     {
1034         msg_Err( p_event->p_vout, "cannot create Vout EventThread" );
1035         return VLC_EGENERIC;
1036     }
1037
1038     vlc_mutex_lock( &p_event->lock );
1039     while( !p_event->b_ready )
1040         vlc_cond_wait( &p_event->wait, &p_event->lock );
1041     const bool b_error = p_event->b_error;
1042     vlc_mutex_unlock( &p_event->lock );
1043
1044     if( b_error )
1045     {
1046         vlc_join( p_event->thread, NULL );
1047         p_event->b_ready = false;
1048         return VLC_EGENERIC;
1049     }
1050     msg_Dbg( p_event->p_vout, "Vout EventThread running" );
1051
1052     p_hwnd->parent_window = p_event->parent_window;
1053     p_hwnd->hparent       = p_event->hparent;
1054     p_hwnd->hwnd          = p_event->hwnd;
1055     p_hwnd->hvideownd     = p_event->hvideownd;
1056     p_hwnd->hfswnd        = p_event->hfswnd;
1057     return VLC_SUCCESS;
1058 }
1059
1060 void EventThreadStop( event_thread_t *p_event )
1061 {
1062     if( !p_event->b_ready )
1063         return;
1064
1065     vlc_mutex_lock( &p_event->lock );
1066     p_event->b_done = true;
1067     vlc_mutex_unlock( &p_event->lock );
1068
1069     /* we need to be sure Vout EventThread won't stay stuck in
1070      * GetMessage, so we send a fake message */
1071     if( p_event->hwnd )
1072         PostMessage( p_event->hwnd, WM_NULL, 0, 0);
1073
1074     vlc_join( p_event->thread, NULL );
1075     p_event->b_ready = false;
1076 }
1077