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.

XserverDesktop.cc 36KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. *
  3. * This is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This software is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this software; if not, write to the Free Software
  15. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  16. * USA.
  17. */
  18. //
  19. // XserverDesktop.cxx
  20. //
  21. #include <stdio.h>
  22. #include <strings.h>
  23. #include <unistd.h>
  24. #include <pwd.h>
  25. #include <sys/types.h>
  26. #include <sys/stat.h>
  27. #include <fcntl.h>
  28. #include <sys/utsname.h>
  29. #include <network/TcpSocket.h>
  30. #include <rfb/Exception.h>
  31. #include <rfb/VNCServerST.h>
  32. #include <rfb/HTTPServer.h>
  33. #include <rfb/LogWriter.h>
  34. #include <rfb/Configuration.h>
  35. #include "XserverDesktop.h"
  36. #include "vncExtInit.h"
  37. extern "C" {
  38. #define public c_public
  39. #define class c_class
  40. // windowTable is in globals.h in XFree 4, but not in XFree 3 unfortunately
  41. extern WindowPtr *WindowTable;
  42. extern char *display;
  43. #include "inputstr.h"
  44. #include "servermd.h"
  45. #include "colormapst.h"
  46. #include "resource.h"
  47. #include "cursorstr.h"
  48. #include "windowstr.h"
  49. #define XK_CYRILLIC
  50. #include "keysym.h"
  51. #undef public
  52. #undef class
  53. }
  54. using namespace rfb;
  55. using namespace network;
  56. static LogWriter vlog("XserverDesktop");
  57. rfb::IntParameter deferUpdateTime("DeferUpdate",
  58. "Time in milliseconds to defer updates",40);
  59. rfb::BoolParameter alwaysSetDeferUpdateTimer("AlwaysSetDeferUpdateTimer",
  60. "Always reset the defer update timer on every change",false);
  61. IntParameter queryConnectTimeout("QueryConnectTimeout",
  62. "Number of seconds to show the Accept Connection dialog before "
  63. "rejecting the connection",
  64. 10);
  65. static KeyCode KeysymToKeycode(KeySymsPtr keymap, KeySym ks, int* col);
  66. static rdr::U8 reverseBits[] = {
  67. 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0,
  68. 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
  69. 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4,
  70. 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
  71. 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc,
  72. 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
  73. 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca,
  74. 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
  75. 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6,
  76. 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
  77. 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1,
  78. 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
  79. 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9,
  80. 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
  81. 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd,
  82. 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
  83. 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3,
  84. 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
  85. 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7,
  86. 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
  87. 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf,
  88. 0x3f, 0xbf, 0x7f, 0xff
  89. };
  90. class FileHTTPServer : public rfb::HTTPServer {
  91. public:
  92. FileHTTPServer(XserverDesktop* d) : desktop(d) {}
  93. virtual ~FileHTTPServer() {}
  94. virtual rdr::InStream* getFile(const char* name, const char** contentType,
  95. int* contentLength, time_t* lastModified)
  96. {
  97. if (name[0] != '/' || strstr(name, "..") != 0) {
  98. vlog.info("http request was for invalid file name");
  99. return 0;
  100. }
  101. if (strcmp(name, "/") == 0) name = "/index.vnc";
  102. CharArray httpDirStr(httpDir.getData());
  103. CharArray fname(strlen(httpDirStr.buf)+strlen(name)+1);
  104. sprintf(fname.buf, "%s%s", httpDirStr.buf, name);
  105. int fd = open(fname.buf, O_RDONLY);
  106. if (fd < 0) return 0;
  107. rdr::InStream* is = new rdr::FdInStream(fd, -1, 0, true);
  108. *contentType = guessContentType(name, *contentType);
  109. if (strlen(name) > 4 && strcasecmp(&name[strlen(name)-4], ".vnc") == 0) {
  110. is = new rdr::SubstitutingInStream(is, desktop, 20);
  111. *contentType = "text/html";
  112. } else {
  113. struct stat st;
  114. if (fstat(fd, &st) == 0) {
  115. *contentLength = st.st_size;
  116. *lastModified = st.st_mtime;
  117. }
  118. }
  119. return is;
  120. }
  121. XserverDesktop* desktop;
  122. };
  123. XserverDesktop::XserverDesktop(ScreenPtr pScreen_,
  124. network::TcpListener* listener_,
  125. network::TcpListener* httpListener_,
  126. const char* name, void* fbptr)
  127. : pScreen(pScreen_), deferredUpdateTimer(0), dummyTimer(0),
  128. server(0), httpServer(0),
  129. listener(listener_), httpListener(httpListener_),
  130. cmap(0), deferredUpdateTimerSet(false),
  131. grabbing(false), ignoreHooks_(false), directFbptr(fbptr != 0),
  132. oldButtonMask(0),
  133. queryConnectId(0)
  134. {
  135. int i;
  136. format.depth = pScreen->rootDepth;
  137. for (i = 0; i < screenInfo.numPixmapFormats; i++) {
  138. if (screenInfo.formats[i].depth == format.depth) {
  139. format.bpp = screenInfo.formats[i].bitsPerPixel;
  140. break;
  141. }
  142. }
  143. if (i == screenInfo.numPixmapFormats) {
  144. fprintf(stderr,"no pixmap format for root depth???\n");
  145. abort();
  146. }
  147. format.bigEndian = (screenInfo.imageByteOrder == MSBFirst);
  148. VisualPtr vis;
  149. for (i = 0; i < pScreen->numVisuals; i++) {
  150. if (pScreen->visuals[i].vid == pScreen->rootVisual) {
  151. vis = &pScreen->visuals[i];
  152. break;
  153. }
  154. }
  155. if (i == pScreen->numVisuals) {
  156. fprintf(stderr,"no visual rec for root visual???\n");
  157. abort();
  158. }
  159. format.trueColour = (vis->c_class == TrueColor);
  160. if (!format.trueColour && format.bpp != 8)
  161. throw rfb::Exception("X server uses unsupported visual");
  162. format.redShift = ffs(vis->redMask) - 1;
  163. format.greenShift = ffs(vis->greenMask) - 1;
  164. format.blueShift = ffs(vis->blueMask) - 1;
  165. format.redMax = vis->redMask >> format.redShift;
  166. format.greenMax = vis->greenMask >> format.greenShift;
  167. format.blueMax = vis->blueMask >> format.blueShift;
  168. width_ = pScreen->width;
  169. height_ = pScreen->height;
  170. if (fbptr)
  171. data = (rdr::U8*)fbptr;
  172. else
  173. data = new rdr::U8[pScreen->width * pScreen->height * (format.bpp/8)];
  174. colourmap = this;
  175. serverReset(pScreen);
  176. server = new VNCServerST(name, this);
  177. server->setPixelBuffer(this);
  178. server->setQueryConnectionHandler(this);
  179. if (httpListener)
  180. httpServer = new FileHTTPServer(this);
  181. }
  182. XserverDesktop::~XserverDesktop()
  183. {
  184. if (!directFbptr)
  185. delete [] data;
  186. TimerFree(deferredUpdateTimer);
  187. TimerFree(dummyTimer);
  188. delete httpServer;
  189. delete server;
  190. }
  191. void XserverDesktop::serverReset(ScreenPtr pScreen_)
  192. {
  193. pScreen = pScreen_;
  194. XID* ids = new XID[pScreen->maxInstalledCmaps];
  195. int nmaps = (*pScreen->ListInstalledColormaps)(pScreen, ids);
  196. cmap = (ColormapPtr)LookupIDByType(ids[0], RT_COLORMAP);
  197. delete [] ids;
  198. }
  199. char* XserverDesktop::substitute(const char* varName)
  200. {
  201. if (strcmp(varName, "$$") == 0) {
  202. return rfb::strDup("$");
  203. }
  204. if (strcmp(varName, "$PORT") == 0) {
  205. char* str = new char[10];
  206. sprintf(str, "%d", listener ? listener->getMyPort() : 0);
  207. return str;
  208. }
  209. if (strcmp(varName, "$WIDTH") == 0) {
  210. char* str = new char[10];
  211. sprintf(str, "%d", width());
  212. return str;
  213. }
  214. if (strcmp(varName, "$HEIGHT") == 0) {
  215. char* str = new char[10];
  216. sprintf(str, "%d", height());
  217. return str;
  218. }
  219. if (strcmp(varName, "$APPLETWIDTH") == 0) {
  220. char* str = new char[10];
  221. sprintf(str, "%d", width());
  222. return str;
  223. }
  224. if (strcmp(varName, "$APPLETHEIGHT") == 0) {
  225. char* str = new char[10];
  226. sprintf(str, "%d", height() + 32);
  227. return str;
  228. }
  229. if (strcmp(varName, "$DESKTOP") == 0) {
  230. return rfb::strDup(server->getName());
  231. }
  232. if (strcmp(varName, "$DISPLAY") == 0) {
  233. struct utsname uts;
  234. uname(&uts);
  235. char* str = new char[256];
  236. strncat(str, uts.nodename, 240);
  237. strcat(str, ":");
  238. strncat(str, display, 10);
  239. return str;
  240. }
  241. if (strcmp(varName, "$USER") == 0) {
  242. struct passwd* user = getpwuid(getuid());
  243. return rfb::strDup(user ? user->pw_name : "?");
  244. }
  245. return 0;
  246. }
  247. rfb::VNCServerST::queryResult
  248. XserverDesktop::queryConnection(network::Socket* sock,
  249. const char* userName,
  250. char** reason) {
  251. if (queryConnectId) {
  252. *reason = strDup("Another connection is currently being queried.");
  253. return rfb::VNCServerST::REJECT;
  254. }
  255. queryConnectAddress.replaceBuf(sock->getPeerAddress());
  256. if (!userName)
  257. userName = "(anonymous)";
  258. queryConnectUsername.replaceBuf(strDup(userName));
  259. queryConnectId = sock;
  260. vncQueryConnect(this, sock);
  261. return rfb::VNCServerST::PENDING;
  262. }
  263. void XserverDesktop::setColormap(ColormapPtr cmap_)
  264. {
  265. if (cmap != cmap_) {
  266. cmap = cmap_;
  267. setColourMapEntries(0, 0);
  268. }
  269. }
  270. void XserverDesktop::setColourMapEntries(ColormapPtr pColormap, int ndef,
  271. xColorItem* pdef)
  272. {
  273. if (cmap != pColormap || ndef <= 0) return;
  274. int first = pdef[0].pixel;
  275. int n = 1;
  276. for (int i = 1; i < ndef; i++) {
  277. if (first + n == pdef[i].pixel) {
  278. n++;
  279. } else {
  280. setColourMapEntries(first, n);
  281. first = pdef[i].pixel;
  282. n = 1;
  283. }
  284. }
  285. setColourMapEntries(first, n);
  286. }
  287. void XserverDesktop::setColourMapEntries(int firstColour, int nColours)
  288. {
  289. try {
  290. server->setColourMapEntries(firstColour, nColours);
  291. } catch (rdr::Exception& e) {
  292. vlog.error("XserverDesktop::setColourMapEntries: %s",e.str());
  293. }
  294. }
  295. void XserverDesktop::bell()
  296. {
  297. server->bell();
  298. }
  299. void XserverDesktop::serverCutText(const char* str, int len)
  300. {
  301. try {
  302. server->serverCutText(str, len);
  303. } catch (rdr::Exception& e) {
  304. vlog.error("XserverDesktop::serverCutText: %s",e.str());
  305. }
  306. }
  307. void XserverDesktop::setCursor(CursorPtr cursor)
  308. {
  309. try {
  310. int w = cursor->bits->width;
  311. int h = cursor->bits->height;
  312. rdr::U8* cursorData = new rdr::U8[w * h * (getPF().bpp / 8)];
  313. xColorItem fg, bg;
  314. fg.red = cursor->foreRed;
  315. fg.green = cursor->foreGreen;
  316. fg.blue = cursor->foreBlue;
  317. FakeAllocColor(cmap, &fg);
  318. bg.red = cursor->backRed;
  319. bg.green = cursor->backGreen;
  320. bg.blue = cursor->backBlue;
  321. FakeAllocColor(cmap, &bg);
  322. FakeFreeColor(cmap, fg.pixel);
  323. FakeFreeColor(cmap, bg.pixel);
  324. int xMaskBytesPerRow = BitmapBytePad(w);
  325. for (int y = 0; y < h; y++) {
  326. for (int x = 0; x < w; x++) {
  327. int byte = y * xMaskBytesPerRow + x / 8;
  328. #if (BITMAP_BIT_ORDER == MSBFirst)
  329. int bit = 7 - x % 8;
  330. #else
  331. int bit = x % 8;
  332. #endif
  333. switch (getPF().bpp) {
  334. case 8:
  335. ((rdr::U8*)cursorData)[y * w + x]
  336. = (cursor->bits->source[byte] & (1 << bit)) ? fg.pixel : bg.pixel;
  337. break;
  338. case 16:
  339. ((rdr::U16*)cursorData)[y * w + x]
  340. = (cursor->bits->source[byte] & (1 << bit)) ? fg.pixel : bg.pixel;
  341. break;
  342. case 32:
  343. ((rdr::U32*)cursorData)[y * w + x]
  344. = (cursor->bits->source[byte] & (1 << bit)) ? fg.pixel : bg.pixel;
  345. break;
  346. }
  347. }
  348. }
  349. int rfbMaskBytesPerRow = (w + 7) / 8;
  350. rdr::U8* cursorMask = new rdr::U8[rfbMaskBytesPerRow * h];
  351. for (int j = 0; j < h; j++) {
  352. for (int i = 0; i < rfbMaskBytesPerRow; i++)
  353. #if (BITMAP_BIT_ORDER == MSBFirst)
  354. cursorMask[j * rfbMaskBytesPerRow + i]
  355. = cursor->bits->mask[j * xMaskBytesPerRow + i];
  356. #else
  357. cursorMask[j * rfbMaskBytesPerRow + i]
  358. = reverseBits[cursor->bits->mask[j * xMaskBytesPerRow + i]];
  359. #endif
  360. }
  361. server->setCursor(cursor->bits->width, cursor->bits->height,
  362. Point(cursor->bits->xhot, cursor->bits->yhot),
  363. cursorData, cursorMask);
  364. server->tryUpdate();
  365. delete [] cursorData;
  366. delete [] cursorMask;
  367. } catch (rdr::Exception& e) {
  368. vlog.error("XserverDesktop::setCursor: %s",e.str());
  369. }
  370. }
  371. static void printRegion(RegionPtr reg)
  372. {
  373. int nrects = REGION_NUM_RECTS(reg);
  374. fprintf(stderr,"Region num rects %2d extents %3d,%3d %3dx%3d\n",nrects,
  375. (REGION_EXTENTS(pScreen,reg))->x1,
  376. (REGION_EXTENTS(pScreen,reg))->y1,
  377. (REGION_EXTENTS(pScreen,reg))->x2-(REGION_EXTENTS(pScreen,reg))->x1,
  378. (REGION_EXTENTS(pScreen,reg))->y2-(REGION_EXTENTS(pScreen,reg))->y1);
  379. for (int i = 0; i < nrects; i++) {
  380. fprintf(stderr," rect %3d,%3d %3dx%3d\n",
  381. REGION_RECTS(reg)[i].x1,
  382. REGION_RECTS(reg)[i].y1,
  383. REGION_RECTS(reg)[i].x2-REGION_RECTS(reg)[i].x1,
  384. REGION_RECTS(reg)[i].y2-REGION_RECTS(reg)[i].y1);
  385. }
  386. }
  387. CARD32 XserverDesktop::deferredUpdateTimerCallback(OsTimerPtr timer,
  388. CARD32 now, pointer arg)
  389. {
  390. XserverDesktop* desktop = (XserverDesktop*)arg;
  391. desktop->deferredUpdateTimerSet = false;
  392. try {
  393. desktop->server->tryUpdate();
  394. } catch (rdr::Exception& e) {
  395. vlog.error("XserverDesktop::deferredUpdateTimerCallback: %s",e.str());
  396. }
  397. return 0;
  398. }
  399. void XserverDesktop::deferUpdate()
  400. {
  401. if (deferUpdateTime != 0) {
  402. if (!deferredUpdateTimerSet || alwaysSetDeferUpdateTimer) {
  403. deferredUpdateTimerSet = true;
  404. deferredUpdateTimer = TimerSet(deferredUpdateTimer, 0,
  405. deferUpdateTime,
  406. deferredUpdateTimerCallback, this);
  407. }
  408. } else {
  409. server->tryUpdate();
  410. }
  411. }
  412. void XserverDesktop::add_changed(RegionPtr reg)
  413. {
  414. if (ignoreHooks_) return;
  415. if (grabbing) return;
  416. try {
  417. rfb::Region rfbReg;
  418. rfbReg.setExtentsAndOrderedRects((ShortRect*)REGION_EXTENTS(pScreen, reg),
  419. REGION_NUM_RECTS(reg),
  420. (ShortRect*)REGION_RECTS(reg));
  421. server->add_changed(rfbReg);
  422. deferUpdate();
  423. } catch (rdr::Exception& e) {
  424. vlog.error("XserverDesktop::add_changed: %s",e.str());
  425. }
  426. }
  427. void XserverDesktop::add_copied(RegionPtr dst, int dx, int dy)
  428. {
  429. if (ignoreHooks_) return;
  430. if (grabbing) return;
  431. try {
  432. rfb::Region rfbReg;
  433. rfbReg.setExtentsAndOrderedRects((ShortRect*)REGION_EXTENTS(pScreen, dst),
  434. REGION_NUM_RECTS(dst),
  435. (ShortRect*)REGION_RECTS(dst));
  436. server->add_copied(rfbReg, rfb::Point(dx, dy));
  437. deferUpdate();
  438. } catch (rdr::Exception& e) {
  439. vlog.error("XserverDesktop::add_copied: %s",e.str());
  440. }
  441. }
  442. void XserverDesktop::positionCursor()
  443. {
  444. if (!cursorPos.equals(oldCursorPos)) {
  445. oldCursorPos = cursorPos;
  446. (*pScreen->SetCursorPosition) (pScreen, cursorPos.x, cursorPos.y, FALSE);
  447. server->setCursorPos(cursorPos);
  448. server->tryUpdate();
  449. }
  450. }
  451. void XserverDesktop::blockHandler(fd_set* fds)
  452. {
  453. try {
  454. ScreenPtr screenWithCursor = GetCurrentRootWindow()->drawable.pScreen;
  455. if (screenWithCursor == pScreen) {
  456. int x, y;
  457. GetSpritePosition(&x, &y);
  458. if (x != cursorPos.x || y != cursorPos.y) {
  459. cursorPos = oldCursorPos = Point(x, y);
  460. server->setCursorPos(cursorPos);
  461. server->tryUpdate();
  462. }
  463. }
  464. if (listener)
  465. FD_SET(listener->getFd(), fds);
  466. if (httpListener)
  467. FD_SET(httpListener->getFd(), fds);
  468. std::list<Socket*> sockets;
  469. server->getSockets(&sockets);
  470. std::list<Socket*>::iterator i;
  471. for (i = sockets.begin(); i != sockets.end(); i++) {
  472. int fd = (*i)->getFd();
  473. if ((*i)->isShutdown()) {
  474. vlog.debug("client gone, sock %d",fd);
  475. server->removeSocket(*i);
  476. vncClientGone(fd);
  477. delete (*i);
  478. } else {
  479. FD_SET(fd, fds);
  480. }
  481. }
  482. if (httpServer) {
  483. httpServer->getSockets(&sockets);
  484. for (i = sockets.begin(); i != sockets.end(); i++) {
  485. int fd = (*i)->getFd();
  486. if ((*i)->isShutdown()) {
  487. vlog.debug("http client gone, sock %d",fd);
  488. httpServer->removeSocket(*i);
  489. delete (*i);
  490. } else {
  491. FD_SET(fd, fds);
  492. }
  493. }
  494. }
  495. } catch (rdr::Exception& e) {
  496. vlog.error("XserverDesktop::blockHandler: %s",e.str());
  497. }
  498. }
  499. static CARD32 dummyTimerCallback(OsTimerPtr timer, CARD32 now, pointer arg) {
  500. return 0;
  501. }
  502. void XserverDesktop::wakeupHandler(fd_set* fds, int nfds)
  503. {
  504. try {
  505. if (nfds >= 1) {
  506. if (listener) {
  507. if (FD_ISSET(listener->getFd(), fds)) {
  508. FD_CLR(listener->getFd(), fds);
  509. Socket* sock = listener->accept();
  510. server->addSocket(sock);
  511. vlog.debug("new client, sock %d",sock->getFd());
  512. }
  513. }
  514. if (httpListener) {
  515. if (FD_ISSET(httpListener->getFd(), fds)) {
  516. FD_CLR(httpListener->getFd(), fds);
  517. Socket* sock = httpListener->accept();
  518. httpServer->addSocket(sock);
  519. vlog.debug("new http client, sock %d",sock->getFd());
  520. }
  521. }
  522. std::list<Socket*> sockets;
  523. server->getSockets(&sockets);
  524. std::list<Socket*>::iterator i;
  525. for (i = sockets.begin(); i != sockets.end(); i++) {
  526. int fd = (*i)->getFd();
  527. if (FD_ISSET(fd, fds)) {
  528. FD_CLR(fd, fds);
  529. server->processSocketEvent(*i);
  530. }
  531. }
  532. if (httpServer) {
  533. httpServer->getSockets(&sockets);
  534. for (i = sockets.begin(); i != sockets.end(); i++) {
  535. int fd = (*i)->getFd();
  536. if (FD_ISSET(fd, fds)) {
  537. FD_CLR(fd, fds);
  538. httpServer->processSocketEvent(*i);
  539. }
  540. }
  541. }
  542. positionCursor();
  543. }
  544. int timeout = server->checkTimeouts();
  545. if (timeout > 0) {
  546. // set a dummy timer just so we are guaranteed be called again next time.
  547. dummyTimer = TimerSet(dummyTimer, 0, timeout,
  548. dummyTimerCallback, 0);
  549. }
  550. } catch (rdr::Exception& e) {
  551. vlog.error("XserverDesktop::wakeupHandler: %s",e.str());
  552. }
  553. }
  554. void XserverDesktop::addClient(Socket* sock, bool reverse)
  555. {
  556. vlog.debug("new client, sock %d reverse %d",sock->getFd(),reverse);
  557. server->addSocket(sock, reverse);
  558. }
  559. void XserverDesktop::disconnectClients()
  560. {
  561. vlog.debug("disconnecting all clients");
  562. return server->closeClients("Disconnection from server end");
  563. }
  564. int XserverDesktop::getQueryTimeout(void* opaqueId,
  565. const char** address,
  566. const char** username)
  567. {
  568. if (opaqueId && queryConnectId == opaqueId) {
  569. vlog.info("address=%s, username=%s, timeout=%d",
  570. queryConnectAddress.buf, queryConnectUsername.buf,
  571. (int)queryConnectTimeout);
  572. if (address) *address = queryConnectAddress.buf;
  573. if (username) *username = queryConnectUsername.buf;
  574. return queryConnectTimeout;
  575. }
  576. return 0;
  577. }
  578. void XserverDesktop::approveConnection(void* opaqueId, bool accept,
  579. const char* rejectMsg)
  580. {
  581. if (queryConnectId == opaqueId) {
  582. server->approveConnection((network::Socket*)opaqueId, accept, rejectMsg);
  583. queryConnectId = 0;
  584. }
  585. }
  586. ///////////////////////////////////////////////////////////////////////////
  587. //
  588. // SDesktop callbacks
  589. void XserverDesktop::pointerEvent(const Point& pos, int buttonMask)
  590. {
  591. xEvent ev;
  592. DevicePtr dev = LookupPointerDevice();
  593. // SetCursorPosition seems to be very expensive (at least on XFree86 3.3.6
  594. // for S3), so we delay calling it until positionCursor() is called at the
  595. // end of processing a load of RFB.
  596. //(*pScreen->SetCursorPosition) (pScreen, pos.x, pos.y, FALSE);
  597. NewCurrentScreen(pScreen, pos.x, pos.y);
  598. ev.u.u.type = MotionNotify;
  599. ev.u.u.detail = 0;
  600. ev.u.keyButtonPointer.rootX = pos.x;
  601. ev.u.keyButtonPointer.rootY = pos.y;
  602. ev.u.keyButtonPointer.time = GetTimeInMillis();
  603. if (!pos.equals(cursorPos))
  604. (*dev->processInputProc)(&ev, (DeviceIntPtr)dev, 1);
  605. for (int i = 0; i < 5; i++) {
  606. if ((buttonMask ^ oldButtonMask) & (1<<i)) {
  607. // Do not use the pointer mapping. Treat VNC buttons as logical
  608. // buttons.
  609. ev.u.u.detail = i + 1;
  610. ev.u.u.type = (buttonMask & (1<<i)) ? ButtonPress : ButtonRelease;
  611. (*dev->processInputProc)(&ev, (DeviceIntPtr)dev, 1);
  612. }
  613. }
  614. cursorPos = pos;
  615. oldButtonMask = buttonMask;
  616. }
  617. void XserverDesktop::clientCutText(const char* str, int len)
  618. {
  619. vncClientCutText(str, len);
  620. }
  621. void XserverDesktop::grabRegion(const rfb::Region& region)
  622. {
  623. if (directFbptr) return;
  624. if (!pScreen->GetImage) {
  625. vlog.error("VNC error: pScreen->GetImage == 0");
  626. return;
  627. }
  628. grabbing = true;
  629. int bytesPerPixel = format.bpp/8;
  630. int bytesPerRow = pScreen->width * bytesPerPixel;
  631. std::vector<rfb::Rect> rects;
  632. std::vector<rfb::Rect>::iterator i;
  633. region.get_rects(&rects);
  634. for (i = rects.begin(); i != rects.end(); i++) {
  635. for (int y = i->tl.y; y < i->br.y; y++) {
  636. (*pScreen->GetImage) ((DrawablePtr)WindowTable[pScreen->myNum],
  637. i->tl.x, y, i->width(), 1,
  638. ZPixmap, (unsigned long)~0L,
  639. ((char*)data
  640. + y * bytesPerRow + i->tl.x * bytesPerPixel));
  641. }
  642. }
  643. grabbing = false;
  644. }
  645. void XserverDesktop::lookup(int index, int* r, int* g, int* b)
  646. {
  647. if ((cmap->c_class | DynamicClass) == DirectColor) {
  648. VisualPtr v = cmap->pVisual;
  649. *r = cmap->red [(index & v->redMask ) >> v->offsetRed ].co.local.red;
  650. *g = cmap->green[(index & v->greenMask) >> v->offsetGreen].co.local.green;
  651. *b = cmap->blue [(index & v->blueMask ) >> v->offsetBlue ].co.local.blue;
  652. } else {
  653. EntryPtr pent;
  654. pent = (EntryPtr)&cmap->red[index];
  655. if (pent->fShared) {
  656. *r = pent->co.shco.red->color;
  657. *g = pent->co.shco.green->color;
  658. *b = pent->co.shco.blue->color;
  659. } else {
  660. *r = pent->co.local.red;
  661. *g = pent->co.local.green;
  662. *b = pent->co.local.blue;
  663. }
  664. }
  665. }
  666. //
  667. // Keyboard handling
  668. //
  669. #define IS_PRESSED(keyc, keycode) \
  670. ((keyc)->down[(keycode) >> 3] & (1 << ((keycode) & 7)))
  671. // ModifierState is a class which helps simplify generating a "fake" press
  672. // or release of shift, ctrl, alt, etc. An instance of the class is created
  673. // for every modifier which may need to be pressed or released. Then either
  674. // press() or release() may be called to make sure that the corresponding keys
  675. // are in the right state. The destructor of the class automatically reverts
  676. // to the previous state. Each modifier may have multiple keys associated with
  677. // it, so in the case of a fake release, this may involve releasing more than
  678. // one key.
  679. class ModifierState {
  680. public:
  681. ModifierState(DeviceIntPtr dev_, int modIndex_)
  682. : dev(dev_), modIndex(modIndex_), nKeys(0), keys(0), pressed(false)
  683. {
  684. }
  685. ~ModifierState() {
  686. for (int i = 0; i < nKeys; i++)
  687. generateXKeyEvent(keys[i], !pressed);
  688. delete [] keys;
  689. }
  690. void press() {
  691. KeyClassPtr keyc = dev->key;
  692. if (!(keyc->state & (1<<modIndex))) {
  693. tempKeyEvent(keyc->modifierKeyMap[modIndex * keyc->maxKeysPerModifier],
  694. true);
  695. pressed = true;
  696. }
  697. }
  698. void release() {
  699. KeyClassPtr keyc = dev->key;
  700. if (keyc->state & (1<<modIndex)) {
  701. for (int k = 0; k < keyc->maxKeysPerModifier; k++) {
  702. int keycode
  703. = keyc->modifierKeyMap[modIndex * keyc->maxKeysPerModifier + k];
  704. if (keycode && IS_PRESSED(keyc, keycode))
  705. tempKeyEvent(keycode, false);
  706. }
  707. }
  708. }
  709. private:
  710. void tempKeyEvent(int keycode, bool down) {
  711. if (keycode) {
  712. if (!keys) keys = new int[dev->key->maxKeysPerModifier];
  713. keys[nKeys++] = keycode;
  714. generateXKeyEvent(keycode, down);
  715. }
  716. }
  717. void generateXKeyEvent(int keycode, bool down) {
  718. xEvent ev;
  719. ev.u.u.type = down ? KeyPress : KeyRelease;
  720. ev.u.u.detail = keycode;
  721. ev.u.keyButtonPointer.time = GetTimeInMillis();
  722. (*dev->c_public.processInputProc)(&ev, dev, 1);
  723. vlog.debug("fake keycode %d %s", keycode, down ? "down" : "up");
  724. }
  725. DeviceIntPtr dev;
  726. int modIndex;
  727. int nKeys;
  728. int* keys;
  729. bool pressed;
  730. };
  731. // altKeysym is a table of alternative keysyms which have the same meaning.
  732. struct altKeysym_t {
  733. KeySym a, b;
  734. };
  735. altKeysym_t altKeysym[] = {
  736. { XK_Shift_L, XK_Shift_R },
  737. { XK_Control_L, XK_Control_R },
  738. { XK_Meta_L, XK_Meta_R },
  739. { XK_Alt_L, XK_Alt_R },
  740. { XK_Super_L, XK_Super_R },
  741. { XK_Hyper_L, XK_Hyper_R },
  742. { XK_KP_Space, XK_space },
  743. { XK_KP_Tab, XK_Tab },
  744. { XK_KP_Enter, XK_Return },
  745. { XK_KP_F1, XK_F1 },
  746. { XK_KP_F2, XK_F2 },
  747. { XK_KP_F3, XK_F3 },
  748. { XK_KP_F4, XK_F4 },
  749. { XK_KP_Home, XK_Home },
  750. { XK_KP_Left, XK_Left },
  751. { XK_KP_Up, XK_Up },
  752. { XK_KP_Right, XK_Right },
  753. { XK_KP_Down, XK_Down },
  754. { XK_KP_Page_Up, XK_Page_Up },
  755. { XK_KP_Page_Down, XK_Page_Down },
  756. { XK_KP_End, XK_End },
  757. { XK_KP_Begin, XK_Begin },
  758. { XK_KP_Insert, XK_Insert },
  759. { XK_KP_Delete, XK_Delete },
  760. { XK_KP_Equal, XK_equal },
  761. { XK_KP_Multiply, XK_asterisk },
  762. { XK_KP_Add, XK_plus },
  763. { XK_KP_Separator, XK_comma },
  764. { XK_KP_Subtract, XK_minus },
  765. { XK_KP_Decimal, XK_period },
  766. { XK_KP_Divide, XK_slash },
  767. { XK_KP_0, XK_0 },
  768. { XK_KP_1, XK_1 },
  769. { XK_KP_2, XK_2 },
  770. { XK_KP_3, XK_3 },
  771. { XK_KP_4, XK_4 },
  772. { XK_KP_5, XK_5 },
  773. { XK_KP_6, XK_6 },
  774. { XK_KP_7, XK_7 },
  775. { XK_KP_8, XK_8 },
  776. { XK_KP_9, XK_9 },
  777. };
  778. // keyEvent() - work out the best keycode corresponding to the keysym sent by
  779. // the viewer. This is non-trivial because we can't assume much about the
  780. // local keyboard layout. We must also find out which column of the keyboard
  781. // mapping the keysym is in, and alter the shift state appropriately. Column 0
  782. // means both shift and "mode_switch" (AltGr) must be released, column 1 means
  783. // shift must be pressed and mode_switch released, column 2 means shift must be
  784. // released and mode_switch pressed, and column 3 means both shift and
  785. // mode_switch must be pressed.
  786. void XserverDesktop::keyEvent(rdr::U32 keysym, bool down)
  787. {
  788. if (keysym == XK_Caps_Lock) {
  789. vlog.debug("Ignoring caps lock");
  790. return;
  791. }
  792. DeviceIntPtr dev = (DeviceIntPtr)LookupKeyboardDevice();
  793. KeyClassPtr keyc = dev->key;
  794. KeySymsPtr keymap = &keyc->curKeySyms;
  795. // find which modifier Mode_switch is on.
  796. int modeSwitchMapIndex = 0;
  797. for (int i = 3; i < 8; i++) {
  798. for (int k = 0; k < keyc->maxKeysPerModifier; k++) {
  799. int keycode = keyc->modifierKeyMap[i * keyc->maxKeysPerModifier + k];
  800. for (int j = 0; j < keymap->mapWidth; j++) {
  801. if (keycode != 0 &&
  802. keymap->map[(keycode - keymap->minKeyCode)
  803. * keymap->mapWidth + j] == XK_Mode_switch)
  804. {
  805. modeSwitchMapIndex = i;
  806. break;
  807. }
  808. }
  809. }
  810. }
  811. int col = 0;
  812. if (keyc->state & (1<<ShiftMapIndex)) col |= 1;
  813. if (modeSwitchMapIndex && (keyc->state & (1<<modeSwitchMapIndex))) col |= 2;
  814. int kc = KeysymToKeycode(keymap, keysym, &col);
  815. // Sort out the "shifted Tab" mess. If we are sent a shifted Tab, generate a
  816. // local shifted Tab regardless of what the "shifted Tab" keysym is on the
  817. // local keyboard (it might be Tab, ISO_Left_Tab or HP's private BackTab
  818. // keysym, and quite possibly some others too). We never get ISO_Left_Tab
  819. // here because it's already been translated in VNCSConnectionST.
  820. if (keysym == XK_Tab && (keyc->state & (1<<ShiftMapIndex)))
  821. col |= 1;
  822. if (kc == 0) {
  823. // Not a direct match in the local keyboard mapping. Check for alternative
  824. // keysyms with the same meaning.
  825. for (int i = 0; i < sizeof(altKeysym) / sizeof(altKeysym_t); i++) {
  826. if (keysym == altKeysym[i].a)
  827. kc = KeysymToKeycode(keymap, altKeysym[i].b, &col);
  828. else if (keysym == altKeysym[i].b)
  829. kc = KeysymToKeycode(keymap, altKeysym[i].a, &col);
  830. if (kc) break;
  831. }
  832. }
  833. if (kc == 0) {
  834. // Last resort - dynamically add a new key to the keyboard mapping.
  835. for (kc = keymap->maxKeyCode; kc >= keymap->minKeyCode; kc--) {
  836. if (!keymap->map[(kc - keymap->minKeyCode) * keymap->mapWidth]) {
  837. keymap->map[(kc - keymap->minKeyCode) * keymap->mapWidth] = keysym;
  838. col = 0;
  839. SendMappingNotify(MappingKeyboard, kc, 1, serverClient);
  840. vlog.info("Added unknown keysym 0x%x to keycode %d",keysym,kc);
  841. break;
  842. }
  843. }
  844. if (kc < keymap->minKeyCode) {
  845. vlog.info("Keyboard mapping full - ignoring unknown keysym 0x%x",keysym);
  846. return;
  847. }
  848. }
  849. // See if it's a modifier key. If so, then don't do any auto-repeat, because
  850. // the X server will translate each press into a release followed by a press.
  851. for (int i = 0; i < 8; i++) {
  852. for (int k = 0; k < keyc->maxKeysPerModifier; k++) {
  853. if (kc == keyc->modifierKeyMap[i * keyc->maxKeysPerModifier + k] &&
  854. IS_PRESSED(keyc,kc) && down)
  855. return;
  856. }
  857. }
  858. ModifierState shift(dev, ShiftMapIndex);
  859. ModifierState modeSwitch(dev, modeSwitchMapIndex);
  860. if (down) {
  861. if (col & 1)
  862. shift.press();
  863. else
  864. shift.release();
  865. if (modeSwitchMapIndex) {
  866. if (col & 2)
  867. modeSwitch.press();
  868. else
  869. modeSwitch.release();
  870. }
  871. }
  872. vlog.debug("keycode %d %s", kc, down ? "down" : "up");
  873. xEvent ev;
  874. ev.u.u.type = down ? KeyPress : KeyRelease;
  875. ev.u.u.detail = kc;
  876. ev.u.keyButtonPointer.time = GetTimeInMillis();
  877. (*dev->c_public.processInputProc)(&ev, dev, 1);
  878. }
  879. void XConvertCase(KeySym sym, KeySym *lower, KeySym *upper)
  880. {
  881. *lower = sym;
  882. *upper = sym;
  883. switch(sym >> 8) {
  884. case 0: /* Latin 1 */
  885. if ((sym >= XK_A) && (sym <= XK_Z))
  886. *lower += (XK_a - XK_A);
  887. else if ((sym >= XK_a) && (sym <= XK_z))
  888. *upper -= (XK_a - XK_A);
  889. else if ((sym >= XK_Agrave) && (sym <= XK_Odiaeresis))
  890. *lower += (XK_agrave - XK_Agrave);
  891. else if ((sym >= XK_agrave) && (sym <= XK_odiaeresis))
  892. *upper -= (XK_agrave - XK_Agrave);
  893. else if ((sym >= XK_Ooblique) && (sym <= XK_Thorn))
  894. *lower += (XK_oslash - XK_Ooblique);
  895. else if ((sym >= XK_oslash) && (sym <= XK_thorn))
  896. *upper -= (XK_oslash - XK_Ooblique);
  897. break;
  898. case 1: /* Latin 2 */
  899. /* Assume the KeySym is a legal value (ignore discontinuities) */
  900. if (sym == XK_Aogonek)
  901. *lower = XK_aogonek;
  902. else if (sym >= XK_Lstroke && sym <= XK_Sacute)
  903. *lower += (XK_lstroke - XK_Lstroke);
  904. else if (sym >= XK_Scaron && sym <= XK_Zacute)
  905. *lower += (XK_scaron - XK_Scaron);
  906. else if (sym >= XK_Zcaron && sym <= XK_Zabovedot)
  907. *lower += (XK_zcaron - XK_Zcaron);
  908. else if (sym == XK_aogonek)
  909. *upper = XK_Aogonek;
  910. else if (sym >= XK_lstroke && sym <= XK_sacute)
  911. *upper -= (XK_lstroke - XK_Lstroke);
  912. else if (sym >= XK_scaron && sym <= XK_zacute)
  913. *upper -= (XK_scaron - XK_Scaron);
  914. else if (sym >= XK_zcaron && sym <= XK_zabovedot)
  915. *upper -= (XK_zcaron - XK_Zcaron);
  916. else if (sym >= XK_Racute && sym <= XK_Tcedilla)
  917. *lower += (XK_racute - XK_Racute);
  918. else if (sym >= XK_racute && sym <= XK_tcedilla)
  919. *upper -= (XK_racute - XK_Racute);
  920. break;
  921. case 2: /* Latin 3 */
  922. /* Assume the KeySym is a legal value (ignore discontinuities) */
  923. if (sym >= XK_Hstroke && sym <= XK_Hcircumflex)
  924. *lower += (XK_hstroke - XK_Hstroke);
  925. else if (sym >= XK_Gbreve && sym <= XK_Jcircumflex)
  926. *lower += (XK_gbreve - XK_Gbreve);
  927. else if (sym >= XK_hstroke && sym <= XK_hcircumflex)
  928. *upper -= (XK_hstroke - XK_Hstroke);
  929. else if (sym >= XK_gbreve && sym <= XK_jcircumflex)
  930. *upper -= (XK_gbreve - XK_Gbreve);
  931. else if (sym >= XK_Cabovedot && sym <= XK_Scircumflex)
  932. *lower += (XK_cabovedot - XK_Cabovedot);
  933. else if (sym >= XK_cabovedot && sym <= XK_scircumflex)
  934. *upper -= (XK_cabovedot - XK_Cabovedot);
  935. break;
  936. case 3: /* Latin 4 */
  937. /* Assume the KeySym is a legal value (ignore discontinuities) */
  938. if (sym >= XK_Rcedilla && sym <= XK_Tslash)
  939. *lower += (XK_rcedilla - XK_Rcedilla);
  940. else if (sym >= XK_rcedilla && sym <= XK_tslash)
  941. *upper -= (XK_rcedilla - XK_Rcedilla);
  942. else if (sym == XK_ENG)
  943. *lower = XK_eng;
  944. else if (sym == XK_eng)
  945. *upper = XK_ENG;
  946. else if (sym >= XK_Amacron && sym <= XK_Umacron)
  947. *lower += (XK_amacron - XK_Amacron);
  948. else if (sym >= XK_amacron && sym <= XK_umacron)
  949. *upper -= (XK_amacron - XK_Amacron);
  950. break;
  951. case 6: /* Cyrillic */
  952. /* Assume the KeySym is a legal value (ignore discontinuities) */
  953. if (sym >= XK_Serbian_DJE && sym <= XK_Serbian_DZE)
  954. *lower -= (XK_Serbian_DJE - XK_Serbian_dje);
  955. else if (sym >= XK_Serbian_dje && sym <= XK_Serbian_dze)
  956. *upper += (XK_Serbian_DJE - XK_Serbian_dje);
  957. else if (sym >= XK_Cyrillic_YU && sym <= XK_Cyrillic_HARDSIGN)
  958. *lower -= (XK_Cyrillic_YU - XK_Cyrillic_yu);
  959. else if (sym >= XK_Cyrillic_yu && sym <= XK_Cyrillic_hardsign)
  960. *upper += (XK_Cyrillic_YU - XK_Cyrillic_yu);
  961. break;
  962. case 7: /* Greek */
  963. /* Assume the KeySym is a legal value (ignore discontinuities) */
  964. if (sym >= XK_Greek_ALPHAaccent && sym <= XK_Greek_OMEGAaccent)
  965. *lower += (XK_Greek_alphaaccent - XK_Greek_ALPHAaccent);
  966. else if (sym >= XK_Greek_alphaaccent && sym <= XK_Greek_omegaaccent &&
  967. sym != XK_Greek_iotaaccentdieresis &&
  968. sym != XK_Greek_upsilonaccentdieresis)
  969. *upper -= (XK_Greek_alphaaccent - XK_Greek_ALPHAaccent);
  970. else if (sym >= XK_Greek_ALPHA && sym <= XK_Greek_OMEGA)
  971. *lower += (XK_Greek_alpha - XK_Greek_ALPHA);
  972. else if (sym >= XK_Greek_alpha && sym <= XK_Greek_omega &&
  973. sym != XK_Greek_finalsmallsigma)
  974. *upper -= (XK_Greek_alpha - XK_Greek_ALPHA);
  975. break;
  976. }
  977. }
  978. static KeySym KeyCodetoKeySym(KeySymsPtr keymap, int keycode, int col)
  979. {
  980. register int per = keymap->mapWidth;
  981. register KeySym *syms;
  982. KeySym lsym, usym;
  983. if ((col < 0) || ((col >= per) && (col > 3)) ||
  984. (keycode < keymap->minKeyCode) || (keycode > keymap->maxKeyCode))
  985. return NoSymbol;
  986. syms = &keymap->map[(keycode - keymap->minKeyCode) * per];
  987. if (col < 4) {
  988. if (col > 1) {
  989. while ((per > 2) && (syms[per - 1] == NoSymbol))
  990. per--;
  991. if (per < 3)
  992. col -= 2;
  993. }
  994. if ((per <= (col|1)) || (syms[col|1] == NoSymbol)) {
  995. XConvertCase(syms[col&~1], &lsym, &usym);
  996. if (!(col & 1))
  997. return lsym;
  998. // I'm commenting out this logic because it's incorrect even though it
  999. // was copied from the Xlib sources. The X protocol book quite clearly
  1000. // states that where a group consists of element 1 being a non-alphabetic
  1001. // keysym and element 2 being NoSymbol that you treat the second element
  1002. // as being the same as the first. This also tallies with the behaviour
  1003. // produced by the installed Xlib on my linux box (I believe this is
  1004. // because it uses some XKB code rather than the original Xlib code -
  1005. // compare XKBBind.c with KeyBind.c in lib/X11).
  1006. // else if (usym == lsym)
  1007. // return NoSymbol;
  1008. else
  1009. return usym;
  1010. }
  1011. }
  1012. return syms[col];
  1013. }
  1014. // KeysymToKeycode() - find the keycode and column corresponding to the given
  1015. // keysym. The value of col passed in should be the column determined from the
  1016. // current shift state. If the keysym can be found in that column we prefer
  1017. // that to finding it in a different column (which would require fake events to
  1018. // alter the shift state).
  1019. static KeyCode KeysymToKeycode(KeySymsPtr keymap, KeySym ks, int* col)
  1020. {
  1021. register int i, j;
  1022. j = *col;
  1023. for (i = keymap->minKeyCode; i <= keymap->maxKeyCode; i++) {
  1024. if (KeyCodetoKeySym(keymap, i, j) == ks)
  1025. return i;
  1026. }
  1027. for (j = 0; j < keymap->mapWidth; j++) {
  1028. for (i = keymap->minKeyCode; i <= keymap->maxKeyCode; i++) {
  1029. if (KeyCodetoKeySym(keymap, i, j) == ks) {
  1030. *col = j;
  1031. return i;
  1032. }
  1033. }
  1034. }
  1035. return 0;
  1036. }