blob: 47ddf7d819e1b7411d6868576af135bfe455b5ac [file] [log] [blame]
Constantin Kaplinskyac306682006-05-16 08:48:31 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 *
3 * This is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This software is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
16 * USA.
17 */
18
19#include <windows.h>
20#include <commctrl.h>
21#include <rfb/Configuration.h>
22#include <rfb/LogWriter.h>
23#include <rfb_win32/WMShatter.h>
24#include <rfb_win32/LowLevelKeyEvents.h>
25#include <rfb_win32/MonitorInfo.h>
26#include <rfb_win32/DeviceContext.h>
27#include <rfb_win32/Win32Util.h>
28#include <vncviewer/DesktopWindow.h>
29#include <vncviewer/resource.h>
30
31using namespace rfb;
32using namespace rfb::win32;
33
34
35// - Statics & consts
36
37static LogWriter vlog("DesktopWindow");
38
39const int TIMER_BUMPSCROLL = 1;
40const int TIMER_POINTER_INTERVAL = 2;
41const int TIMER_POINTER_3BUTTON = 3;
42
43
44//
45// -=- DesktopWindowClass
46
47//
48// Window class used as the basis for all DesktopWindow instances
49//
50
51class DesktopWindowClass {
52public:
53 DesktopWindowClass();
54 ~DesktopWindowClass();
55 ATOM classAtom;
56 HINSTANCE instance;
57};
58
59LRESULT CALLBACK DesktopWindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) {
60 LRESULT result;
61 if (msg == WM_CREATE)
62 SetWindowLong(wnd, GWL_USERDATA, (long)((CREATESTRUCT*)lParam)->lpCreateParams);
63 else if (msg == WM_DESTROY)
64 SetWindowLong(wnd, GWL_USERDATA, 0);
65 DesktopWindow* _this = (DesktopWindow*) GetWindowLong(wnd, GWL_USERDATA);
66 if (!_this) {
67 vlog.info("null _this in %x, message %u", wnd, msg);
68 return rfb::win32::SafeDefWindowProc(wnd, msg, wParam, lParam);
69 }
70
71 try {
72 result = _this->processMessage(msg, wParam, lParam);
73 } catch (rdr::Exception& e) {
74 vlog.error("untrapped: %s", e.str());
75 }
76
77 return result;
78};
79
80static HCURSOR dotCursor = (HCURSOR)LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(IDC_DOT_CURSOR), IMAGE_CURSOR, 0, 0, LR_SHARED);
81static HCURSOR arrowCursor = (HCURSOR)LoadImage(NULL, IDC_ARROW, IMAGE_CURSOR, 0, 0, LR_SHARED);
82
83DesktopWindowClass::DesktopWindowClass() : classAtom(0) {
84 WNDCLASS wndClass;
85 wndClass.style = 0;
86 wndClass.lpfnWndProc = DesktopWindowProc;
87 wndClass.cbClsExtra = 0;
88 wndClass.cbWndExtra = 0;
89 wndClass.hInstance = instance = GetModuleHandle(0);
90 wndClass.hIcon = (HICON)LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(IDI_ICON), IMAGE_ICON, 0, 0, LR_SHARED);
91 if (!wndClass.hIcon)
92 printf("unable to load icon:%ld", GetLastError());
93 wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
94 wndClass.hbrBackground = NULL;
95 wndClass.lpszMenuName = 0;
96 wndClass.lpszClassName = _T("rfb::win32::DesktopWindowClass");
97 classAtom = RegisterClass(&wndClass);
98 if (!classAtom) {
99 throw rdr::SystemException("unable to register DesktopWindow window class", GetLastError());
100 }
101}
102
103DesktopWindowClass::~DesktopWindowClass() {
104 if (classAtom) {
105 UnregisterClass((const TCHAR*)classAtom, instance);
106 }
107}
108
109DesktopWindowClass baseClass;
110
111//
112// -=- FrameClass
113
114//
115// Window class used for child windows that display pixel data
116//
117
118class FrameClass {
119public:
120 FrameClass();
121 ~FrameClass();
122 ATOM classAtom;
123 HINSTANCE instance;
124};
125
126LRESULT CALLBACK FrameProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) {
127 LRESULT result;
128 if (msg == WM_CREATE)
129 SetWindowLong(wnd, GWL_USERDATA, (long)((CREATESTRUCT*)lParam)->lpCreateParams);
130 else if (msg == WM_DESTROY)
131 SetWindowLong(wnd, GWL_USERDATA, 0);
132 DesktopWindow* _this = (DesktopWindow*) GetWindowLong(wnd, GWL_USERDATA);
133 if (!_this) {
134 vlog.info("null _this in %x, message %u", wnd, msg);
135 return rfb::win32::SafeDefWindowProc(wnd, msg, wParam, lParam);
136 }
137
138 try {
139 result = _this->processFrameMessage(msg, wParam, lParam);
140 } catch (rdr::Exception& e) {
141 vlog.error("untrapped: %s", e.str());
142 }
143
144 return result;
145}
146
147FrameClass::FrameClass() : classAtom(0) {
148 WNDCLASS wndClass;
149 wndClass.style = 0;
150 wndClass.lpfnWndProc = FrameProc;
151 wndClass.cbClsExtra = 0;
152 wndClass.cbWndExtra = 0;
153 wndClass.hInstance = instance = GetModuleHandle(0);
154 wndClass.hIcon = 0;
155 wndClass.hCursor = NULL;
156 wndClass.hbrBackground = NULL;
157 wndClass.lpszMenuName = 0;
158 wndClass.lpszClassName = _T("rfb::win32::FrameClass");
159 classAtom = RegisterClass(&wndClass);
160 if (!classAtom) {
161 throw rdr::SystemException("unable to register Frame window class", GetLastError());
162 }
163}
164
165FrameClass::~FrameClass() {
166 if (classAtom) {
167 UnregisterClass((const TCHAR*)classAtom, instance);
168 }
169}
170
171FrameClass frameClass;
172
173
174//
175// -=- DesktopWindow instance implementation
176//
177
178DesktopWindow::DesktopWindow(Callback* cb)
179 : buffer(0),
Constantin Kaplinsky318eb4a2006-05-17 09:39:42 +0000180 showToolbar(false),
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000181 client_size(0, 0, 16, 16), window_size(0, 0, 32, 32),
182 cursorVisible(false), cursorAvailable(false), cursorInBuffer(false),
183 systemCursorVisible(true), trackingMouseLeave(false),
184 handle(0), frameHandle(0), has_focus(false), palette_changed(false),
185 fullscreenActive(false), fullscreenRestore(false),
186 bumpScroll(false), callback(cb) {
187
188 // Create the window
189 const char* name = "DesktopWindow";
190 handle = CreateWindow((const TCHAR*)baseClass.classAtom, TStr(name),
191 WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
192 0, 0, 10, 10, 0, 0, baseClass.instance, this);
193 if (!handle)
194 throw rdr::SystemException("unable to create WMNotifier window instance", GetLastError());
195 vlog.debug("created window \"%s\" (%x)", name, handle);
196
197 // Create the toolbar
Constantin Kaplinskyf4038832006-05-17 04:17:25 +0000198 tb.create(handle);
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000199 vlog.debug("created toolbar window \"%s\" (%x)", "ViewerToolBar", tb.getHandle());
200
201 // Create the frame window
202 frameHandle = CreateWindowEx(WS_EX_CLIENTEDGE, (const TCHAR*)frameClass.classAtom,
203 0, WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
Constantin Kaplinskyf4038832006-05-17 04:17:25 +0000204 CW_USEDEFAULT, CW_USEDEFAULT, handle, 0, frameClass.instance, this);
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000205 if (!frameHandle) {
206 throw rdr::SystemException("unable to create rfb frame window instance", GetLastError());
207 }
208 vlog.debug("created window \"%s\" (%x)", "Frame Window", frameHandle);
209
210 // Initialise the CPointer pointer handler
211 ptr.setHWND(frameHandle);
212 ptr.setIntervalTimerId(TIMER_POINTER_INTERVAL);
213 ptr.set3ButtonTimerId(TIMER_POINTER_3BUTTON);
214
215 // Initialise the bumpscroll timer
216 bumpScrollTimer.setHWND(handle);
217 bumpScrollTimer.setId(TIMER_BUMPSCROLL);
218
219 // Hook the clipboard
220 clipboard.setNotifier(this);
221
222 // Create the backing buffer
223 buffer = new win32::DIBSectionBuffer(frameHandle);
224
225 // Show the window
226 centerWindow(handle, 0);
227 ShowWindow(handle, SW_SHOW);
228}
229
230DesktopWindow::~DesktopWindow() {
231 vlog.debug("~DesktopWindow");
232 showSystemCursor();
233 if (handle) {
234 disableLowLevelKeyEvents(handle);
235 DestroyWindow(handle);
236 handle = 0;
237 }
238 delete buffer;
239 vlog.debug("~DesktopWindow done");
240}
241
242
243void DesktopWindow::setFullscreen(bool fs) {
244 if (fs && !fullscreenActive) {
245 fullscreenActive = bumpScroll = true;
246
247 // Un-minimize the window if required
248 if (GetWindowLong(handle, GWL_STYLE) & WS_MINIMIZE)
249 ShowWindow(handle, SW_RESTORE);
250
251 // Save the current window position
252 GetWindowRect(handle, &fullscreenOldRect);
253
254 // Find the size of the display the window is on
255 MonitorInfo mi(handle);
256
257 // Hide the toolbar
Constantin Kaplinsky318eb4a2006-05-17 09:39:42 +0000258 if (tb.isVisible())
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000259 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
Constantin Kaplinsky318eb4a2006-05-17 09:39:42 +0000297void DesktopWindow::setShowToolbar(bool st)
298{
299 showToolbar = st;
300
301 if (showToolbar && !tb.isVisible()) {
302 tb.show();
303 } else if (!showToolbar && tb.isVisible()) {
304 tb.hide();
305 }
306}
307
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000308void 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
Constantin Kaplinskyf4038832006-05-17 04:17:25 +0000411 SetRect(&r, reqd_size.tl.x, reqd_size.tl.y, reqd_size.br.x, reqd_size.br.y);
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000412 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
Constantin Kaplinskyf4038832006-05-17 04:17:25 +0000442 GetClientRect(handle, &r);
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000443 if (tb.isVisible()) {
Constantin Kaplinskyf4038832006-05-17 04:17:25 +0000444 MoveWindow(frameHandle, 0, tb.getHeight(),
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000445 r.right, r.bottom - tb.getHeight(), TRUE);
446 } else {
Constantin Kaplinskyf4038832006-05-17 04:17:25 +0000447 MoveWindow(frameHandle, 0, 0, r.right, r.bottom, TRUE);
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000448 }
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 // -=- Handle the extra window menu items
494
495 // Pass system menu messages to the callback and only attempt
496 // to process them ourselves if the callback returns false.
497 case WM_SYSCOMMAND:
498 // Call the supplied callback
499 if (callback->sysCommand(wParam, lParam))
500 break;
501
502 // - Not processed by the callback, so process it as a system message
503 switch (wParam & 0xfff0) {
504
505 // When restored, ensure that full-screen mode is re-enabled if required.
506 case SC_RESTORE:
507 {
508 if (GetWindowLong(handle, GWL_STYLE) & WS_MINIMIZE) {
509 rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
510 setFullscreen(fullscreenRestore);
511 }
512 else if (fullscreenActive)
513 setFullscreen(false);
514 else
515 rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
516
517 return 0;
518 }
519
520 // If we are maximized or minimized then that cancels full-screen mode.
521 case SC_MINIMIZE:
522 case SC_MAXIMIZE:
523 fullscreenRestore = fullscreenActive;
524 setFullscreen(false);
525 break;
526
527 // If the menu is about to be shown, make sure it's up to date
528 case SC_KEYMENU:
529 case SC_MOUSEMENU:
530 callback->refreshMenu(true);
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 callback->refreshMenu(false);
557
558 // Show it under the pointer
559 POINT pt;
560 GetCursorPos(&pt);
561 cursorInBuffer = false;
562 TrackPopupMenu(GetSystemMenu(handle, FALSE),
563 TPM_CENTERALIGN | TPM_VCENTERALIGN, pt.x, pt.y, 0, handle, 0);
564 }
565
566 // Ignore the MenuKey keypress for both press & release events
567 return 0;
568 }
569 }
570 case WM_SYSKEYDOWN:
571 case WM_SYSKEYUP:
572 kbd.keyEvent(callback, wParam, lParam, (msg == WM_KEYDOWN) || (msg == WM_SYSKEYDOWN));
573 return 0;
574
575 // -=- Handle the window closing
576
577 case WM_CLOSE:
578 vlog.debug("WM_CLOSE %x", handle);
579 callback->closeWindow();
580 break;
581
582 }
583
584 return rfb::win32::SafeDefWindowProc(handle, msg, wParam, lParam);
585}
586
587LRESULT
588DesktopWindow::processFrameMessage(UINT msg, WPARAM wParam, LPARAM lParam) {
589 switch (msg) {
590
591 // -=- Paint the remote frame buffer
592
593 case WM_PAINT:
594 {
595 PAINTSTRUCT ps;
596 HDC paintDC = BeginPaint(frameHandle, &ps);
597 if (!paintDC)
598 throw rdr::SystemException("unable to BeginPaint", GetLastError());
599 Rect pr = Rect(ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom);
600
601 if (!pr.is_empty()) {
602
603 // Draw using the correct palette
604 PaletteSelector pSel(paintDC, windowPalette.getHandle());
605
606 if (buffer->bitmap) {
607 // Update the bitmap's palette
608 if (palette_changed) {
609 palette_changed = false;
610 buffer->refreshPalette();
611 }
612
613 // Get device context
614 BitmapDC bitmapDC(paintDC, buffer->bitmap);
615
616 // Blit the border if required
617 Rect bufpos = desktopToClient(buffer->getRect());
618 if (!pr.enclosed_by(bufpos)) {
619 vlog.debug("draw border");
620 HBRUSH black = (HBRUSH) GetStockObject(BLACK_BRUSH);
621 RECT r;
622 SetRect(&r, 0, 0, bufpos.tl.x, client_size.height()); FillRect(paintDC, &r, black);
623 SetRect(&r, bufpos.tl.x, 0, bufpos.br.x, bufpos.tl.y); FillRect(paintDC, &r, black);
624 SetRect(&r, bufpos.br.x, 0, client_size.width(), client_size.height()); FillRect(paintDC, &r, black);
625 SetRect(&r, bufpos.tl.x, bufpos.br.y, bufpos.br.x, client_size.height()); FillRect(paintDC, &r, black);
626 }
627
628 // Do the blit
629 Point buf_pos = clientToDesktop(pr.tl);
630
631 if (!BitBlt(paintDC, pr.tl.x, pr.tl.y, pr.width(), pr.height(),
632 bitmapDC, buf_pos.x, buf_pos.y, SRCCOPY))
633 throw rdr::SystemException("unable to BitBlt to window", GetLastError());
634 }
635 }
636
637 EndPaint(frameHandle, &ps);
638
639 // - Notify the callback that a paint message has finished processing
640 callback->paintCompleted();
641 }
642 return 0;
643
644 // -=- Palette management
645
646 case WM_PALETTECHANGED:
647 vlog.debug("WM_PALETTECHANGED");
648 if ((HWND)wParam == frameHandle) {
649 vlog.debug("ignoring");
650 break;
651 }
652 case WM_QUERYNEWPALETTE:
653 vlog.debug("re-selecting palette");
654 {
655 WindowDC wdc(frameHandle);
656 PaletteSelector pSel(wdc, windowPalette.getHandle());
657 if (pSel.isRedrawRequired()) {
658 InvalidateRect(frameHandle, 0, FALSE);
659 UpdateWindow(frameHandle);
660 }
661 }
662 return TRUE;
663
664 case WM_VSCROLL:
665 case WM_HSCROLL:
666 {
667 Point delta;
668 int newpos = (msg == WM_VSCROLL) ? scrolloffset.y : scrolloffset.x;
669
670 switch (LOWORD(wParam)) {
671 case SB_PAGEUP: newpos -= 50; break;
672 case SB_PAGEDOWN: newpos += 50; break;
673 case SB_LINEUP: newpos -= 5; break;
674 case SB_LINEDOWN: newpos += 5; break;
675 case SB_THUMBTRACK:
676 case SB_THUMBPOSITION: newpos = HIWORD(wParam); break;
677 default: vlog.info("received unknown scroll message");
678 };
679
680 if (msg == WM_HSCROLL)
681 setViewportOffset(Point(newpos, scrolloffset.y));
682 else
683 setViewportOffset(Point(scrolloffset.x, newpos));
684
685 SCROLLINFO si;
686 si.cbSize = sizeof(si);
687 si.fMask = SIF_POS;
688 si.nPos = newpos;
689 SetScrollInfo(frameHandle, (msg == WM_VSCROLL) ? SB_VERT : SB_HORZ, &si, TRUE);
690 }
691 break;
692
693 // -=- Cursor shape/visibility handling
694
695 case WM_SETCURSOR:
696 if (LOWORD(lParam) != HTCLIENT)
697 break;
698 SetCursor(cursorInBuffer ? dotCursor : arrowCursor);
699 return TRUE;
700
701 case WM_MOUSELEAVE:
702 trackingMouseLeave = false;
703 cursorOutsideBuffer();
704 return 0;
705
706 // -=- Mouse input handling
707
708 case WM_MOUSEMOVE:
709 case WM_LBUTTONUP:
710 case WM_MBUTTONUP:
711 case WM_RBUTTONUP:
712 case WM_LBUTTONDOWN:
713 case WM_MBUTTONDOWN:
714 case WM_RBUTTONDOWN:
715#ifdef WM_MOUSEWHEEL
716 case WM_MOUSEWHEEL:
717#endif
718 if (has_focus)
719 {
720 if (!trackingMouseLeave) {
721 TRACKMOUSEEVENT tme;
722 tme.cbSize = sizeof(TRACKMOUSEEVENT);
723 tme.dwFlags = TME_LEAVE;
724 tme.hwndTrack = frameHandle;
725 _TrackMouseEvent(&tme);
726 trackingMouseLeave = true;
727 }
728 int mask = 0;
729 if (LOWORD(wParam) & MK_LBUTTON) mask |= 1;
730 if (LOWORD(wParam) & MK_MBUTTON) mask |= 2;
731 if (LOWORD(wParam) & MK_RBUTTON) mask |= 4;
732
733#ifdef WM_MOUSEWHEEL
734 if (msg == WM_MOUSEWHEEL) {
735 int delta = (short)HIWORD(wParam);
736 int repeats = (abs(delta)+119) / 120;
737 int wheelMask = (delta > 0) ? 8 : 16;
738 vlog.debug("repeats %d, mask %d\n",repeats,wheelMask);
739 for (int i=0; i<repeats; i++) {
740 ptr.pointerEvent(callback, oldpos, mask | wheelMask);
741 ptr.pointerEvent(callback, oldpos, mask);
742 }
743 } else {
744#endif
745 Point clientPos = Point(LOWORD(lParam), HIWORD(lParam));
746 Point p = clientToDesktop(clientPos);
747
748 // If the mouse is not within the server buffer area, do nothing
749 cursorInBuffer = buffer->getRect().contains(p);
750 if (!cursorInBuffer) {
751 cursorOutsideBuffer();
752 break;
753 }
754
755 // If we're locally rendering the cursor then redraw it
756 if (cursorAvailable) {
757 // - Render the cursor!
758 if (!p.equals(cursorPos)) {
759 hideLocalCursor();
760 cursorPos = p;
761 showLocalCursor();
762 if (cursorVisible)
763 hideSystemCursor();
764 }
765 }
766
767 // If we are doing bump-scrolling then try that first...
768 if (processBumpScroll(clientPos))
769 break;
770
771 // Send a pointer event to the server
772 ptr.pointerEvent(callback, p, mask);
773 oldpos = p;
774#ifdef WM_MOUSEWHEEL
775 }
776#endif
777 } else {
778 cursorOutsideBuffer();
779 }
780 break;
781 }
782
783 return rfb::win32::SafeDefWindowProc(frameHandle, msg, wParam, lParam);
784}
785
786
787void
788DesktopWindow::hideLocalCursor() {
789 // - Blit the cursor backing store over the cursor
790 // *** ALWAYS call this BEFORE changing buffer PF!!!
791 if (cursorVisible) {
792 cursorVisible = false;
793 buffer->imageRect(cursorBackingRect, cursorBacking.data);
794 invalidateDesktopRect(cursorBackingRect);
795 }
796}
797
798void
799DesktopWindow::showLocalCursor() {
800 if (cursorAvailable && !cursorVisible && cursorInBuffer) {
801 if (!buffer->getPF().equal(cursor.getPF()) ||
802 cursor.getRect().is_empty()) {
803 vlog.info("attempting to render invalid local cursor");
804 cursorAvailable = false;
805 showSystemCursor();
806 return;
807 }
808 cursorVisible = true;
809
810 cursorBackingRect = cursor.getRect().translate(cursorPos).translate(cursor.hotspot.negate());
811 cursorBackingRect = cursorBackingRect.intersect(buffer->getRect());
812 buffer->getImage(cursorBacking.data, cursorBackingRect);
813
814 renderLocalCursor();
815
816 invalidateDesktopRect(cursorBackingRect);
817 }
818}
819
820void DesktopWindow::cursorOutsideBuffer()
821{
822 cursorInBuffer = false;
823 hideLocalCursor();
824 showSystemCursor();
825}
826
827void
828DesktopWindow::renderLocalCursor()
829{
830 Rect r = cursor.getRect();
831 r = r.translate(cursorPos).translate(cursor.hotspot.negate());
832 buffer->maskRect(r, cursor.data, cursor.mask.buf);
833}
834
835void
836DesktopWindow::hideSystemCursor() {
837 if (systemCursorVisible) {
838 vlog.debug("hide system cursor");
839 systemCursorVisible = false;
840 ShowCursor(FALSE);
841 }
842}
843
844void
845DesktopWindow::showSystemCursor() {
846 if (!systemCursorVisible) {
847 vlog.debug("show system cursor");
848 systemCursorVisible = true;
849 ShowCursor(TRUE);
850 }
851}
852
853
854bool
855DesktopWindow::invalidateDesktopRect(const Rect& crect) {
856 Rect rect = desktopToClient(crect);
857 if (rect.intersect(client_size).is_empty()) return false;
858 RECT invalid = {rect.tl.x, rect.tl.y, rect.br.x, rect.br.y};
859 InvalidateRect(frameHandle, &invalid, FALSE);
860 return true;
861}
862
863
864void
865DesktopWindow::notifyClipboardChanged(const char* text, int len) {
866 callback->clientCutText(text, len);
867}
868
869
870void
871DesktopWindow::setPF(const PixelFormat& pf) {
872 // If the cursor is the wrong format then clear it
873 if (!pf.equal(buffer->getPF()))
874 setCursor(0, 0, Point(), 0, 0);
875
876 // Update the desktop buffer
877 buffer->setPF(pf);
878
879 // Redraw the window
Constantin Kaplinskyccc653a2006-05-17 05:04:25 +0000880 InvalidateRect(frameHandle, 0, FALSE);
Constantin Kaplinskyac306682006-05-16 08:48:31 +0000881}
882
883void
884DesktopWindow::setSize(int w, int h) {
885 vlog.debug("setSize %dx%d", w, h);
886
887 // If the locally-rendered cursor is visible then remove it
888 hideLocalCursor();
889
890 // Resize the backing buffer
891 buffer->setSize(w, h);
892
893 // If the window is not maximised or full-screen then resize it
894 if (!(GetWindowLong(handle, GWL_STYLE) & WS_MAXIMIZE) && !fullscreenActive) {
895 // Resize the window to the required size
896 RECT r = {0, 0, w, h};
897 AdjustWindowRectEx(&r, GetWindowLong(frameHandle, GWL_STYLE), FALSE,
898 GetWindowLong(frameHandle, GWL_EXSTYLE));
899 if (tb.isVisible())
900 r.bottom += tb.getHeight();
901 AdjustWindowRect(&r, GetWindowLong(handle, GWL_STYLE), FALSE);
902
903 // Resize about the center of the window, and clip to current monitor
904 MonitorInfo mi(handle);
905 resizeWindow(handle, r.right-r.left, r.bottom-r.top);
906 mi.clipTo(handle);
907 } else {
908 // Ensure the screen contents are consistent
909 InvalidateRect(frameHandle, 0, FALSE);
910 }
911
912 // Enable/disable scrollbars as appropriate
913 calculateScrollBars();
914}
915
916void
917DesktopWindow::setCursor(int w, int h, const Point& hotspot, void* data, void* mask) {
918 hideLocalCursor();
919
920 cursor.hotspot = hotspot;
921
922 cursor.setSize(w, h);
923 cursor.setPF(buffer->getPF());
924 cursor.imageRect(cursor.getRect(), data);
925 memcpy(cursor.mask.buf, mask, cursor.maskLen());
926 cursor.crop();
927
928 cursorBacking.setSize(w, h);
929 cursorBacking.setPF(buffer->getPF());
930
931 cursorAvailable = true;
932
933 showLocalCursor();
934}
935
936PixelFormat
937DesktopWindow::getNativePF() const {
938 vlog.debug("getNativePF()");
939 return WindowDC(handle).getPF();
940}
941
942
943void
944DesktopWindow::refreshWindowPalette(int start, int count) {
945 vlog.debug("refreshWindowPalette(%d, %d)", start, count);
946
947 Colour colours[256];
948 if (count > 256) {
949 vlog.debug("%d palette entries", count);
950 throw rdr::Exception("too many palette entries");
951 }
952
953 // Copy the palette from the DIBSectionBuffer
954 ColourMap* cm = buffer->getColourMap();
955 if (!cm) return;
956 for (int i=0; i<count; i++) {
957 int r, g, b;
958 cm->lookup(i, &r, &g, &b);
959 colours[i].r = r;
960 colours[i].g = g;
961 colours[i].b = b;
962 }
963
964 // Set the window palette
965 windowPalette.setEntries(start, count, colours);
966
967 // Cause the window to be redrawn
968 palette_changed = true;
969 InvalidateRect(handle, 0, FALSE);
970}
971
972
973void DesktopWindow::calculateScrollBars() {
974 // Calculate the required size of window
975 DWORD current_style = GetWindowLong(frameHandle, GWL_STYLE);
976 DWORD style = current_style & ~(WS_VSCROLL | WS_HSCROLL);
977 DWORD style_ex = GetWindowLong(frameHandle, GWL_EXSTYLE);
978 DWORD old_style;
979 RECT r;
980 SetRect(&r, 0, 0, buffer->width(), buffer->height());
981 AdjustWindowRectEx(&r, style, FALSE, style_ex);
982 Rect reqd_size = Rect(r.left, r.top, r.right, r.bottom);
983
984 if (!bumpScroll) {
985 // We only enable scrollbars if bump-scrolling is not active.
986 // Effectively, this means if full-screen is not active,
987 // but I think it's better to make these things explicit.
988
989 // Work out whether scroll bars are required
990 do {
991 old_style = style;
992
993 if (!(style & WS_HSCROLL) && (reqd_size.width() > window_size.width())) {
994 style |= WS_HSCROLL;
995 reqd_size.br.y += GetSystemMetrics(SM_CXHSCROLL);
996 }
997 if (!(style & WS_VSCROLL) && (reqd_size.height() > window_size.height())) {
998 style |= WS_VSCROLL;
999 reqd_size.br.x += GetSystemMetrics(SM_CXVSCROLL);
1000 }
1001 } while (style != old_style);
1002 }
1003
1004 // Tell Windows to update the window style & cached settings
1005 if (style != current_style) {
1006 SetWindowLong(frameHandle, GWL_STYLE, style);
1007 SetWindowPos(frameHandle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
1008 }
1009
1010 // Update the scroll settings
1011 SCROLLINFO si;
1012 if (style & WS_VSCROLL) {
1013 si.cbSize = sizeof(si);
1014 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1015 si.nMin = 0;
1016 si.nMax = buffer->height();
1017 si.nPage = buffer->height() - (reqd_size.height() - window_size.height());
1018 maxscrolloffset.y = max(0, si.nMax-si.nPage);
1019 scrolloffset.y = min(maxscrolloffset.y, scrolloffset.y);
1020 si.nPos = scrolloffset.y;
1021 SetScrollInfo(frameHandle, SB_VERT, &si, TRUE);
1022 }
1023 if (style & WS_HSCROLL) {
1024 si.cbSize = sizeof(si);
1025 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1026 si.nMin = 0;
1027 si.nMax = buffer->width();
1028 si.nPage = buffer->width() - (reqd_size.width() - window_size.width());
1029 maxscrolloffset.x = max(0, si.nMax-si.nPage);
1030 scrolloffset.x = min(maxscrolloffset.x, scrolloffset.x);
1031 si.nPos = scrolloffset.x;
1032 SetScrollInfo(frameHandle, SB_HORZ, &si, TRUE);
1033 }
1034
1035 // Update the cached client size
1036 GetClientRect(frameHandle, &r);
1037 client_size = Rect(r.left, r.top, r.right, r.bottom);
1038}
1039
1040
1041void
1042DesktopWindow::setName(const char* name) {
1043 SetWindowText(handle, TStr(name));
1044}
1045
1046
1047void
1048DesktopWindow::serverCutText(const char* str, int len) {
1049 CharArray t(len+1);
1050 memcpy(t.buf, str, len);
1051 t.buf[len] = 0;
1052 clipboard.setClipText(t.buf);
1053}
1054
1055
1056void DesktopWindow::fillRect(const Rect& r, Pixel pix) {
1057 if (cursorBackingRect.overlaps(r)) hideLocalCursor();
1058 buffer->fillRect(r, pix);
1059 invalidateDesktopRect(r);
1060}
1061void DesktopWindow::imageRect(const Rect& r, void* pixels) {
1062 if (cursorBackingRect.overlaps(r)) hideLocalCursor();
1063 buffer->imageRect(r, pixels);
1064 invalidateDesktopRect(r);
1065}
1066void DesktopWindow::copyRect(const Rect& r, int srcX, int srcY) {
1067 if (cursorBackingRect.overlaps(r) ||
1068 cursorBackingRect.overlaps(Rect(srcX, srcY, srcX+r.width(), srcY+r.height())))
1069 hideLocalCursor();
1070 buffer->copyRect(r, Point(r.tl.x-srcX, r.tl.y-srcY));
1071 invalidateDesktopRect(r);
1072}
1073
1074void DesktopWindow::invertRect(const Rect& r) {
1075 int stride;
1076 rdr::U8* p = buffer->getPixelsRW(r, &stride);
1077 for (int y = 0; y < r.height(); y++) {
1078 for (int x = 0; x < r.width(); x++) {
1079 switch (buffer->getPF().bpp) {
1080 case 8: ((rdr::U8* )p)[x+y*stride] ^= 0xff; break;
1081 case 16: ((rdr::U16*)p)[x+y*stride] ^= 0xffff; break;
1082 case 32: ((rdr::U32*)p)[x+y*stride] ^= 0xffffffff; break;
1083 }
1084 }
1085 }
1086 invalidateDesktopRect(r);
1087}