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