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

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