1 /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 * Copyright 2011 Pierre Ossman <ossman@cendio.se> for Cendio AB
3 *
4 * This is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this software; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 * USA.
18 */
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <assert.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <sys/time.h>
28
29 #include <rfb/LogWriter.h>
30 #include <rfb/CMsgWriter.h>
31
32 #include "DesktopWindow.h"
33 #include "OptionsDialog.h"
34 #include "i18n.h"
35 #include "parameters.h"
36 #include "vncviewer.h"
37 #include "CConn.h"
38 #include "Surface.h"
39 #include "Viewport.h"
40 #include "touch.h"
41
42 #include <FL/Fl.H>
43 #include <FL/Fl_Image_Surface.H>
44 #include <FL/Fl_Scrollbar.H>
45 #include <FL/fl_draw.H>
46 #include <FL/x.H>
47
48 #ifdef WIN32
49 #include "win32.h"
50 #endif
51
52 #ifdef __APPLE__
53 #include "cocoa.h"
54 #include <Carbon/Carbon.h>
55 #endif
56
57 // width of each "edge" region where scrolling happens,
58 // as a ratio compared to the viewport size
59 // default: 1/16th of the viewport size
60 #define EDGE_SCROLL_SIZE 16
61 // edge width is calculated at runtime; these values are just examples
62 static int edge_scroll_size_x = 128;
63 static int edge_scroll_size_y = 96;
64 // maximum pixels to scroll per frame
65 #define EDGE_SCROLL_SPEED 16
66 // how long to wait between viewport scroll position changes
67 // default: roughly 60 fps for smooth motion
68 #define EDGE_SCROLL_SECONDS_PER_FRAME 0.016666
69
70 using namespace rfb;
71
72 static rfb::LogWriter vlog("DesktopWindow");
73
74 // Global due to http://www.fltk.org/str.php?L2177 and the similar
75 // issue for Fl::event_dispatch.
76 static std::set<DesktopWindow *> instances;
77
DesktopWindow(int w,int h,const char * name,const rfb::PixelFormat & serverPF,CConn * cc_)78 DesktopWindow::DesktopWindow(int w, int h, const char *name,
79 const rfb::PixelFormat& serverPF,
80 CConn* cc_)
81 : Fl_Window(w, h), cc(cc_), offscreen(NULL), overlay(NULL),
82 firstUpdate(true),
83 delayedFullscreen(false), delayedDesktopSize(false),
84 keyboardGrabbed(false), mouseGrabbed(false),
85 statsLastUpdates(0), statsLastPixels(0), statsLastPosition(0),
86 statsGraph(NULL)
87 {
88 Fl_Group* group;
89
90 // Dummy group to prevent FLTK from moving our widgets around
91 group = new Fl_Group(0, 0, w, h);
92 group->resizable(NULL);
93 resizable(group);
94
95 viewport = new Viewport(w, h, serverPF, cc);
96
97 // Position will be adjusted later
98 hscroll = new Fl_Scrollbar(0, 0, 0, 0);
99 vscroll = new Fl_Scrollbar(0, 0, 0, 0);
100 hscroll->type(FL_HORIZONTAL);
101 hscroll->callback(handleScroll, this);
102 vscroll->callback(handleScroll, this);
103
104 group->end();
105
106 callback(handleClose, this);
107
108 setName(name);
109
110 OptionsDialog::addCallback(handleOptions, this);
111
112 // Some events need to be caught globally
113 if (instances.size() == 0)
114 Fl::add_handler(fltkHandle);
115 instances.insert(this);
116
117 // Hack. See below...
118 Fl::event_dispatch(fltkDispatch);
119
120 // Support for -geometry option. Note that although we do support
121 // negative coordinates, we do not support -XOFF-YOFF (ie
122 // coordinates relative to the right edge / bottom edge) at this
123 // time.
124 int geom_x = 0, geom_y = 0;
125 if (strcmp(geometry, "") != 0) {
126 int matched;
127 matched = sscanf((const char*)geometry, "+%d+%d", &geom_x, &geom_y);
128 if (matched == 2) {
129 force_position(1);
130 } else {
131 int geom_w, geom_h;
132 matched = sscanf((const char*)geometry, "%dx%d+%d+%d", &geom_w, &geom_h, &geom_x, &geom_y);
133 switch (matched) {
134 case 4:
135 force_position(1);
136 /* fall through */
137 case 2:
138 w = geom_w;
139 h = geom_h;
140 break;
141 default:
142 geom_x = geom_y = 0;
143 vlog.error(_("Invalid geometry specified!"));
144 }
145 }
146 }
147
148 #ifdef __APPLE__
149 // On OS X we can do the maximize thing properly before the
150 // window is showned. Other platforms handled further down...
151 if (maximize) {
152 int dummy;
153 Fl::screen_work_area(dummy, dummy, w, h, geom_x, geom_y);
154 }
155 #endif
156
157 if (force_position()) {
158 resize(geom_x, geom_y, w, h);
159 } else {
160 size(w, h);
161 }
162
163 if (fullScreen) {
164 // Hack: Window managers seem to be rather crappy at respecting
165 // fullscreen hints on initial windows. So on X11 we'll have to
166 // wait until after we've been mapped.
167 #if defined(WIN32) || defined(__APPLE__)
168 fullscreen_on();
169 #else
170 delayedFullscreen = true;
171 #endif
172 }
173
174 show();
175
176 // Full screen events are not sent out for a hidden window,
177 // so send a fake one here to set up things properly.
178 if (fullscreen_active())
179 handle(FL_FULLSCREEN);
180
181 // Unfortunately, current FLTK does not allow us to set the
182 // maximized property on Windows and X11 before showing the window.
183 // See STR #2083 and STR #2178
184 #ifndef __APPLE__
185 if (maximize) {
186 maximizeWindow();
187 }
188 #endif
189
190 // Adjust layout now that we're visible and know our final size
191 repositionWidgets();
192
193 if (delayedFullscreen) {
194 // Hack: Fullscreen requests may be ignored, so we need a timeout for
195 // when we should stop waiting. We also really need to wait for the
196 // resize, which can come after the fullscreen event.
197 Fl::add_timeout(0.5, handleFullscreenTimeout, this);
198 fullscreen_on();
199 }
200
201 // Throughput graph for debugging
202 if (vlog.getLevel() >= LogWriter::LEVEL_DEBUG) {
203 memset(&stats, 0, sizeof(stats));
204 Fl::add_timeout(0, handleStatsTimeout, this);
205 }
206
207 // Show hint about menu key
208 Fl::add_timeout(0.5, menuOverlay, this);
209
210 // By default we get a slight delay when we warp the pointer, something
211 // we don't want or we'll get jerky movement
212 #ifdef __APPLE__
213 CGEventSourceRef event = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
214 CGEventSourceSetLocalEventsSuppressionInterval(event, 0);
215 CFRelease(event);
216 #endif
217 }
218
219
~DesktopWindow()220 DesktopWindow::~DesktopWindow()
221 {
222 // Unregister all timeouts in case they get a change tro trigger
223 // again later when this object is already gone.
224 Fl::remove_timeout(handleGrab, this);
225 Fl::remove_timeout(handleResizeTimeout, this);
226 Fl::remove_timeout(handleFullscreenTimeout, this);
227 Fl::remove_timeout(handleEdgeScroll, this);
228 Fl::remove_timeout(handleStatsTimeout, this);
229 Fl::remove_timeout(menuOverlay, this);
230 Fl::remove_timeout(updateOverlay, this);
231
232 OptionsDialog::removeCallback(handleOptions);
233
234 delete overlay;
235 delete offscreen;
236
237 delete statsGraph;
238
239 instances.erase(this);
240
241 if (instances.size() == 0)
242 Fl::remove_handler(fltkHandle);
243
244 Fl::event_dispatch(Fl::handle_);
245
246 // FLTK automatically deletes all child widgets, so we shouldn't touch
247 // them ourselves here
248 }
249
250
getPreferredPF()251 const rfb::PixelFormat &DesktopWindow::getPreferredPF()
252 {
253 return viewport->getPreferredPF();
254 }
255
256
setName(const char * name)257 void DesktopWindow::setName(const char *name)
258 {
259 CharArray windowNameStr;
260 windowNameStr.replaceBuf(new char[256]);
261
262 snprintf(windowNameStr.buf, 256, "%.240s - TigerVNC", name);
263
264 copy_label(windowNameStr.buf);
265 }
266
267
268 // Copy the areas of the framebuffer that have been changed (damaged)
269 // to the displayed window.
270
updateWindow()271 void DesktopWindow::updateWindow()
272 {
273 if (firstUpdate) {
274 if (cc->server.supportsSetDesktopSize) {
275 // Hack: Wait until we're in the proper mode and position until
276 // resizing things, otherwise we might send the wrong thing.
277 if (delayedFullscreen)
278 delayedDesktopSize = true;
279 else
280 handleDesktopSize();
281 }
282 firstUpdate = false;
283 }
284
285 viewport->updateWindow();
286 }
287
288
resizeFramebuffer(int new_w,int new_h)289 void DesktopWindow::resizeFramebuffer(int new_w, int new_h)
290 {
291 bool maximized;
292
293 if ((new_w == viewport->w()) && (new_h == viewport->h()))
294 return;
295
296 maximized = false;
297
298 #ifdef WIN32
299 WINDOWPLACEMENT wndpl;
300 memset(&wndpl, 0, sizeof(WINDOWPLACEMENT));
301 wndpl.length = sizeof(WINDOWPLACEMENT);
302 GetWindowPlacement(fl_xid(this), &wndpl);
303 if (wndpl.showCmd == SW_SHOWMAXIMIZED)
304 maximized = true;
305 #elif defined(__APPLE__)
306 if (cocoa_win_is_zoomed(this))
307 maximized = true;
308 #else
309 Atom net_wm_state = XInternAtom (fl_display, "_NET_WM_STATE", 0);
310 Atom net_wm_state_maximized_vert = XInternAtom (fl_display, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
311 Atom net_wm_state_maximized_horz = XInternAtom (fl_display, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
312
313 Atom type;
314 int format;
315 unsigned long nitems, remain;
316 Atom *atoms;
317
318 XGetWindowProperty(fl_display, fl_xid(this), net_wm_state, 0, 1024, False, XA_ATOM, &type, &format, &nitems, &remain, (unsigned char**)&atoms);
319
320 for (unsigned long i = 0;i < nitems;i++) {
321 if ((atoms[i] == net_wm_state_maximized_vert) ||
322 (atoms[i] == net_wm_state_maximized_horz)) {
323 maximized = true;
324 break;
325 }
326 }
327
328 XFree(atoms);
329 #endif
330
331 // If we're letting the viewport match the window perfectly, then
332 // keep things that way for the new size, otherwise just keep things
333 // like they are.
334 if (!fullscreen_active() && !maximized) {
335 if ((w() == viewport->w()) && (h() == viewport->h()))
336 size(new_w, new_h);
337 else {
338 // Make sure the window isn't too big. We do this manually because
339 // we have to disable the window size restriction (and it isn't
340 // entirely trustworthy to begin with).
341 if ((w() > new_w) || (h() > new_h))
342 size(__rfbmin(w(), new_w), __rfbmin(h(), new_h));
343 }
344 }
345
346 viewport->size(new_w, new_h);
347
348 repositionWidgets();
349 }
350
351
setCursor(int width,int height,const rfb::Point & hotspot,const rdr::U8 * data)352 void DesktopWindow::setCursor(int width, int height,
353 const rfb::Point& hotspot,
354 const rdr::U8* data)
355 {
356 viewport->setCursor(width, height, hotspot, data);
357 }
358
359
setCursorPos(const rfb::Point & pos)360 void DesktopWindow::setCursorPos(const rfb::Point& pos)
361 {
362 if (!mouseGrabbed) {
363 // Do nothing if we do not have the mouse captured.
364 return;
365 }
366 #if defined(WIN32)
367 SetCursorPos(pos.x + x_root() + viewport->x(),
368 pos.y + y_root() + viewport->y());
369 #elif defined(__APPLE__)
370 CGPoint new_pos;
371 new_pos.x = pos.x + x_root() + viewport->x();
372 new_pos.y = pos.y + y_root() + viewport->y();
373 CGWarpMouseCursorPosition(new_pos);
374 #else // Assume this is Xlib
375 Window rootwindow = DefaultRootWindow(fl_display);
376 XWarpPointer(fl_display, rootwindow, rootwindow, 0, 0, 0, 0,
377 pos.x + x_root() + viewport->x(),
378 pos.y + y_root() + viewport->y());
379 #endif
380 }
381
382
show()383 void DesktopWindow::show()
384 {
385 Fl_Window::show();
386
387 #if !defined(WIN32) && !defined(__APPLE__)
388 XEvent e;
389
390 // Request ability to grab keyboard under Xwayland
391 e.xany.type = ClientMessage;
392 e.xany.window = fl_xid(this);
393 e.xclient.message_type = XInternAtom (fl_display, "_XWAYLAND_MAY_GRAB_KEYBOARD", 0);
394 e.xclient.format = 32;
395 e.xclient.data.l[0] = 1;
396 e.xclient.data.l[1] = 0;
397 e.xclient.data.l[2] = 0;
398 e.xclient.data.l[3] = 0;
399 e.xclient.data.l[4] = 0;
400 XSendEvent(fl_display, RootWindow(fl_display, fl_screen), 0, SubstructureNotifyMask | SubstructureRedirectMask, &e);
401 #endif
402 }
403
404
draw()405 void DesktopWindow::draw()
406 {
407 bool redraw;
408
409 int X, Y, W, H;
410
411 // X11 needs an off screen buffer for compositing to avoid flicker,
412 // and alpha blending doesn't work for windows on Win32
413 #if !defined(__APPLE__)
414
415 // Adjust offscreen surface dimensions
416 if ((offscreen == NULL) ||
417 (offscreen->width() != w()) || (offscreen->height() != h())) {
418 delete offscreen;
419 offscreen = new Surface(w(), h());
420 }
421
422 #endif
423
424 // Active area inside scrollbars
425 W = w() - (vscroll->visible() ? vscroll->w() : 0);
426 H = h() - (hscroll->visible() ? hscroll->h() : 0);
427
428 // Full redraw?
429 redraw = (damage() & ~FL_DAMAGE_CHILD);
430
431 // Simplify the clip region to a simple rectangle in order to
432 // properly draw all the layers even if they only partially overlap
433 if (redraw)
434 X = Y = 0;
435 else
436 fl_clip_box(0, 0, W, H, X, Y, W, H);
437 fl_push_no_clip();
438 fl_push_clip(X, Y, W, H);
439
440 // Redraw background only on full redraws
441 if (redraw) {
442 if (offscreen)
443 offscreen->clear(40, 40, 40);
444 else
445 fl_rectf(0, 0, W, H, 40, 40, 40);
446 }
447
448 if (offscreen) {
449 viewport->draw(offscreen);
450 viewport->clear_damage();
451 } else {
452 if (redraw)
453 draw_child(*viewport);
454 else
455 update_child(*viewport);
456 }
457
458 // Debug graph (if active)
459 if (statsGraph) {
460 int ox, oy, ow, oh;
461
462 ox = X = w() - statsGraph->width() - 30;
463 oy = Y = h() - statsGraph->height() - 30;
464 ow = statsGraph->width();
465 oh = statsGraph->height();
466
467 fl_clip_box(ox, oy, ow, oh, ox, oy, ow, oh);
468
469 if ((ow != 0) && (oh != 0)) {
470 if (offscreen)
471 statsGraph->blend(offscreen, ox - X, oy - Y, ox, oy, ow, oh, 204);
472 else
473 statsGraph->blend(ox - X, oy - Y, ox, oy, ow, oh, 204);
474 }
475 }
476
477 // Overlay (if active)
478 if (overlay) {
479 int ox, oy, ow, oh;
480 int sx, sy, sw, sh;
481
482 // Make sure it's properly seen by adjusting it relative to the
483 // primary screen rather than the entire window
484 if (fullscreen_active()) {
485 assert(Fl::screen_count() >= 1);
486
487 rfb::Rect windowRect, screenRect;
488 windowRect.setXYWH(x(), y(), w(), h());
489
490 bool foundEnclosedScreen = false;
491 for (int i = 0; i < Fl::screen_count(); i++) {
492 Fl::screen_xywh(sx, sy, sw, sh, i);
493
494 // The screen with the smallest index that are enclosed by
495 // the viewport will be used for showing the overlay.
496 screenRect.setXYWH(sx, sy, sw, sh);
497 if (screenRect.enclosed_by(windowRect)) {
498 foundEnclosedScreen = true;
499 break;
500 }
501 }
502
503 // If no monitor inside the viewport was found,
504 // use the one primary instead.
505 if (!foundEnclosedScreen)
506 Fl::screen_xywh(sx, sy, sw, sh, 0);
507
508 // Adjust the coordinates so they are relative to the viewport.
509 sx -= x();
510 sy -= y();
511
512 } else {
513 sx = 0;
514 sy = 0;
515 sw = w();
516 }
517
518 ox = X = sx + (sw - overlay->width()) / 2;
519 oy = Y = sy + 50;
520 ow = overlay->width();
521 oh = overlay->height();
522
523 fl_clip_box(ox, oy, ow, oh, ox, oy, ow, oh);
524
525 if ((ow != 0) && (oh != 0)) {
526 if (offscreen)
527 overlay->blend(offscreen, ox - X, oy - Y, ox, oy, ow, oh, overlayAlpha);
528 else
529 overlay->blend(ox - X, oy - Y, ox, oy, ow, oh, overlayAlpha);
530 }
531 }
532
533 // Flush offscreen surface to screen
534 if (offscreen) {
535 fl_clip_box(0, 0, w(), h(), X, Y, W, H);
536 offscreen->draw(X, Y, X, Y, W, H);
537 }
538
539 fl_pop_clip();
540 fl_pop_clip();
541
542 // Finally the scrollbars
543
544 if (redraw) {
545 draw_child(*hscroll);
546 draw_child(*vscroll);
547 } else {
548 update_child(*hscroll);
549 update_child(*vscroll);
550 }
551 }
552
553
setLEDState(unsigned int state)554 void DesktopWindow::setLEDState(unsigned int state)
555 {
556 viewport->setLEDState(state);
557 }
558
559
handleClipboardRequest()560 void DesktopWindow::handleClipboardRequest()
561 {
562 viewport->handleClipboardRequest();
563 }
564
handleClipboardAnnounce(bool available)565 void DesktopWindow::handleClipboardAnnounce(bool available)
566 {
567 viewport->handleClipboardAnnounce(available);
568 }
569
handleClipboardData(const char * data)570 void DesktopWindow::handleClipboardData(const char* data)
571 {
572 viewport->handleClipboardData(data);
573 }
574
575
resize(int x,int y,int w,int h)576 void DesktopWindow::resize(int x, int y, int w, int h)
577 {
578 bool resizing;
579
580 #if ! (defined(WIN32) || defined(__APPLE__))
581 // X11 window managers will treat a resize to cover the entire
582 // monitor as a request to go full screen. Make sure we avoid this.
583 if (!fullscreen_active()) {
584 bool resize_req;
585
586 // If there is no X11 window, then this must be a resize request,
587 // not a notification from the X server.
588 if (!shown())
589 resize_req = true;
590 else {
591 // Otherwise we need to get the real window coordinates to tell
592 // the difference
593 XWindowAttributes actual;
594 Window cr;
595 int wx, wy;
596
597 XGetWindowAttributes(fl_display, fl_xid(this), &actual);
598 XTranslateCoordinates(fl_display, fl_xid(this), actual.root,
599 0, 0, &wx, &wy, &cr);
600
601 // Actual resize request?
602 if ((wx != x) || (wy != y) ||
603 (actual.width != w) || (actual.height != h))
604 resize_req = true;
605 else
606 resize_req = false;
607 }
608
609 if (resize_req) {
610 for (int i = 0;i < Fl::screen_count();i++) {
611 int sx, sy, sw, sh;
612
613 Fl::screen_xywh(sx, sy, sw, sh, i);
614
615 if ((sx == x) && (sy == y) && (sw == w) && (sh == h)) {
616 vlog.info(_("Adjusting window size to avoid accidental full screen request"));
617 // Assume a panel of some form and adjust the height
618 y += 20;
619 h -= 40;
620 }
621 }
622 }
623 }
624 #endif
625
626 if ((this->w() != w) || (this->h() != h))
627 resizing = true;
628 else
629 resizing = false;
630
631 Fl_Window::resize(x, y, w, h);
632
633 if (resizing) {
634 // Try to get the remote size to match our window size, provided
635 // the following conditions are true:
636 //
637 // a) The user has this feature turned on
638 // b) The server supports it
639 // c) We're not still waiting for a chance to handle DesktopSize
640 // d) We're not still waiting for startup fullscreen to kick in
641 //
642 if (not firstUpdate and not delayedFullscreen and
643 ::remoteResize and cc->server.supportsSetDesktopSize) {
644 // We delay updating the remote desktop as we tend to get a flood
645 // of resize events as the user is dragging the window.
646 Fl::remove_timeout(handleResizeTimeout, this);
647 Fl::add_timeout(0.5, handleResizeTimeout, this);
648 }
649
650 repositionWidgets();
651 }
652
653 // Some systems require a grab after the window size has been changed.
654 // Otherwise they might hold on to displays, resulting in them being unusable.
655 maybeGrabKeyboard();
656 }
657
658
menuOverlay(void * data)659 void DesktopWindow::menuOverlay(void* data)
660 {
661 DesktopWindow *self;
662
663 self = (DesktopWindow*)data;
664
665 if (strcmp((const char*)menuKey, "") != 0) {
666 self->setOverlay(_("Press %s to open the context menu"),
667 (const char*)menuKey);
668 }
669 }
670
setOverlay(const char * text,...)671 void DesktopWindow::setOverlay(const char* text, ...)
672 {
673 const Fl_Fontsize fontsize = 16;
674 const int margin = 10;
675
676 va_list ap;
677 char textbuf[1024];
678
679 Fl_Image_Surface *surface;
680
681 Fl_RGB_Image* imageText;
682 Fl_RGB_Image* image;
683
684 unsigned char* buffer;
685
686 int x, y;
687 int w, h;
688
689 unsigned char* a;
690 const unsigned char* b;
691
692 delete overlay;
693 Fl::remove_timeout(updateOverlay, this);
694
695 va_start(ap, text);
696 vsnprintf(textbuf, sizeof(textbuf), text, ap);
697 textbuf[sizeof(textbuf)-1] = '\0';
698 va_end(ap);
699
700 #if !defined(WIN32) && !defined(__APPLE__)
701 // FLTK < 1.3.5 crashes if fl_gc is unset
702 if (!fl_gc)
703 fl_gc = XDefaultGC(fl_display, 0);
704 #endif
705
706 fl_font(FL_HELVETICA, fontsize);
707 w = 0;
708 fl_measure(textbuf, w, h);
709
710 // Margins
711 w += margin * 2 * 2;
712 h += margin * 2;
713
714 surface = new Fl_Image_Surface(w, h);
715 surface->set_current();
716
717 fl_rectf(0, 0, w, h, 0, 0, 0);
718
719 fl_font(FL_HELVETICA, fontsize);
720 fl_color(FL_WHITE);
721 fl_draw(textbuf, 0, 0, w, h, FL_ALIGN_CENTER);
722
723 imageText = surface->image();
724 delete surface;
725
726 Fl_Display_Device::display_device()->set_current();
727
728 buffer = new unsigned char[w * h * 4];
729 image = new Fl_RGB_Image(buffer, w, h, 4);
730
731 a = buffer;
732 for (x = 0;x < image->w() * image->h();x++) {
733 a[0] = a[1] = a[2] = 0x40;
734 a[3] = 0xcc;
735 a += 4;
736 }
737
738 a = buffer;
739 b = (const unsigned char*)imageText->data()[0];
740 for (y = 0;y < h;y++) {
741 for (x = 0;x < w;x++) {
742 unsigned char alpha;
743 alpha = *b;
744 a[0] = (unsigned)a[0] * (255 - alpha) / 255 + alpha;
745 a[1] = (unsigned)a[1] * (255 - alpha) / 255 + alpha;
746 a[2] = (unsigned)a[2] * (255 - alpha) / 255 + alpha;
747 a[3] = 255 - (255 - a[3]) * (255 - alpha) / 255;
748 a += 4;
749 b += imageText->d();
750 }
751 if (imageText->ld() != 0)
752 b += imageText->ld() - w * imageText->d();
753 }
754
755 delete imageText;
756
757 overlay = new Surface(image);
758 overlayAlpha = 0;
759 gettimeofday(&overlayStart, NULL);
760
761 delete image;
762
763 Fl::add_timeout(1.0/60, updateOverlay, this);
764 }
765
updateOverlay(void * data)766 void DesktopWindow::updateOverlay(void *data)
767 {
768 DesktopWindow *self;
769 unsigned elapsed;
770
771 self = (DesktopWindow*)data;
772
773 elapsed = msSince(&self->overlayStart);
774
775 if (elapsed < 500) {
776 self->overlayAlpha = (unsigned)255 * elapsed / 500;
777 Fl::add_timeout(1.0/60, updateOverlay, self);
778 } else if (elapsed < 3500) {
779 self->overlayAlpha = 255;
780 Fl::add_timeout(3.0, updateOverlay, self);
781 } else if (elapsed < 4000) {
782 self->overlayAlpha = (unsigned)255 * (4000 - elapsed) / 500;
783 Fl::add_timeout(1.0/60, updateOverlay, self);
784 } else {
785 delete self->overlay;
786 self->overlay = NULL;
787 }
788
789 self->damage(FL_DAMAGE_USER1);
790 }
791
792
handle(int event)793 int DesktopWindow::handle(int event)
794 {
795 switch (event) {
796 case FL_FULLSCREEN:
797 fullScreen.setParam(fullscreen_active());
798
799 // Update scroll bars
800 repositionWidgets();
801
802 if (fullscreen_active())
803 maybeGrabKeyboard();
804 else
805 ungrabKeyboard();
806
807 break;
808
809 case FL_ENTER:
810 if (keyboardGrabbed)
811 grabPointer();
812 case FL_LEAVE:
813 case FL_DRAG:
814 case FL_MOVE:
815 // We don't get FL_LEAVE with a grabbed pointer, so check manually
816 if (mouseGrabbed) {
817 if ((Fl::event_x() < 0) || (Fl::event_x() >= w()) ||
818 (Fl::event_y() < 0) || (Fl::event_y() >= h())) {
819 ungrabPointer();
820 }
821 }
822 if (fullscreen_active()) {
823 // calculate width of "edge" regions
824 edge_scroll_size_x = viewport->w() / EDGE_SCROLL_SIZE;
825 edge_scroll_size_y = viewport->h() / EDGE_SCROLL_SIZE;
826 // if cursor is near the edge of the viewport, scroll
827 if (((viewport->x() < 0) && (Fl::event_x() < edge_scroll_size_x)) ||
828 ((viewport->x() + viewport->w() >= w()) && (Fl::event_x() >= w() - edge_scroll_size_x)) ||
829 ((viewport->y() < 0) && (Fl::event_y() < edge_scroll_size_y)) ||
830 ((viewport->y() + viewport->h() >= h()) && (Fl::event_y() >= h() - edge_scroll_size_y))) {
831 if (!Fl::has_timeout(handleEdgeScroll, this))
832 Fl::add_timeout(EDGE_SCROLL_SECONDS_PER_FRAME, handleEdgeScroll, this);
833 }
834 }
835 // Continue processing so that the viewport also gets mouse events
836 break;
837 }
838
839 return Fl_Window::handle(event);
840 }
841
842
fltkDispatch(int event,Fl_Window * win)843 int DesktopWindow::fltkDispatch(int event, Fl_Window *win)
844 {
845 int ret;
846
847 // FLTK keeps spamming bogus FL_MOVE events if _any_ X event is
848 // received with the mouse pointer outside our windows
849 // https://github.com/fltk/fltk/issues/76
850 if ((event == FL_MOVE) && (win == NULL))
851 return 0;
852
853 ret = Fl::handle_(event, win);
854
855 // This is hackish and the result of the dodgy focus handling in FLTK.
856 // The basic problem is that FLTK's view of focus and the system's tend
857 // to differ, and as a result we do not see all the FL_FOCUS events we
858 // need. Fortunately we can grab them here...
859
860 DesktopWindow *dw = dynamic_cast<DesktopWindow*>(win);
861
862 if (dw) {
863 switch (event) {
864 // Focus might not stay with us just because we have grabbed the
865 // keyboard. E.g. we might have sub windows, or we're not using
866 // all monitors and the user clicked on another application.
867 // Make sure we update our grabs with the focus changes.
868 case FL_FOCUS:
869 dw->maybeGrabKeyboard();
870 break;
871 case FL_UNFOCUS:
872 if (fullscreenSystemKeys) {
873 dw->ungrabKeyboard();
874 }
875 break;
876
877 case FL_RELEASE:
878 // We usually fail to grab the mouse if a mouse button was
879 // pressed when we gained focus (e.g. clicking on our window),
880 // so we may need to try again when the button is released.
881 // (We do it here rather than handle() because a window does not
882 // see FL_RELEASE events if a child widget grabs it first)
883 if (dw->keyboardGrabbed && !dw->mouseGrabbed)
884 dw->grabPointer();
885 break;
886 }
887 }
888
889 return ret;
890 }
891
fltkHandle(int event)892 int DesktopWindow::fltkHandle(int event)
893 {
894 switch (event) {
895 case FL_SCREEN_CONFIGURATION_CHANGED:
896 // Screens removed or added. Recreate fullscreen window if
897 // necessary. On Windows, adding a second screen only works
898 // reliable if we are using a timer. Otherwise, the window will
899 // not be resized to cover the new screen. A timer makes sense
900 // also on other systems, to make sure that whatever desktop
901 // environment has a chance to deal with things before we do.
902 // Please note that when using FullscreenSystemKeys on macOS, the
903 // display configuration cannot be changed: macOS will not detect
904 // added or removed screens and there will be no
905 // FL_SCREEN_CONFIGURATION_CHANGED event. This is by design:
906 // "When you capture a display, you have exclusive use of the
907 // display. Other applications and system services are not allowed
908 // to use the display or change its configuration. In addition,
909 // they are not notified of display changes"
910 Fl::remove_timeout(reconfigureFullscreen);
911 Fl::add_timeout(0.5, reconfigureFullscreen);
912 }
913
914 return 0;
915 }
916
fullscreen_on()917 void DesktopWindow::fullscreen_on()
918 {
919 bool allMonitors = !strcasecmp(fullScreenMode, "all");
920 bool selectedMonitors = !strcasecmp(fullScreenMode, "selected");
921 int top, bottom, left, right;
922
923 if (not selectedMonitors and not allMonitors) {
924 top = bottom = left = right = Fl::screen_num(x(), y(), w(), h());
925 } else {
926 int top_y, bottom_y, left_x, right_x;
927
928 int sx, sy, sw, sh;
929
930 std::set<int> monitors;
931
932 if (selectedMonitors and not allMonitors) {
933 std::set<int> selected = fullScreenSelectedMonitors.getParam();
934 monitors.insert(selected.begin(), selected.end());
935 } else {
936 for (int i = 0; i < Fl::screen_count(); i++) {
937 monitors.insert(i);
938 }
939 }
940
941 // If no monitors were found in the selected monitors case, we want
942 // to explicitly use the window's current monitor.
943 if (monitors.size() == 0) {
944 monitors.insert(Fl::screen_num(x(), y(), w(), h()));
945 }
946
947 // If there are monitors selected, calculate the dimensions
948 // of the frame buffer, expressed in the monitor indices that
949 // limits it.
950 std::set<int>::iterator it = monitors.begin();
951
952 // Get first monitor dimensions.
953 Fl::screen_xywh(sx, sy, sw, sh, *it);
954 top = bottom = left = right = *it;
955 top_y = sy;
956 bottom_y = sy + sh;
957 left_x = sx;
958 right_x = sx + sw;
959
960 // Keep going through the rest of the monitors.
961 for (; it != monitors.end(); it++) {
962 Fl::screen_xywh(sx, sy, sw, sh, *it);
963
964 if (sy < top_y) {
965 top = *it;
966 top_y = sy;
967 }
968
969 if ((sy + sh) > bottom_y) {
970 bottom = *it;
971 bottom_y = sy + sh;
972 }
973
974 if (sx < left_x) {
975 left = *it;
976 left_x = sx;
977 }
978
979 if ((sx + sw) > right_x) {
980 right = *it;
981 right_x = sx + sw;
982 }
983 }
984
985 }
986 #ifdef __APPLE__
987 // This is a workaround for a bug in FLTK, see: https://github.com/fltk/fltk/pull/277
988 int savedLevel;
989 savedLevel = cocoa_get_level(this);
990 #endif
991 fullscreen_screens(top, bottom, left, right);
992 #ifdef __APPLE__
993 // This is a workaround for a bug in FLTK, see: https://github.com/fltk/fltk/pull/277
994 cocoa_set_level(this, savedLevel);
995 #endif
996
997 if (!fullscreen_active())
998 fullscreen();
999 }
1000
1001 #if !defined(WIN32) && !defined(__APPLE__)
eventIsFocusWithSerial(Display * display,XEvent * event,XPointer arg)1002 Bool eventIsFocusWithSerial(Display *display, XEvent *event, XPointer arg)
1003 {
1004 unsigned long serial;
1005
1006 serial = *(unsigned long*)arg;
1007
1008 if (event->xany.serial != serial)
1009 return False;
1010
1011 if ((event->type != FocusIn) && (event->type != FocusOut))
1012 return False;
1013
1014 return True;
1015 }
1016 #endif
1017
hasFocus()1018 bool DesktopWindow::hasFocus()
1019 {
1020 Fl_Widget* focus;
1021
1022 focus = Fl::grab();
1023 if (!focus)
1024 focus = Fl::focus();
1025
1026 if (!focus)
1027 return false;
1028
1029 return focus->window() == this;
1030 }
1031
maybeGrabKeyboard()1032 void DesktopWindow::maybeGrabKeyboard()
1033 {
1034 if (fullscreenSystemKeys && fullscreen_active() && hasFocus())
1035 grabKeyboard();
1036 }
1037
grabKeyboard()1038 void DesktopWindow::grabKeyboard()
1039 {
1040 // Grabbing the keyboard is fairly safe as FLTK reroutes events to the
1041 // correct widget regardless of which low level window got the system
1042 // event.
1043
1044 // FIXME: Push this stuff into FLTK.
1045
1046 #if defined(WIN32)
1047 int ret;
1048
1049 ret = win32_enable_lowlevel_keyboard(fl_xid(this));
1050 if (ret != 0) {
1051 vlog.error(_("Failure grabbing keyboard"));
1052 return;
1053 }
1054 #elif defined(__APPLE__)
1055 int ret;
1056
1057 ret = cocoa_capture_displays(this);
1058 if (ret != 0) {
1059 vlog.error(_("Failure grabbing keyboard"));
1060 return;
1061 }
1062 #else
1063 int ret;
1064
1065 XEvent xev;
1066 unsigned long serial;
1067
1068 serial = XNextRequest(fl_display);
1069
1070 ret = XGrabKeyboard(fl_display, fl_xid(this), True,
1071 GrabModeAsync, GrabModeAsync, CurrentTime);
1072 if (ret) {
1073 if (ret == AlreadyGrabbed) {
1074 // It seems like we can race with the WM in some cases.
1075 // Try again in a bit.
1076 if (!Fl::has_timeout(handleGrab, this))
1077 Fl::add_timeout(0.500, handleGrab, this);
1078 } else {
1079 vlog.error(_("Failure grabbing keyboard"));
1080 }
1081 return;
1082 }
1083
1084 // Xorg 1.20+ generates FocusIn/FocusOut even when there is no actual
1085 // change of focus. This causes us to get stuck in an endless loop
1086 // grabbing and ungrabbing the keyboard. Avoid this by filtering out
1087 // any focus events generated by XGrabKeyboard().
1088 XSync(fl_display, False);
1089 while (XCheckIfEvent(fl_display, &xev, &eventIsFocusWithSerial,
1090 (XPointer)&serial) == True) {
1091 vlog.debug("Ignored synthetic focus event cause by grab change");
1092 }
1093 #endif
1094
1095 keyboardGrabbed = true;
1096
1097 if (contains(Fl::belowmouse()))
1098 grabPointer();
1099 }
1100
1101
ungrabKeyboard()1102 void DesktopWindow::ungrabKeyboard()
1103 {
1104 Fl::remove_timeout(handleGrab, this);
1105
1106 keyboardGrabbed = false;
1107
1108 ungrabPointer();
1109
1110 #if defined(WIN32)
1111 win32_disable_lowlevel_keyboard(fl_xid(this));
1112 #elif defined(__APPLE__)
1113 cocoa_release_displays(this);
1114 #else
1115 // FLTK has a grab so lets not mess with it
1116 if (Fl::grab())
1117 return;
1118
1119 XEvent xev;
1120 unsigned long serial;
1121
1122 serial = XNextRequest(fl_display);
1123
1124 XUngrabKeyboard(fl_display, CurrentTime);
1125
1126 // See grabKeyboard()
1127 XSync(fl_display, False);
1128 while (XCheckIfEvent(fl_display, &xev, &eventIsFocusWithSerial,
1129 (XPointer)&serial) == True) {
1130 vlog.debug("Ignored synthetic focus event cause by grab change");
1131 }
1132 #endif
1133 }
1134
1135
grabPointer()1136 void DesktopWindow::grabPointer()
1137 {
1138 #if !defined(WIN32) && !defined(__APPLE__)
1139 // We also need to grab the pointer as some WMs like to grab buttons
1140 // combined with modifies (e.g. Alt+Button0 in metacity).
1141
1142 // Having a button pressed prevents us from grabbing, we make
1143 // a new attempt in fltkHandle()
1144 if (!x11_grab_pointer(fl_xid(this)))
1145 return;
1146 #endif
1147
1148 mouseGrabbed = true;
1149 }
1150
1151
ungrabPointer()1152 void DesktopWindow::ungrabPointer()
1153 {
1154 mouseGrabbed = false;
1155
1156 #if !defined(WIN32) && !defined(__APPLE__)
1157 x11_ungrab_pointer(fl_xid(this));
1158 #endif
1159 }
1160
1161
handleGrab(void * data)1162 void DesktopWindow::handleGrab(void *data)
1163 {
1164 DesktopWindow *self = (DesktopWindow*)data;
1165
1166 assert(self);
1167
1168 self->maybeGrabKeyboard();
1169 }
1170
1171
1172 #define _NET_WM_STATE_ADD 1 /* add/set property */
maximizeWindow()1173 void DesktopWindow::maximizeWindow()
1174 {
1175 #if defined(WIN32)
1176 // We cannot use ShowWindow() in full screen mode as it will
1177 // resize things implicitly. Fortunately modifying the style
1178 // directly results in a maximized state once we leave full screen.
1179 if (fullscreen_active()) {
1180 WINDOWINFO wi;
1181 wi.cbSize = sizeof(WINDOWINFO);
1182 GetWindowInfo(fl_xid(this), &wi);
1183 SetWindowLongPtr(fl_xid(this), GWL_STYLE, wi.dwStyle | WS_MAXIMIZE);
1184 } else
1185 ShowWindow(fl_xid(this), SW_MAXIMIZE);
1186 #elif defined(__APPLE__)
1187 if (fullscreen_active())
1188 return;
1189 cocoa_win_zoom(this);
1190 #else
1191 // X11
1192 fl_open_display();
1193 Atom net_wm_state = XInternAtom (fl_display, "_NET_WM_STATE", 0);
1194 Atom net_wm_state_maximized_vert = XInternAtom (fl_display, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
1195 Atom net_wm_state_maximized_horz = XInternAtom (fl_display, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
1196
1197 XEvent e;
1198 e.xany.type = ClientMessage;
1199 e.xany.window = fl_xid(this);
1200 e.xclient.message_type = net_wm_state;
1201 e.xclient.format = 32;
1202 e.xclient.data.l[0] = _NET_WM_STATE_ADD;
1203 e.xclient.data.l[1] = net_wm_state_maximized_vert;
1204 e.xclient.data.l[2] = net_wm_state_maximized_horz;
1205 e.xclient.data.l[3] = 0;
1206 e.xclient.data.l[4] = 0;
1207 XSendEvent(fl_display, RootWindow(fl_display, fl_screen), 0, SubstructureNotifyMask | SubstructureRedirectMask, &e);
1208 #endif
1209 }
1210
1211
handleDesktopSize()1212 void DesktopWindow::handleDesktopSize()
1213 {
1214 if (strcmp(desktopSize, "") != 0) {
1215 int width, height;
1216
1217 // An explicit size has been requested
1218
1219 if (sscanf(desktopSize, "%dx%d", &width, &height) != 2)
1220 return;
1221
1222 remoteResize(width, height);
1223 } else if (::remoteResize) {
1224 // No explicit size, but remote resizing is on so make sure it
1225 // matches whatever size the window ended up being
1226 remoteResize(w(), h());
1227 }
1228 }
1229
1230
handleResizeTimeout(void * data)1231 void DesktopWindow::handleResizeTimeout(void *data)
1232 {
1233 DesktopWindow *self = (DesktopWindow *)data;
1234
1235 assert(self);
1236
1237 self->remoteResize(self->w(), self->h());
1238 }
1239
1240
reconfigureFullscreen(void * data)1241 void DesktopWindow::reconfigureFullscreen(void *data)
1242 {
1243 std::set<DesktopWindow *>::iterator iter;
1244
1245 for (iter = instances.begin(); iter != instances.end(); ++iter) {
1246 if ((*iter)->fullscreen_active())
1247 (*iter)->fullscreen_on();
1248 }
1249 }
1250
1251
remoteResize(int width,int height)1252 void DesktopWindow::remoteResize(int width, int height)
1253 {
1254 ScreenSet layout;
1255 ScreenSet::const_iterator iter;
1256
1257 if (!fullscreen_active() || (width > w()) || (height > h())) {
1258 // In windowed mode (or the framebuffer is so large that we need
1259 // to scroll) we just report a single virtual screen that covers
1260 // the entire framebuffer.
1261
1262 layout = cc->server.screenLayout();
1263
1264 // Not sure why we have no screens, but adding a new one should be
1265 // safe as there is nothing to conflict with...
1266 if (layout.num_screens() == 0)
1267 layout.add_screen(rfb::Screen());
1268 else if (layout.num_screens() != 1) {
1269 // More than one screen. Remove all but the first (which we
1270 // assume is the "primary").
1271
1272 while (true) {
1273 iter = layout.begin();
1274 ++iter;
1275
1276 if (iter == layout.end())
1277 break;
1278
1279 layout.remove_screen(iter->id);
1280 }
1281 }
1282
1283 // Resize the remaining single screen to the complete framebuffer
1284 layout.begin()->dimensions.tl.x = 0;
1285 layout.begin()->dimensions.tl.y = 0;
1286 layout.begin()->dimensions.br.x = width;
1287 layout.begin()->dimensions.br.y = height;
1288 } else {
1289 int i;
1290 rdr::U32 id;
1291 int sx, sy, sw, sh;
1292 rfb::Rect viewport_rect, screen_rect;
1293
1294 // In full screen we report all screens that are fully covered.
1295
1296 viewport_rect.setXYWH(x() + (w() - width)/2, y() + (h() - height)/2,
1297 width, height);
1298
1299 // If we can find a matching screen in the existing set, we use
1300 // that, otherwise we create a brand new screen.
1301 //
1302 // FIXME: We should really track screens better so we can handle
1303 // a resized one.
1304 //
1305 for (i = 0;i < Fl::screen_count();i++) {
1306 Fl::screen_xywh(sx, sy, sw, sh, i);
1307
1308 // Check that the screen is fully inside the framebuffer
1309 screen_rect.setXYWH(sx, sy, sw, sh);
1310 if (!screen_rect.enclosed_by(viewport_rect))
1311 continue;
1312
1313 // Adjust the coordinates so they are relative to our viewport
1314 sx -= viewport_rect.tl.x;
1315 sy -= viewport_rect.tl.y;
1316
1317 // Look for perfectly matching existing screen...
1318 for (iter = cc->server.screenLayout().begin();
1319 iter != cc->server.screenLayout().end(); ++iter) {
1320 if ((iter->dimensions.tl.x == sx) &&
1321 (iter->dimensions.tl.y == sy) &&
1322 (iter->dimensions.width() == sw) &&
1323 (iter->dimensions.height() == sh))
1324 break;
1325 }
1326
1327 // Found it?
1328 if (iter != cc->server.screenLayout().end()) {
1329 layout.add_screen(*iter);
1330 continue;
1331 }
1332
1333 // Need to add a new one, which means we need to find an unused id
1334 while (true) {
1335 id = rand();
1336 for (iter = cc->server.screenLayout().begin();
1337 iter != cc->server.screenLayout().end(); ++iter) {
1338 if (iter->id == id)
1339 break;
1340 }
1341
1342 if (iter == cc->server.screenLayout().end())
1343 break;
1344 }
1345
1346 layout.add_screen(rfb::Screen(id, sx, sy, sw, sh, 0));
1347 }
1348
1349 // If the viewport doesn't match a physical screen, then we might
1350 // end up with no screens in the layout. Add a fake one...
1351 if (layout.num_screens() == 0)
1352 layout.add_screen(rfb::Screen(0, 0, 0, width, height, 0));
1353 }
1354
1355 // Do we actually change anything?
1356 if ((width == cc->server.width()) &&
1357 (height == cc->server.height()) &&
1358 (layout == cc->server.screenLayout()))
1359 return;
1360
1361 char buffer[2048];
1362 vlog.debug("Requesting framebuffer resize from %dx%d to %dx%d",
1363 cc->server.width(), cc->server.height(), width, height);
1364 layout.print(buffer, sizeof(buffer));
1365 vlog.debug("%s", buffer);
1366
1367 if (!layout.validate(width, height)) {
1368 vlog.error(_("Invalid screen layout computed for resize request!"));
1369 return;
1370 }
1371
1372 cc->writer()->writeSetDesktopSize(width, height, layout);
1373 }
1374
1375
repositionWidgets()1376 void DesktopWindow::repositionWidgets()
1377 {
1378 int new_x, new_y;
1379
1380 // Viewport position
1381
1382 new_x = viewport->x();
1383 new_y = viewport->y();
1384
1385 if (w() > viewport->w())
1386 new_x = (w() - viewport->w()) / 2;
1387 else {
1388 if (viewport->x() > 0)
1389 new_x = 0;
1390 else if (w() > (viewport->x() + viewport->w()))
1391 new_x = w() - viewport->w();
1392 }
1393
1394 // Same thing for y axis
1395 if (h() > viewport->h())
1396 new_y = (h() - viewport->h()) / 2;
1397 else {
1398 if (viewport->y() > 0)
1399 new_y = 0;
1400 else if (h() > (viewport->y() + viewport->h()))
1401 new_y = h() - viewport->h();
1402 }
1403
1404 if ((new_x != viewport->x()) || (new_y != viewport->y())) {
1405 viewport->position(new_x, new_y);
1406 damage(FL_DAMAGE_SCROLL);
1407 }
1408
1409 // Scrollbars visbility
1410
1411 if (fullscreen_active()) {
1412 hscroll->hide();
1413 vscroll->hide();
1414 } else {
1415 // Decide whether to show a scrollbar by checking if the window
1416 // size (possibly minus scrollbar_size) is less than the viewport
1417 // (remote framebuffer) size.
1418 //
1419 // We decide whether to subtract scrollbar_size on an axis by
1420 // checking if the other axis *definitely* needs a scrollbar. You
1421 // might be tempted to think that this becomes a weird recursive
1422 // problem, but it isn't: If the window size is less than the
1423 // viewport size (without subtracting the scrollbar_size), then
1424 // that axis *definitely* needs a scrollbar; if the check changes
1425 // when we subtract scrollbar_size, then that axis only *maybe*
1426 // needs a scrollbar. If both axes only "maybe" need a scrollbar,
1427 // then neither does; so we don't need to recurse on the "maybe"
1428 // cases.
1429
1430 if (w() - (h() < viewport->h() ? Fl::scrollbar_size() : 0) < viewport->w())
1431 hscroll->show();
1432 else
1433 hscroll->hide();
1434
1435 if (h() - (w() < viewport->w() ? Fl::scrollbar_size() : 0) < viewport->h())
1436 vscroll->show();
1437 else
1438 vscroll->hide();
1439 }
1440
1441 // Scrollbars positions
1442
1443 hscroll->resize(0, h() - Fl::scrollbar_size(),
1444 w() - (vscroll->visible() ? Fl::scrollbar_size() : 0),
1445 Fl::scrollbar_size());
1446 vscroll->resize(w() - Fl::scrollbar_size(), 0,
1447 Fl::scrollbar_size(),
1448 h() - (hscroll->visible() ? Fl::scrollbar_size() : 0));
1449
1450 // Scrollbars range
1451
1452 hscroll->value(-viewport->x(),
1453 w() - (vscroll->visible() ? vscroll->w() : 0),
1454 0, viewport->w());
1455 vscroll->value(-viewport->y(),
1456 h() - (hscroll->visible() ? hscroll->h() : 0),
1457 0, viewport->h());
1458 hscroll->value(hscroll->clamp(hscroll->value()));
1459 vscroll->value(vscroll->clamp(vscroll->value()));
1460 }
1461
handleClose(Fl_Widget * wnd,void * data)1462 void DesktopWindow::handleClose(Fl_Widget *wnd, void *data)
1463 {
1464 disconnect();
1465 }
1466
1467
handleOptions(void * data)1468 void DesktopWindow::handleOptions(void *data)
1469 {
1470 DesktopWindow *self = (DesktopWindow*)data;
1471
1472 if (fullscreenSystemKeys)
1473 self->maybeGrabKeyboard();
1474 else
1475 self->ungrabKeyboard();
1476
1477 // Call fullscreen_on even if active since it handles
1478 // fullScreenMode
1479 if (fullScreen)
1480 self->fullscreen_on();
1481 else if (!fullScreen && self->fullscreen_active())
1482 self->fullscreen_off();
1483 }
1484
handleFullscreenTimeout(void * data)1485 void DesktopWindow::handleFullscreenTimeout(void *data)
1486 {
1487 DesktopWindow *self = (DesktopWindow *)data;
1488
1489 assert(self);
1490
1491 self->delayedFullscreen = false;
1492
1493 if (self->delayedDesktopSize) {
1494 self->handleDesktopSize();
1495 self->delayedDesktopSize = false;
1496 }
1497 }
1498
scrollTo(int x,int y)1499 void DesktopWindow::scrollTo(int x, int y)
1500 {
1501 x = hscroll->clamp(x);
1502 y = vscroll->clamp(y);
1503
1504 hscroll->value(x);
1505 vscroll->value(y);
1506
1507 // Scrollbar position results in inverse movement of
1508 // the viewport widget
1509 x = -x;
1510 y = -y;
1511
1512 if ((viewport->x() == x) && (viewport->y() == y))
1513 return;
1514
1515 viewport->position(x, y);
1516 damage(FL_DAMAGE_SCROLL);
1517 }
1518
handleScroll(Fl_Widget * widget,void * data)1519 void DesktopWindow::handleScroll(Fl_Widget *widget, void *data)
1520 {
1521 DesktopWindow *self = (DesktopWindow *)data;
1522
1523 self->scrollTo(self->hscroll->value(), self->vscroll->value());
1524 }
1525
handleEdgeScroll(void * data)1526 void DesktopWindow::handleEdgeScroll(void *data)
1527 {
1528 DesktopWindow *self = (DesktopWindow *)data;
1529
1530 int mx, my;
1531 int dx, dy;
1532
1533 assert(self);
1534
1535 if (!self->fullscreen_active())
1536 return;
1537
1538 mx = Fl::event_x();
1539 my = Fl::event_y();
1540
1541 dx = dy = 0;
1542
1543 // Clamp mouse position in case it is outside the window
1544 if (mx < 0)
1545 mx = 0;
1546 if (mx > self->w())
1547 mx = self->w();
1548 if (my < 0)
1549 my = 0;
1550 if (my > self->h())
1551 my = self->h();
1552
1553 if ((self->viewport->x() < 0) && (mx < edge_scroll_size_x))
1554 dx = EDGE_SCROLL_SPEED -
1555 EDGE_SCROLL_SPEED * mx / edge_scroll_size_x;
1556 if ((self->viewport->x() + self->viewport->w() >= self->w()) &&
1557 (mx >= self->w() - edge_scroll_size_x))
1558 dx = EDGE_SCROLL_SPEED * (self->w() - mx) / edge_scroll_size_x -
1559 EDGE_SCROLL_SPEED - 1;
1560 if ((self->viewport->y() < 0) && (my < edge_scroll_size_y))
1561 dy = EDGE_SCROLL_SPEED -
1562 EDGE_SCROLL_SPEED * my / edge_scroll_size_y;
1563 if ((self->viewport->y() + self->viewport->h() >= self->h()) &&
1564 (my >= self->h() - edge_scroll_size_y))
1565 dy = EDGE_SCROLL_SPEED * (self->h() - my) / edge_scroll_size_y -
1566 EDGE_SCROLL_SPEED - 1;
1567
1568 if ((dx == 0) && (dy == 0))
1569 return;
1570
1571 self->scrollTo(self->hscroll->value() - dx, self->vscroll->value() - dy);
1572
1573 Fl::repeat_timeout(EDGE_SCROLL_SECONDS_PER_FRAME, handleEdgeScroll, data);
1574 }
1575
handleStatsTimeout(void * data)1576 void DesktopWindow::handleStatsTimeout(void *data)
1577 {
1578 DesktopWindow *self = (DesktopWindow*)data;
1579
1580 const size_t statsCount = sizeof(self->stats)/sizeof(self->stats[0]);
1581
1582 unsigned updates, pixels, pos;
1583 unsigned elapsed;
1584
1585 const unsigned statsWidth = 200;
1586 const unsigned statsHeight = 100;
1587 const unsigned graphWidth = statsWidth - 10;
1588 const unsigned graphHeight = statsHeight - 25;
1589
1590 Fl_Image_Surface *surface;
1591 Fl_RGB_Image *image;
1592
1593 unsigned maxUPS, maxPPS, maxBPS;
1594 size_t i;
1595
1596 char buffer[256];
1597
1598 updates = self->cc->getUpdateCount();
1599 pixels = self->cc->getPixelCount();
1600 pos = self->cc->getPosition();
1601 elapsed = msSince(&self->statsLastTime);
1602 if (elapsed < 1)
1603 elapsed = 1;
1604
1605 memmove(&self->stats[0], &self->stats[1], sizeof(self->stats[0])*(statsCount-1));
1606
1607 self->stats[statsCount-1].ups = (updates - self->statsLastUpdates) * 1000 / elapsed;
1608 self->stats[statsCount-1].pps = (pixels - self->statsLastPixels) * 1000 / elapsed;
1609 self->stats[statsCount-1].bps = (pos - self->statsLastPosition) * 1000 / elapsed;
1610
1611 gettimeofday(&self->statsLastTime, NULL);
1612 self->statsLastUpdates = updates;
1613 self->statsLastPixels = pixels;
1614 self->statsLastPosition = pos;
1615
1616 #if !defined(WIN32) && !defined(__APPLE__)
1617 // FLTK < 1.3.5 crashes if fl_gc is unset
1618 if (!fl_gc)
1619 fl_gc = XDefaultGC(fl_display, 0);
1620 #endif
1621
1622 surface = new Fl_Image_Surface(statsWidth, statsHeight);
1623 surface->set_current();
1624
1625 fl_rectf(0, 0, statsWidth, statsHeight, FL_BLACK);
1626
1627 fl_rect(5, 5, graphWidth, graphHeight, FL_WHITE);
1628
1629 maxUPS = maxPPS = maxBPS = 0;
1630 for (i = 0;i < statsCount;i++) {
1631 if (self->stats[i].ups > maxUPS)
1632 maxUPS = self->stats[i].ups;
1633 if (self->stats[i].pps > maxPPS)
1634 maxPPS = self->stats[i].pps;
1635 if (self->stats[i].bps > maxBPS)
1636 maxBPS = self->stats[i].bps;
1637 }
1638
1639 if (maxUPS != 0) {
1640 fl_color(FL_GREEN);
1641 for (i = 0;i < statsCount-1;i++) {
1642 fl_line(5 + i * graphWidth / statsCount,
1643 5 + graphHeight - graphHeight * self->stats[i].ups / maxUPS,
1644 5 + (i+1) * graphWidth / statsCount,
1645 5 + graphHeight - graphHeight * self->stats[i+1].ups / maxUPS);
1646 }
1647 }
1648
1649 if (maxPPS != 0) {
1650 fl_color(FL_YELLOW);
1651 for (i = 0;i < statsCount-1;i++) {
1652 fl_line(5 + i * graphWidth / statsCount,
1653 5 + graphHeight - graphHeight * self->stats[i].pps / maxPPS,
1654 5 + (i+1) * graphWidth / statsCount,
1655 5 + graphHeight - graphHeight * self->stats[i+1].pps / maxPPS);
1656 }
1657 }
1658
1659 if (maxBPS != 0) {
1660 fl_color(FL_RED);
1661 for (i = 0;i < statsCount-1;i++) {
1662 fl_line(5 + i * graphWidth / statsCount,
1663 5 + graphHeight - graphHeight * self->stats[i].bps / maxBPS,
1664 5 + (i+1) * graphWidth / statsCount,
1665 5 + graphHeight - graphHeight * self->stats[i+1].bps / maxBPS);
1666 }
1667 }
1668
1669 fl_font(FL_HELVETICA, 10);
1670
1671 fl_color(FL_GREEN);
1672 snprintf(buffer, sizeof(buffer), "%u upd/s", self->stats[statsCount-1].ups);
1673 fl_draw(buffer, 5, statsHeight - 5);
1674
1675 fl_color(FL_YELLOW);
1676 siPrefix(self->stats[statsCount-1].pps, "pix/s",
1677 buffer, sizeof(buffer), 3);
1678 fl_draw(buffer, 5 + (statsWidth-10)/3, statsHeight - 5);
1679
1680 fl_color(FL_RED);
1681 siPrefix(self->stats[statsCount-1].bps * 8, "bps",
1682 buffer, sizeof(buffer), 3);
1683 fl_draw(buffer, 5 + (statsWidth-10)*2/3, statsHeight - 5);
1684
1685 image = surface->image();
1686 delete surface;
1687
1688 Fl_Display_Device::display_device()->set_current();
1689
1690 delete self->statsGraph;
1691 self->statsGraph = new Surface(image);
1692 delete image;
1693
1694 self->damage(FL_DAMAGE_CHILD, self->w() - statsWidth - 30,
1695 self->h() - statsHeight - 30,
1696 statsWidth, statsHeight);
1697
1698 Fl::repeat_timeout(0.5, handleStatsTimeout, data);
1699 }
1700