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

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