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