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

DesktopWindow.cxx 46KB

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