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 45KB

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