You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DesktopWindow.cxx 46KB

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