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

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