summaryrefslogtreecommitdiff
path: root/src/SourceWin32.cxx
blob: 1007e358e90b168e7709447c499a87eb34964d0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
namespace PluggIt {

D_DEBUG_DOMAIN( PluggIt_SourceWin32, "PluggIt/SourceWin32", "PluggIt Source Win32" );


#include "ScreenHooks.h"

// Constants
const UINT RFB_SCREEN_UPDATE = RegisterWindowMessage("WinVNC.Update.DrawRect");
const UINT RFB_COPYRECT_UPDATE = RegisterWindowMessage("WinVNC.Update.CopyRect");
const UINT RFB_MOUSE_UPDATE = RegisterWindowMessage("WinVNC.Update.Mouse");
const char szDesktopSink[] = "WinVNC desktop sink";

typedef BOOL (*SetHooksFn)(DWORD thread_id,UINT UpdateMsg,UINT CopyMsg,UINT MouseMsg,BOOL ddihook);


class SourceWin32 extends Source, Runnable
{
     private HINSTANCE        m_hInstance;

     private HWND             m_root;
     private HWND             m_window;

     private DFBPoint         m_position;
     private DFBDimension     m_size;

     private HBITMAP          m_bitmap;
     private void            *m_pixels;
     private int              m_pitch;

     private HBITMAP          m_bitmap2;
     private void            *m_pixels2;
     private int              m_pitch2;

     private HDC              m_window_dc;
     private HDC              m_bitmap_dc;
     private HDC              m_bitmap_dc2;

     private Thread          *m_thread;

     private Updates          m_updates;

     private VIDEODRIVER      m_driver;
     private bool             m_using_driver;

     private pthread_mutex_t  m_lock;
     private pthread_cond_t   m_cond;


	SetHooksFn SetHooks;


     public class Config extends Source::Config {
          friend class SourceWin32;

          public typedef enum {
               WINDOW_SELECTION_NONE,
               WINDOW_SELECTION_TITLE,
               WINDOW_SELECTION_INTERACTIVE
          } WindowSelection;

          private WindowSelection m_selection;
          private std::string     m_title;
          private bool            m_updating;
          private bool            m_use_driver;


          public Config( WindowSelection selection,
                         const std::string &title = std::string(),
                         bool updating = false, bool use_driver = true )
          {
               m_selection  = selection;
               m_title      = title;
               m_updating   = updating;
               m_use_driver = use_driver;
          }
     };


     public SourceWin32( View *view, const Config &config ) : Source( view, config ), m_updates(16) {
          D_DEBUG_AT( PluggIt_SourceWin32, "%s( %p )\n", __FUNCTION__, view );

          m_hInstance = GetModuleHandle( NULL );

          D_DEBUG_AT( PluggIt_SourceWin32, "  -> hInstance %p\n", m_hInstance );


          m_root = GetDesktopWindow();

          switch (config.m_selection) {
               case Config::WINDOW_SELECTION_NONE:
                    m_window = m_root;
                    break;

               case Config::WINDOW_SELECTION_TITLE:
                    m_window = findWindow( config.m_title );
                    if (m_window == 0)
                         throw new Exception( "Could not find window with title containing '%s'\n", config.m_title.c_str() );
                    break;

               case Config::WINDOW_SELECTION_INTERACTIVE:
                    pickWindow();
                    if (m_window == 0)
                         throw new Exception( "Could not interactively pick a window\n" );
                    break;

               default:
                    throw new Exception( "Invalid window selection method\n" );
          }


          RECT rect;

          GetClientRect( m_window, &rect );

          m_position.x = rect.left;
          m_position.y = rect.top;

          m_size.w = rect.right  - rect.left;
          m_size.h = rect.bottom - rect.top;

          queueUpdate( 0, 0, m_size.w - 1, m_size.h - 1 );


          std::string t = getWindowTitle( m_window );

          D_INFO( "Source/Win32: Window %d,%d-%ux%u, name '%s'\n",
                  m_position.x, m_position.y, m_size.w, m_size.h, t.c_str() );

          if (config.m_use_driver)
               m_driver.VIDEODRIVER_start( m_position.x, m_position.y, m_size.w, m_size.h );

          m_using_driver = m_driver.mypchangebuf != NULL;

          m_view->config( m_size );


          m_window_dc  = GetDC( m_window );
          m_bitmap_dc  = CreateCompatibleDC( m_window_dc );
          m_bitmap_dc2 = CreateCompatibleDC( m_window_dc );


          BITMAPINFO bitmap_info = {{
               biSize:           sizeof(BITMAPINFOHEADER),
               biWidth:          m_size.w,
               biHeight:         m_size.h,
               biPlanes:         1,
               biBitCount:       32,
               biCompression:    BI_RGB,
               biSizeImage:      0,
               biXPelsPerMeter:  0,
               biYPelsPerMeter:  0,
               biClrUsed:        0,
               biClrImportant:   0,
          }};

          m_bitmap  = CreateDIBSection( m_window_dc, &bitmap_info, DIB_RGB_COLORS, &m_pixels, NULL, 0 );
          m_bitmap2 = CreateDIBSection( m_window_dc, &bitmap_info, DIB_RGB_COLORS, &m_pixels2, NULL, 0 );


          BITMAP bitmap;

          GetObject( m_bitmap, sizeof(BITMAP), &bitmap );

          m_pitch = bitmap.bmWidthBytes;

          GetObject( m_bitmap2, sizeof(BITMAP), &bitmap );

          m_pitch2 = bitmap.bmWidthBytes;


          SelectObject( m_bitmap_dc, m_bitmap );
          SelectObject( m_bitmap_dc2, m_bitmap2 );


          pthread_mutex_init( &m_lock, NULL );
          pthread_cond_init( &m_cond, NULL );


          /* Create the thread object. */
          m_thread = new Thread( this, "SourceWin32" );

          m_thread->start();
     }

     virtual ~SourceWin32() {
          m_thread->interrupt();
          m_thread->join();
          delete m_thread;

          pthread_mutex_destroy( &m_lock );
          pthread_cond_destroy( &m_cond );

          DeleteDC( m_window_dc );
          DeleteDC( m_bitmap_dc );
          DeleteDC( m_bitmap_dc2 );

          DeleteObject( m_bitmap );
          DeleteObject( m_bitmap2 );
     }

     private void run() {
          D_DEBUG_AT( PluggIt_SourceWin32, "%s()\n", __FUNCTION__ );

          while (!m_thread->isInterrupted()) {
               pthread_mutex_lock( &m_lock );

               while (m_updates.num_regions() == 0)
                    pthread_cond_wait( &m_cond, &m_lock );


               vector<DFBRectangle_C> rects;

               m_updates.GetRectangles( rects );


               const DFBRegion &bounding = m_updates.bounding();

               D_DEBUG_AT( PluggIt_SourceWin32, "  -> %4d,%4d-%4dx%4d (%d regions, %d rectangles)\n",
                           DFB_RECTANGLE_VALS_FROM_REGION( &bounding ), m_updates.num_regions(), rects.size() );


               m_updates.reset();

               pthread_mutex_unlock( &m_lock );


               for (unsigned int i=0; i<rects.size(); i++) {
                    BitBlt( m_bitmap_dc,
                            rects[i].x,
                            rects[i].y,
                            rects[i].w,
                            rects[i].h,
                            m_window_dc,
                            rects[i].x,
                            rects[i].y,
                            SRCCOPY );
               }


               m_view->update( rects, (void*)((char*) m_pixels + m_pitch * (m_size.h - 1)), - m_pitch );
          }
     }

/**********************************************************************************************************************/

     private void queueUpdate( int x1, int y1, int x2, int y2 ) {
          D_DEBUG_AT( PluggIt_SourceWin32, "%s( %d,%d-%dx%d )\n", __FUNCTION__, x1, y1, x2 - x1 + 1, y2 - y1 + 1 );

          pthread_mutex_lock( &m_lock );

          DFBRegion damage( x1, y1, x2, y2 );

          m_updates.addRegion( damage );

          pthread_cond_signal( &m_cond );

          pthread_mutex_unlock( &m_lock );
     }

/**********************************************************************************************************************/

     private static std::string getWindowTitle( HWND window ) {
          char buf[1024] = { 0 };

          GetWindowText( window, buf, sizeof(buf) );

          D_DEBUG_AT( PluggIt_SourceWin32, "%s( %p ) -> '%s'\n", __FUNCTION__, window, buf );

          return buf;
     }


/**********************************************************************************************************************/

     class EnumContext {
          public const std::string &title;
          public HWND               window;

          public EnumContext( const std::string &title ) : title(title), window(0) {}
     };

     private static BOOL CALLBACK enumWindowsProc( HWND   hwnd,
                                                   LPARAM lParam )
     {
          EnumContext *ctx = reinterpret_cast<EnumContext *>( lParam );

          D_DEBUG_AT( PluggIt_SourceWin32, "%s( %p )\n", __FUNCTION__, hwnd );

          std::string title = getWindowTitle( hwnd );

          if (title == ctx->title || title.find( ctx->title ) < title.size())
               ctx->window = hwnd;

          return ctx->window == NULL;
     }

     private HWND findWindow( const std::string &title ) {
          D_DEBUG_AT( PluggIt_SourceWin32, "%s( %s )\n", __FUNCTION__, title.c_str() );

          EnumContext ctx( title );

          EnumWindows( enumWindowsProc, reinterpret_cast<LPARAM>( &ctx ) );

          return ctx.window;
     }


/**********************************************************************************************************************/

     static LRESULT CALLBACK WndProc( HWND hwnd,        // handle to window
                                      UINT uMsg,        // message identifier
                                      WPARAM wParam,    // first message parameter
                                      LPARAM lParam )   // second message parameter
     {
          static SourceWin32 *thiz;
          POINT               point;
          CREATESTRUCT       *create;

          switch (uMsg) {
               case WM_CREATE:
                    create = reinterpret_cast<LPCREATESTRUCT>( lParam );
                    thiz   = reinterpret_cast<SourceWin32 *>( create->lpCreateParams );

                    SetCursor( LoadCursor( NULL, IDC_CROSS ) );
                    break;

               case WM_LBUTTONDOWN:
                    ShowWindow( hwnd, SW_HIDE );


                    GetCursorPos( &point );

                    D_DEBUG_AT( PluggIt_SourceWin32, "  -> Cursor position is %ld,%ld\n", point.x, point.y );


                    thiz->m_window = WindowFromPoint( point );
                    if (thiz->m_window) {
                         HWND parent;

                         while ((parent = GetParent( thiz->m_window )) != NULL)
                              thiz->m_window = parent;
                    }

                    D_DEBUG_AT( PluggIt_SourceWin32, "  -> Window at cursor is %p: %s\n",
                                thiz->m_window, getWindowTitle( thiz->m_window ).c_str() );

                    DestroyWindow( hwnd );
                    break;
 
               case WM_TIMER:
                    if (wParam == 666)
                         DestroyWindow( hwnd );
                    break;

               case WM_DESTROY:
                    KillTimer( hwnd, 666 );
                    PostQuitMessage( 0 );
                    break;
 
              default:
                   SetTimer( hwnd, 666, 5000, NULL );

                   return DefWindowProc( hwnd, uMsg, wParam, lParam );
          }
 
          return 0;
     }

     private void pickWindow() {
          D_DEBUG_AT( PluggIt_SourceWin32, "%s()\n", __FUNCTION__ );

          HDC hdc;

          hdc = GetDC( NULL );
          if (!hdc)
               throw new Exception( "GetDC() returned NULL" );

          RECT rect;

          GetClipBox( hdc, &rect );

          D_DEBUG_AT( PluggIt_SourceWin32, "  -> Desktop size: %ldx%ld\n",
                      rect.right - rect.left, rect.bottom - rect.top );

          ReleaseDC( NULL, hdc );



          WNDCLASSEX wndClass;

          ZeroMemory( &wndClass, sizeof(wndClass) );

          wndClass.cbSize        = sizeof(wndClass);
          wndClass.style         = CS_HREDRAW | CS_VREDRAW;
          wndClass.lpfnWndProc   = WndProc;
          wndClass.cbClsExtra    = 0;
          wndClass.cbWndExtra    = 0;
          wndClass.hInstance     = m_hInstance;
          wndClass.hIcon         = NULL;
          wndClass.hIconSm       = NULL;
          wndClass.hCursor       = LoadCursor( NULL, IDC_UPARROW );
          wndClass.hbrBackground = (HBRUSH) GetStockObject( NULL_BRUSH );
          wndClass.lpszMenuName  = NULL;
          wndClass.lpszClassName = "GrabWindow";

          if (!RegisterClassEx( &wndClass ))
               throw new Exception( "RegisterClassEx() failed!\n" );


          AdjustWindowRect( &rect, WS_CAPTION, FALSE );


          HWND grabwin;

          grabwin = CreateWindowEx( 0,
                                    "GrabWindow",
                                    "GrabWindow",
                                    WS_POPUP,// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_BORDER,
                                    CW_USEDEFAULT,
                                    CW_USEDEFAULT,
                                    rect.right  - rect.left,
                                    rect.bottom - rect.top,
                                    NULL,
                                    NULL,
                                    m_hInstance,
                                    this );

          SetWindowLong( grabwin, GWL_EXSTYLE,
                         GetWindowLong( grabwin, GWL_EXSTYLE ) | WS_EX_TRANSPARENT | WS_EX_TOPMOST );

          ShowWindow( grabwin, SW_SHOW );



          MSG msg;

          while (GetMessage( &msg, 0, 0, 0 )) {
               TranslateMessage( &msg );

               D_DEBUG_AT( PluggIt_SourceWin32, "  -> Dispatching event (id %u)...\n", msg.message );

               DispatchMessage( &msg );
          }
     }

/**********************************************************************************************************************/

     public virtual int MainLoop() {

          HMODULE hModule;
          char szCurrentDir[MAX_PATH];

          if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) {
               char* p = strrchr(szCurrentDir, '\\');
               if (p == NULL) return 0;
               *p = '\0';
               strcat (szCurrentDir,"\\vnchooks.dll");
          }

          hModule = LoadLibrary( szCurrentDir );
          if (!hModule)
               throw new Exception( "Failed to load vnchooks.dll!" );

          SetHooks = (SetHooksFn) GetProcAddress( hModule, "SetHooks" );


          if (!SetHooks(
                    GetCurrentThreadId(),
                    RFB_SCREEN_UPDATE,
                    RFB_COPYRECT_UPDATE,
                    RFB_MOUSE_UPDATE, false
                    ))
               throw new Exception( "Failed to set hooks!" );


          MSG msg;

          printf( "  -> RFB_SCREEN_UPDATE = %u\n", RFB_SCREEN_UPDATE );
          printf( "  -> RFB_COPYRECT_UPDATE = %u\n", RFB_COPYRECT_UPDATE );

          while (WaitMessage()/*GetMessage( &msg, 0, 0, 0 )*/) {
               printf( "  -> Dispatching event (id %u)...\n", msg.message );

               if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) {
                    if (msg.message == RFB_SCREEN_UPDATE) {
                         queueUpdate( (SHORT)LOWORD(msg.wParam),
                                      (SHORT)HIWORD(msg.wParam),
                                      (SHORT)LOWORD(msg.lParam) - 1,
                                      (SHORT)HIWORD(msg.lParam) - 1 );
                    }
                    else {
                         TranslateMessage( &msg );
                         DispatchMessage( &msg );
                    }
               }
          }

          printf( "  -> EXIT!\n" );

          return 0;
     }
};

}