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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  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. 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. rdr::U32 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. siPrefix(self->stats[statsCount-1].pps, "pix/s",
  1376. buffer, sizeof(buffer), 3);
  1377. fl_draw(buffer, 5 + (statsWidth-10)/3, statsHeight - 5);
  1378. fl_color(FL_RED);
  1379. siPrefix(self->stats[statsCount-1].bps * 8, "bps",
  1380. buffer, sizeof(buffer), 3);
  1381. fl_draw(buffer, 5 + (statsWidth-10)*2/3, statsHeight - 5);
  1382. image = surface->image();
  1383. delete surface;
  1384. Fl_Display_Device::display_device()->set_current();
  1385. delete self->statsGraph;
  1386. self->statsGraph = new Surface(image);
  1387. delete image;
  1388. self->damage(FL_DAMAGE_CHILD, self->w() - statsWidth - 30,
  1389. self->h() - statsHeight - 30,
  1390. statsWidth, statsHeight);
  1391. Fl::repeat_timeout(0.5, handleStatsTimeout, data);
  1392. }