1 /* Copyright (C) 2002-2005 RealVNC Ltd.  All Rights Reserved.
2  *
3  * This is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation; either version 2 of the License, or
6  * (at your option) any later version.
7  *
8  * This software is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this software; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
16  * USA.
17  */
18 
19 // -=- WMHooks.cxx
20 
21 #include <os/Mutex.h>
22 #include <os/Thread.h>
23 
24 #include <rfb_win32/WMHooks.h>
25 #include <rfb_win32/Service.h>
26 #include <rfb_win32/MsgWindow.h>
27 #include <rfb_win32/IntervalTimer.h>
28 #include <rfb/LogWriter.h>
29 
30 #include <list>
31 
32 using namespace rfb;
33 using namespace rfb::win32;
34 
35 static LogWriter vlog("WMHooks");
36 
37 
38 static HMODULE hooksLibrary;
39 
40 typedef UINT (*WM_Hooks_WMVAL_proto)();
41 static WM_Hooks_WMVAL_proto WM_Hooks_WindowChanged;
42 static WM_Hooks_WMVAL_proto WM_Hooks_WindowBorderChanged;
43 static WM_Hooks_WMVAL_proto WM_Hooks_WindowClientAreaChanged;
44 static WM_Hooks_WMVAL_proto WM_Hooks_RectangleChanged;
45 #ifdef _DEBUG
46 static WM_Hooks_WMVAL_proto WM_Hooks_Diagnostic;
47 #endif
48 
49 typedef BOOL (*WM_Hooks_Install_proto)(DWORD owner, DWORD thread);
50 static WM_Hooks_Install_proto WM_Hooks_Install;
51 typedef BOOL (*WM_Hooks_Remove_proto)(DWORD owner);
52 static WM_Hooks_Remove_proto WM_Hooks_Remove;
53 #ifdef _DEBUG
54 typedef void (*WM_Hooks_SetDiagnosticRange_proto)(UINT min, UINT max);
55 static WM_Hooks_SetDiagnosticRange_proto WM_Hooks_SetDiagnosticRange;
56 #endif
57 
58 typedef BOOL (*WM_Hooks_EnableRealInputs_proto)(BOOL pointer, BOOL keyboard);
59 static WM_Hooks_EnableRealInputs_proto WM_Hooks_EnableRealInputs;
60 
61 
LoadHooks()62 static void LoadHooks()
63 {
64   if (hooksLibrary != NULL)
65     return;
66 
67   hooksLibrary = LoadLibrary("wm_hooks.dll");
68   if (hooksLibrary == NULL)
69     return;
70 
71   WM_Hooks_WindowChanged = (WM_Hooks_WMVAL_proto)GetProcAddress(hooksLibrary, "WM_Hooks_WindowChanged");
72   if (WM_Hooks_WindowChanged == NULL)
73     goto error;
74   WM_Hooks_WindowBorderChanged = (WM_Hooks_WMVAL_proto)GetProcAddress(hooksLibrary, "WM_Hooks_WindowBorderChanged");
75   if (WM_Hooks_WindowBorderChanged == NULL)
76     goto error;
77   WM_Hooks_WindowClientAreaChanged = (WM_Hooks_WMVAL_proto)GetProcAddress(hooksLibrary, "WM_Hooks_WindowClientAreaChanged");
78   if (WM_Hooks_WindowClientAreaChanged == NULL)
79     goto error;
80   WM_Hooks_RectangleChanged = (WM_Hooks_WMVAL_proto)GetProcAddress(hooksLibrary, "WM_Hooks_RectangleChanged");
81   if (WM_Hooks_RectangleChanged == NULL)
82     goto error;
83 #ifdef _DEBUG
84   WM_Hooks_Diagnostic = (WM_Hooks_WMVAL_proto)GetProcAddress(hooksLibrary, "WM_Hooks_Diagnostic");
85   if (WM_Hooks_Diagnostic == NULL)
86     goto error;
87 #endif
88 
89   WM_Hooks_Install = (WM_Hooks_Install_proto)GetProcAddress(hooksLibrary, "WM_Hooks_Install");
90   if (WM_Hooks_Install == NULL)
91     goto error;
92   WM_Hooks_Remove = (WM_Hooks_Remove_proto)GetProcAddress(hooksLibrary, "WM_Hooks_Remove");
93   if (WM_Hooks_Remove == NULL)
94     goto error;
95 #ifdef _DEBUG
96   WM_Hooks_SetDiagnosticRange = (WM_Hooks_SetDiagnosticRange_proto)GetProcAddress(hooksLibrary, "WM_Hooks_SetDiagnosticRange");
97   if (WM_Hooks_SetDiagnosticRange == NULL)
98     goto error;
99 #endif
100 
101   WM_Hooks_EnableRealInputs = (WM_Hooks_EnableRealInputs_proto)GetProcAddress(hooksLibrary, "WM_Hooks_EnableRealInputs");
102   if (WM_Hooks_EnableRealInputs == NULL)
103     goto error;
104 
105   return;
106 
107 error:
108   FreeLibrary(hooksLibrary);
109   hooksLibrary = NULL;
110 }
111 
112 
113 class WMHooksThread : public os::Thread {
114 public:
WMHooksThread()115   WMHooksThread() : active(true), thread_id(-1) { }
116   void stop();
getThreadId()117   DWORD getThreadId() { return thread_id; }
118 protected:
119   virtual void worker();
120 protected:
121   bool active;
122   DWORD thread_id;
123 };
124 
125 static WMHooksThread* hook_mgr = 0;
126 static std::list<WMHooks*> hooks;
127 static os::Mutex hook_mgr_lock;
128 
129 
StartHookThread()130 static bool StartHookThread() {
131   if (hook_mgr)
132     return true;
133   if (hooksLibrary == NULL)
134     return false;
135   vlog.debug("creating thread");
136   hook_mgr = new WMHooksThread();
137   hook_mgr->start();
138   while (hook_mgr->getThreadId() == (DWORD)-1)
139     Sleep(0);
140   vlog.debug("installing hooks");
141   if (!WM_Hooks_Install(hook_mgr->getThreadId(), 0)) {
142     vlog.error("failed to initialise hooks");
143     hook_mgr->stop();
144     delete hook_mgr;
145     hook_mgr = 0;
146     return false;
147   }
148   return true;
149 }
150 
StopHookThread()151 static void StopHookThread() {
152   if (!hook_mgr)
153     return;
154   if (!hooks.empty())
155     return;
156   vlog.debug("closing thread");
157   hook_mgr->stop();
158   delete hook_mgr;
159   hook_mgr = 0;
160 }
161 
162 
AddHook(WMHooks * hook)163 static bool AddHook(WMHooks* hook) {
164   vlog.debug("adding hook");
165   os::AutoMutex a(&hook_mgr_lock);
166   if (!StartHookThread())
167     return false;
168   hooks.push_back(hook);
169   return true;
170 }
171 
RemHook(WMHooks * hook)172 static bool RemHook(WMHooks* hook) {
173   {
174     vlog.debug("removing hook");
175     os::AutoMutex a(&hook_mgr_lock);
176     hooks.remove(hook);
177   }
178   StopHookThread();
179   return true;
180 }
181 
NotifyHooksRegion(const Region & r)182 static void NotifyHooksRegion(const Region& r) {
183   os::AutoMutex a(&hook_mgr_lock);
184   std::list<WMHooks*>::iterator i;
185   for (i=hooks.begin(); i!=hooks.end(); i++)
186     (*i)->NotifyHooksRegion(r);
187 }
188 
189 
190 void
worker()191 WMHooksThread::worker() {
192   // Obtain message ids for all supported hook messages
193   UINT windowMsg = WM_Hooks_WindowChanged();
194   UINT clientAreaMsg = WM_Hooks_WindowClientAreaChanged();
195   UINT borderMsg = WM_Hooks_WindowBorderChanged();
196   UINT rectangleMsg = WM_Hooks_RectangleChanged();
197 #ifdef _DEBUG
198   UINT diagnosticMsg = WM_Hooks_Diagnostic();
199 #endif
200   MSG msg;
201   RECT wrect;
202   HWND hwnd;
203   int count = 0;
204 
205   // Update delay handling
206   //   We delay updates by 40-80ms, so that the triggering application has time to
207   //   actually complete them before we notify the hook callbacks & they go off
208   //   capturing screen state.
209   const int updateDelayMs = 40;
210   MsgWindow updateDelayWnd(_T("WMHooks::updateDelay"));
211   IntervalTimer updateDelayTimer(updateDelayWnd.getHandle(), 1);
212   Region updates[2];
213   int activeRgn = 0;
214 
215   vlog.debug("starting hook thread");
216 
217   thread_id = GetCurrentThreadId();
218 
219   while (active && GetMessage(&msg, NULL, 0, 0)) {
220     count++;
221 
222     if (msg.message == WM_TIMER) {
223       // Actually notify callbacks of graphical updates
224       NotifyHooksRegion(updates[1-activeRgn]);
225       if (updates[activeRgn].is_empty())
226         updateDelayTimer.stop();
227       activeRgn = 1-activeRgn;
228       updates[activeRgn].clear();
229 
230     } else if (msg.message == windowMsg) {
231       // An entire window has (potentially) changed
232       hwnd = (HWND) msg.lParam;
233       if (IsWindow(hwnd) && IsWindowVisible(hwnd) && !IsIconic(hwnd) &&
234         GetWindowRect(hwnd, &wrect) && !IsRectEmpty(&wrect)) {
235           updates[activeRgn].assign_union(Rect(wrect.left, wrect.top,
236                                                wrect.right, wrect.bottom));
237           updateDelayTimer.start(updateDelayMs);
238       }
239 
240     } else if (msg.message == clientAreaMsg) {
241       // The client area of a window has (potentially) changed
242       hwnd = (HWND) msg.lParam;
243       if (IsWindow(hwnd) && IsWindowVisible(hwnd) && !IsIconic(hwnd) &&
244           GetClientRect(hwnd, &wrect) && !IsRectEmpty(&wrect))
245       {
246         POINT pt = {0,0};
247         if (ClientToScreen(hwnd, &pt)) {
248           updates[activeRgn].assign_union(Rect(wrect.left+pt.x, wrect.top+pt.y,
249                                                wrect.right+pt.x, wrect.bottom+pt.y));
250           updateDelayTimer.start(updateDelayMs);
251         }
252       }
253 
254     } else if (msg.message == borderMsg) {
255       hwnd = (HWND) msg.lParam;
256       if (IsWindow(hwnd) && IsWindowVisible(hwnd) && !IsIconic(hwnd) &&
257           GetWindowRect(hwnd, &wrect) && !IsRectEmpty(&wrect))
258       {
259         Region changed(Rect(wrect.left, wrect.top, wrect.right, wrect.bottom));
260         RECT crect;
261         POINT pt = {0,0};
262         if (GetClientRect(hwnd, &crect) && ClientToScreen(hwnd, &pt) &&
263             !IsRectEmpty(&crect))
264         {
265           changed.assign_subtract(Rect(crect.left+pt.x, crect.top+pt.y,
266                                        crect.right+pt.x, crect.bottom+pt.y));
267         }
268         if (!changed.is_empty()) {
269           updates[activeRgn].assign_union(changed);
270           updateDelayTimer.start(updateDelayMs);
271         }
272       }
273     } else if (msg.message == rectangleMsg) {
274       Rect r = Rect(LOWORD(msg.wParam), HIWORD(msg.wParam),
275                     LOWORD(msg.lParam), HIWORD(msg.lParam));
276       if (!r.is_empty()) {
277         updates[activeRgn].assign_union(r);
278         updateDelayTimer.start(updateDelayMs);
279       }
280 
281 #ifdef _DEBUG
282     } else if (msg.message == diagnosticMsg) {
283       vlog.info("DIAG msg=%x(%d) wnd=%lx",
284                 (unsigned)msg.wParam, (int)msg.wParam,
285                 (unsigned long)msg.lParam);
286 #endif
287     }
288   }
289 
290   vlog.debug("stopping hook thread - processed %d events", count);
291   WM_Hooks_Remove(getThreadId());
292 }
293 
294 void
stop()295 WMHooksThread::stop() {
296   vlog.debug("stopping WMHooks thread");
297   active = false;
298   PostThreadMessage(thread_id, WM_QUIT, 0, 0);
299   vlog.debug("waiting for WMHooks thread");
300   wait();
301 }
302 
303 // -=- WMHooks class
304 
WMHooks()305 rfb::win32::WMHooks::WMHooks() : updateEvent(0) {
306   LoadHooks();
307 }
308 
~WMHooks()309 rfb::win32::WMHooks::~WMHooks() {
310   RemHook(this);
311 }
312 
setEvent(HANDLE ue)313 bool rfb::win32::WMHooks::setEvent(HANDLE ue) {
314   if (updateEvent)
315     RemHook(this);
316   updateEvent = ue;
317   return AddHook(this);
318 }
319 
getUpdates(UpdateTracker * ut)320 bool rfb::win32::WMHooks::getUpdates(UpdateTracker* ut) {
321   if (!updatesReady) return false;
322   os::AutoMutex a(&hook_mgr_lock);
323   updates.copyTo(ut);
324   updates.clear();
325   updatesReady = false;
326   return true;
327 }
328 
329 #ifdef _DEBUG
330 void
setDiagnosticRange(UINT min,UINT max)331 rfb::win32::WMHooks::setDiagnosticRange(UINT min, UINT max) {
332   WM_Hooks_SetDiagnosticRange(min, max);
333 }
334 #endif
335 
NotifyHooksRegion(const Region & r)336 void rfb::win32::WMHooks::NotifyHooksRegion(const Region& r) {
337   // hook_mgr_lock is already held at this point
338   updates.add_changed(r);
339   updatesReady = true;
340   SetEvent(updateEvent);
341 }
342 
343 
344 // -=- WMBlockInput class
345 
WMBlockInput()346 rfb::win32::WMBlockInput::WMBlockInput() : active(false) {
347   LoadHooks();
348 }
349 
~WMBlockInput()350 rfb::win32::WMBlockInput::~WMBlockInput() {
351   blockInputs(false);
352 }
353 
354 static bool blocking = false;
blockRealInputs(bool block_)355 static bool blockRealInputs(bool block_) {
356   // NB: Requires blockMutex to be held!
357   if (hooksLibrary == NULL)
358     return false;
359   if (block_) {
360     if (blocking)
361       return true;
362     // Enable blocking
363     if (!WM_Hooks_EnableRealInputs(false, false))
364       return false;
365     blocking = true;
366   }
367   if (blocking) {
368     WM_Hooks_EnableRealInputs(true, true);
369     blocking = false;
370   }
371   return block_ == blocking;
372 }
373 
374 static os::Mutex blockMutex;
375 static int blockCount = 0;
376 
blockInputs(bool on)377 bool rfb::win32::WMBlockInput::blockInputs(bool on) {
378   if (active == on) return true;
379   os::AutoMutex a(&blockMutex);
380   int newCount = on ? blockCount+1 : blockCount-1;
381   if (!blockRealInputs(newCount > 0))
382     return false;
383   blockCount = newCount;
384   active = on;
385   return true;
386 }
387