Fixed uninitialized variables (msw).
[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         else
461             p_event->hparent = NULL;
462     #ifdef MODULE_NAME_IS_direct3d
463     }
464     else
465     {
466         /* Find Program Manager */
467         HWND hwnd = FindWindow( _T("Progman"), NULL );
468         if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SHELLDLL_DefView"), NULL );
469         if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SysListView32"), NULL );
470         if( !hwnd )
471             msg_Err( p_vout, "Couldn't find desktop icon window. Desktop mode can't be established." );
472         p_event->hparent = hwnd;
473     }
474     #endif
475
476     /* Get the Icon from the main app */
477     vlc_icon = NULL;
478 #ifndef UNDER_CE
479     if( GetModuleFileName( NULL, vlc_path, MAX_PATH ) )
480     {
481         vlc_icon = ExtractIcon( hInstance, vlc_path, 0 );
482     }
483 #endif
484
485     /* Fill in the window class structure */
486     wc.style         = CS_OWNDC|CS_DBLCLKS;          /* style: dbl click */
487     wc.lpfnWndProc   = (WNDPROC)DirectXEventProc;       /* event handler */
488     wc.cbClsExtra    = 0;                         /* no extra class data */
489     wc.cbWndExtra    = 0;                        /* no extra window data */
490     wc.hInstance     = hInstance;                            /* instance */
491     wc.hIcon         = vlc_icon;                /* load the vlc big icon */
492     wc.hCursor       = LoadCursor(NULL, IDC_ARROW);    /* default cursor */
493     wc.hbrBackground = GetStockObject(BLACK_BRUSH);  /* background color */
494     wc.lpszMenuName  = NULL;                                  /* no menu */
495     wc.lpszClassName = _T("VLC DirectX");         /* use a special class */
496
497     /* Register the window class */
498     if( !RegisterClass(&wc) )
499     {
500         WNDCLASS wndclass;
501
502         if( vlc_icon ) DestroyIcon( vlc_icon );
503
504         /* Check why it failed. If it's because one already exists
505          * then fine, otherwise return with an error. */
506         if( !GetClassInfo( hInstance, _T("VLC DirectX"), &wndclass ) )
507         {
508             msg_Err( p_vout, "DirectXCreateWindow RegisterClass FAILED (err=%lu)", GetLastError() );
509             return VLC_EGENERIC;
510         }
511     }
512
513     /* Register the video sub-window class */
514     wc.lpszClassName = _T("VLC DirectX video"); wc.hIcon = 0;
515     wc.hbrBackground = NULL; /* no background color */
516     if( !RegisterClass(&wc) )
517     {
518         WNDCLASS wndclass;
519
520         /* Check why it failed. If it's because one already exists
521          * then fine, otherwise return with an error. */
522         if( !GetClassInfo( hInstance, _T("VLC DirectX video"), &wndclass ) )
523         {
524             msg_Err( p_vout, "DirectXCreateWindow RegisterClass FAILED (err=%lu)", GetLastError() );
525             return VLC_EGENERIC;
526         }
527     }
528
529     /* When you create a window you give the dimensions you wish it to
530      * have. Unfortunatly these dimensions will include the borders and
531      * titlebar. We use the following function to find out the size of
532      * the window corresponding to the useable surface we want */
533     rect_window.top    = 10;
534     rect_window.left   = 10;
535     rect_window.right  = rect_window.left + p_event->wnd_cfg.width;
536     rect_window.bottom = rect_window.top  + p_event->wnd_cfg.height;
537
538     if( var_GetBool( p_vout, "video-deco" ) )
539     {
540         /* Open with window decoration */
541         AdjustWindowRect( &rect_window, WS_OVERLAPPEDWINDOW|WS_SIZEBOX, 0 );
542         i_style = WS_OVERLAPPEDWINDOW|WS_SIZEBOX|WS_VISIBLE|WS_CLIPCHILDREN;
543         i_stylex = 0;
544     }
545     else
546     {
547         /* No window decoration */
548         AdjustWindowRect( &rect_window, WS_POPUP, 0 );
549         i_style = WS_POPUP|WS_VISIBLE|WS_CLIPCHILDREN;
550         i_stylex = 0; // WS_EX_TOOLWINDOW; Is TOOLWINDOW really needed ?
551                       // It messes up the fullscreen window.
552     }
553
554     if( p_event->hparent )
555     {
556         i_style = WS_VISIBLE|WS_CLIPCHILDREN|WS_CHILD;
557         i_stylex = 0;
558     }
559
560     p_event->i_window_style = i_style;
561
562     /* Create the window */
563     p_event->hwnd =
564         CreateWindowEx( WS_EX_NOPARENTNOTIFY | i_stylex,
565                     _T("VLC DirectX"),               /* name of window class */
566                     _T(VOUT_TITLE) _T(" (DirectX Output)"),  /* window title */
567                     i_style,                                 /* window style */
568                     (p_event->wnd_cfg.x < 0) ? CW_USEDEFAULT :
569                         (UINT)p_event->wnd_cfg.x,   /* default X coordinate */
570                     (p_event->wnd_cfg.y < 0) ? CW_USEDEFAULT :
571                         (UINT)p_event->wnd_cfg.y,   /* default Y coordinate */
572                     rect_window.right - rect_window.left,    /* window width */
573                     rect_window.bottom - rect_window.top,   /* window height */
574                     p_event->hparent,                       /* parent window */
575                     NULL,                          /* no menu in this window */
576                     hInstance,            /* handle of this program instance */
577                     (LPVOID)p_event );           /* send p_vout to WM_CREATE */
578
579     if( !p_event->hwnd )
580     {
581         msg_Warn( p_vout, "DirectXCreateWindow create window FAILED (err=%lu)", GetLastError() );
582         return VLC_EGENERIC;
583     }
584
585     if( p_event->hparent )
586     {
587         LONG i_style;
588
589         /* We don't want the window owner to overwrite our client area */
590         i_style = GetWindowLong( p_event->hparent, GWL_STYLE );
591
592         if( !(i_style & WS_CLIPCHILDREN) )
593             /* Hmmm, apparently this is a blocking call... */
594             SetWindowLong( p_event->hparent, GWL_STYLE,
595                            i_style | WS_CLIPCHILDREN );
596
597         /* Create our fullscreen window */
598         p_event->hfswnd =
599             CreateWindowEx( WS_EX_APPWINDOW, _T("VLC DirectX"),
600                             _T(VOUT_TITLE) _T(" (DirectX Output)"),
601                             WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN|WS_SIZEBOX,
602                             CW_USEDEFAULT, CW_USEDEFAULT,
603                             CW_USEDEFAULT, CW_USEDEFAULT,
604                             NULL, NULL, hInstance, NULL );
605     }
606     else
607     {
608         p_event->hfswnd = NULL;
609     }
610
611     /* Append a "Always On Top" entry in the system menu */
612     hMenu = GetSystemMenu( p_event->hwnd, FALSE );
613     AppendMenu( hMenu, MF_SEPARATOR, 0, _T("") );
614     AppendMenu( hMenu, MF_STRING | MF_UNCHECKED,
615                        IDM_TOGGLE_ON_TOP, _T("Always on &Top") );
616
617     /* Create video sub-window. This sub window will always exactly match
618      * the size of the video, which allows us to use crazy overlay colorkeys
619      * without having them shown outside of the video area. */
620     p_event->hvideownd =
621     CreateWindow( _T("VLC DirectX video"), _T(""),   /* window class */
622         WS_CHILD,                   /* window style, not visible initially */
623         0, 0,
624         p_vout->render.i_width,          /* default width */
625         p_vout->render.i_height,        /* default height */
626         p_event->hwnd,                   /* parent window */
627         NULL, hInstance,
628         (LPVOID)p_event );    /* send p_vout to WM_CREATE */
629
630     if( !p_event->hvideownd )
631         msg_Warn( p_vout, "can't create video sub-window" );
632     else
633         msg_Dbg( p_vout, "created video sub-window" );
634
635     /* Now display the window */
636     ShowWindow( p_event->hwnd, SW_SHOW );
637
638     return VLC_SUCCESS;
639 }
640
641 /*****************************************************************************
642  * DirectXCloseWindow: close the window created by DirectXCreateWindow
643  *****************************************************************************
644  * This function returns all resources allocated by DirectXCreateWindow.
645  *****************************************************************************/
646 static void DirectXCloseWindow( event_thread_t *p_event )
647 {
648     vout_thread_t *p_vout = p_event->p_vout;
649     msg_Dbg( p_vout, "DirectXCloseWindow" );
650
651     DestroyWindow( p_event->hwnd );
652     if( p_event->hfswnd ) DestroyWindow( p_event->hfswnd );
653
654     #ifdef MODULE_NAME_IS_direct3d
655     if( !p_event->use_desktop )
656     #endif
657         vout_window_Delete( p_event->parent_window );
658     p_event->hwnd = NULL;
659
660     /* We don't unregister the Window Class because it could lead to race
661      * conditions and it will be done anyway by the system when the app will
662      * exit */
663 }
664
665 /*****************************************************************************
666  * DirectXEventProc: This is the window event processing function.
667  *****************************************************************************
668  * On Windows, when you create a window you have to attach an event processing
669  * function to it. The aim of this function is to manage "Queued Messages" and
670  * "Nonqueued Messages".
671  * Queued Messages are those picked up and retransmitted by vout_Manage
672  * (using the GetMessage and DispatchMessage functions).
673  * Nonqueued Messages are those that Windows will send directly to this
674  * procedure (like WM_DESTROY, WM_WINDOWPOSCHANGED...)
675  *****************************************************************************/
676 static long FAR PASCAL DirectXEventProc( HWND hwnd, UINT message,
677                                          WPARAM wParam, LPARAM lParam )
678 {
679     event_thread_t *p_event;
680
681     if( message == WM_CREATE )
682     {
683         /* Store p_vout for future use */
684         p_event = (event_thread_t *)((CREATESTRUCT *)lParam)->lpCreateParams;
685         SetWindowLongPtr( hwnd, GWLP_USERDATA, (LONG_PTR)p_event );
686         return TRUE;
687     }
688     else
689     {
690         LONG_PTR p_user_data = GetWindowLongPtr( hwnd, GWLP_USERDATA );
691         p_event = (event_thread_t *)p_user_data;
692         if( !p_event )
693         {
694             /* Hmmm mozilla does manage somehow to save the pointer to our
695              * windowproc and still calls it after the vout has been closed. */
696             return DefWindowProc(hwnd, message, wParam, lParam);
697         }
698     }
699     vout_thread_t *p_vout = p_event->p_vout;
700
701 #ifndef UNDER_CE
702     /* Catch the screensaver and the monitor turn-off */
703     if( message == WM_SYSCOMMAND &&
704         ( (wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER ) )
705     {
706         //if( p_vout ) msg_Dbg( p_vout, "WinProc WM_SYSCOMMAND screensaver" );
707         return 0; /* this stops them from happening */
708     }
709 #endif
710
711     if( hwnd == p_event->hvideownd )
712     {
713         switch( message )
714         {
715 #ifdef MODULE_NAME_IS_directx
716         case WM_ERASEBKGND:
717         /* For overlay, we need to erase background */
718             return !p_event->use_overlay ?
719                 1 : DefWindowProc(hwnd, message, wParam, lParam);
720         case WM_PAINT:
721         /*
722         ** For overlay, DefWindowProc() will erase dirty regions
723         ** with colorkey.
724         ** For non-overlay, vout will paint the whole window at
725         ** regular interval, therefore dirty regions can be ignored
726         ** to minimize repaint.
727         */
728             if( !p_event->use_overlay )
729             {
730                 ValidateRect(hwnd, NULL);
731             }
732             // fall through to default
733 #else
734         /*
735         ** For OpenGL and Direct3D, vout will update the whole
736         ** window at regular interval, therefore dirty region
737         ** can be ignored to minimize repaint.
738         */
739         case WM_ERASEBKGND:
740             /* nothing to erase */
741             return 1;
742         case WM_PAINT:
743             /* nothing to repaint */
744             ValidateRect(hwnd, NULL);
745             // fall through
746 #endif
747         default:
748             return DefWindowProc(hwnd, message, wParam, lParam);
749         }
750     }
751
752     switch( message )
753     {
754
755     case WM_WINDOWPOSCHANGED:
756         UpdateRects( p_vout, true );
757         return 0;
758
759     /* the user wants to close the window */
760     case WM_CLOSE:
761     {
762         playlist_t * p_playlist = pl_Hold( p_vout );
763         if( p_playlist )
764         {
765             playlist_Stop( p_playlist );
766             pl_Release( p_vout );
767         }
768         return 0;
769     }
770
771     /* the window has been closed so shut down everything now */
772     case WM_DESTROY:
773         msg_Dbg( p_vout, "WinProc WM_DESTROY" );
774         /* just destroy the window */
775         PostQuitMessage( 0 );
776         return 0;
777
778     case WM_SYSCOMMAND:
779         switch (wParam)
780         {
781             case IDM_TOGGLE_ON_TOP:            /* toggle the "on top" status */
782             {
783                 msg_Dbg( p_vout, "WinProc WM_SYSCOMMAND: IDM_TOGGLE_ON_TOP");
784
785                 /* Change the current value */
786                 var_ToggleBool( p_vout, "video-on-top" );
787                 return 0;
788             }
789         }
790         break;
791
792     case WM_PAINT:
793     case WM_NCPAINT:
794     case WM_ERASEBKGND:
795         return DefWindowProc(hwnd, message, wParam, lParam);
796
797     case WM_KILLFOCUS:
798 #ifdef MODULE_NAME_IS_wingapi
799         GXSuspend();
800 #endif
801 #ifdef UNDER_CE
802         if( hwnd == p_event->hfswnd )
803         {
804             HWND htbar = FindWindow( _T("HHTaskbar"), NULL );
805             ShowWindow( htbar, SW_SHOW );
806         }
807
808         if( !p_event->hparent ||
809             hwnd == p_event->hfswnd )
810         {
811             SHFullScreen( hwnd, SHFS_SHOWSIPBUTTON );
812         }
813 #endif
814         return 0;
815
816     case WM_SETFOCUS:
817 #ifdef MODULE_NAME_IS_wingapi
818         GXResume();
819 #endif
820 #ifdef UNDER_CE
821         if( p_event->hparent &&
822             hwnd != p_event->hfswnd && p_vout->b_fullscreen )
823         {
824             vlc_mutex_lock( &p_event->lock );
825             p_event->i_changes |= VOUT_FULLSCREEN_CHANGE;
826             vlc_mutex_unlock( &p_event->lock );
827         }
828
829         if( hwnd == p_event->hfswnd )
830         {
831             HWND htbar = FindWindow( _T("HHTaskbar"), NULL );
832             ShowWindow( htbar, SW_HIDE );
833         }
834
835         if( !p_event->hparent ||
836             hwnd == p_event->hfswnd )
837         {
838             SHFullScreen( hwnd, SHFS_HIDESIPBUTTON );
839         }
840 #endif
841         return 0;
842
843     default:
844         //msg_Dbg( p_vout, "WinProc WM Default %i", message );
845         break;
846     }
847
848     /* Let windows handle the message */
849     return DefWindowProc(hwnd, message, wParam, lParam);
850 }
851
852 static struct
853 {
854     int i_dxkey;
855     int i_vlckey;
856
857 } dxkeys_to_vlckeys[] =
858 {
859     { VK_F1, KEY_F1 }, { VK_F2, KEY_F2 }, { VK_F3, KEY_F3 }, { VK_F4, KEY_F4 },
860     { VK_F5, KEY_F5 }, { VK_F6, KEY_F6 }, { VK_F7, KEY_F7 }, { VK_F8, KEY_F8 },
861     { VK_F9, KEY_F9 }, { VK_F10, KEY_F10 }, { VK_F11, KEY_F11 },
862     { VK_F12, KEY_F12 },
863
864     { VK_RETURN, KEY_ENTER },
865     { VK_SPACE, ' ' },
866     { VK_ESCAPE, KEY_ESC },
867
868     { VK_LEFT, KEY_LEFT },
869     { VK_RIGHT, KEY_RIGHT },
870     { VK_UP, KEY_UP },
871     { VK_DOWN, KEY_DOWN },
872
873     { VK_HOME, KEY_HOME },
874     { VK_END, KEY_END },
875     { VK_PRIOR, KEY_PAGEUP },
876     { VK_NEXT, KEY_PAGEDOWN },
877
878     { VK_INSERT, KEY_INSERT },
879     { VK_DELETE, KEY_DELETE },
880
881     { VK_CONTROL, 0 },
882     { VK_SHIFT, 0 },
883     { VK_MENU, 0 },
884
885     { VK_BROWSER_BACK, KEY_BROWSER_BACK },
886     { VK_BROWSER_FORWARD, KEY_BROWSER_FORWARD },
887     { VK_BROWSER_REFRESH, KEY_BROWSER_REFRESH },
888     { VK_BROWSER_STOP, KEY_BROWSER_STOP },
889     { VK_BROWSER_SEARCH, KEY_BROWSER_SEARCH },
890     { VK_BROWSER_FAVORITES, KEY_BROWSER_FAVORITES },
891     { VK_BROWSER_HOME, KEY_BROWSER_HOME },
892     { VK_VOLUME_MUTE, KEY_VOLUME_MUTE },
893     { VK_VOLUME_DOWN, KEY_VOLUME_DOWN },
894     { VK_VOLUME_UP, KEY_VOLUME_UP },
895     { VK_MEDIA_NEXT_TRACK, KEY_MEDIA_NEXT_TRACK },
896     { VK_MEDIA_PREV_TRACK, KEY_MEDIA_PREV_TRACK },
897     { VK_MEDIA_STOP, KEY_MEDIA_STOP },
898     { VK_MEDIA_PLAY_PAUSE, KEY_MEDIA_PLAY_PAUSE },
899
900     { 0, 0 }
901 };
902
903 static int DirectXConvertKey( int i_key )
904 {
905     int i;
906
907     for( i = 0; dxkeys_to_vlckeys[i].i_dxkey != 0; i++ )
908     {
909         if( dxkeys_to_vlckeys[i].i_dxkey == i_key )
910         {
911             return dxkeys_to_vlckeys[i].i_vlckey;
912         }
913     }
914
915     return 0;
916 }
917
918 void EventThreadMouseAutoHide( event_thread_t *p_event )
919 {
920     vout_thread_t *p_vout = p_event->p_vout;
921
922     if( p_vout->b_fullscreen &&
923         !p_event->b_cursor_hidden &&
924         (mdate() - p_event->i_lastmoved) > p_event->i_mouse_hide_timeout )
925     {
926         /* Hide the cursor only if it is inside our window */
927         POINT point;
928         GetCursorPos( &point );
929
930         HWND hwnd = WindowFromPoint(point);
931         if( hwnd == p_event->hwnd || hwnd == p_event->hvideownd )
932         {
933             PostMessage( p_event->hwnd, WM_VLC_HIDE_MOUSE, 0, 0 );
934         }
935         else
936         {
937             p_event->i_lastmoved = mdate();
938         }
939     }
940 }
941 void EventThreadMouseShow( event_thread_t *p_event )
942 {
943     PostMessage( p_event->hwnd, WM_VLC_SHOW_MOUSE, 0, 0 );
944 }
945 void EventThreadUpdateTitle( event_thread_t *p_event, const char *psz_fallback )
946 {
947     char *psz_title = var_GetNonEmptyString( p_event->p_vout, "video-title" );
948     if( !psz_title )
949         psz_title = strdup( psz_fallback );
950     if( !psz_title )
951         return;
952
953     vlc_mutex_lock( &p_event->lock );
954     free( p_event->psz_title );
955     p_event->psz_title = psz_title;
956     vlc_mutex_unlock( &p_event->lock );
957
958     PostMessage( p_event->hwnd, WM_VLC_CHANGE_TEXT, 0, 0 );
959 }
960 unsigned EventThreadRetreiveChanges( event_thread_t *p_event )
961 {
962     vlc_mutex_lock( &p_event->lock );
963     unsigned i_changes = p_event->i_changes;
964     p_event->i_changes = 0;
965     vlc_mutex_unlock( &p_event->lock );
966
967     return i_changes;
968 }
969 int EventThreadGetWindowStyle( event_thread_t *p_event )
970 {
971     /* No need to lock, it is serialized by EventThreadStart */
972     return p_event->i_window_style;
973 }
974
975 void EventThreadUpdateWindowPosition( event_thread_t *p_event, bool *pb_changed,
976                                       int x, int y, int w, int h )
977 {
978     vlc_mutex_lock( &p_event->lock );
979     *pb_changed = x != p_event->wnd_cfg.x ||
980                   y != p_event->wnd_cfg.y ||
981                   w != p_event->wnd_cfg.width ||
982                   h != p_event->wnd_cfg.height;
983
984     p_event->wnd_cfg.x      = x;
985     p_event->wnd_cfg.y      = y;
986     p_event->wnd_cfg.width  = y;
987     p_event->wnd_cfg.height = h;
988     vlc_mutex_unlock( &p_event->lock );
989 }
990 event_thread_t *EventThreadCreate( vout_thread_t *p_vout, const vout_window_cfg_t *p_wnd_cfg )
991 {
992      /* Create the Vout EventThread, this thread is created by us to isolate
993      * the Win32 PeekMessage function calls. We want to do this because
994      * Windows can stay blocked inside this call for a long time, and when
995      * this happens it thus blocks vlc's video_output thread.
996      * Vout EventThread will take care of the creation of the video
997      * window (because PeekMessage has to be called from the same thread which
998      * created the window). */
999     msg_Dbg( p_vout, "creating Vout EventThread" );
1000     event_thread_t *p_event = malloc( sizeof(*p_event) );
1001     if( !p_event )
1002         return NULL;
1003
1004     p_event->p_vout = p_vout;
1005     vlc_mutex_init( &p_event->lock );
1006     vlc_cond_init( &p_event->wait );
1007
1008     p_event->b_cursor_hidden      = false;
1009     p_event->i_lastmoved          = mdate();
1010     p_event->i_mouse_hide_timeout =
1011         var_GetInteger(p_vout, "mouse-hide-timeout") * 1000;
1012     p_event->psz_title = NULL;
1013     p_event->wnd_cfg = *p_wnd_cfg;
1014    
1015     return p_event;
1016 }
1017
1018 void EventThreadDestroy( event_thread_t *p_event )
1019 {
1020     free( p_event->psz_title );
1021     vlc_cond_destroy( &p_event->wait );
1022     vlc_mutex_destroy( &p_event->lock );
1023     free( p_event );
1024 }
1025
1026 int EventThreadStart( event_thread_t *p_event, event_hwnd_t *p_hwnd, const event_cfg_t *p_cfg )
1027 {
1028     p_event->use_desktop = p_cfg->use_desktop;
1029     p_event->use_overlay = p_cfg->use_overlay;
1030
1031     p_event->i_changes = 0;
1032
1033     p_event->b_ready = false;
1034     p_event->b_done  = false;
1035     p_event->b_error = false;
1036
1037     if( vlc_clone( &p_event->thread, EventThread, p_event,
1038                    VLC_THREAD_PRIORITY_LOW ) )
1039     {
1040         msg_Err( p_event->p_vout, "cannot create Vout EventThread" );
1041         return VLC_EGENERIC;
1042     }
1043
1044     vlc_mutex_lock( &p_event->lock );
1045     while( !p_event->b_ready )
1046         vlc_cond_wait( &p_event->wait, &p_event->lock );
1047     const bool b_error = p_event->b_error;
1048     vlc_mutex_unlock( &p_event->lock );
1049
1050     if( b_error )
1051     {
1052         vlc_join( p_event->thread, NULL );
1053         p_event->b_ready = false;
1054         return VLC_EGENERIC;
1055     }
1056     msg_Dbg( p_event->p_vout, "Vout EventThread running" );
1057
1058     if( !p_event->use_desktop )
1059         p_hwnd->parent_window = p_event->parent_window;
1060     else
1061         p_hwnd->parent_window = NULL;
1062     p_hwnd->hparent       = p_event->hparent;
1063     p_hwnd->hwnd          = p_event->hwnd;
1064     p_hwnd->hvideownd     = p_event->hvideownd;
1065     p_hwnd->hfswnd        = p_event->hfswnd;
1066     return VLC_SUCCESS;
1067 }
1068
1069 void EventThreadStop( event_thread_t *p_event )
1070 {
1071     if( !p_event->b_ready )
1072         return;
1073
1074     vlc_mutex_lock( &p_event->lock );
1075     p_event->b_done = true;
1076     vlc_mutex_unlock( &p_event->lock );
1077
1078     /* we need to be sure Vout EventThread won't stay stuck in
1079      * GetMessage, so we send a fake message */
1080     if( p_event->hwnd )
1081         PostMessage( p_event->hwnd, WM_NULL, 0, 0);
1082
1083     vlc_join( p_event->thread, NULL );
1084     p_event->b_ready = false;
1085 }
1086