blob: 00f4c10f36175dec2daaac851b0406dc8d2e7eef [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);
george82d8b01e42006-06-05 14:32:23 +0000273 SetWindowPos(handle, HWND_TOPMOST, 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()) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000311 tb.show();
george8222856792006-06-10 11:47:22 +0000312 if (!maximized) r.bottom += tb.getHeight();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000313 } else if (!showToolbar && tb.isVisible()) {
314 tb.hide();
george8222856792006-06-10 11:47:22 +0000315 if (!maximized) r.bottom -= tb.getHeight();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000316 }
george8222856792006-06-10 11:47:22 +0000317 // Resize the chiled windows even if the parent window size
318 // has not been changed (the main window is maximized)
319 if (maximized) SendMessage(handle, WM_SIZE, 0, 0);
320 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 +0000321}
322
323void DesktopWindow::setDisableWinKeys(bool dwk) {
324 // Enable low-level event hooking, so we get special keys directly
325 if (dwk)
326 enableLowLevelKeyEvents(handle);
327 else
328 disableLowLevelKeyEvents(handle);
329}
330
331
332void DesktopWindow::setMonitor(const char* monitor) {
333 MonitorInfo mi(monitor);
334 mi.moveTo(handle);
335}
336
337char* DesktopWindow::getMonitor() const {
338 MonitorInfo mi(handle);
339 return strDup(mi.szDevice);
340}
341
342
343bool DesktopWindow::setViewportOffset(const Point& tl) {
344 Point np = Point(max(0, min(tl.x, buffer->width()-client_size.width())),
345 max(0, min(tl.y, buffer->height()-client_size.height())));
346 Point delta = np.translate(scrolloffset.negate());
347 if (!np.equals(scrolloffset)) {
348 scrolloffset = np;
349 ScrollWindowEx(frameHandle, -delta.x, -delta.y, 0, 0, 0, 0, SW_INVALIDATE);
350 UpdateWindow(frameHandle);
351 return true;
352 }
353 return false;
354}
355
356
357bool DesktopWindow::processBumpScroll(const Point& pos)
358{
359 if (!bumpScroll) return false;
360 int bumpScrollPixels = 20;
361 bumpScrollDelta = Point();
362
363 if (pos.x == client_size.width()-1)
364 bumpScrollDelta.x = bumpScrollPixels;
365 else if (pos.x == 0)
366 bumpScrollDelta.x = -bumpScrollPixels;
367 if (pos.y == client_size.height()-1)
368 bumpScrollDelta.y = bumpScrollPixels;
369 else if (pos.y == 0)
370 bumpScrollDelta.y = -bumpScrollPixels;
371
372 if (bumpScrollDelta.x || bumpScrollDelta.y) {
373 if (bumpScrollTimer.isActive()) return true;
374 if (setViewportOffset(scrolloffset.translate(bumpScrollDelta))) {
375 bumpScrollTimer.start(25);
376 return true;
377 }
378 }
379
380 bumpScrollTimer.stop();
381 return false;
382}
383
384
385LRESULT
386DesktopWindow::processMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
387 switch (msg) {
388
389 // -=- Process standard window messages
390
391 case WM_NOTIFY:
392 if (wParam == ID_TOOLBAR)
393 tb.processWM_NOTIFY(wParam, lParam);
394 break;
395
396 case WM_DISPLAYCHANGE:
397 // Display format has changed - notify callback
398 callback->displayChanged();
399 break;
400
401 // -=- Window position
402
403 // Prevent the window from being resized to be too large if in normal mode.
404 // If maximized or fullscreen the allow oversized windows.
405
406 case WM_WINDOWPOSCHANGING:
407 {
408 WINDOWPOS* wpos = (WINDOWPOS*)lParam;
george82ffc14a62006-09-05 06:51:41 +0000409 if ((wpos->flags & SWP_NOSIZE) || isAutoScaling())
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000410 break;
411
412 // Work out how big the window should ideally be
413 DWORD current_style = GetWindowLong(frameHandle, GWL_STYLE);
414 DWORD style = current_style & ~(WS_VSCROLL | WS_HSCROLL);
415 DWORD style_ex = GetWindowLong(frameHandle, GWL_EXSTYLE);
416
417 RECT r;
418 SetRect(&r, 0, 0, buffer->width(), buffer->height());
419 AdjustWindowRectEx(&r, style, FALSE, style_ex);
420 Rect reqd_size = Rect(r.left, r.top, r.right, r.bottom);
421 if (current_style & WS_VSCROLL)
422 reqd_size.br.x += GetSystemMetrics(SM_CXVSCROLL);
423 if (current_style & WS_HSCROLL)
424 reqd_size.br.y += GetSystemMetrics(SM_CXHSCROLL);
425
426 SetRect(&r, reqd_size.tl.x, reqd_size.tl.y, reqd_size.br.x, reqd_size.br.y);
427 if (tb.isVisible())
428 r.bottom += tb.getHeight();
429 AdjustWindowRect(&r, GetWindowLong(handle, GWL_STYLE), FALSE);
430 reqd_size = Rect(r.left, r.top, r.right, r.bottom);
431
432 RECT current;
433 GetWindowRect(handle, &current);
434
435 if (!(GetWindowLong(handle, GWL_STYLE) & WS_MAXIMIZE) && !fullscreenActive) {
436 // Ensure that the window isn't resized too large
437 if (wpos->cx > reqd_size.width()) {
438 wpos->cx = reqd_size.width();
439 wpos->x = current.left;
440 }
441 if (wpos->cy > reqd_size.height()) {
442 wpos->cy = reqd_size.height();
443 wpos->y = current.top;
444 }
445 }
446 }
447 break;
448
449 // Resize child windows and update window size info we have cached.
450
451 case WM_SIZE:
452 {
453 Point old_offset = desktopToClient(Point(0, 0));
454 RECT r;
455
456 // Resize child windows
457 GetClientRect(handle, &r);
458 if (tb.isVisible()) {
459 MoveWindow(frameHandle, 0, tb.getHeight(),
460 r.right, r.bottom - tb.getHeight(), TRUE);
461 } else {
462 MoveWindow(frameHandle, 0, 0, r.right, r.bottom, TRUE);
463 }
464 tb.autoSize();
465
466 // Update the cached sizing information
467 GetWindowRect(frameHandle, &r);
468 window_size = Rect(r.left, r.top, r.right, r.bottom);
469 GetClientRect(frameHandle, &r);
470 client_size = Rect(r.left, r.top, r.right, r.bottom);
471
george82ffc14a62006-09-05 06:51:41 +0000472 // Perform the AutoScaling operation
473 if (isAutoScaling()) {
474 fitBufferToWindow(false);
475 } else {
476 // Determine whether scrollbars are required
477 calculateScrollBars();
478 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000479
480 // Redraw if required
george82ffc14a62006-09-05 06:51:41 +0000481 if ((!old_offset.equals(desktopToClient(Point(0, 0)))) || isAutoScaling())
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000482 InvalidateRect(frameHandle, 0, TRUE);
483 }
484 break;
485
486 // -=- Bump-scrolling
487
488 case WM_TIMER:
489 switch (wParam) {
490 case TIMER_BUMPSCROLL:
491 if (!setViewportOffset(scrolloffset.translate(bumpScrollDelta)))
492 bumpScrollTimer.stop();
493 break;
494 case TIMER_POINTER_INTERVAL:
495 case TIMER_POINTER_3BUTTON:
496 ptr.handleTimer(callback, wParam);
497 break;
498 }
499 break;
500
501 // -=- Track whether or not the window has focus
502
503 case WM_SETFOCUS:
504 has_focus = true;
505 break;
506 case WM_KILLFOCUS:
507 has_focus = false;
508 cursorOutsideBuffer();
509 // Restore the keyboard to a consistent state
510 kbd.releaseAllKeys(callback);
511 break;
512
513 // -=- If the menu is about to be shown, make sure it's up to date
514
515 case WM_INITMENU:
516 callback->refreshMenu(true);
517 break;
518
519 // -=- Handle the extra window menu items
520
521 // Pass system menu messages to the callback and only attempt
522 // to process them ourselves if the callback returns false.
523 case WM_SYSCOMMAND:
524 // Call the supplied callback
525 if (callback->sysCommand(wParam, lParam))
526 break;
527
528 // - Not processed by the callback, so process it as a system message
529 switch (wParam & 0xfff0) {
530
531 // When restored, ensure that full-screen mode is re-enabled if required.
532 case SC_RESTORE:
533 {
534 if (GetWindowLong(handle, GWL_STYLE) & WS_MINIMIZE) {
535 rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
536 setFullscreen(fullscreenRestore);
537 }
538 else if (fullscreenActive)
539 setFullscreen(false);
540 else
541 rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
542
543 return 0;
544 }
545
546 // If we are maximized or minimized then that cancels full-screen mode.
547 case SC_MINIMIZE:
548 case SC_MAXIMIZE:
549 fullscreenRestore = fullscreenActive;
550 setFullscreen(false);
551 break;
552
553 }
554 break;
555
556 // Treat all menu commands as system menu commands
557 case WM_COMMAND:
558 SendMessage(handle, WM_SYSCOMMAND, wParam, lParam);
559 return 0;
560
561 // -=- Handle keyboard input
562
563 case WM_KEYUP:
564 case WM_KEYDOWN:
565 // Hook the MenuKey to pop-up the window menu
566 if (menuKey && (wParam == menuKey)) {
567
568 bool ctrlDown = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
569 bool altDown = (GetAsyncKeyState(VK_MENU) & 0x8000) != 0;
570 bool shiftDown = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
571 if (!(ctrlDown || altDown || shiftDown)) {
572
573 // If MenuKey is being released then pop-up the menu
574 if ((msg == WM_KEYDOWN)) {
575 // Make sure it's up to date
576 //
577 // NOTE: Here we call refreshMenu only to grey out Move and Size
578 // menu items. Other things will be refreshed once again
579 // while processing the WM_INITMENU message.
580 //
581 callback->refreshMenu(false);
582
583 // Show it under the pointer
584 POINT pt;
585 GetCursorPos(&pt);
586 cursorInBuffer = false;
587 TrackPopupMenu(GetSystemMenu(handle, FALSE),
588 TPM_CENTERALIGN | TPM_VCENTERALIGN, pt.x, pt.y, 0, handle, 0);
589 }
590
591 // Ignore the MenuKey keypress for both press & release events
592 return 0;
593 }
594 }
595 case WM_SYSKEYDOWN:
596 case WM_SYSKEYUP:
597 kbd.keyEvent(callback, wParam, lParam, (msg == WM_KEYDOWN) || (msg == WM_SYSKEYDOWN));
598 return 0;
599
600 // -=- Handle the window closing
601
602 case WM_CLOSE:
603 vlog.debug("WM_CLOSE %x", handle);
604 callback->closeWindow();
605 break;
606
607 }
608
609 return rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
610}
611
612LRESULT
613DesktopWindow::processFrameMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
614 switch (msg) {
615
616 // -=- Paint the remote frame buffer
617
618 case WM_PAINT:
619 {
620 PAINTSTRUCT ps;
621 HDC paintDC = BeginPaint(frameHandle, &ps);
622 if (!paintDC)
623 throw rdr::SystemException("unable to BeginPaint", GetLastError());
624 Rect pr = Rect(ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom);
625
626 if (!pr.is_empty()) {
627
628 // Draw using the correct palette
629 PaletteSelector pSel(paintDC, windowPalette.getHandle());
630
631 if (buffer->bitmap) {
632 // Update the bitmap's palette
633 if (palette_changed) {
634 palette_changed = false;
635 buffer->refreshPalette();
636 }
637
638 // Get device context
639 BitmapDC bitmapDC(paintDC, buffer->bitmap);
640
641 // Blit the border if required
642 Rect bufpos = desktopToClient(buffer->getRect());
643 if (!pr.enclosed_by(bufpos)) {
644 vlog.debug("draw border");
645 HBRUSH black = (HBRUSH) GetStockObject(BLACK_BRUSH);
646 RECT r;
647 SetRect(&r, 0, 0, bufpos.tl.x, client_size.height()); FillRect(paintDC, &r, black);
648 SetRect(&r, bufpos.tl.x, 0, bufpos.br.x, bufpos.tl.y); FillRect(paintDC, &r, black);
649 SetRect(&r, bufpos.br.x, 0, client_size.width(), client_size.height()); FillRect(paintDC, &r, black);
650 SetRect(&r, bufpos.tl.x, bufpos.br.y, bufpos.br.x, client_size.height()); FillRect(paintDC, &r, black);
651 }
652
653 // Do the blit
654 Point buf_pos = clientToDesktop(pr.tl);
655
656 if (!BitBlt(paintDC, pr.tl.x, pr.tl.y, pr.width(), pr.height(),
657 bitmapDC, buf_pos.x, buf_pos.y, SRCCOPY))
658 throw rdr::SystemException("unable to BitBlt to window", GetLastError());
659 }
660 }
661
662 EndPaint(frameHandle, &ps);
663
664 // - Notify the callback that a paint message has finished processing
665 callback->paintCompleted();
666 }
667 return 0;
668
669 // -=- Palette management
670
671 case WM_PALETTECHANGED:
672 vlog.debug("WM_PALETTECHANGED");
673 if ((HWND)wParam == frameHandle) {
674 vlog.debug("ignoring");
675 break;
676 }
677 case WM_QUERYNEWPALETTE:
678 vlog.debug("re-selecting palette");
679 {
680 WindowDC wdc(frameHandle);
681 PaletteSelector pSel(wdc, windowPalette.getHandle());
682 if (pSel.isRedrawRequired()) {
683 InvalidateRect(frameHandle, 0, FALSE);
684 UpdateWindow(frameHandle);
685 }
686 }
687 return TRUE;
688
689 case WM_VSCROLL:
690 case WM_HSCROLL:
691 {
692 Point delta;
693 int newpos = (msg == WM_VSCROLL) ? scrolloffset.y : scrolloffset.x;
694
695 switch (LOWORD(wParam)) {
696 case SB_PAGEUP: newpos -= 50; break;
697 case SB_PAGEDOWN: newpos += 50; break;
698 case SB_LINEUP: newpos -= 5; break;
699 case SB_LINEDOWN: newpos += 5; break;
700 case SB_THUMBTRACK:
701 case SB_THUMBPOSITION: newpos = HIWORD(wParam); break;
702 default: vlog.info("received unknown scroll message");
703 };
704
705 if (msg == WM_HSCROLL)
706 setViewportOffset(Point(newpos, scrolloffset.y));
707 else
708 setViewportOffset(Point(scrolloffset.x, newpos));
709
710 SCROLLINFO si;
711 si.cbSize = sizeof(si);
712 si.fMask = SIF_POS;
713 si.nPos = newpos;
714 SetScrollInfo(frameHandle, (msg == WM_VSCROLL) ? SB_VERT : SB_HORZ, &si, TRUE);
715 }
716 break;
717
718 // -=- Cursor shape/visibility handling
719
720 case WM_SETCURSOR:
721 if (LOWORD(lParam) != HTCLIENT)
722 break;
723 SetCursor(cursorInBuffer ? dotCursor : arrowCursor);
724 return TRUE;
725
726 case WM_MOUSELEAVE:
727 trackingMouseLeave = false;
728 cursorOutsideBuffer();
729 return 0;
730
731 // -=- Mouse input handling
732
733 case WM_MOUSEMOVE:
734 case WM_LBUTTONUP:
735 case WM_MBUTTONUP:
736 case WM_RBUTTONUP:
737 case WM_LBUTTONDOWN:
738 case WM_MBUTTONDOWN:
739 case WM_RBUTTONDOWN:
740#ifdef WM_MOUSEWHEEL
741 case WM_MOUSEWHEEL:
742#endif
743 if (has_focus)
744 {
745 if (!trackingMouseLeave) {
746 TRACKMOUSEEVENT tme;
747 tme.cbSize = sizeof(TRACKMOUSEEVENT);
748 tme.dwFlags = TME_LEAVE;
749 tme.hwndTrack = frameHandle;
750 _TrackMouseEvent(&tme);
751 trackingMouseLeave = true;
752 }
753 int mask = 0;
754 if (LOWORD(wParam) & MK_LBUTTON) mask |= 1;
755 if (LOWORD(wParam) & MK_MBUTTON) mask |= 2;
756 if (LOWORD(wParam) & MK_RBUTTON) mask |= 4;
757
758#ifdef WM_MOUSEWHEEL
759 if (msg == WM_MOUSEWHEEL) {
760 int delta = (short)HIWORD(wParam);
761 int repeats = (abs(delta)+119) / 120;
762 int wheelMask = (delta > 0) ? 8 : 16;
763 vlog.debug("repeats %d, mask %d\n",repeats,wheelMask);
764 for (int i=0; i<repeats; i++) {
765 ptr.pointerEvent(callback, oldpos, mask | wheelMask);
766 ptr.pointerEvent(callback, oldpos, mask);
767 }
768 } else {
769#endif
770 Point clientPos = Point(LOWORD(lParam), HIWORD(lParam));
771 Point p = clientToDesktop(clientPos);
772
773 // If the mouse is not within the server buffer area, do nothing
774 cursorInBuffer = buffer->getRect().contains(p);
775 if (!cursorInBuffer) {
776 cursorOutsideBuffer();
777 break;
778 }
779
780 // If we're locally rendering the cursor then redraw it
781 if (cursorAvailable) {
782 // - Render the cursor!
783 if (!p.equals(cursorPos)) {
784 hideLocalCursor();
785 cursorPos = p;
786 showLocalCursor();
787 if (cursorVisible)
788 hideSystemCursor();
789 }
790 }
791
792 // If we are doing bump-scrolling then try that first...
793 if (processBumpScroll(clientPos))
794 break;
795
796 // Send a pointer event to the server
797 oldpos = p;
798 if (buffer->isScaling()) {
george82ffc14a62006-09-05 06:51:41 +0000799 p.x /= buffer->getScaleRatio();
800 p.y /= buffer->getScaleRatio();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000801 }
802 ptr.pointerEvent(callback, p, mask);
803#ifdef WM_MOUSEWHEEL
804 }
805#endif
806 } else {
807 cursorOutsideBuffer();
808 }
809 break;
810 }
811
812 return rfb::win32::SafeDefWindowProc(frameHandle, msg, wParam, lParam);
813}
814
815
816void
817DesktopWindow::hideLocalCursor() {
818 // - Blit the cursor backing store over the cursor
819 // *** ALWAYS call this BEFORE changing buffer PF!!!
820 if (cursorVisible) {
821 cursorVisible = false;
822 buffer->DIBSectionBuffer::imageRect(cursorBackingRect, cursorBacking.data);
823 invalidateDesktopRect(cursorBackingRect, false);
824 }
825}
826
827void
828DesktopWindow::showLocalCursor() {
829 if (cursorAvailable && !cursorVisible && cursorInBuffer) {
830 if (!buffer->getPF().equal(cursor.getPF()) ||
831 cursor.getRect().is_empty()) {
832 vlog.info("attempting to render invalid local cursor");
833 cursorAvailable = false;
834 showSystemCursor();
835 return;
836 }
837 cursorVisible = true;
838
839 cursorBackingRect = cursor.getRect().translate(cursorPos).translate(cursor.hotspot.negate());
840 cursorBackingRect = cursorBackingRect.intersect(buffer->getRect());
841 buffer->getImage(cursorBacking.data, cursorBackingRect);
842
843 renderLocalCursor();
844
845 invalidateDesktopRect(cursorBackingRect, false);
846 }
847}
848
849void DesktopWindow::cursorOutsideBuffer()
850{
851 cursorInBuffer = false;
852 hideLocalCursor();
853 showSystemCursor();
854}
855
856void
857DesktopWindow::renderLocalCursor()
858{
859 Rect r = cursor.getRect();
860 r = r.translate(cursorPos).translate(cursor.hotspot.negate());
861 buffer->DIBSectionBuffer::maskRect(r, cursor.data, cursor.mask.buf);
862}
863
864void
865DesktopWindow::hideSystemCursor() {
866 if (systemCursorVisible) {
867 vlog.debug("hide system cursor");
868 systemCursorVisible = false;
869 ShowCursor(FALSE);
870 }
871}
872
873void
874DesktopWindow::showSystemCursor() {
875 if (!systemCursorVisible) {
876 vlog.debug("show system cursor");
877 systemCursorVisible = true;
878 ShowCursor(TRUE);
879 }
880}
881
882
883bool
884DesktopWindow::invalidateDesktopRect(const Rect& crect, bool scaling) {
885 Rect rect;
886 if (buffer->isScaling() && scaling) {
887 rect = desktopToClient(buffer->calculateScaleBoundary(crect));
888 } else rect = desktopToClient(crect);
889 if (rect.intersect(client_size).is_empty()) return false;
890 RECT invalid = {rect.tl.x, rect.tl.y, rect.br.x, rect.br.y};
891 InvalidateRect(frameHandle, &invalid, FALSE);
892 return true;
893}
894
895
896void
897DesktopWindow::notifyClipboardChanged(const char* text, int len) {
898 callback->clientCutText(text, len);
899}
900
901
902void
903DesktopWindow::setPF(const PixelFormat& pf) {
904 // If the cursor is the wrong format then clear it
905 if (!pf.equal(buffer->getPF()))
906 setCursor(0, 0, Point(), 0, 0);
907
908 // Update the desktop buffer
909 buffer->setPF(pf);
910
911 // Redraw the window
912 InvalidateRect(frameHandle, 0, FALSE);
913}
914
915void
916DesktopWindow::setSize(int w, int h) {
917 vlog.debug("setSize %dx%d", w, h);
918
919 // If the locally-rendered cursor is visible then remove it
920 hideLocalCursor();
921
922 // Resize the backing buffer
923 buffer->setSize(w, h);
924
george82ffc14a62006-09-05 06:51:41 +0000925 // Calculate the pixel buffer aspect correlation. It's used
926 // for the autoScaling operation.
927 aspect_corr = (double)w / h;
928
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000929 // If the window is not maximised or full-screen then resize it
930 if (!(GetWindowLong(handle, GWL_STYLE) & WS_MAXIMIZE) && !fullscreenActive) {
931 // Resize the window to the required size
932 RECT r = {0, 0, w, h};
933 AdjustWindowRectEx(&r, GetWindowLong(frameHandle, GWL_STYLE), FALSE,
934 GetWindowLong(frameHandle, GWL_EXSTYLE));
935 if (tb.isVisible())
936 r.bottom += tb.getHeight();
937 AdjustWindowRect(&r, GetWindowLong(handle, GWL_STYLE), FALSE);
938
939 // Resize about the center of the window, and clip to current monitor
940 MonitorInfo mi(handle);
941 resizeWindow(handle, r.right-r.left, r.bottom-r.top);
942 mi.clipTo(handle);
943 } else {
944 // Ensure the screen contents are consistent
945 InvalidateRect(frameHandle, 0, FALSE);
946 }
947
948 // Enable/disable scrollbars as appropriate
949 calculateScrollBars();
950}
951
george8204a77712006-05-29 14:18:14 +0000952void DesktopWindow::setDesktopScale(int scale) {
953 buffer->setScale(scale);
954 InvalidateRect(frameHandle, 0, FALSE);
955 calculateScrollBars();
956}
957
george823c68f5f2006-09-05 06:17:01 +0000958void DesktopWindow::fitBufferToWindow(bool repaint) {
959 double scale_ratio;
960 double resized_aspect_corr = double(client_size.width()) / client_size.height();
961 DWORD style = GetWindowLong(frameHandle, GWL_STYLE);
962 if (style & (WS_VSCROLL | WS_HSCROLL)) {
963 style &= ~(WS_VSCROLL | WS_HSCROLL);
964 SetWindowLong(frameHandle, GWL_STYLE, style);
965 SetWindowPos(frameHandle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
966 // Update the cached client size
967 RECT r;
968 GetClientRect(frameHandle, &r);
969 client_size = Rect(r.left, r.top, r.right, r.bottom);
970 }
971 if (resized_aspect_corr > aspect_corr) {
972 scale_ratio = double(client_size.height()) / buffer->getSrcHeight();
973 } else {
974 scale_ratio = double(client_size.width()) / buffer->getSrcWidth();
975 }
976 buffer->setScaleRatio(scale_ratio);
977 if (repaint) InvalidateRect(frameHandle, 0, TRUE);
978}
979
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000980void
981DesktopWindow::setCursor(int w, int h, const Point& hotspot, void* data, void* mask) {
982 hideLocalCursor();
983
984 cursor.hotspot = hotspot;
985
986 cursor.setSize(w, h);
987 cursor.setPF(buffer->getPF());
988 cursor.imageRect(cursor.getRect(), data);
989 memcpy(cursor.mask.buf, mask, cursor.maskLen());
990 cursor.crop();
991
992 cursorBacking.setSize(w, h);
993 cursorBacking.setPF(buffer->getPF());
994
995 cursorAvailable = true;
996
997 showLocalCursor();
998}
999
1000PixelFormat
1001DesktopWindow::getNativePF() const {
1002 vlog.debug("getNativePF()");
1003 return WindowDC(handle).getPF();
1004}
1005
1006
1007void
1008DesktopWindow::refreshWindowPalette(int start, int count) {
1009 vlog.debug("refreshWindowPalette(%d, %d)", start, count);
1010
1011 Colour colours[256];
1012 if (count > 256) {
1013 vlog.debug("%d palette entries", count);
1014 throw rdr::Exception("too many palette entries");
1015 }
1016
1017 // Copy the palette from the DIBSectionBuffer
1018 ColourMap* cm = buffer->getColourMap();
1019 if (!cm) return;
1020 for (int i=0; i<count; i++) {
1021 int r, g, b;
1022 cm->lookup(i, &r, &g, &b);
1023 colours[i].r = r;
1024 colours[i].g = g;
1025 colours[i].b = b;
1026 }
1027
1028 // Set the window palette
1029 windowPalette.setEntries(start, count, colours);
1030
1031 // Cause the window to be redrawn
1032 palette_changed = true;
1033 InvalidateRect(handle, 0, FALSE);
1034}
1035
1036
1037void DesktopWindow::calculateScrollBars() {
1038 // Calculate the required size of window
1039 DWORD current_style = GetWindowLong(frameHandle, GWL_STYLE);
1040 DWORD style = current_style & ~(WS_VSCROLL | WS_HSCROLL);
1041 DWORD style_ex = GetWindowLong(frameHandle, GWL_EXSTYLE);
1042 DWORD old_style;
1043 RECT r;
1044 SetRect(&r, 0, 0, buffer->width(), buffer->height());
1045 AdjustWindowRectEx(&r, style, FALSE, style_ex);
1046 Rect reqd_size = Rect(r.left, r.top, r.right, r.bottom);
1047
1048 if (!bumpScroll) {
1049 // We only enable scrollbars if bump-scrolling is not active.
1050 // Effectively, this means if full-screen is not active,
1051 // but I think it's better to make these things explicit.
1052
1053 // Work out whether scroll bars are required
1054 do {
1055 old_style = style;
1056
1057 if (!(style & WS_HSCROLL) && (reqd_size.width() > window_size.width())) {
1058 style |= WS_HSCROLL;
1059 reqd_size.br.y += GetSystemMetrics(SM_CXHSCROLL);
1060 }
1061 if (!(style & WS_VSCROLL) && (reqd_size.height() > window_size.height())) {
1062 style |= WS_VSCROLL;
1063 reqd_size.br.x += GetSystemMetrics(SM_CXVSCROLL);
1064 }
1065 } while (style != old_style);
1066 }
1067
1068 // Tell Windows to update the window style & cached settings
1069 if (style != current_style) {
1070 SetWindowLong(frameHandle, GWL_STYLE, style);
1071 SetWindowPos(frameHandle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
1072 }
1073
1074 // Update the scroll settings
1075 SCROLLINFO si;
1076 if (style & WS_VSCROLL) {
1077 si.cbSize = sizeof(si);
1078 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1079 si.nMin = 0;
1080 si.nMax = buffer->height();
1081 si.nPage = buffer->height() - (reqd_size.height() - window_size.height());
1082 maxscrolloffset.y = max(0, si.nMax-si.nPage);
1083 scrolloffset.y = min(maxscrolloffset.y, scrolloffset.y);
1084 si.nPos = scrolloffset.y;
1085 SetScrollInfo(frameHandle, SB_VERT, &si, TRUE);
1086 }
1087 if (style & WS_HSCROLL) {
1088 si.cbSize = sizeof(si);
1089 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1090 si.nMin = 0;
1091 si.nMax = buffer->width();
1092 si.nPage = buffer->width() - (reqd_size.width() - window_size.width());
1093 maxscrolloffset.x = max(0, si.nMax-si.nPage);
1094 scrolloffset.x = min(maxscrolloffset.x, scrolloffset.x);
1095 si.nPos = scrolloffset.x;
1096 SetScrollInfo(frameHandle, SB_HORZ, &si, TRUE);
1097 }
1098
1099 // Update the cached client size
1100 GetClientRect(frameHandle, &r);
1101 client_size = Rect(r.left, r.top, r.right, r.bottom);
1102}
1103
1104
1105void
1106DesktopWindow::setName(const char* name) {
1107 SetWindowText(handle, TStr(name));
1108}
1109
1110
1111void
1112DesktopWindow::serverCutText(const char* str, int len) {
1113 CharArray t(len+1);
1114 memcpy(t.buf, str, len);
1115 t.buf[len] = 0;
1116 clipboard.setClipText(t.buf);
1117}
1118
1119
1120void DesktopWindow::fillRect(const Rect& r, Pixel pix) {
1121 Rect img_rect = buffer->isScaling() ? buffer->calculateScaleBoundary(r) : r;
1122 if (cursorBackingRect.overlaps(img_rect)) hideLocalCursor();
1123 buffer->fillRect(r, pix);
1124 invalidateDesktopRect(r);
1125}
1126void DesktopWindow::imageRect(const Rect& r, void* pixels) {
1127 Rect img_rect = buffer->isScaling() ? buffer->calculateScaleBoundary(r) : r;
1128 if (cursorBackingRect.overlaps(img_rect)) hideLocalCursor();
1129 buffer->imageRect(r, pixels);
1130 invalidateDesktopRect(r);
1131}
1132void DesktopWindow::copyRect(const Rect& r, int srcX, int srcY) {
1133 Rect img_rect = buffer->isScaling() ? buffer->calculateScaleBoundary(r) : r;
1134 if (cursorBackingRect.overlaps(img_rect) ||
1135 cursorBackingRect.overlaps(Rect(srcX, srcY, srcX+img_rect.width(), srcY+img_rect.height())))
1136 hideLocalCursor();
1137 buffer->copyRect(r, Point(r.tl.x-srcX, r.tl.y-srcY));
1138 invalidateDesktopRect(r);
1139}
1140
1141void DesktopWindow::invertRect(const Rect& r) {
1142 int stride;
1143 rdr::U8* p = buffer->isScaling() ? buffer->getPixelsRW(buffer->calculateScaleBoundary(r), &stride)
1144 : buffer->getPixelsRW(r, &stride);
1145 for (int y = 0; y < r.height(); y++) {
1146 for (int x = 0; x < r.width(); x++) {
1147 switch (buffer->getPF().bpp) {
1148 case 8: ((rdr::U8* )p)[x+y*stride] ^= 0xff; break;
1149 case 16: ((rdr::U16*)p)[x+y*stride] ^= 0xffff; break;
1150 case 32: ((rdr::U32*)p)[x+y*stride] ^= 0xffffffff; break;
1151 }
1152 }
1153 }
1154 invalidateDesktopRect(r);
1155}