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.

XDesktop.cxx 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright (C) 2004-2008 Constantin Kaplinsky. All Rights Reserved.
  3. * Copyright 2017 Peter Astrand <astrand@cendio.se> for Cendio AB
  4. *
  5. * This is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This software is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this software; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  18. * USA.
  19. */
  20. #include <assert.h>
  21. #include <signal.h>
  22. #include <unistd.h>
  23. #include <rfb/LogWriter.h>
  24. #include <x0vncserver/XDesktop.h>
  25. #include <X11/XKBlib.h>
  26. #ifdef HAVE_XTEST
  27. #include <X11/extensions/XTest.h>
  28. #endif
  29. #ifdef HAVE_XDAMAGE
  30. #include <X11/extensions/Xdamage.h>
  31. #endif
  32. #ifdef HAVE_XFIXES
  33. #include <X11/extensions/Xfixes.h>
  34. #endif
  35. #ifdef HAVE_XRANDR
  36. #include <X11/extensions/Xrandr.h>
  37. #include <RandrGlue.h>
  38. extern "C" {
  39. void vncSetGlueContext(Display *dpy, void *res);
  40. }
  41. #endif
  42. #include <x0vncserver/Geometry.h>
  43. #include <x0vncserver/XPixelBuffer.h>
  44. using namespace rfb;
  45. extern const unsigned short code_map_qnum_to_xorgevdev[];
  46. extern const unsigned int code_map_qnum_to_xorgevdev_len;
  47. extern const unsigned short code_map_qnum_to_xorgkbd[];
  48. extern const unsigned int code_map_qnum_to_xorgkbd_len;
  49. BoolParameter useShm("UseSHM", "Use MIT-SHM extension if available", true);
  50. BoolParameter rawKeyboard("RawKeyboard",
  51. "Send keyboard events straight through and "
  52. "avoid mapping them to the current keyboard "
  53. "layout", false);
  54. IntParameter queryConnectTimeout("QueryConnectTimeout",
  55. "Number of seconds to show the Accept Connection dialog before "
  56. "rejecting the connection",
  57. 10);
  58. static rfb::LogWriter vlog("XDesktop");
  59. // order is important as it must match RFB extension
  60. static const char * ledNames[XDESKTOP_N_LEDS] = {
  61. "Scroll Lock", "Num Lock", "Caps Lock"
  62. };
  63. XDesktop::XDesktop(Display* dpy_, Geometry *geometry_)
  64. : dpy(dpy_), geometry(geometry_), pb(0), server(0),
  65. queryConnectDialog(0), queryConnectSock(0),
  66. oldButtonMask(0), haveXtest(false), haveDamage(false),
  67. maxButtons(0), running(false), ledMasks(), ledState(0),
  68. codeMap(0), codeMapLen(0)
  69. {
  70. int major, minor;
  71. int xkbOpcode, xkbErrorBase;
  72. major = XkbMajorVersion;
  73. minor = XkbMinorVersion;
  74. if (!XkbQueryExtension(dpy, &xkbOpcode, &xkbEventBase,
  75. &xkbErrorBase, &major, &minor)) {
  76. vlog.error("XKEYBOARD extension not present");
  77. throw Exception();
  78. }
  79. XkbSelectEvents(dpy, XkbUseCoreKbd, XkbIndicatorStateNotifyMask,
  80. XkbIndicatorStateNotifyMask);
  81. // figure out bit masks for the indicators we are interested in
  82. for (int i = 0; i < XDESKTOP_N_LEDS; i++) {
  83. Atom a;
  84. int shift;
  85. Bool on;
  86. a = XInternAtom(dpy, ledNames[i], True);
  87. if (!a || !XkbGetNamedIndicator(dpy, a, &shift, &on, NULL, NULL))
  88. continue;
  89. ledMasks[i] = 1u << shift;
  90. vlog.debug("Mask for '%s' is 0x%x", ledNames[i], ledMasks[i]);
  91. if (on)
  92. ledState |= 1u << i;
  93. }
  94. // X11 unfortunately uses keyboard driver specific keycodes and provides no
  95. // direct way to query this, so guess based on the keyboard mapping
  96. XkbDescPtr desc = XkbGetKeyboard(dpy, XkbAllComponentsMask, XkbUseCoreKbd);
  97. if (desc && desc->names) {
  98. char *keycodes = XGetAtomName(dpy, desc->names->keycodes);
  99. if (keycodes) {
  100. if (strncmp("evdev", keycodes, strlen("evdev")) == 0) {
  101. codeMap = code_map_qnum_to_xorgevdev;
  102. codeMapLen = code_map_qnum_to_xorgevdev_len;
  103. vlog.info("Using evdev codemap\n");
  104. } else if (strncmp("xfree86", keycodes, strlen("xfree86")) == 0) {
  105. codeMap = code_map_qnum_to_xorgkbd;
  106. codeMapLen = code_map_qnum_to_xorgkbd_len;
  107. vlog.info("Using xorgkbd codemap\n");
  108. } else {
  109. vlog.info("Unknown keycode '%s', no codemap\n", keycodes);
  110. }
  111. XFree(keycodes);
  112. } else {
  113. vlog.debug("Unable to get keycode map\n");
  114. }
  115. XkbFreeKeyboard(desc, XkbAllComponentsMask, True);
  116. }
  117. #ifdef HAVE_XTEST
  118. int xtestEventBase;
  119. int xtestErrorBase;
  120. if (XTestQueryExtension(dpy, &xtestEventBase,
  121. &xtestErrorBase, &major, &minor)) {
  122. XTestGrabControl(dpy, True);
  123. vlog.info("XTest extension present - version %d.%d",major,minor);
  124. haveXtest = true;
  125. } else {
  126. #endif
  127. vlog.info("XTest extension not present");
  128. vlog.info("Unable to inject events or display while server is grabbed");
  129. #ifdef HAVE_XTEST
  130. }
  131. #endif
  132. #ifdef HAVE_XDAMAGE
  133. int xdamageErrorBase;
  134. if (XDamageQueryExtension(dpy, &xdamageEventBase, &xdamageErrorBase)) {
  135. haveDamage = true;
  136. } else {
  137. #endif
  138. vlog.info("DAMAGE extension not present");
  139. vlog.info("Will have to poll screen for changes");
  140. #ifdef HAVE_XDAMAGE
  141. }
  142. #endif
  143. #ifdef HAVE_XFIXES
  144. int xfixesErrorBase;
  145. if (XFixesQueryExtension(dpy, &xfixesEventBase, &xfixesErrorBase)) {
  146. XFixesSelectCursorInput(dpy, DefaultRootWindow(dpy),
  147. XFixesDisplayCursorNotifyMask);
  148. } else {
  149. #endif
  150. vlog.info("XFIXES extension not present");
  151. vlog.info("Will not be able to display cursors");
  152. #ifdef HAVE_XFIXES
  153. }
  154. #endif
  155. #ifdef HAVE_XRANDR
  156. int xrandrErrorBase;
  157. randrSyncSerial = 0;
  158. if (XRRQueryExtension(dpy, &xrandrEventBase, &xrandrErrorBase)) {
  159. XRRSelectInput(dpy, DefaultRootWindow(dpy),
  160. RRScreenChangeNotifyMask | RRCrtcChangeNotifyMask);
  161. /* Override TXWindow::init input mask */
  162. XSelectInput(dpy, DefaultRootWindow(dpy),
  163. PropertyChangeMask | StructureNotifyMask | ExposureMask);
  164. } else {
  165. #endif
  166. vlog.info("RANDR extension not present");
  167. vlog.info("Will not be able to handle session resize");
  168. #ifdef HAVE_XRANDR
  169. }
  170. #endif
  171. TXWindow::setGlobalEventHandler(this);
  172. }
  173. XDesktop::~XDesktop() {
  174. if (running)
  175. stop();
  176. }
  177. void XDesktop::poll() {
  178. if (pb and not haveDamage)
  179. pb->poll(server);
  180. if (running) {
  181. Window root, child;
  182. int x, y, wx, wy;
  183. unsigned int mask;
  184. XQueryPointer(dpy, DefaultRootWindow(dpy), &root, &child,
  185. &x, &y, &wx, &wy, &mask);
  186. x -= geometry->offsetLeft();
  187. y -= geometry->offsetTop();
  188. server->setCursorPos(rfb::Point(x, y));
  189. }
  190. }
  191. void XDesktop::start(VNCServer* vs) {
  192. // Determine actual number of buttons of the X pointer device.
  193. unsigned char btnMap[8];
  194. int numButtons = XGetPointerMapping(dpy, btnMap, 8);
  195. maxButtons = (numButtons > 8) ? 8 : numButtons;
  196. vlog.info("Enabling %d button%s of X pointer device",
  197. maxButtons, (maxButtons != 1) ? "s" : "");
  198. // Create an ImageFactory instance for producing Image objects.
  199. ImageFactory factory((bool)useShm);
  200. // Create pixel buffer and provide it to the server object.
  201. pb = new XPixelBuffer(dpy, factory, geometry->getRect());
  202. vlog.info("Allocated %s", pb->getImage()->classDesc());
  203. server = vs;
  204. server->setPixelBuffer(pb, computeScreenLayout());
  205. #ifdef HAVE_XDAMAGE
  206. if (haveDamage) {
  207. damage = XDamageCreate(dpy, DefaultRootWindow(dpy),
  208. XDamageReportRawRectangles);
  209. }
  210. #endif
  211. #ifdef HAVE_XFIXES
  212. setCursor();
  213. #endif
  214. server->setLEDState(ledState);
  215. running = true;
  216. }
  217. void XDesktop::stop() {
  218. running = false;
  219. #ifdef HAVE_XDAMAGE
  220. if (haveDamage)
  221. XDamageDestroy(dpy, damage);
  222. #endif
  223. delete queryConnectDialog;
  224. queryConnectDialog = 0;
  225. server->setPixelBuffer(0);
  226. server = 0;
  227. delete pb;
  228. pb = 0;
  229. }
  230. void XDesktop::terminate() {
  231. kill(getpid(), SIGTERM);
  232. }
  233. bool XDesktop::isRunning() {
  234. return running;
  235. }
  236. void XDesktop::queryConnection(network::Socket* sock,
  237. const char* userName)
  238. {
  239. assert(isRunning());
  240. if (queryConnectSock) {
  241. server->approveConnection(sock, false, "Another connection is currently being queried.");
  242. return;
  243. }
  244. if (!userName)
  245. userName = "(anonymous)";
  246. queryConnectSock = sock;
  247. CharArray address(sock->getPeerAddress());
  248. delete queryConnectDialog;
  249. queryConnectDialog = new QueryConnectDialog(dpy, address.buf,
  250. userName,
  251. queryConnectTimeout,
  252. this);
  253. queryConnectDialog->map();
  254. }
  255. void XDesktop::pointerEvent(const Point& pos, int buttonMask) {
  256. #ifdef HAVE_XTEST
  257. if (!haveXtest) return;
  258. XTestFakeMotionEvent(dpy, DefaultScreen(dpy),
  259. geometry->offsetLeft() + pos.x,
  260. geometry->offsetTop() + pos.y,
  261. CurrentTime);
  262. if (buttonMask != oldButtonMask) {
  263. for (int i = 0; i < maxButtons; i++) {
  264. if ((buttonMask ^ oldButtonMask) & (1<<i)) {
  265. if (buttonMask & (1<<i)) {
  266. XTestFakeButtonEvent(dpy, i+1, True, CurrentTime);
  267. } else {
  268. XTestFakeButtonEvent(dpy, i+1, False, CurrentTime);
  269. }
  270. }
  271. }
  272. }
  273. oldButtonMask = buttonMask;
  274. #endif
  275. }
  276. #ifdef HAVE_XTEST
  277. KeyCode XDesktop::XkbKeysymToKeycode(Display* dpy, KeySym keysym) {
  278. XkbDescPtr xkb;
  279. XkbStateRec state;
  280. unsigned int mods;
  281. unsigned keycode;
  282. xkb = XkbGetMap(dpy, XkbAllComponentsMask, XkbUseCoreKbd);
  283. if (!xkb)
  284. return 0;
  285. XkbGetState(dpy, XkbUseCoreKbd, &state);
  286. // XkbStateFieldFromRec() doesn't work properly because
  287. // state.lookup_mods isn't properly updated, so we do this manually
  288. mods = XkbBuildCoreState(XkbStateMods(&state), state.group);
  289. for (keycode = xkb->min_key_code;
  290. keycode <= xkb->max_key_code;
  291. keycode++) {
  292. KeySym cursym;
  293. unsigned int out_mods;
  294. XkbTranslateKeyCode(xkb, keycode, mods, &out_mods, &cursym);
  295. if (cursym == keysym)
  296. break;
  297. }
  298. if (keycode > xkb->max_key_code)
  299. keycode = 0;
  300. XkbFreeKeyboard(xkb, XkbAllComponentsMask, True);
  301. // Shift+Tab is usually ISO_Left_Tab, but RFB hides this fact. Do
  302. // another attempt if we failed the initial lookup
  303. if ((keycode == 0) && (keysym == XK_Tab) && (mods & ShiftMask))
  304. return XkbKeysymToKeycode(dpy, XK_ISO_Left_Tab);
  305. return keycode;
  306. }
  307. #endif
  308. void XDesktop::keyEvent(rdr::U32 keysym, rdr::U32 xtcode, bool down) {
  309. #ifdef HAVE_XTEST
  310. int keycode = 0;
  311. if (!haveXtest)
  312. return;
  313. // Use scan code if provided and mapping exists
  314. if (codeMap && rawKeyboard && xtcode < codeMapLen)
  315. keycode = codeMap[xtcode];
  316. if (!keycode) {
  317. if (pressedKeys.find(keysym) != pressedKeys.end())
  318. keycode = pressedKeys[keysym];
  319. else {
  320. // XKeysymToKeycode() doesn't respect state, so we have to use
  321. // something slightly more complex
  322. keycode = XkbKeysymToKeycode(dpy, keysym);
  323. }
  324. }
  325. if (!keycode) {
  326. vlog.error("Could not map key event to X11 key code");
  327. return;
  328. }
  329. if (down)
  330. pressedKeys[keysym] = keycode;
  331. else
  332. pressedKeys.erase(keysym);
  333. vlog.debug("%d %s", keycode, down ? "down" : "up");
  334. XTestFakeKeyEvent(dpy, keycode, down, CurrentTime);
  335. #endif
  336. }
  337. void XDesktop::clientCutText(const char* str, int len) {
  338. }
  339. ScreenSet XDesktop::computeScreenLayout()
  340. {
  341. ScreenSet layout;
  342. #ifdef HAVE_XRANDR
  343. XRRScreenResources *res = XRRGetScreenResources(dpy, DefaultRootWindow(dpy));
  344. if (!res) {
  345. vlog.error("XRRGetScreenResources failed");
  346. return layout;
  347. }
  348. vncSetGlueContext(dpy, res);
  349. layout = ::computeScreenLayout(&outputIdMap);
  350. XRRFreeScreenResources(res);
  351. #endif
  352. return layout;
  353. }
  354. #ifdef HAVE_XRANDR
  355. /* Get the biggest mode which is equal or smaller to requested
  356. size. If no such mode exists, return the smallest. */
  357. static void GetSmallerMode(XRRScreenResources *res,
  358. XRROutputInfo *output,
  359. unsigned int *width, unsigned int *height)
  360. {
  361. XRRModeInfo best = {};
  362. XRRModeInfo smallest = {};
  363. smallest.width = -1;
  364. smallest.height = -1;
  365. for (int i = 0; i < res->nmode; i++) {
  366. for (int j = 0; j < output->nmode; j++) {
  367. if (output->modes[j] == res->modes[i].id) {
  368. if ((res->modes[i].width > best.width && res->modes[i].width <= *width) &&
  369. (res->modes[i].height > best.height && res->modes[i].height <= *height)) {
  370. best = res->modes[i];
  371. }
  372. if ((res->modes[i].width < smallest.width) && res->modes[i].height < smallest.height) {
  373. smallest = res->modes[i];
  374. }
  375. }
  376. }
  377. }
  378. if (best.id == 0 && smallest.id != 0) {
  379. best = smallest;
  380. }
  381. *width = best.width;
  382. *height = best.height;
  383. }
  384. #endif /* HAVE_XRANDR */
  385. unsigned int XDesktop::setScreenLayout(int fb_width, int fb_height,
  386. const rfb::ScreenSet& layout)
  387. {
  388. #ifdef HAVE_XRANDR
  389. char buffer[2048];
  390. vlog.debug("Got request for framebuffer resize to %dx%d",
  391. fb_width, fb_height);
  392. layout.print(buffer, sizeof(buffer));
  393. vlog.debug("%s", buffer);
  394. XRRScreenResources *res = XRRGetScreenResources(dpy, DefaultRootWindow(dpy));
  395. if (!res) {
  396. vlog.error("XRRGetScreenResources failed");
  397. return rfb::resultProhibited;
  398. }
  399. vncSetGlueContext(dpy, res);
  400. /* The client may request a screen layout which is not supported by
  401. the Xserver. This happens, for example, when adjusting the size
  402. of a non-fullscreen vncviewer window. To handle this and other
  403. cases, we first call tryScreenLayout. If this fails, we try to
  404. adjust the request to one screen with a smaller mode. */
  405. vlog.debug("Testing screen layout");
  406. unsigned int tryresult = ::tryScreenLayout(fb_width, fb_height, layout, &outputIdMap);
  407. rfb::ScreenSet adjustedLayout;
  408. if (tryresult == rfb::resultSuccess) {
  409. adjustedLayout = layout;
  410. } else {
  411. vlog.debug("Impossible layout - trying to adjust");
  412. ScreenSet::const_iterator firstscreen = layout.begin();
  413. adjustedLayout.add_screen(*firstscreen);
  414. ScreenSet::iterator iter = adjustedLayout.begin();
  415. RROutput outputId = None;
  416. for (int i = 0;i < vncRandRGetOutputCount();i++) {
  417. unsigned int oi = vncRandRGetOutputId(i);
  418. /* Known? */
  419. if (outputIdMap.count(oi) == 0)
  420. continue;
  421. /* Find the corresponding screen... */
  422. if (iter->id == outputIdMap[oi]) {
  423. outputId = oi;
  424. } else {
  425. outputIdMap.erase(oi);
  426. }
  427. }
  428. /* New screen */
  429. if (outputId == None) {
  430. int i = getPreferredScreenOutput(&outputIdMap, std::set<unsigned int>());
  431. if (i != -1) {
  432. outputId = vncRandRGetOutputId(i);
  433. }
  434. }
  435. if (outputId == None) {
  436. vlog.debug("Resize adjust: Could not find corresponding screen");
  437. XRRFreeScreenResources(res);
  438. return rfb::resultInvalid;
  439. }
  440. XRROutputInfo *output = XRRGetOutputInfo(dpy, res, outputId);
  441. if (!output) {
  442. vlog.debug("Resize adjust: XRRGetOutputInfo failed");
  443. XRRFreeScreenResources(res);
  444. return rfb::resultInvalid;
  445. }
  446. if (!output->crtc) {
  447. vlog.debug("Resize adjust: Selected output has no CRTC");
  448. XRRFreeScreenResources(res);
  449. XRRFreeOutputInfo(output);
  450. return rfb::resultInvalid;
  451. }
  452. XRRCrtcInfo *crtc = XRRGetCrtcInfo(dpy, res, output->crtc);
  453. if (!crtc) {
  454. vlog.debug("Resize adjust: XRRGetCrtcInfo failed");
  455. XRRFreeScreenResources(res);
  456. XRRFreeOutputInfo(output);
  457. return rfb::resultInvalid;
  458. }
  459. unsigned int swidth = iter->dimensions.width();
  460. unsigned int sheight = iter->dimensions.height();
  461. switch (crtc->rotation) {
  462. case RR_Rotate_90:
  463. case RR_Rotate_270:
  464. unsigned int swap = swidth;
  465. swidth = sheight;
  466. sheight = swap;
  467. break;
  468. }
  469. GetSmallerMode(res, output, &swidth, &sheight);
  470. XRRFreeOutputInfo(output);
  471. switch (crtc->rotation) {
  472. case RR_Rotate_90:
  473. case RR_Rotate_270:
  474. unsigned int swap = swidth;
  475. swidth = sheight;
  476. sheight = swap;
  477. break;
  478. }
  479. XRRFreeCrtcInfo(crtc);
  480. if (sheight != 0 && swidth != 0) {
  481. vlog.debug("Adjusted resize request to %dx%d", swidth, sheight);
  482. iter->dimensions.setXYWH(0, 0, swidth, sheight);
  483. fb_width = swidth;
  484. fb_height = sheight;
  485. } else {
  486. vlog.error("Failed to find smaller or equal screen size");
  487. XRRFreeScreenResources(res);
  488. return rfb::resultInvalid;
  489. }
  490. }
  491. vlog.debug("Changing screen layout");
  492. unsigned int ret = ::setScreenLayout(fb_width, fb_height, adjustedLayout, &outputIdMap);
  493. XRRFreeScreenResources(res);
  494. /* Send a dummy event to the root window. When this event is seen,
  495. earlier change events (ConfigureNotify and/or CrtcChange) have
  496. been processed. An Expose event is used for simplicity; does not
  497. require any Atoms, and will not affect other applications. */
  498. unsigned long serial = XNextRequest(dpy);
  499. XExposeEvent ev = {}; /* zero x, y, width, height, count */
  500. ev.type = Expose;
  501. ev.display = dpy;
  502. ev.window = DefaultRootWindow(dpy);
  503. if (XSendEvent(dpy, DefaultRootWindow(dpy), False, ExposureMask, (XEvent*)&ev)) {
  504. while (randrSyncSerial < serial) {
  505. TXWindow::handleXEvents(dpy);
  506. }
  507. } else {
  508. vlog.error("XSendEvent failed");
  509. }
  510. /* The protocol requires that an error is returned if the requested
  511. layout could not be set. This is checked by
  512. VNCSConnectionST::setDesktopSize. Another ExtendedDesktopSize
  513. with reason=0 will be sent in response to the changes seen by the
  514. event handler. */
  515. if (adjustedLayout != layout)
  516. return rfb::resultInvalid;
  517. // Explicitly update the server state with the result as there
  518. // can be corner cases where we don't get feedback from the X server
  519. server->setScreenLayout(computeScreenLayout());
  520. return ret;
  521. #else
  522. return rfb::resultProhibited;
  523. #endif /* HAVE_XRANDR */
  524. }
  525. bool XDesktop::handleGlobalEvent(XEvent* ev) {
  526. if (ev->type == xkbEventBase + XkbEventCode) {
  527. XkbEvent *kb = (XkbEvent *)ev;
  528. if (kb->any.xkb_type != XkbIndicatorStateNotify)
  529. return false;
  530. vlog.debug("Got indicator update, mask is now 0x%x", kb->indicators.state);
  531. ledState = 0;
  532. for (int i = 0; i < XDESKTOP_N_LEDS; i++) {
  533. if (kb->indicators.state & ledMasks[i])
  534. ledState |= 1u << i;
  535. }
  536. if (running)
  537. server->setLEDState(ledState);
  538. return true;
  539. #ifdef HAVE_XDAMAGE
  540. } else if (ev->type == xdamageEventBase) {
  541. XDamageNotifyEvent* dev;
  542. Rect rect;
  543. if (!running)
  544. return true;
  545. dev = (XDamageNotifyEvent*)ev;
  546. rect.setXYWH(dev->area.x, dev->area.y, dev->area.width, dev->area.height);
  547. rect = rect.translate(Point(-geometry->offsetLeft(),
  548. -geometry->offsetTop()));
  549. server->add_changed(rect);
  550. return true;
  551. #endif
  552. #ifdef HAVE_XFIXES
  553. } else if (ev->type == xfixesEventBase + XFixesCursorNotify) {
  554. XFixesCursorNotifyEvent* cev;
  555. if (!running)
  556. return true;
  557. cev = (XFixesCursorNotifyEvent*)ev;
  558. if (cev->subtype != XFixesDisplayCursorNotify)
  559. return false;
  560. return setCursor();
  561. #endif
  562. #ifdef HAVE_XRANDR
  563. } else if (ev->type == Expose) {
  564. XExposeEvent* eev = (XExposeEvent*)ev;
  565. randrSyncSerial = eev->serial;
  566. return false;
  567. } else if (ev->type == ConfigureNotify) {
  568. XConfigureEvent* cev = (XConfigureEvent*)ev;
  569. if (cev->window != DefaultRootWindow(dpy)) {
  570. return false;
  571. }
  572. XRRUpdateConfiguration(ev);
  573. geometry->recalc(cev->width, cev->height);
  574. if (!running) {
  575. return false;
  576. }
  577. if ((cev->width != pb->width() || (cev->height != pb->height()))) {
  578. // Recreate pixel buffer
  579. ImageFactory factory((bool)useShm);
  580. delete pb;
  581. pb = new XPixelBuffer(dpy, factory, geometry->getRect());
  582. server->setPixelBuffer(pb, computeScreenLayout());
  583. // Mark entire screen as changed
  584. server->add_changed(rfb::Region(Rect(0, 0, cev->width, cev->height)));
  585. }
  586. return true;
  587. } else if (ev->type == xrandrEventBase + RRNotify) {
  588. XRRNotifyEvent* rev = (XRRNotifyEvent*)ev;
  589. if (rev->window != DefaultRootWindow(dpy)) {
  590. return false;
  591. }
  592. if (!running)
  593. return false;
  594. if (rev->subtype == RRNotify_CrtcChange) {
  595. server->setScreenLayout(computeScreenLayout());
  596. }
  597. return true;
  598. #endif
  599. }
  600. return false;
  601. }
  602. void XDesktop::queryApproved()
  603. {
  604. assert(isRunning());
  605. server->approveConnection(queryConnectSock, true, 0);
  606. queryConnectSock = 0;
  607. }
  608. void XDesktop::queryRejected()
  609. {
  610. assert(isRunning());
  611. server->approveConnection(queryConnectSock, false,
  612. "Connection rejected by local user");
  613. queryConnectSock = 0;
  614. }
  615. bool XDesktop::setCursor()
  616. {
  617. XFixesCursorImage *cim;
  618. cim = XFixesGetCursorImage(dpy);
  619. if (cim == NULL)
  620. return false;
  621. // Copied from XserverDesktop::setCursor() in
  622. // unix/xserver/hw/vnc/XserverDesktop.cc and adapted to
  623. // handle long -> U32 conversion for 64-bit Xlib
  624. rdr::U8* cursorData;
  625. rdr::U8 *out;
  626. const unsigned long *pixels;
  627. cursorData = new rdr::U8[cim->width * cim->height * 4];
  628. // Un-premultiply alpha
  629. pixels = cim->pixels;
  630. out = cursorData;
  631. for (int y = 0; y < cim->height; y++) {
  632. for (int x = 0; x < cim->width; x++) {
  633. rdr::U8 alpha;
  634. rdr::U32 pixel = *pixels++;
  635. alpha = (pixel >> 24) & 0xff;
  636. if (alpha == 0)
  637. alpha = 1; // Avoid division by zero
  638. *out++ = ((pixel >> 16) & 0xff) * 255/alpha;
  639. *out++ = ((pixel >> 8) & 0xff) * 255/alpha;
  640. *out++ = ((pixel >> 0) & 0xff) * 255/alpha;
  641. *out++ = ((pixel >> 24) & 0xff);
  642. }
  643. }
  644. try {
  645. server->setCursor(cim->width, cim->height, Point(cim->xhot, cim->yhot),
  646. cursorData);
  647. } catch (rdr::Exception& e) {
  648. vlog.error("XserverDesktop::setCursor: %s",e.str());
  649. }
  650. delete [] cursorData;
  651. XFree(cim);
  652. return true;
  653. }