blob: 8460f58183b098aa641011aca30e48d256475860 [file] [log] [blame]
Constantin Kaplinsky729598c2006-05-25 05:12:25 +00001/* 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#include <windows.h>
20#include <commctrl.h>
21#include <rfb/Configuration.h>
22#include <rfb/LogWriter.h>
23#include <rfb_win32/WMShatter.h>
24#include <rfb_win32/LowLevelKeyEvents.h>
25#include <rfb_win32/MonitorInfo.h>
26#include <rfb_win32/DeviceContext.h>
27#include <rfb_win32/Win32Util.h>
george82fd334ad2006-05-29 14:05:20 +000028#include <rfb_win32/MsgBox.h>
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000029#include <vncviewer/DesktopWindow.h>
30#include <vncviewer/resource.h>
31
32using namespace rfb;
33using namespace rfb::win32;
34
35
36// - Statics & consts
37
38static LogWriter vlog("DesktopWindow");
39
40const int TIMER_BUMPSCROLL = 1;
41const int TIMER_POINTER_INTERVAL = 2;
42const int TIMER_POINTER_3BUTTON = 3;
43
44
45//
46// -=- DesktopWindowClass
47
48//
49// Window class used as the basis for all DesktopWindow instances
50//
51
52class DesktopWindowClass {
53public:
54 DesktopWindowClass();
55 ~DesktopWindowClass();
56 ATOM classAtom;
57 HINSTANCE instance;
58};
59
60LRESULT CALLBACK DesktopWindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) {
61 LRESULT result;
62 if (msg == WM_CREATE)
63 SetWindowLong(wnd, GWL_USERDATA, (long)((CREATESTRUCT*)lParam)->lpCreateParams);
64 else if (msg == WM_DESTROY)
65 SetWindowLong(wnd, GWL_USERDATA, 0);
66 DesktopWindow* _this = (DesktopWindow*) GetWindowLong(wnd, GWL_USERDATA);
67 if (!_this) {
68 vlog.info("null _this in %x, message %u", wnd, msg);
69 return rfb::win32::SafeDefWindowProc(wnd, msg, wParam, lParam);
70 }
71
72 try {
73 result = _this->processMessage(msg, wParam, lParam);
george82fd334ad2006-05-29 14:05:20 +000074 } catch (rfb::UnsupportedPixelFormatException &e) {
75 MsgBox(0, e.str(), MB_OK);
76 _this->getCallback()->closeWindow();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000077 } catch (rdr::Exception& e) {
78 vlog.error("untrapped: %s", e.str());
79 }
80
81 return result;
82};
83
84static HCURSOR dotCursor = (HCURSOR)LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(IDC_DOT_CURSOR), IMAGE_CURSOR, 0, 0, LR_SHARED);
85static HCURSOR arrowCursor = (HCURSOR)LoadImage(NULL, IDC_ARROW, IMAGE_CURSOR, 0, 0, LR_SHARED);
86
87DesktopWindowClass::DesktopWindowClass() : classAtom(0) {
88 WNDCLASS wndClass;
89 wndClass.style = 0;
90 wndClass.lpfnWndProc = DesktopWindowProc;
91 wndClass.cbClsExtra = 0;
92 wndClass.cbWndExtra = 0;
93 wndClass.hInstance = instance = GetModuleHandle(0);
94 wndClass.hIcon = (HICON)LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(IDI_ICON), IMAGE_ICON, 0, 0, LR_SHARED);
95 if (!wndClass.hIcon)
96 printf("unable to load icon:%ld", GetLastError());
97 wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
98 wndClass.hbrBackground = NULL;
99 wndClass.lpszMenuName = 0;
100 wndClass.lpszClassName = _T("rfb::win32::DesktopWindowClass");
101 classAtom = RegisterClass(&wndClass);
102 if (!classAtom) {
103 throw rdr::SystemException("unable to register DesktopWindow window class", GetLastError());
104 }
105}
106
107DesktopWindowClass::~DesktopWindowClass() {
108 if (classAtom) {
109 UnregisterClass((const TCHAR*)classAtom, instance);
110 }
111}
112
113DesktopWindowClass baseClass;
114
115//
116// -=- FrameClass
117
118//
119// Window class used for child windows that display pixel data
120//
121
122class FrameClass {
123public:
124 FrameClass();
125 ~FrameClass();
126 ATOM classAtom;
127 HINSTANCE instance;
128};
129
130LRESULT CALLBACK FrameProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) {
131 LRESULT result;
132 if (msg == WM_CREATE)
133 SetWindowLong(wnd, GWL_USERDATA, (long)((CREATESTRUCT*)lParam)->lpCreateParams);
134 else if (msg == WM_DESTROY)
135 SetWindowLong(wnd, GWL_USERDATA, 0);
136 DesktopWindow* _this = (DesktopWindow*) GetWindowLong(wnd, GWL_USERDATA);
137 if (!_this) {
138 vlog.info("null _this in %x, message %u", wnd, msg);
139 return rfb::win32::SafeDefWindowProc(wnd, msg, wParam, lParam);
140 }
141
142 try {
143 result = _this->processFrameMessage(msg, wParam, lParam);
144 } catch (rdr::Exception& e) {
145 vlog.error("untrapped: %s", e.str());
146 }
147
148 return result;
149}
150
151FrameClass::FrameClass() : classAtom(0) {
152 WNDCLASS wndClass;
153 wndClass.style = 0;
154 wndClass.lpfnWndProc = FrameProc;
155 wndClass.cbClsExtra = 0;
156 wndClass.cbWndExtra = 0;
157 wndClass.hInstance = instance = GetModuleHandle(0);
158 wndClass.hIcon = 0;
159 wndClass.hCursor = NULL;
160 wndClass.hbrBackground = NULL;
161 wndClass.lpszMenuName = 0;
162 wndClass.lpszClassName = _T("rfb::win32::FrameClass");
163 classAtom = RegisterClass(&wndClass);
164 if (!classAtom) {
165 throw rdr::SystemException("unable to register Frame window class", GetLastError());
166 }
167}
168
169FrameClass::~FrameClass() {
170 if (classAtom) {
171 UnregisterClass((const TCHAR*)classAtom, instance);
172 }
173}
174
175FrameClass frameClass;
176
177
178//
179// -=- DesktopWindow instance implementation
180//
181
182DesktopWindow::DesktopWindow(Callback* cb)
183 : buffer(0),
george82ffc14a62006-09-05 06:51:41 +0000184 showToolbar(false), autoScaling(false),
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000185 client_size(0, 0, 16, 16), window_size(0, 0, 32, 32),
186 cursorVisible(false), cursorAvailable(false), cursorInBuffer(false),
187 systemCursorVisible(true), trackingMouseLeave(false),
188 handle(0), frameHandle(0), has_focus(false), palette_changed(false),
189 fullscreenActive(false), fullscreenRestore(false),
190 bumpScroll(false), callback(cb) {
191
192 // Create the window
193 const char* name = "DesktopWindow";
194 handle = CreateWindow((const TCHAR*)baseClass.classAtom, TStr(name),
195 WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
196 0, 0, 10, 10, 0, 0, baseClass.instance, this);
197 if (!handle)
198 throw rdr::SystemException("unable to create WMNotifier window instance", GetLastError());
199 vlog.debug("created window \"%s\" (%x)", name, handle);
200
201 // Create the toolbar
202 tb.create(handle);
203 vlog.debug("created toolbar window \"%s\" (%x)", "ViewerToolBar", tb.getHandle());
204
205 // Create the frame window
206 frameHandle = CreateWindowEx(WS_EX_CLIENTEDGE, (const TCHAR*)frameClass.classAtom,
207 0, WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
208 CW_USEDEFAULT, CW_USEDEFAULT, handle, 0, frameClass.instance, this);
209 if (!frameHandle) {
210 throw rdr::SystemException("unable to create rfb frame window instance", GetLastError());
211 }
212 vlog.debug("created window \"%s\" (%x)", "Frame Window", frameHandle);
213
214 // Initialise the CPointer pointer handler
215 ptr.setHWND(frameHandle);
216 ptr.setIntervalTimerId(TIMER_POINTER_INTERVAL);
217 ptr.set3ButtonTimerId(TIMER_POINTER_3BUTTON);
218
219 // Initialise the bumpscroll timer
220 bumpScrollTimer.setHWND(handle);
221 bumpScrollTimer.setId(TIMER_BUMPSCROLL);
222
223 // Hook the clipboard
224 clipboard.setNotifier(this);
225
226 // Create the backing buffer
227 buffer = new win32::ScaledDIBSectionBuffer(frameHandle);
228
229 // Show the window
230 centerWindow(handle, 0);
231 ShowWindow(handle, SW_SHOW);
232}
233
234DesktopWindow::~DesktopWindow() {
235 vlog.debug("~DesktopWindow");
236 showSystemCursor();
237 if (handle) {
238 disableLowLevelKeyEvents(handle);
239 DestroyWindow(handle);
240 handle = 0;
241 }
242 delete buffer;
243 vlog.debug("~DesktopWindow done");
244}
245
246
247void DesktopWindow::setFullscreen(bool fs) {
248 if (fs && !fullscreenActive) {
249 fullscreenActive = bumpScroll = true;
250
251 // Un-minimize the window if required
252 if (GetWindowLong(handle, GWL_STYLE) & WS_MINIMIZE)
253 ShowWindow(handle, SW_RESTORE);
254
255 // Save the current window position
256 GetWindowRect(handle, &fullscreenOldRect);
257
258 // Find the size of the display the window is on
259 MonitorInfo mi(handle);
260
261 // Hide the toolbar
262 if (tb.isVisible())
263 tb.hide();
264 SetWindowLong(frameHandle, GWL_EXSTYLE, 0);
265
266 // Set the window full-screen
267 DWORD flags = GetWindowLong(handle, GWL_STYLE);
268 fullscreenOldFlags = flags;
269 flags = flags & ~(WS_CAPTION | WS_THICKFRAME | WS_MAXIMIZE | WS_MINIMIZE);
270 vlog.debug("flags=%x", flags);
271
272 SetWindowLong(handle, GWL_STYLE, flags);
george82ced9db12006-09-11 09:09:14 +0000273 SetWindowPos(handle, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top,
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000274 mi.rcMonitor.right-mi.rcMonitor.left,
275 mi.rcMonitor.bottom-mi.rcMonitor.top,
276 SWP_FRAMECHANGED);
277 } else if (!fs && fullscreenActive) {
278 fullscreenActive = bumpScroll = false;
279
280 // Show the toolbar
281 if (showToolbar)
282 tb.show();
283 SetWindowLong(frameHandle, GWL_EXSTYLE, WS_EX_CLIENTEDGE);
284
285 // Set the window non-fullscreen
286 SetWindowLong(handle, GWL_STYLE, fullscreenOldFlags);
287
288 // Set the window position
289 SetWindowPos(handle, HWND_NOTOPMOST,
290 fullscreenOldRect.left, fullscreenOldRect.top,
291 fullscreenOldRect.right - fullscreenOldRect.left,
292 fullscreenOldRect.bottom - fullscreenOldRect.top,
293 SWP_FRAMECHANGED);
294 }
295
296 // Adjust the viewport offset to cope with change in size between FS
297 // and previous window state.
298 setViewportOffset(scrolloffset);
299}
300
301void DesktopWindow::setShowToolbar(bool st)
302{
303 showToolbar = st;
george82be3e9692006-06-10 12:58:41 +0000304 if (fullscreenActive) return;
305
george8222856792006-06-10 11:47:22 +0000306 RECT r;
307 GetWindowRect(handle, &r);
308 bool maximized = GetWindowLong(handle, GWL_STYLE) & WS_MAXIMIZE;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000309
george8222856792006-06-10 11:47:22 +0000310 if (showToolbar && !tb.isVisible()) {
george8274ea5f32006-09-11 11:40:12 +0000311 refreshToolbarButtons();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000312 tb.show();
george8222856792006-06-10 11:47:22 +0000313 if (!maximized) r.bottom += tb.getHeight();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000314 } else if (!showToolbar && tb.isVisible()) {
315 tb.hide();
george8222856792006-06-10 11:47:22 +0000316 if (!maximized) r.bottom -= tb.getHeight();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000317 }
george8222856792006-06-10 11:47:22 +0000318 // Resize the chiled windows even if the parent window size
319 // has not been changed (the main window is maximized)
320 if (maximized) SendMessage(handle, WM_SIZE, 0, 0);
321 else SetWindowPos(handle, NULL, 0, 0, r.right-r.left, r.bottom-r.top, SWP_NOMOVE | SWP_NOZORDER);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000322}
323
george8274ea5f32006-09-11 11:40:12 +0000324void DesktopWindow::refreshToolbarButtons() {
325 int scale = getDesktopScale();
326 if (scale == 100) tb.enableButton(ID_ACTUAL_SIZE, false);
327 else tb.enableButton(ID_ACTUAL_SIZE, true);
328 if (scale <= 10) {
329 tb.enableButton(ID_ZOOM_IN, true);
330 tb.enableButton(ID_ZOOM_OUT, false);
331 } else if (scale >= 200) {
332 tb.enableButton(ID_ZOOM_IN, false);
333 tb.enableButton(ID_ZOOM_OUT, true);
334 } else {
335 tb.enableButton(ID_ZOOM_IN, true);
336 tb.enableButton(ID_ZOOM_OUT, true);
337 }
338 if (isAutoScaling()) tb.pressButton(ID_AUTO_SIZE, true);
339 else tb.pressButton(ID_AUTO_SIZE, false);
340}
341
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000342void DesktopWindow::setDisableWinKeys(bool dwk) {
343 // Enable low-level event hooking, so we get special keys directly
344 if (dwk)
345 enableLowLevelKeyEvents(handle);
346 else
347 disableLowLevelKeyEvents(handle);
348}
349
350
351void DesktopWindow::setMonitor(const char* monitor) {
352 MonitorInfo mi(monitor);
353 mi.moveTo(handle);
354}
355
356char* DesktopWindow::getMonitor() const {
357 MonitorInfo mi(handle);
358 return strDup(mi.szDevice);
359}
360
361
362bool DesktopWindow::setViewportOffset(const Point& tl) {
363 Point np = Point(max(0, min(tl.x, buffer->width()-client_size.width())),
364 max(0, min(tl.y, buffer->height()-client_size.height())));
365 Point delta = np.translate(scrolloffset.negate());
366 if (!np.equals(scrolloffset)) {
367 scrolloffset = np;
368 ScrollWindowEx(frameHandle, -delta.x, -delta.y, 0, 0, 0, 0, SW_INVALIDATE);
369 UpdateWindow(frameHandle);
370 return true;
371 }
372 return false;
373}
374
375
376bool DesktopWindow::processBumpScroll(const Point& pos)
377{
378 if (!bumpScroll) return false;
379 int bumpScrollPixels = 20;
380 bumpScrollDelta = Point();
381
382 if (pos.x == client_size.width()-1)
383 bumpScrollDelta.x = bumpScrollPixels;
384 else if (pos.x == 0)
385 bumpScrollDelta.x = -bumpScrollPixels;
386 if (pos.y == client_size.height()-1)
387 bumpScrollDelta.y = bumpScrollPixels;
388 else if (pos.y == 0)
389 bumpScrollDelta.y = -bumpScrollPixels;
390
391 if (bumpScrollDelta.x || bumpScrollDelta.y) {
392 if (bumpScrollTimer.isActive()) return true;
393 if (setViewportOffset(scrolloffset.translate(bumpScrollDelta))) {
394 bumpScrollTimer.start(25);
395 return true;
396 }
397 }
398
399 bumpScrollTimer.stop();
400 return false;
401}
402
403
404LRESULT
405DesktopWindow::processMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
406 switch (msg) {
407
408 // -=- Process standard window messages
409
410 case WM_NOTIFY:
411 if (wParam == ID_TOOLBAR)
412 tb.processWM_NOTIFY(wParam, lParam);
413 break;
414
415 case WM_DISPLAYCHANGE:
416 // Display format has changed - notify callback
417 callback->displayChanged();
418 break;
419
420 // -=- Window position
421
422 // Prevent the window from being resized to be too large if in normal mode.
423 // If maximized or fullscreen the allow oversized windows.
424
425 case WM_WINDOWPOSCHANGING:
426 {
427 WINDOWPOS* wpos = (WINDOWPOS*)lParam;
george82ffc14a62006-09-05 06:51:41 +0000428 if ((wpos->flags & SWP_NOSIZE) || isAutoScaling())
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000429 break;
430
431 // Work out how big the window should ideally be
432 DWORD current_style = GetWindowLong(frameHandle, GWL_STYLE);
433 DWORD style = current_style & ~(WS_VSCROLL | WS_HSCROLL);
434 DWORD style_ex = GetWindowLong(frameHandle, GWL_EXSTYLE);
435
436 RECT r;
437 SetRect(&r, 0, 0, buffer->width(), buffer->height());
438 AdjustWindowRectEx(&r, style, FALSE, style_ex);
439 Rect reqd_size = Rect(r.left, r.top, r.right, r.bottom);
440 if (current_style & WS_VSCROLL)
441 reqd_size.br.x += GetSystemMetrics(SM_CXVSCROLL);
442 if (current_style & WS_HSCROLL)
443 reqd_size.br.y += GetSystemMetrics(SM_CXHSCROLL);
444
445 SetRect(&r, reqd_size.tl.x, reqd_size.tl.y, reqd_size.br.x, reqd_size.br.y);
george82ced9db12006-09-11 09:09:14 +0000446 if (isToolbarEnabled())
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000447 r.bottom += tb.getHeight();
448 AdjustWindowRect(&r, GetWindowLong(handle, GWL_STYLE), FALSE);
449 reqd_size = Rect(r.left, r.top, r.right, r.bottom);
450
451 RECT current;
452 GetWindowRect(handle, &current);
453
454 if (!(GetWindowLong(handle, GWL_STYLE) & WS_MAXIMIZE) && !fullscreenActive) {
455 // Ensure that the window isn't resized too large
456 if (wpos->cx > reqd_size.width()) {
457 wpos->cx = reqd_size.width();
458 wpos->x = current.left;
459 }
460 if (wpos->cy > reqd_size.height()) {
461 wpos->cy = reqd_size.height();
462 wpos->y = current.top;
463 }
464 }
465 }
466 break;
467
468 // Resize child windows and update window size info we have cached.
469
470 case WM_SIZE:
471 {
472 Point old_offset = desktopToClient(Point(0, 0));
473 RECT r;
474
475 // Resize child windows
476 GetClientRect(handle, &r);
477 if (tb.isVisible()) {
478 MoveWindow(frameHandle, 0, tb.getHeight(),
479 r.right, r.bottom - tb.getHeight(), TRUE);
480 } else {
481 MoveWindow(frameHandle, 0, 0, r.right, r.bottom, TRUE);
482 }
483 tb.autoSize();
484
485 // Update the cached sizing information
486 GetWindowRect(frameHandle, &r);
487 window_size = Rect(r.left, r.top, r.right, r.bottom);
488 GetClientRect(frameHandle, &r);
489 client_size = Rect(r.left, r.top, r.right, r.bottom);
490
george82ffc14a62006-09-05 06:51:41 +0000491 // Perform the AutoScaling operation
492 if (isAutoScaling()) {
493 fitBufferToWindow(false);
494 } else {
495 // Determine whether scrollbars are required
496 calculateScrollBars();
497 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000498
499 // Redraw if required
george82ffc14a62006-09-05 06:51:41 +0000500 if ((!old_offset.equals(desktopToClient(Point(0, 0)))) || isAutoScaling())
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000501 InvalidateRect(frameHandle, 0, TRUE);
502 }
503 break;
504
505 // -=- Bump-scrolling
506
507 case WM_TIMER:
508 switch (wParam) {
509 case TIMER_BUMPSCROLL:
510 if (!setViewportOffset(scrolloffset.translate(bumpScrollDelta)))
511 bumpScrollTimer.stop();
512 break;
513 case TIMER_POINTER_INTERVAL:
514 case TIMER_POINTER_3BUTTON:
515 ptr.handleTimer(callback, wParam);
516 break;
517 }
518 break;
519
520 // -=- Track whether or not the window has focus
521
522 case WM_SETFOCUS:
523 has_focus = true;
524 break;
525 case WM_KILLFOCUS:
526 has_focus = false;
527 cursorOutsideBuffer();
528 // Restore the keyboard to a consistent state
529 kbd.releaseAllKeys(callback);
530 break;
531
532 // -=- If the menu is about to be shown, make sure it's up to date
533
534 case WM_INITMENU:
535 callback->refreshMenu(true);
536 break;
537
538 // -=- Handle the extra window menu items
539
540 // Pass system menu messages to the callback and only attempt
541 // to process them ourselves if the callback returns false.
542 case WM_SYSCOMMAND:
543 // Call the supplied callback
544 if (callback->sysCommand(wParam, lParam))
545 break;
546
547 // - Not processed by the callback, so process it as a system message
548 switch (wParam & 0xfff0) {
549
550 // When restored, ensure that full-screen mode is re-enabled if required.
551 case SC_RESTORE:
552 {
553 if (GetWindowLong(handle, GWL_STYLE) & WS_MINIMIZE) {
554 rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
555 setFullscreen(fullscreenRestore);
556 }
557 else if (fullscreenActive)
558 setFullscreen(false);
559 else
560 rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
561
562 return 0;
563 }
564
565 // If we are maximized or minimized then that cancels full-screen mode.
566 case SC_MINIMIZE:
567 case SC_MAXIMIZE:
568 fullscreenRestore = fullscreenActive;
569 setFullscreen(false);
570 break;
571
572 }
573 break;
574
575 // Treat all menu commands as system menu commands
576 case WM_COMMAND:
577 SendMessage(handle, WM_SYSCOMMAND, wParam, lParam);
578 return 0;
579
580 // -=- Handle keyboard input
581
582 case WM_KEYUP:
583 case WM_KEYDOWN:
584 // Hook the MenuKey to pop-up the window menu
585 if (menuKey && (wParam == menuKey)) {
586
587 bool ctrlDown = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
588 bool altDown = (GetAsyncKeyState(VK_MENU) & 0x8000) != 0;
589 bool shiftDown = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
590 if (!(ctrlDown || altDown || shiftDown)) {
591
592 // If MenuKey is being released then pop-up the menu
593 if ((msg == WM_KEYDOWN)) {
594 // Make sure it's up to date
595 //
596 // NOTE: Here we call refreshMenu only to grey out Move and Size
597 // menu items. Other things will be refreshed once again
598 // while processing the WM_INITMENU message.
599 //
600 callback->refreshMenu(false);
601
602 // Show it under the pointer
603 POINT pt;
604 GetCursorPos(&pt);
605 cursorInBuffer = false;
606 TrackPopupMenu(GetSystemMenu(handle, FALSE),
607 TPM_CENTERALIGN | TPM_VCENTERALIGN, pt.x, pt.y, 0, handle, 0);
608 }
609
610 // Ignore the MenuKey keypress for both press & release events
611 return 0;
612 }
613 }
614 case WM_SYSKEYDOWN:
615 case WM_SYSKEYUP:
616 kbd.keyEvent(callback, wParam, lParam, (msg == WM_KEYDOWN) || (msg == WM_SYSKEYDOWN));
617 return 0;
618
619 // -=- Handle the window closing
620
621 case WM_CLOSE:
622 vlog.debug("WM_CLOSE %x", handle);
623 callback->closeWindow();
624 break;
625
626 }
627
628 return rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
629}
630
631LRESULT
632DesktopWindow::processFrameMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
633 switch (msg) {
634
635 // -=- Paint the remote frame buffer
636
637 case WM_PAINT:
638 {
639 PAINTSTRUCT ps;
640 HDC paintDC = BeginPaint(frameHandle, &ps);
641 if (!paintDC)
642 throw rdr::SystemException("unable to BeginPaint", GetLastError());
643 Rect pr = Rect(ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom);
644
645 if (!pr.is_empty()) {
646
647 // Draw using the correct palette
648 PaletteSelector pSel(paintDC, windowPalette.getHandle());
649
650 if (buffer->bitmap) {
651 // Update the bitmap's palette
652 if (palette_changed) {
653 palette_changed = false;
654 buffer->refreshPalette();
655 }
656
657 // Get device context
658 BitmapDC bitmapDC(paintDC, buffer->bitmap);
659
660 // Blit the border if required
661 Rect bufpos = desktopToClient(buffer->getRect());
662 if (!pr.enclosed_by(bufpos)) {
663 vlog.debug("draw border");
664 HBRUSH black = (HBRUSH) GetStockObject(BLACK_BRUSH);
665 RECT r;
666 SetRect(&r, 0, 0, bufpos.tl.x, client_size.height()); FillRect(paintDC, &r, black);
667 SetRect(&r, bufpos.tl.x, 0, bufpos.br.x, bufpos.tl.y); FillRect(paintDC, &r, black);
668 SetRect(&r, bufpos.br.x, 0, client_size.width(), client_size.height()); FillRect(paintDC, &r, black);
669 SetRect(&r, bufpos.tl.x, bufpos.br.y, bufpos.br.x, client_size.height()); FillRect(paintDC, &r, black);
670 }
671
672 // Do the blit
673 Point buf_pos = clientToDesktop(pr.tl);
674
675 if (!BitBlt(paintDC, pr.tl.x, pr.tl.y, pr.width(), pr.height(),
676 bitmapDC, buf_pos.x, buf_pos.y, SRCCOPY))
677 throw rdr::SystemException("unable to BitBlt to window", GetLastError());
678 }
679 }
680
681 EndPaint(frameHandle, &ps);
682
683 // - Notify the callback that a paint message has finished processing
684 callback->paintCompleted();
685 }
686 return 0;
687
688 // -=- Palette management
689
690 case WM_PALETTECHANGED:
691 vlog.debug("WM_PALETTECHANGED");
692 if ((HWND)wParam == frameHandle) {
693 vlog.debug("ignoring");
694 break;
695 }
696 case WM_QUERYNEWPALETTE:
697 vlog.debug("re-selecting palette");
698 {
699 WindowDC wdc(frameHandle);
700 PaletteSelector pSel(wdc, windowPalette.getHandle());
701 if (pSel.isRedrawRequired()) {
702 InvalidateRect(frameHandle, 0, FALSE);
703 UpdateWindow(frameHandle);
704 }
705 }
706 return TRUE;
707
708 case WM_VSCROLL:
709 case WM_HSCROLL:
710 {
711 Point delta;
712 int newpos = (msg == WM_VSCROLL) ? scrolloffset.y : scrolloffset.x;
713
714 switch (LOWORD(wParam)) {
715 case SB_PAGEUP: newpos -= 50; break;
716 case SB_PAGEDOWN: newpos += 50; break;
717 case SB_LINEUP: newpos -= 5; break;
718 case SB_LINEDOWN: newpos += 5; break;
719 case SB_THUMBTRACK:
720 case SB_THUMBPOSITION: newpos = HIWORD(wParam); break;
721 default: vlog.info("received unknown scroll message");
722 };
723
724 if (msg == WM_HSCROLL)
725 setViewportOffset(Point(newpos, scrolloffset.y));
726 else
727 setViewportOffset(Point(scrolloffset.x, newpos));
728
729 SCROLLINFO si;
730 si.cbSize = sizeof(si);
731 si.fMask = SIF_POS;
732 si.nPos = newpos;
733 SetScrollInfo(frameHandle, (msg == WM_VSCROLL) ? SB_VERT : SB_HORZ, &si, TRUE);
734 }
735 break;
736
737 // -=- Cursor shape/visibility handling
738
739 case WM_SETCURSOR:
740 if (LOWORD(lParam) != HTCLIENT)
741 break;
742 SetCursor(cursorInBuffer ? dotCursor : arrowCursor);
743 return TRUE;
744
745 case WM_MOUSELEAVE:
746 trackingMouseLeave = false;
747 cursorOutsideBuffer();
748 return 0;
749
750 // -=- Mouse input handling
751
752 case WM_MOUSEMOVE:
753 case WM_LBUTTONUP:
754 case WM_MBUTTONUP:
755 case WM_RBUTTONUP:
756 case WM_LBUTTONDOWN:
757 case WM_MBUTTONDOWN:
758 case WM_RBUTTONDOWN:
759#ifdef WM_MOUSEWHEEL
760 case WM_MOUSEWHEEL:
761#endif
762 if (has_focus)
763 {
764 if (!trackingMouseLeave) {
765 TRACKMOUSEEVENT tme;
766 tme.cbSize = sizeof(TRACKMOUSEEVENT);
767 tme.dwFlags = TME_LEAVE;
768 tme.hwndTrack = frameHandle;
769 _TrackMouseEvent(&tme);
770 trackingMouseLeave = true;
771 }
772 int mask = 0;
773 if (LOWORD(wParam) & MK_LBUTTON) mask |= 1;
774 if (LOWORD(wParam) & MK_MBUTTON) mask |= 2;
775 if (LOWORD(wParam) & MK_RBUTTON) mask |= 4;
776
777#ifdef WM_MOUSEWHEEL
778 if (msg == WM_MOUSEWHEEL) {
779 int delta = (short)HIWORD(wParam);
780 int repeats = (abs(delta)+119) / 120;
781 int wheelMask = (delta > 0) ? 8 : 16;
782 vlog.debug("repeats %d, mask %d\n",repeats,wheelMask);
783 for (int i=0; i<repeats; i++) {
784 ptr.pointerEvent(callback, oldpos, mask | wheelMask);
785 ptr.pointerEvent(callback, oldpos, mask);
786 }
787 } else {
788#endif
789 Point clientPos = Point(LOWORD(lParam), HIWORD(lParam));
790 Point p = clientToDesktop(clientPos);
791
792 // If the mouse is not within the server buffer area, do nothing
793 cursorInBuffer = buffer->getRect().contains(p);
794 if (!cursorInBuffer) {
795 cursorOutsideBuffer();
796 break;
797 }
798
799 // If we're locally rendering the cursor then redraw it
800 if (cursorAvailable) {
801 // - Render the cursor!
802 if (!p.equals(cursorPos)) {
803 hideLocalCursor();
804 cursorPos = p;
805 showLocalCursor();
806 if (cursorVisible)
807 hideSystemCursor();
808 }
809 }
810
811 // If we are doing bump-scrolling then try that first...
812 if (processBumpScroll(clientPos))
813 break;
814
815 // Send a pointer event to the server
816 oldpos = p;
817 if (buffer->isScaling()) {
george82ffc14a62006-09-05 06:51:41 +0000818 p.x /= buffer->getScaleRatio();
819 p.y /= buffer->getScaleRatio();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000820 }
821 ptr.pointerEvent(callback, p, mask);
822#ifdef WM_MOUSEWHEEL
823 }
824#endif
825 } else {
826 cursorOutsideBuffer();
827 }
828 break;
829 }
830
831 return rfb::win32::SafeDefWindowProc(frameHandle, msg, wParam, lParam);
832}
833
834
835void
836DesktopWindow::hideLocalCursor() {
837 // - Blit the cursor backing store over the cursor
838 // *** ALWAYS call this BEFORE changing buffer PF!!!
839 if (cursorVisible) {
840 cursorVisible = false;
841 buffer->DIBSectionBuffer::imageRect(cursorBackingRect, cursorBacking.data);
842 invalidateDesktopRect(cursorBackingRect, false);
843 }
844}
845
846void
847DesktopWindow::showLocalCursor() {
848 if (cursorAvailable && !cursorVisible && cursorInBuffer) {
849 if (!buffer->getPF().equal(cursor.getPF()) ||
850 cursor.getRect().is_empty()) {
851 vlog.info("attempting to render invalid local cursor");
852 cursorAvailable = false;
853 showSystemCursor();
854 return;
855 }
856 cursorVisible = true;
857
858 cursorBackingRect = cursor.getRect().translate(cursorPos).translate(cursor.hotspot.negate());
859 cursorBackingRect = cursorBackingRect.intersect(buffer->getRect());
860 buffer->getImage(cursorBacking.data, cursorBackingRect);
861
862 renderLocalCursor();
863
864 invalidateDesktopRect(cursorBackingRect, false);
865 }
866}
867
868void DesktopWindow::cursorOutsideBuffer()
869{
870 cursorInBuffer = false;
871 hideLocalCursor();
872 showSystemCursor();
873}
874
875void
876DesktopWindow::renderLocalCursor()
877{
878 Rect r = cursor.getRect();
879 r = r.translate(cursorPos).translate(cursor.hotspot.negate());
880 buffer->DIBSectionBuffer::maskRect(r, cursor.data, cursor.mask.buf);
881}
882
883void
884DesktopWindow::hideSystemCursor() {
885 if (systemCursorVisible) {
886 vlog.debug("hide system cursor");
887 systemCursorVisible = false;
888 ShowCursor(FALSE);
889 }
890}
891
892void
893DesktopWindow::showSystemCursor() {
894 if (!systemCursorVisible) {
895 vlog.debug("show system cursor");
896 systemCursorVisible = true;
897 ShowCursor(TRUE);
898 }
899}
900
901
902bool
903DesktopWindow::invalidateDesktopRect(const Rect& crect, bool scaling) {
904 Rect rect;
905 if (buffer->isScaling() && scaling) {
906 rect = desktopToClient(buffer->calculateScaleBoundary(crect));
907 } else rect = desktopToClient(crect);
908 if (rect.intersect(client_size).is_empty()) return false;
909 RECT invalid = {rect.tl.x, rect.tl.y, rect.br.x, rect.br.y};
910 InvalidateRect(frameHandle, &invalid, FALSE);
911 return true;
912}
913
914
915void
916DesktopWindow::notifyClipboardChanged(const char* text, int len) {
917 callback->clientCutText(text, len);
918}
919
920
921void
922DesktopWindow::setPF(const PixelFormat& pf) {
923 // If the cursor is the wrong format then clear it
924 if (!pf.equal(buffer->getPF()))
925 setCursor(0, 0, Point(), 0, 0);
926
927 // Update the desktop buffer
928 buffer->setPF(pf);
929
930 // Redraw the window
931 InvalidateRect(frameHandle, 0, FALSE);
932}
933
934void
935DesktopWindow::setSize(int w, int h) {
936 vlog.debug("setSize %dx%d", w, h);
937
938 // If the locally-rendered cursor is visible then remove it
939 hideLocalCursor();
940
941 // Resize the backing buffer
942 buffer->setSize(w, h);
943
george82ffc14a62006-09-05 06:51:41 +0000944 // Calculate the pixel buffer aspect correlation. It's used
945 // for the autoScaling operation.
946 aspect_corr = (double)w / h;
947
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000948 // If the window is not maximised or full-screen then resize it
949 if (!(GetWindowLong(handle, GWL_STYLE) & WS_MAXIMIZE) && !fullscreenActive) {
950 // Resize the window to the required size
951 RECT r = {0, 0, w, h};
952 AdjustWindowRectEx(&r, GetWindowLong(frameHandle, GWL_STYLE), FALSE,
953 GetWindowLong(frameHandle, GWL_EXSTYLE));
george82ced9db12006-09-11 09:09:14 +0000954 if (isToolbarEnabled())
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000955 r.bottom += tb.getHeight();
956 AdjustWindowRect(&r, GetWindowLong(handle, GWL_STYLE), FALSE);
957
958 // Resize about the center of the window, and clip to current monitor
959 MonitorInfo mi(handle);
960 resizeWindow(handle, r.right-r.left, r.bottom-r.top);
961 mi.clipTo(handle);
962 } else {
963 // Ensure the screen contents are consistent
964 InvalidateRect(frameHandle, 0, FALSE);
965 }
966
967 // Enable/disable scrollbars as appropriate
968 calculateScrollBars();
969}
970
george8274ea5f32006-09-11 11:40:12 +0000971void DesktopWindow::setAutoScaling(bool as) {
972 autoScaling = as;
973 if (as) fitBufferToWindow();
974}
975
george8204a77712006-05-29 14:18:14 +0000976void DesktopWindow::setDesktopScale(int scale) {
977 buffer->setScale(scale);
978 InvalidateRect(frameHandle, 0, FALSE);
979 calculateScrollBars();
george8274ea5f32006-09-11 11:40:12 +0000980 if (isToolbarEnabled()) refreshToolbarButtons();
george8204a77712006-05-29 14:18:14 +0000981}
982
george823c68f5f2006-09-05 06:17:01 +0000983void DesktopWindow::fitBufferToWindow(bool repaint) {
984 double scale_ratio;
985 double resized_aspect_corr = double(client_size.width()) / client_size.height();
986 DWORD style = GetWindowLong(frameHandle, GWL_STYLE);
987 if (style & (WS_VSCROLL | WS_HSCROLL)) {
988 style &= ~(WS_VSCROLL | WS_HSCROLL);
989 SetWindowLong(frameHandle, GWL_STYLE, style);
990 SetWindowPos(frameHandle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
991 // Update the cached client size
992 RECT r;
993 GetClientRect(frameHandle, &r);
994 client_size = Rect(r.left, r.top, r.right, r.bottom);
995 }
996 if (resized_aspect_corr > aspect_corr) {
997 scale_ratio = double(client_size.height()) / buffer->getSrcHeight();
998 } else {
999 scale_ratio = double(client_size.width()) / buffer->getSrcWidth();
1000 }
1001 buffer->setScaleRatio(scale_ratio);
1002 if (repaint) InvalidateRect(frameHandle, 0, TRUE);
george8274ea5f32006-09-11 11:40:12 +00001003 if (isToolbarEnabled()) refreshToolbarButtons();
george823c68f5f2006-09-05 06:17:01 +00001004}
1005
Constantin Kaplinsky729598c2006-05-25 05:12:25 +00001006void
1007DesktopWindow::setCursor(int w, int h, const Point& hotspot, void* data, void* mask) {
1008 hideLocalCursor();
1009
1010 cursor.hotspot = hotspot;
1011
1012 cursor.setSize(w, h);
1013 cursor.setPF(buffer->getPF());
1014 cursor.imageRect(cursor.getRect(), data);
1015 memcpy(cursor.mask.buf, mask, cursor.maskLen());
1016 cursor.crop();
1017
1018 cursorBacking.setSize(w, h);
1019 cursorBacking.setPF(buffer->getPF());
1020
1021 cursorAvailable = true;
1022
1023 showLocalCursor();
1024}
1025
1026PixelFormat
1027DesktopWindow::getNativePF() const {
1028 vlog.debug("getNativePF()");
1029 return WindowDC(handle).getPF();
1030}
1031
1032
1033void
1034DesktopWindow::refreshWindowPalette(int start, int count) {
1035 vlog.debug("refreshWindowPalette(%d, %d)", start, count);
1036
1037 Colour colours[256];
1038 if (count > 256) {
1039 vlog.debug("%d palette entries", count);
1040 throw rdr::Exception("too many palette entries");
1041 }
1042
1043 // Copy the palette from the DIBSectionBuffer
1044 ColourMap* cm = buffer->getColourMap();
1045 if (!cm) return;
1046 for (int i=0; i<count; i++) {
1047 int r, g, b;
1048 cm->lookup(i, &r, &g, &b);
1049 colours[i].r = r;
1050 colours[i].g = g;
1051 colours[i].b = b;
1052 }
1053
1054 // Set the window palette
1055 windowPalette.setEntries(start, count, colours);
1056
1057 // Cause the window to be redrawn
1058 palette_changed = true;
1059 InvalidateRect(handle, 0, FALSE);
1060}
1061
1062
1063void DesktopWindow::calculateScrollBars() {
1064 // Calculate the required size of window
1065 DWORD current_style = GetWindowLong(frameHandle, GWL_STYLE);
1066 DWORD style = current_style & ~(WS_VSCROLL | WS_HSCROLL);
1067 DWORD style_ex = GetWindowLong(frameHandle, GWL_EXSTYLE);
1068 DWORD old_style;
1069 RECT r;
1070 SetRect(&r, 0, 0, buffer->width(), buffer->height());
1071 AdjustWindowRectEx(&r, style, FALSE, style_ex);
1072 Rect reqd_size = Rect(r.left, r.top, r.right, r.bottom);
1073
1074 if (!bumpScroll) {
1075 // We only enable scrollbars if bump-scrolling is not active.
1076 // Effectively, this means if full-screen is not active,
1077 // but I think it's better to make these things explicit.
1078
1079 // Work out whether scroll bars are required
1080 do {
1081 old_style = style;
1082
1083 if (!(style & WS_HSCROLL) && (reqd_size.width() > window_size.width())) {
1084 style |= WS_HSCROLL;
1085 reqd_size.br.y += GetSystemMetrics(SM_CXHSCROLL);
1086 }
1087 if (!(style & WS_VSCROLL) && (reqd_size.height() > window_size.height())) {
1088 style |= WS_VSCROLL;
1089 reqd_size.br.x += GetSystemMetrics(SM_CXVSCROLL);
1090 }
1091 } while (style != old_style);
1092 }
1093
1094 // Tell Windows to update the window style & cached settings
1095 if (style != current_style) {
1096 SetWindowLong(frameHandle, GWL_STYLE, style);
1097 SetWindowPos(frameHandle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
1098 }
1099
1100 // Update the scroll settings
1101 SCROLLINFO si;
1102 if (style & WS_VSCROLL) {
1103 si.cbSize = sizeof(si);
1104 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1105 si.nMin = 0;
1106 si.nMax = buffer->height();
1107 si.nPage = buffer->height() - (reqd_size.height() - window_size.height());
1108 maxscrolloffset.y = max(0, si.nMax-si.nPage);
1109 scrolloffset.y = min(maxscrolloffset.y, scrolloffset.y);
1110 si.nPos = scrolloffset.y;
1111 SetScrollInfo(frameHandle, SB_VERT, &si, TRUE);
1112 }
1113 if (style & WS_HSCROLL) {
1114 si.cbSize = sizeof(si);
1115 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1116 si.nMin = 0;
1117 si.nMax = buffer->width();
1118 si.nPage = buffer->width() - (reqd_size.width() - window_size.width());
1119 maxscrolloffset.x = max(0, si.nMax-si.nPage);
1120 scrolloffset.x = min(maxscrolloffset.x, scrolloffset.x);
1121 si.nPos = scrolloffset.x;
1122 SetScrollInfo(frameHandle, SB_HORZ, &si, TRUE);
1123 }
1124
1125 // Update the cached client size
1126 GetClientRect(frameHandle, &r);
1127 client_size = Rect(r.left, r.top, r.right, r.bottom);
1128}
1129
1130
1131void
1132DesktopWindow::setName(const char* name) {
1133 SetWindowText(handle, TStr(name));
1134}
1135
1136
1137void
1138DesktopWindow::serverCutText(const char* str, int len) {
1139 CharArray t(len+1);
1140 memcpy(t.buf, str, len);
1141 t.buf[len] = 0;
1142 clipboard.setClipText(t.buf);
1143}
1144
1145
1146void DesktopWindow::fillRect(const Rect& r, Pixel pix) {
1147 Rect img_rect = buffer->isScaling() ? buffer->calculateScaleBoundary(r) : r;
1148 if (cursorBackingRect.overlaps(img_rect)) hideLocalCursor();
1149 buffer->fillRect(r, pix);
1150 invalidateDesktopRect(r);
1151}
1152void DesktopWindow::imageRect(const Rect& r, void* pixels) {
1153 Rect img_rect = buffer->isScaling() ? buffer->calculateScaleBoundary(r) : r;
1154 if (cursorBackingRect.overlaps(img_rect)) hideLocalCursor();
1155 buffer->imageRect(r, pixels);
1156 invalidateDesktopRect(r);
1157}
1158void DesktopWindow::copyRect(const Rect& r, int srcX, int srcY) {
1159 Rect img_rect = buffer->isScaling() ? buffer->calculateScaleBoundary(r) : r;
1160 if (cursorBackingRect.overlaps(img_rect) ||
1161 cursorBackingRect.overlaps(Rect(srcX, srcY, srcX+img_rect.width(), srcY+img_rect.height())))
1162 hideLocalCursor();
1163 buffer->copyRect(r, Point(r.tl.x-srcX, r.tl.y-srcY));
1164 invalidateDesktopRect(r);
1165}
1166
1167void DesktopWindow::invertRect(const Rect& r) {
1168 int stride;
1169 rdr::U8* p = buffer->isScaling() ? buffer->getPixelsRW(buffer->calculateScaleBoundary(r), &stride)
1170 : buffer->getPixelsRW(r, &stride);
1171 for (int y = 0; y < r.height(); y++) {
1172 for (int x = 0; x < r.width(); x++) {
1173 switch (buffer->getPF().bpp) {
1174 case 8: ((rdr::U8* )p)[x+y*stride] ^= 0xff; break;
1175 case 16: ((rdr::U16*)p)[x+y*stride] ^= 0xffff; break;
1176 case 32: ((rdr::U32*)p)[x+y*stride] ^= 0xffffffff; break;
1177 }
1178 }
1179 }
1180 invalidateDesktopRect(r);
1181}