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

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