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