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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. // Adjust the layout relative to the geometry
  352. ScreenSet::iterator iter, iter_next;
  353. Point offset(-geometry->offsetLeft(), -geometry->offsetTop());
  354. for (iter = layout.begin();iter != layout.end();iter = iter_next) {
  355. iter_next = iter; ++iter_next;
  356. iter->dimensions = iter->dimensions.translate(offset);
  357. if (iter->dimensions.enclosed_by(geometry->getRect()))
  358. continue;
  359. iter->dimensions = iter->dimensions.intersect(geometry->getRect());
  360. if (iter->dimensions.is_empty()) {
  361. layout.remove_screen(iter->id);
  362. }
  363. }
  364. #endif
  365. // Make sure that we have at least one screen
  366. if (layout.num_screens() == 0)
  367. layout.add_screen(rfb::Screen(0, 0, 0, geometry->width(),
  368. geometry->height(), 0));
  369. return layout;
  370. }
  371. #ifdef HAVE_XRANDR
  372. /* Get the biggest mode which is equal or smaller to requested
  373. size. If no such mode exists, return the smallest. */
  374. static void GetSmallerMode(XRRScreenResources *res,
  375. XRROutputInfo *output,
  376. unsigned int *width, unsigned int *height)
  377. {
  378. XRRModeInfo best = {};
  379. XRRModeInfo smallest = {};
  380. smallest.width = -1;
  381. smallest.height = -1;
  382. for (int i = 0; i < res->nmode; i++) {
  383. for (int j = 0; j < output->nmode; j++) {
  384. if (output->modes[j] == res->modes[i].id) {
  385. if ((res->modes[i].width > best.width && res->modes[i].width <= *width) &&
  386. (res->modes[i].height > best.height && res->modes[i].height <= *height)) {
  387. best = res->modes[i];
  388. }
  389. if ((res->modes[i].width < smallest.width) && res->modes[i].height < smallest.height) {
  390. smallest = res->modes[i];
  391. }
  392. }
  393. }
  394. }
  395. if (best.id == 0 && smallest.id != 0) {
  396. best = smallest;
  397. }
  398. *width = best.width;
  399. *height = best.height;
  400. }
  401. #endif /* HAVE_XRANDR */
  402. unsigned int XDesktop::setScreenLayout(int fb_width, int fb_height,
  403. const rfb::ScreenSet& layout)
  404. {
  405. #ifdef HAVE_XRANDR
  406. char buffer[2048];
  407. vlog.debug("Got request for framebuffer resize to %dx%d",
  408. fb_width, fb_height);
  409. layout.print(buffer, sizeof(buffer));
  410. vlog.debug("%s", buffer);
  411. XRRScreenResources *res = XRRGetScreenResources(dpy, DefaultRootWindow(dpy));
  412. if (!res) {
  413. vlog.error("XRRGetScreenResources failed");
  414. return rfb::resultProhibited;
  415. }
  416. vncSetGlueContext(dpy, res);
  417. /* The client may request a screen layout which is not supported by
  418. the Xserver. This happens, for example, when adjusting the size
  419. of a non-fullscreen vncviewer window. To handle this and other
  420. cases, we first call tryScreenLayout. If this fails, we try to
  421. adjust the request to one screen with a smaller mode. */
  422. vlog.debug("Testing screen layout");
  423. unsigned int tryresult = ::tryScreenLayout(fb_width, fb_height, layout, &outputIdMap);
  424. rfb::ScreenSet adjustedLayout;
  425. if (tryresult == rfb::resultSuccess) {
  426. adjustedLayout = layout;
  427. } else {
  428. vlog.debug("Impossible layout - trying to adjust");
  429. ScreenSet::const_iterator firstscreen = layout.begin();
  430. adjustedLayout.add_screen(*firstscreen);
  431. ScreenSet::iterator iter = adjustedLayout.begin();
  432. RROutput outputId = None;
  433. for (int i = 0;i < vncRandRGetOutputCount();i++) {
  434. unsigned int oi = vncRandRGetOutputId(i);
  435. /* Known? */
  436. if (outputIdMap.count(oi) == 0)
  437. continue;
  438. /* Find the corresponding screen... */
  439. if (iter->id == outputIdMap[oi]) {
  440. outputId = oi;
  441. } else {
  442. outputIdMap.erase(oi);
  443. }
  444. }
  445. /* New screen */
  446. if (outputId == None) {
  447. int i = getPreferredScreenOutput(&outputIdMap, std::set<unsigned int>());
  448. if (i != -1) {
  449. outputId = vncRandRGetOutputId(i);
  450. }
  451. }
  452. if (outputId == None) {
  453. vlog.debug("Resize adjust: Could not find corresponding screen");
  454. XRRFreeScreenResources(res);
  455. return rfb::resultInvalid;
  456. }
  457. XRROutputInfo *output = XRRGetOutputInfo(dpy, res, outputId);
  458. if (!output) {
  459. vlog.debug("Resize adjust: XRRGetOutputInfo failed");
  460. XRRFreeScreenResources(res);
  461. return rfb::resultInvalid;
  462. }
  463. if (!output->crtc) {
  464. vlog.debug("Resize adjust: Selected output has no CRTC");
  465. XRRFreeScreenResources(res);
  466. XRRFreeOutputInfo(output);
  467. return rfb::resultInvalid;
  468. }
  469. XRRCrtcInfo *crtc = XRRGetCrtcInfo(dpy, res, output->crtc);
  470. if (!crtc) {
  471. vlog.debug("Resize adjust: XRRGetCrtcInfo failed");
  472. XRRFreeScreenResources(res);
  473. XRRFreeOutputInfo(output);
  474. return rfb::resultInvalid;
  475. }
  476. unsigned int swidth = iter->dimensions.width();
  477. unsigned int sheight = iter->dimensions.height();
  478. switch (crtc->rotation) {
  479. case RR_Rotate_90:
  480. case RR_Rotate_270:
  481. unsigned int swap = swidth;
  482. swidth = sheight;
  483. sheight = swap;
  484. break;
  485. }
  486. GetSmallerMode(res, output, &swidth, &sheight);
  487. XRRFreeOutputInfo(output);
  488. switch (crtc->rotation) {
  489. case RR_Rotate_90:
  490. case RR_Rotate_270:
  491. unsigned int swap = swidth;
  492. swidth = sheight;
  493. sheight = swap;
  494. break;
  495. }
  496. XRRFreeCrtcInfo(crtc);
  497. if (sheight != 0 && swidth != 0) {
  498. vlog.debug("Adjusted resize request to %dx%d", swidth, sheight);
  499. iter->dimensions.setXYWH(0, 0, swidth, sheight);
  500. fb_width = swidth;
  501. fb_height = sheight;
  502. } else {
  503. vlog.error("Failed to find smaller or equal screen size");
  504. XRRFreeScreenResources(res);
  505. return rfb::resultInvalid;
  506. }
  507. }
  508. vlog.debug("Changing screen layout");
  509. unsigned int ret = ::setScreenLayout(fb_width, fb_height, adjustedLayout, &outputIdMap);
  510. XRRFreeScreenResources(res);
  511. /* Send a dummy event to the root window. When this event is seen,
  512. earlier change events (ConfigureNotify and/or CrtcChange) have
  513. been processed. An Expose event is used for simplicity; does not
  514. require any Atoms, and will not affect other applications. */
  515. unsigned long serial = XNextRequest(dpy);
  516. XExposeEvent ev = {}; /* zero x, y, width, height, count */
  517. ev.type = Expose;
  518. ev.display = dpy;
  519. ev.window = DefaultRootWindow(dpy);
  520. if (XSendEvent(dpy, DefaultRootWindow(dpy), False, ExposureMask, (XEvent*)&ev)) {
  521. while (randrSyncSerial < serial) {
  522. TXWindow::handleXEvents(dpy);
  523. }
  524. } else {
  525. vlog.error("XSendEvent failed");
  526. }
  527. /* The protocol requires that an error is returned if the requested
  528. layout could not be set. This is checked by
  529. VNCSConnectionST::setDesktopSize. Another ExtendedDesktopSize
  530. with reason=0 will be sent in response to the changes seen by the
  531. event handler. */
  532. if (adjustedLayout != layout)
  533. return rfb::resultInvalid;
  534. // Explicitly update the server state with the result as there
  535. // can be corner cases where we don't get feedback from the X server
  536. server->setScreenLayout(computeScreenLayout());
  537. return ret;
  538. #else
  539. return rfb::resultProhibited;
  540. #endif /* HAVE_XRANDR */
  541. }
  542. bool XDesktop::handleGlobalEvent(XEvent* ev) {
  543. if (ev->type == xkbEventBase + XkbEventCode) {
  544. XkbEvent *kb = (XkbEvent *)ev;
  545. if (kb->any.xkb_type != XkbIndicatorStateNotify)
  546. return false;
  547. vlog.debug("Got indicator update, mask is now 0x%x", kb->indicators.state);
  548. ledState = 0;
  549. for (int i = 0; i < XDESKTOP_N_LEDS; i++) {
  550. if (kb->indicators.state & ledMasks[i])
  551. ledState |= 1u << i;
  552. }
  553. if (running)
  554. server->setLEDState(ledState);
  555. return true;
  556. #ifdef HAVE_XDAMAGE
  557. } else if (ev->type == xdamageEventBase) {
  558. XDamageNotifyEvent* dev;
  559. Rect rect;
  560. if (!running)
  561. return true;
  562. dev = (XDamageNotifyEvent*)ev;
  563. rect.setXYWH(dev->area.x, dev->area.y, dev->area.width, dev->area.height);
  564. rect = rect.translate(Point(-geometry->offsetLeft(),
  565. -geometry->offsetTop()));
  566. server->add_changed(rect);
  567. return true;
  568. #endif
  569. #ifdef HAVE_XFIXES
  570. } else if (ev->type == xfixesEventBase + XFixesCursorNotify) {
  571. XFixesCursorNotifyEvent* cev;
  572. if (!running)
  573. return true;
  574. cev = (XFixesCursorNotifyEvent*)ev;
  575. if (cev->subtype != XFixesDisplayCursorNotify)
  576. return false;
  577. return setCursor();
  578. #endif
  579. #ifdef HAVE_XRANDR
  580. } else if (ev->type == Expose) {
  581. XExposeEvent* eev = (XExposeEvent*)ev;
  582. randrSyncSerial = eev->serial;
  583. return false;
  584. } else if (ev->type == ConfigureNotify) {
  585. XConfigureEvent* cev = (XConfigureEvent*)ev;
  586. if (cev->window != DefaultRootWindow(dpy)) {
  587. return false;
  588. }
  589. XRRUpdateConfiguration(ev);
  590. geometry->recalc(cev->width, cev->height);
  591. if (!running) {
  592. return false;
  593. }
  594. if ((cev->width != pb->width() || (cev->height != pb->height()))) {
  595. // Recreate pixel buffer
  596. ImageFactory factory((bool)useShm);
  597. delete pb;
  598. pb = new XPixelBuffer(dpy, factory, geometry->getRect());
  599. server->setPixelBuffer(pb, computeScreenLayout());
  600. // Mark entire screen as changed
  601. server->add_changed(rfb::Region(Rect(0, 0, cev->width, cev->height)));
  602. }
  603. return true;
  604. } else if (ev->type == xrandrEventBase + RRNotify) {
  605. XRRNotifyEvent* rev = (XRRNotifyEvent*)ev;
  606. if (rev->window != DefaultRootWindow(dpy)) {
  607. return false;
  608. }
  609. if (!running)
  610. return false;
  611. if (rev->subtype == RRNotify_CrtcChange) {
  612. server->setScreenLayout(computeScreenLayout());
  613. }
  614. return true;
  615. #endif
  616. }
  617. return false;
  618. }
  619. void XDesktop::queryApproved()
  620. {
  621. assert(isRunning());
  622. server->approveConnection(queryConnectSock, true, 0);
  623. queryConnectSock = 0;
  624. }
  625. void XDesktop::queryRejected()
  626. {
  627. assert(isRunning());
  628. server->approveConnection(queryConnectSock, false,
  629. "Connection rejected by local user");
  630. queryConnectSock = 0;
  631. }
  632. bool XDesktop::setCursor()
  633. {
  634. XFixesCursorImage *cim;
  635. cim = XFixesGetCursorImage(dpy);
  636. if (cim == NULL)
  637. return false;
  638. // Copied from XserverDesktop::setCursor() in
  639. // unix/xserver/hw/vnc/XserverDesktop.cc and adapted to
  640. // handle long -> U32 conversion for 64-bit Xlib
  641. rdr::U8* cursorData;
  642. rdr::U8 *out;
  643. const unsigned long *pixels;
  644. cursorData = new rdr::U8[cim->width * cim->height * 4];
  645. // Un-premultiply alpha
  646. pixels = cim->pixels;
  647. out = cursorData;
  648. for (int y = 0; y < cim->height; y++) {
  649. for (int x = 0; x < cim->width; x++) {
  650. rdr::U8 alpha;
  651. rdr::U32 pixel = *pixels++;
  652. alpha = (pixel >> 24) & 0xff;
  653. if (alpha == 0)
  654. alpha = 1; // Avoid division by zero
  655. *out++ = ((pixel >> 16) & 0xff) * 255/alpha;
  656. *out++ = ((pixel >> 8) & 0xff) * 255/alpha;
  657. *out++ = ((pixel >> 0) & 0xff) * 255/alpha;
  658. *out++ = ((pixel >> 24) & 0xff);
  659. }
  660. }
  661. try {
  662. server->setCursor(cim->width, cim->height, Point(cim->xhot, cim->yhot),
  663. cursorData);
  664. } catch (rdr::Exception& e) {
  665. vlog.error("XserverDesktop::setCursor: %s",e.str());
  666. }
  667. delete [] cursorData;
  668. XFree(cim);
  669. return true;
  670. }