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