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