aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/programs/Xserver/hw/nxagent/Keyboard.c
blob: c8038955b4e09c97200b44241750538d835c0dfe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2014 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2011-2016 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2014-2016 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2014-2016 Ulrich Sibiller <uli42@gmx.de>                 */
/* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)           */
/*                                                                        */
/* NXAGENT, NX protocol compression and NX extensions to this software    */
/* are copyright of the aforementioned persons and companies.             */
/*                                                                        */
/* Redistribution and use of the present software is allowed according    */
/* to terms specified in the file LICENSE which comes in the source       */
/* distribution.                                                          */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/* NOTE: This software has received contributions from various other      */
/* contributors, only the core maintainers and supporters are listed as   */
/* copyright holders. Please contact us, if you feel you should be listed */
/* as copyright holder, as well.                                          */
/*                                                                        */
/**************************************************************************/

/*

Copyright 1993 by Davor Matic

Permission to use, copy, modify, distribute, and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation.  Davor Matic makes no representations about
the suitability of this software for any purpose.  It is provided "as
is" without express or implied warranty.

*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#include "keysym.h"
#include "screenint.h"
#include "inputstr.h"
#include "misc.h"
#include "scrnintstr.h"
#include "servermd.h"
#include "extnsionst.h"

#include "Agent.h"
#include "Display.h"
#include "Screen.h"
#include "Keyboard.h"
#include "Events.h"
#include "Options.h"
#include "Error.h"
#include "Init.h"

#include "compext/Compext.h"

#include <nx/Shadow.h>

#ifdef XKB

#include <nx-X11/extensions/XKB.h>

/*
  we need the client side header here, xkbsrv.h will not work because
  server and libX11 have different struct sizes on
  64bit. Interestingly upstream xnest does not take care of this.
*/
#include <nx-X11/extensions/XKBsrv.h>
#include <nx-X11/extensions/XKBconfig.h>

#include "Xatom.h"

#include <errno.h>

static void nxagentXkbGetNames(void);

void nxagentKeycodeConversionSetup(void);

static void nxagentWriteKeyboardDir(void);
static void nxagentWriteKeyboardFile(char *rules, char *model, char *layout, char *variant, char *options);

#endif /* XKB */

/*
 * Set here the required log level.
 */

#define PANIC
#define WARNING
#undef  TEST
#undef  DEBUG
#undef  WATCH

#ifdef WATCH
#include "unistd.h"
#endif

/*
 * Unfortunately we cannot just include XKBlib.h.
 * It conflicts with the server side definitions
 * of the same symbols. This is more a X problem
 * than our.
 */

#ifdef XKB

extern Bool XkbQueryExtension(
#if NeedFunctionPrototypes
        Display *        /* dpy */,
        int *            /* opcodeReturn */,
        int *            /* eventBaseReturn */,
        int *            /* errorBaseReturn */,
        int *            /* majorRtrn */,
        int *            /* minorRtrn */
#endif
);

extern        XkbDescPtr XkbGetKeyboard(
#if NeedFunctionPrototypes
        Display *        /* dpy */,
        unsigned int     /* which */,
        unsigned int     /* deviceSpec */
#endif
);

extern        Status        XkbGetControls(
#if NeedFunctionPrototypes
        Display *        /* dpy */,
        unsigned long    /* which */,
        XkbDescPtr       /* desc */
#endif
);

extern int XkbDfltRepeatDelay;
extern int XkbDfltRepeatInterval;

/* xkb configuration of the real X server */
static char *nxagentRemoteRules = NULL;
static char *nxagentRemoteModel = NULL;
static char *nxagentRemoteLayout = NULL;
static char *nxagentRemoteVariant = NULL;
static char *nxagentRemoteOptions = NULL;

#endif /* XKB */

/*
 * Save the values queried from X server.
 */

XkbAgentInfoRec nxagentXkbInfo = { -1, -1, -1, -1, -1 };

/*
 * Keyboard status, updated through XKB
 * events.
 */

XkbAgentStateRec nxagentXkbState = { 0, 0, 0, 0, 0 };

/*
 * Info for disabling/enabling Xkb extension.
 */

XkbWrapperRec nxagentXkbWrapper;

extern char *nxagentKeyboard;

unsigned int nxagentAltMetaMask;
unsigned int nxagentAltMask;
unsigned int nxagentMetaMask;
unsigned int nxagentCapsMask;
unsigned int nxagentNumlockMask;

static void nxagentCheckModifierMasks(CARD8, int);

CARD8 nxagentCapsLockKeycode = 66;
CARD8 nxagentNumLockKeycode  = 77;

static void nxagentCheckRemoteKeycodes(void);

static CARD8 nxagentConvertedKeycodes[] =
{
  /* evdev  pc105*/
  /*   0 */   0,
  /*   1 */   1,
  /*   2 */   2,
  /*   3 */   3,
  /*   4 */   4,
  /*   5 */   5,
  /*   6 */   6,
  /*   7 */   7,
  /*   8 */   8,
  /*   9 */   9,
  /*  10 */   10,
  /*  11 */   11,
  /*  12 */   12,
  /*  13 */   13,
  /*  14 */   14,
  /*  15 */   15,
  /*  16 */   16,
  /*  17 */   17,
  /*  18 */   18,
  /*  19 */   19,
  /*  20 */   20,
  /*  21 */   21,
  /*  22 */   22,
  /*  23 */   23,
  /*  24 */   24,
  /*  25 */   25,
  /*  26 */   26,
  /*  27 */   27,
  /*  28 */   28,
  /*  29 */   29,
  /*  30 */   30,
  /*  31 */   31,
  /*  32 */   32,
  /*  33 */   33,
  /*  34 */   34,
  /*  35 */   35,
  /*  36 */   36,
  /*  37 */   37,
  /*  38 */   38,
  /*  39 */   39,
  /*  40 */   40,
  /*  41 */   41,
  /*  42 */   42,
  /*  43 */   43,
  /*  44 */   44,
  /*  45 */   45,
  /*  46 */   46,
  /*  47 */   47,
  /*  48 */   48,
  /*  49 */   49,
  /*  50 */   50,
  /*  51 */   51,
  /*  52 */   52,
  /*  53 */   53,
  /*  54 */   54,
  /*  55 */   55,
  /*  56 */   56,
  /*  57 */   57,
  /*  58 */   58,
  /*  59 */   59,
  /*  60 */   60,
  /*  61 */   61,
  /*  62 */   62,
  /*  63 */   63,
  /*  64 */   64,
  /*  65 */   65,
  /*  66 */   66,
  /*  67 */   67,
  /*  68 */   68,
  /*  69 */   69,
  /*  70 */   70,
  /*  71 */   71,
  /*  72 */   72,
  /*  73 */   73,
  /*  74 */   74,
  /*  75 */   75,
  /*  76 */   76,
  /*  77 */   77,
  /*  78 */   78,
  /*  79 */   79,
  /*  80 */   80,
  /*  81 */   81,
  /*  82 */   82,
  /*  83 */   83,
  /*  84 */   84,
  /*  85 */   85,
  /*  86 */   86,
  /*  87 */   87,
  /*  88 */   88,
  /*  89 */   89,
  /*  90 */   90,
  /*  91 */   91,
  /*  92 */  124,
  /*  93 */   93,
  /*  94 */   94,
  /*  95 */   95,
  /*  96 */   96,
  /*  97 */  211,
  /*  98 */   98,
  /*  99 */   99,
  /* 100 */  100,
  /* 101 */  208,
  /* 102 */  102,
  /* 103 */  103,
  /* 104 */  108,
  /* 105 */  109,
  /* 106 */  112,
  /* 107 */  111,
  /* 108 */  113,
  /* 109 */  109,
  /* 110 */   97,
  /* 111 */   98,
  /* 112 */   99,
  /* 113 */  100,
  /* 114 */  102,
  /* 115 */  103,
  /* 116 */  104,
  /* 117 */  105,
  /* 118 */  106,
  /* 119 */  107,
  /* 120 */  120,
  /* 121 */  121,
  /* 122 */  122,
  /* 123 */  123,
  /* 124 */  124,
  /* 125 */  126,
  /* 126 */  126,
  /* 127 */  110,
  /* 128 */  128,
  /* 129 */  129,
  /* 130 */  130,
  /* 131 */  131,
  /* 132 */  133,
  /* 133 */  115,
  /* 134 */  116,
  /* 135 */  117,
  /* 136 */  136,
  /* 137 */  137,
  /* 138 */  138,
  /* 139 */  139,
  /* 140 */  140,
  /* 141 */  141,
  /* 142 */  142,
  /* 143 */  143,
  /* 144 */  144,
  /* 145 */  145,
  /* 146 */  146,
  /* 147 */  147,
  /* 148 */  148,
  /* 149 */  149,
  /* 150 */  150,
  /* 151 */  151,
  /* 152 */  152,
  /* 153 */  153,
  /* 154 */  154,
  /* 155 */  155,
  /* 156 */  156,
  /* 157 */  157,
  /* 158 */  158,
  /* 159 */  159,
  /* 160 */  160,
  /* 161 */  161,
  /* 162 */  162,
  /* 163 */  163,
  /* 164 */  164,
  /* 165 */  165,
  /* 166 */  166,
  /* 167 */  167,
  /* 168 */  168,
  /* 169 */  169,
  /* 170 */  170,
  /* 171 */  171,
  /* 172 */  172,
  /* 173 */  173,
  /* 174 */  174,
  /* 175 */  175,
  /* 176 */  176,
  /* 177 */  177,
  /* 178 */  178,
  /* 179 */  179,
  /* 180 */  180,
  /* 181 */  181,
  /* 182 */  182,
  /* 183 */  183,
  /* 184 */  184,
  /* 185 */  185,
  /* 186 */  186,
  /* 187 */  187,
  /* 188 */  188,
  /* 189 */  189,
  /* 190 */  190,
  /* 191 */  118,
  /* 192 */  119,
  /* 193 */  120,
  /* 194 */  121,
  /* 195 */  122,
  /* 196 */  196,
  /* 197 */  197,
  /* 198 */  198,
  /* 199 */  199,
  /* 200 */  200,
  /* 201 */  201,
  /* 202 */  202,
  /* 203 */   93,
  /* 204 */  125,
  /* 205 */  156,
  /* 206 */  127,
  /* 207 */  128,
  /* 208 */  208,
  /* 209 */  209,
  /* 210 */  210,
  /* 211 */  211,
  /* 212 */  212,
  /* 213 */  213,
  /* 214 */  214,
  /* 215 */  215,
  /* 216 */  216,
  /* 217 */  217,
  /* 218 */  218,
  /* 219 */  219,
  /* 220 */  220,
  /* 221 */  221,
  /* 222 */  222,
  /* 223 */  223,
  /* 224 */  224,
  /* 225 */  225,
  /* 226 */  226,
  /* 227 */  227,
  /* 228 */  228,
  /* 229 */  229,
  /* 230 */  230,
  /* 231 */  231,
  /* 232 */  232,
  /* 233 */  233,
  /* 234 */  234,
  /* 235 */  235,
  /* 236 */  236,
  /* 237 */  237,
  /* 238 */  238,
  /* 239 */  239,
  /* 240 */  240,
  /* 241 */  241,
  /* 242 */  242,
  /* 243 */  243,
  /* 244 */  244,
  /* 245 */  245,
  /* 246 */  246,
  /* 247 */  247,
  /* 248 */  248,
  /* 249 */  249,
  /* 250 */  250,
  /* 251 */  251,
  /* 252 */  252,
  /* 253 */  253,
  /* 254 */  254,
  /* 255 */  255
};

static Bool nxagentKeycodeConversion = False;

CARD8 nxagentConvertKeycode(CARD8 k)
{
 if (nxagentKeycodeConversion)
 {
   #ifdef DEBUG
   if (k != nxagentConvertedKeycodes[k])
     fprintf(stderr, "nxagentConvertKeycode: converting keycode [%d] to [%d]\n", k, nxagentConvertedKeycodes[k]);
   #endif

   return nxagentConvertedKeycodes[k];
 }
 else
 {
   return k;
 }
}

static int nxagentSaveKeyboardDeviceData(DeviceIntPtr dev, DeviceIntPtr devBackup);

static int nxagentRestoreKeyboardDeviceData(DeviceIntPtr devBackup, DeviceIntPtr dev);

static int nxagentFreeKeyboardDeviceData(DeviceIntPtr dev);

void nxagentBell(int volume, DeviceIntPtr pDev, void * ctrl, int cls)
{
  XBell(nxagentDisplay, volume);
}

void nxagentChangeKeyboardControl(DeviceIntPtr pDev, KeybdCtrl *ctrl)
{
  #ifdef XKB

  XkbSrvInfoPtr  xkbi;
  XkbControlsPtr xkbc;

  if (!noXkbExtension)
  {
    xkbi = pDev -> key -> xkbInfo;
    xkbc = xkbi -> desc -> ctrls;

    /*
     * We want to prevent agent generating auto-repeated
     * keystrokes. Let's intercept any attempt by appli-
     * cations to change the default timeouts on the
     * nxagent device.
     */

    #ifdef TEST
    fprintf(stderr, "nxagentChangeKeyboardControl: Repeat delay was [%d] interval was [%d].\n",
                xkbc -> repeat_delay, xkbc -> repeat_interval);
    #endif

    xkbc -> repeat_delay = ~ 0;
    xkbc -> repeat_interval = ~ 0;

    #ifdef TEST
    fprintf(stderr, "nxagentChangeKeyboardControl: Repeat delay is now [%d] interval is now [%d].\n",
                xkbc -> repeat_delay, xkbc -> repeat_interval);
    #endif
  }

  #endif

  /*
   * If enabled, propagate the changes to the
   * devices attached to the real X server.
   */

  if (nxagentOption(DeviceControl))
  {
    unsigned long value_mask;
    XKeyboardControl values;

    #ifdef TEST
    fprintf(stderr, "nxagentChangeKeyboardControl: WARNING! Propagating changes to keyboard settings.\n");
    #endif

    value_mask = KBKeyClickPercent |
                 KBBellPercent |
                 KBBellPitch |
                 KBBellDuration;

    values.key_click_percent = ctrl->click;
    values.bell_percent = ctrl->bell;
    values.bell_pitch = ctrl->bell_pitch;
    values.bell_duration = ctrl->bell_duration;

    /*
     * Don't propagate the auto repeat mode. It is forced to be
     * off in the agent server.
     *
     * value_mask |= KBAutoRepeatMode;
     * values.auto_repeat_mode = ctrl->autoRepeat ?
     *                          AutoRepeatModeOn : AutoRepeatModeOff;
     */

    XChangeKeyboardControl(nxagentDisplay, value_mask, &values);

    /*
     * At this point, we need to walk through the vector and
     * compare it to the current server vector. If there are
     * differences, report them.
     */

    value_mask = KBLed | KBLedMode;

    for (int i = 1; i <= 32; i++)
    {
      values.led = i;
      values.led_mode = (ctrl->leds & (1 << (i - 1))) ? LedModeOn : LedModeOff;

      XChangeKeyboardControl(nxagentDisplay, value_mask, &values);
    }

    return;
  }

  #ifdef TEST
  fprintf(stderr, "nxagentChangeKeyboardControl: WARNING! Not propagating changes to keyboard settings.\n");
  #endif
}

int nxagentKeyboardProc(DeviceIntPtr pDev, int onoff)
{
  XModifierKeymap *modifier_keymap;
  KeySym *keymap;
  int mapWidth;
  int min_keycode, max_keycode;
  KeySymsRec keySyms;
  CARD8 modmap[MAP_LENGTH];
  int i, j;
  XKeyboardState values;
#ifdef XKB
  char *model = NULL, *layout = NULL;
  XkbDescPtr xkb = NULL;
#endif

  switch (onoff)
  {
    case DEVICE_INIT:

      #ifdef TEST
      fprintf(stderr, "nxagentKeyboardProc: Called for [DEVICE_INIT].\n");
      #endif

      if (NXDisplayError(nxagentDisplay) == 1)
      {
        return Success;
      }

      #ifdef WATCH

      fprintf(stderr, "nxagentKeyboardProc: Watchpoint 9.\n");

/*
Reply   Total	Cached	Bits In			Bits Out		Bits/Reply	  Ratio
------- -----	------	-------			--------		----------	  -----
N/A
*/

      sleep(30);

      #endif

      /*
       * Prevent agent from generating auto-repeat keystroke.
       * Note that this is working only if XKB is enabled.
       * A better solution should account cases where XKB is
       * not available. Check also the behaviour of the
       * DeviceControl nxagent option.
       */

      XkbDfltRepeatDelay = ~ 0;
      XkbDfltRepeatInterval = ~ 0;

      #ifdef TEST
      fprintf(stderr, "nxagentKeyboardProc: Set repeat delay to [%d] interval to [%d].\n",
                  XkbDfltRepeatDelay, XkbDfltRepeatInterval);
      #endif

      modifier_keymap = XGetModifierMapping(nxagentDisplay);

      if (modifier_keymap == NULL)
      {
        return -1;
      }

      XDisplayKeycodes(nxagentDisplay, &min_keycode, &max_keycode);
#ifdef _XSERVER64
      {
        KeySym64 *keymap64;
        int len;
        keymap64 = XGetKeyboardMapping(nxagentDisplay,
                                     min_keycode,
                                     max_keycode - min_keycode + 1,
                                     &mapWidth);

        if (keymap64 == NULL)
        {
          XFreeModifiermap(modifier_keymap);
          return -1;
        }

        len = (max_keycode - min_keycode + 1) * mapWidth;
        keymap = (KeySym *)malloc(len * sizeof(KeySym));
        for(i = 0; i < len; ++i)
        {
          keymap[i] = keymap64[i];
        }
        XFree(keymap64);
      }

#else /* #ifdef _XSERVER64 */

      keymap = XGetKeyboardMapping(nxagentDisplay,
                                   min_keycode,
                                   max_keycode - min_keycode + 1,
                                   &mapWidth);

      if (keymap == NULL)
      {
        XFreeModifiermap(modifier_keymap);
        return -1;
      }

#endif /* #ifdef _XSERVER64 */

      nxagentAltMetaMask = 0;
      nxagentAltMask = 0;
      nxagentMetaMask = 0;
      nxagentCapsMask = 0;
      nxagentNumlockMask = 0;

      memset(modmap, 0, sizeof(modmap));
      for (j = 0; j < 8; j++)
      {
        for(i = 0; i < modifier_keymap->max_keypermod; i++)
        {
          CARD8 keycode;
          if ((keycode =
              modifier_keymap->
                modifiermap[j * modifier_keymap->max_keypermod + i]))
          {
            modmap[keycode] |= 1<<j;
          }

          if (keycode > 0)
          {
            nxagentCheckModifierMasks(keycode, j);
          }
        }
      }

      XFreeModifiermap(modifier_keymap);
      modifier_keymap = NULL;

      nxagentCheckRemoteKeycodes();

      keySyms.minKeyCode = min_keycode;
      keySyms.maxKeyCode = max_keycode;
      keySyms.mapWidth = mapWidth;
      keySyms.map = keymap;

#ifdef XKB
      if (!nxagentGetRemoteXkbExtension())
      {
        ErrorF("Unable to query XKEYBOARD extension.\n");
        goto XkbError;
      }

      if (noXkbExtension) {
        #ifdef TEST
        fprintf(stderr, "nxagentKeyboardProc: No XKB extension.\n");
        #endif

XkbError:

        #ifdef TEST
        fprintf(stderr, "nxagentKeyboardProc: XKB error.\n");
        #endif

#endif
        XGetKeyboardControl(nxagentDisplay, &values);

        memmove((char *) defaultKeyboardControl.autoRepeats,
               (char *) values.auto_repeats, sizeof(values.auto_repeats));

        #ifdef TEST
        {
          int ret =
        #endif
          InitKeyboardDeviceStruct((DevicePtr) pDev, &keySyms, modmap,
                                 nxagentBell, nxagentChangeKeyboardControl);

        #ifdef TEST
          fprintf(stderr, "nxagentKeyboardProc: InitKeyboardDeviceStruct returns [%d].\n", ret);
        }
        #endif

#ifdef XKB
      } else { /* if (noXkbExtension) */
        XkbComponentNamesRec names = {0};
        char *rules = NULL, *variant = NULL, *options = NULL; /* use xkb default */

        #ifdef TEST
        fprintf(stderr, "nxagentKeyboardProc: Using XKB extension.\n");
        fprintf(stderr, "nxagentKeyboardProc: nxagentKeyboard is [%s].\n", nxagentKeyboard ? nxagentKeyboard : "NULL");
        #endif

        if (nxagentX2go && nxagentKeyboard && (strcmp(nxagentKeyboard, "null/null") == 0))
        {
          #ifdef TEST
          fprintf(stderr, "%s: changing nxagentKeyboard from [null/null] to [clone].\n", __func__);
          #endif
          free(nxagentKeyboard);
          nxagentKeyboard = strdup("clone");
        }

        /*
          from nxagent changelog:
          2.0.22:
          - Implemented handling of value "query" for nxagentKbtype. This value
          is passed by the NX client for MacOSX. If value of nxagentKbtype is
          "query" or NULL we init keyboard by core protocol functions reading
          the keyboard mapping of the X server. The property _XKB_RULES_NAMES
          is always set on the root window with default values of model and
          layout.
        */

        if (nxagentKeyboard &&
            (strcmp(nxagentKeyboard, "query") != 0) &&
            (strcmp(nxagentKeyboard, "clone") != 0))
        {
          for (i = 0; nxagentKeyboard[i] != '/' && nxagentKeyboard[i] != 0; i++);

          if (nxagentKeyboard[i] == 0 || nxagentKeyboard[i + 1] == 0 || i == 0)
          {
            ErrorF("Warning: Wrong keyboard type: %s.\n", nxagentKeyboard);
            goto XkbError;
          }

          /*
            The original nxagent only supports model/layout values
            here. It uses these values together with the default rules
            and empty variant and options. We use a more or less
            compatible hack here: The special keyword rlmvo for model
            means that the layout part of the string will contain a
            full RMLVO config, separated by #, e.g.
            rlmvo/base#pc105#de,us#nodeadkeys#lv3:rwin_switch
          */
          if (strncmp(nxagentKeyboard, "rlmvo/", 6) == 0)
          {
            const char * sep = "#";
            char * rmlvo = strdup(&nxagentKeyboard[i+1]);
            char * tmp = rmlvo;
            /* strtok cannot handle empty fields, so use strsep */
            rules = strdup(strsep(&tmp, sep));
            model = strdup(strsep(&tmp, sep));
            layout = strdup(strsep(&tmp, sep));
            variant = strdup(strsep(&tmp, sep));
            options = strdup(strsep(&tmp, sep));
            free(rmlvo);
          }
          else
          {
            model = strndup(nxagentKeyboard, i);
            layout = strdup(&nxagentKeyboard[i + 1]);
          }

          /*
           * There is no description for pc105 on Solaris.
           * Need to revert to the closest approximation.
           */

          #ifdef TEST
          fprintf(stderr, "%s: Using [rules='%s',model='%s',layout='%s',variant='%s',options='%s'].\n",
                  __func__, rules, model, layout, variant, options);
          #endif

          #ifdef __sun

          if (strcmp(model, "pc105") == 0)
          {
            #ifdef TEST
            fprintf(stderr, "nxagentKeyboardProc: WARNING! Keyboard model 'pc105' unsupported on Solaris.\n");
            fprintf(stderr, "nxagentKeyboardProc: WARNING! Forcing keyboard model to 'pc104'.\n");
            #endif

            strcpy(model, "pc104");
          }

          #endif
        }
        else
        {
          #ifdef TEST
          fprintf(stderr, "nxagentKeyboardProc: Using default keyboard: model [%s] layout [%s].\n",
                      model?model:"(default)", layout?layout:"(default)");
          #endif
        }

        #ifdef TEST
        fprintf(stderr, "nxagentKeyboardProc: Init XKB extension.\n");
        #endif

        if (nxagentRemoteRules && nxagentRemoteModel)
        {
          #ifdef DEBUG
          fprintf(stderr, "%s: Remote: [rules='%s',model='%s',layout='%s',variant='%s',options='%s'].\n",
                  __func__, nxagentRemoteRules, nxagentRemoteModel, nxagentRemoteLayout, nxagentRemoteVariant, nxagentRemoteOptions);
          #endif


          /* Only setup keycode conversion if we are NOT in clone mode */
          if (nxagentKeyboard && (strcmp(nxagentKeyboard, "clone") == 0))
          {
            free(rules); rules = strdup(nxagentRemoteRules);
            free(model); model = strdup(nxagentRemoteModel);
            free(layout); layout = strdup(nxagentRemoteLayout);
            free(variant); variant = strdup(nxagentRemoteVariant);
            free(options); options = strdup(nxagentRemoteOptions);
            /*
             * when cloning we do not want X2Go to set the keyboard
             * via a keyboard file generated by nxagent. The defined
             * method for switching that off is the creation of a dir
             * instead of a file.
             */
            if (nxagentX2go)
            {
              nxagentWriteKeyboardDir();
            }
          }
          else
          {
            nxagentKeycodeConversionSetup();
            /*
             * Keyboard has always been tricky with nxagent. For that
             * reason X2Go offers "auto" keyboard configuration. You can
             * specify it in the client side session configuration. In
             * "auto" mode x2goserver expects nxagent to write the
             * remote keyboard config to a file on startup and
             * x2goserver would then pick that file and pass it to
             * setxkbmap. This functionality is obsoleted by the "clone"
             * stuff but we still need it because x2goserver does not
             * know about that yet. Once x2go starts using clone
             * we can drop this here.
             */
            if (nxagentX2go)
            {
              nxagentWriteKeyboardFile(nxagentRemoteRules, nxagentRemoteModel, nxagentRemoteLayout, nxagentRemoteVariant, nxagentRemoteOptions);
            }
          }
        }
        #ifdef DEBUG
        else
        {
          fprintf(stderr, "%s: Failed to retrieve remote rules.\n", __func__);
        }
        #endif

        xkb = XkbGetKeyboard(nxagentDisplay, XkbGBN_AllComponentsMask, XkbUseCoreKbd);

        if (xkb && xkb->geom)
        {
          XkbGetControls(nxagentDisplay, XkbAllControlsMask, xkb);
        }
#ifdef TEST
        else
        {
          fprintf(stderr, "nxagentKeyboardProc: No current keyboard.\n");
        }
#endif

        #ifdef DEBUG
        fprintf(stderr, "nxagentKeyboardProc: Going to set rules and init device: "
                        "[rules='%s',model='%s',layout='%s',variant='%s',options='%s'].\n",
                        rules?rules:"(default)", model?model:"(default)", layout?layout:"(default)",
                        variant?variant:"(default)", options?options:"(default)");
        #endif

        XkbSetRulesDflts(rules, model, layout, variant, options);
        XkbInitKeyboardDeviceStruct((void *)pDev, &names, &keySyms, modmap,
                                    nxagentBell, nxagentChangeKeyboardControl);

        if (nxagentKeyboard && strcmp(nxagentKeyboard, "query") == 0)
        {
          goto XkbError;
        }

        if (xkb && xkb->geom)
        {
          XkbDDXChangeControls(pDev, xkb->ctrls, xkb->ctrls);
        }

        if (nxagentOption(Shadow) == 1 && pDev && pDev->key)
        {
          NXShadowInitKeymap(&(pDev->key->curKeySyms));
        }
      }

      if (xkb)
      {
        XkbFreeKeyboard(xkb, XkbAllComponentsMask, True);
        xkb = NULL;
      }

      free(model);
      free(layout);
#endif

      #ifdef WATCH

      fprintf(stderr, "nxagentKeyboardProc: Watchpoint 10.\n");

/*
Reply   Total	Cached	Bits In			Bits Out		Bits/Reply	  Ratio
------- -----	------	-------			--------		----------	  -----
#1   U  3	2	80320 bits (10 KB) ->	28621 bits (3 KB) ->	26773/1 -> 9540/1	= 2.806:1
#98     1		256 bits (0 KB) ->	27 bits (0 KB) ->	256/1 -> 27/1	= 9.481:1
#101    1		32000 bits (4 KB) ->	2940 bits (0 KB) ->	32000/1 -> 2940/1	= 10.884:1
#119    1		384 bits (0 KB) ->	126 bits (0 KB) ->	384/1 -> 126/1	= 3.048:1
*/

      sleep(30);

      #endif

#ifdef _XSERVER64
      free(keymap);
#else
      XFree(keymap);
#endif
      break;
    case DEVICE_ON:

      #ifdef TEST
      fprintf(stderr, "nxagentKeyboardProc: Called for [DEVICE_ON].\n");
      #endif

      if (NXDisplayError(nxagentDisplay) == 1)
      {
        return Success;
      }

      #ifdef WATCH

      fprintf(stderr, "nxagentKeyboardProc: Watchpoint 11.\n");

/*
Reply   Total	Cached	Bits In			Bits Out		Bits/Reply	  Ratio
------- -----	------	-------			--------		----------	  -----
#117    1		320 bits (0 KB) ->	52 bits (0 KB) ->	320/1 -> 52/1	= 6.154:1
*/

      sleep(30);

      #endif

      nxagentEnableKeyboardEvents();

      break;

    case DEVICE_OFF:

      #ifdef TEST
      fprintf(stderr, "nxagentKeyboardProc: Called for [DEVICE_OFF].\n");
      #endif

      if (NXDisplayError(nxagentDisplay) == 1)
      {
        return Success;
      }

      nxagentDisableKeyboardEvents();

      break;

    case DEVICE_CLOSE:
      #ifdef TEST
      fprintf(stderr, "nxagentKeyboardProc: Called for [DEVICE_CLOSE].\n");
      #endif

      for (int i = 0; i < pDev->nPrivates; i++)
      {
        free(pDev->devPrivates[i].ptr);
        pDev->devPrivates[i].ptr = NULL;
      }
      free(pDev->devPrivates);
      pDev->devPrivates = NULL;

      break;
  }

  return Success;
}

Bool LegalModifier(key, pDev)
     unsigned int key;
     DevicePtr pDev;
{
  return TRUE;
}

void nxagentNotifyKeyboardChanges(int oldMinKeycode, int oldMaxKeycode)
{
  #ifdef XKB

  if (!noXkbExtension)
  {
    DeviceIntPtr dev;
    xkbNewKeyboardNotify nkn = {0};

    dev = inputInfo.keyboard;

    nkn.deviceID = nkn.oldDeviceID = dev -> id;
    nkn.minKeyCode = 8;
    nkn.maxKeyCode = 255;
    nkn.oldMinKeyCode = oldMinKeycode;
    nkn.oldMaxKeyCode = oldMaxKeycode;
    nkn.requestMajor = XkbReqCode;
    nkn.requestMinor = X_kbGetKbdByName;
    nkn.changed = XkbNKN_KeycodesMask;

    XkbSendNewKeyboardNotify(dev, &nkn);
  }
  else
  {

  #endif

    int i;
    xEvent event = {0};

    event.u.u.type = MappingNotify;
    event.u.mappingNotify.request = MappingKeyboard;
    event.u.mappingNotify.firstKeyCode = inputInfo.keyboard -> key -> curKeySyms.minKeyCode;
    event.u.mappingNotify.count = inputInfo.keyboard -> key -> curKeySyms.maxKeyCode -
                                      inputInfo.keyboard -> key -> curKeySyms.minKeyCode;

    /*
     *  0 is the server client
     */

    for (i = 1; i < currentMaxClients; i++)
    {
      if (clients[i] && clients[i] -> clientState == ClientStateRunning)
      {
        event.u.u.sequenceNumber = clients[i] -> sequence;
        WriteEventsToClient(clients[i], 1, &event);
      }
    }

  #ifdef XKB

  }

  #endif

}

int nxagentResetKeyboard(void)
{
  DeviceIntPtr dev = inputInfo.keyboard;
  DeviceIntPtr devBackup;

  int result;
  int oldMinKeycode = 8;
  int oldMaxKeycode = 255;

  int savedBellPercent;
  int savedBellPitch;
  int savedBellDuration;

  if (NXDisplayError(nxagentDisplay) == 1)
  {
    return 0;
  }

  /*
   * Save bell settings.
   */

  savedBellPercent = inputInfo.keyboard -> kbdfeed -> ctrl.bell;
  savedBellPitch = inputInfo.keyboard -> kbdfeed -> ctrl.bell_pitch;
  savedBellDuration = inputInfo.keyboard -> kbdfeed -> ctrl.bell_duration;

  #ifdef TEST
  fprintf(stderr, "nxagentResetKeyboard: bellPercent [%d]  bellPitch [%d]  bellDuration [%d].\n",
              savedBellPercent, savedBellPitch, savedBellDuration);
  #endif

  if (!(devBackup = calloc(1, sizeof(DeviceIntRec))))
  {
    #ifdef PANIC
    fprintf(stderr, "nxagentResetKeyboard: PANIC! Can't allocate backup structure.\n");
    #endif
  }

  nxagentSaveKeyboardDeviceData(dev, devBackup);

  if (dev->key)
  {
    #ifdef XKB
    if (noXkbExtension == 0 && dev->key->xkbInfo)
    {
      oldMinKeycode = dev->key->xkbInfo -> desc -> min_key_code;
      oldMaxKeycode = dev->key->xkbInfo -> desc -> max_key_code;
    }
    #endif

    dev->key=NULL;
  }

  dev->focus=NULL;

  dev->kbdfeed=NULL;

  #ifdef XKB
  nxagentTuneXkbWrapper();
  #endif

  result = (*inputInfo.keyboard -> deviceProc)(inputInfo.keyboard, DEVICE_INIT);

  if (result == Success && inputInfo.keyboard -> key != NULL)
  {

    /*
     * Restore bell settings.
     */

    inputInfo.keyboard -> kbdfeed -> ctrl.bell = savedBellPercent;
    inputInfo.keyboard -> kbdfeed -> ctrl.bell_pitch = savedBellPitch;
    inputInfo.keyboard -> kbdfeed -> ctrl.bell_duration = savedBellDuration;

    nxagentNotifyKeyboardChanges(oldMinKeycode, oldMaxKeycode);

    nxagentFreeKeyboardDeviceData(devBackup);

    free(devBackup);

    return 1;
  }
  else
  {
    #ifdef WARNING
    fprintf(stderr, "nxagentResetKeyboard: Can't initialize the keyboard device.\n");
    #endif

    nxagentRestoreKeyboardDeviceData(devBackup, dev);

    return 0;
  }
}

void nxagentCheckModifierMasks(CARD8 keycode, int j)
{
  if (keycode == XKeysymToKeycode(nxagentDisplay, XK_Meta_L))
  {
    nxagentAltMetaMask |= 1 << j;
    nxagentMetaMask |= 1 << j;
  }

  if (keycode == XKeysymToKeycode(nxagentDisplay, XK_Meta_R))
  {
    nxagentAltMetaMask |= 1 << j;
    nxagentMetaMask |= 1 << j;
  }

  if (keycode == XKeysymToKeycode(nxagentDisplay, XK_Alt_L))
  {
    nxagentAltMetaMask |= 1 << j;
    nxagentAltMask |= 1 << j;
  }

  if (keycode == XKeysymToKeycode(nxagentDisplay, XK_Alt_R))
  {
    nxagentAltMetaMask |= 1 << j;
    nxagentAltMask |= 1 << j;
  }

  if (keycode == XKeysymToKeycode(nxagentDisplay, XK_Num_Lock))
  {
    nxagentNumlockMask |= 1 << j;
  }

  if (keycode == XKeysymToKeycode(nxagentDisplay, XK_Caps_Lock) ||
      keycode == XKeysymToKeycode(nxagentDisplay, XK_Shift_Lock) )
  {
    nxagentCapsMask |= 1 << j;
  }

}

void nxagentCheckRemoteKeycodes(void)
{
  nxagentCapsLockKeycode = XKeysymToKeycode(nxagentDisplay, XK_Caps_Lock);
  nxagentNumLockKeycode  = XKeysymToKeycode(nxagentDisplay, XK_Num_Lock);

  #ifdef DEBUG
  fprintf(stderr, "nxagentCheckRemoteKeycodes: Remote keycodes: CapsLock "
                  "[%d] NumLock [%d].\n", nxagentCapsLockKeycode,
                  nxagentNumLockKeycode);
  #endif
}

static int nxagentSaveKeyboardDeviceData(DeviceIntPtr dev, DeviceIntPtr devBackup)
{
  if (!devBackup)
  {
    #ifdef PANIC
    fprintf(stderr, "nxagentSaveKeyboardDeviceData: PANIC! Pointer to backup structure is null.\n");
    #endif

    return -1;
  }

  devBackup -> key     = dev -> key;
  devBackup -> focus   = dev -> focus;
  devBackup -> kbdfeed = dev -> kbdfeed;

  #ifdef DEBUG
  fprintf(stderr, "nxagentSaveKeyboardDeviceData: Saved device data.\n");
  #endif

  return 1;
}

static int nxagentRestoreKeyboardDeviceData(DeviceIntPtr devBackup, DeviceIntPtr dev)
{
  if (!devBackup)
  {
    #ifdef PANIC
    fprintf(stderr, "nxagentRestoreKeyboardDeviceData: PANIC! Pointer to backup structure is null.\n");
    #endif

    return -1;
  }

  dev -> key     = devBackup -> key;
  dev -> focus   = devBackup -> focus;
  dev -> kbdfeed = devBackup -> kbdfeed;

  #ifdef DEBUG
  fprintf(stderr, "nxagentRestoreKeyboardDeviceData: Restored device data.\n");
  #endif

  return 1;
}


static int nxagentFreeKeyboardDeviceData(DeviceIntPtr dev)
{
  KbdFeedbackPtr k, knext;

  if (!dev)
  {
    #ifdef PANIC
    fprintf(stderr, "nxagentFreeKeyboardDeviceData: PANIC! Pointer to device structure is null.\n");
    #endif

    return -1;
  }

  if (dev->key)
  {
      #ifdef XKB
      if (noXkbExtension == 0 && dev->key->xkbInfo)
      {
          XkbFreeInfo(dev->key->xkbInfo);
          dev->key->xkbInfo = NULL;
      }
      #endif

      free(dev->key->curKeySyms.map);
      free(dev->key->modifierKeyMap);
      free(dev->key);

      dev->key = NULL;
  }

  if (dev->focus)
  {
      free(dev->focus->trace);
      free(dev->focus);
      dev->focus = NULL;
  }

  if (dev->kbdfeed)
  {
      for (k = dev->kbdfeed; k; k = knext)
      {
          knext = k->next;
          #ifdef XKB
          if (k->xkb_sli)
              XkbFreeSrvLedInfo(k->xkb_sli);
          #endif
          free(k);
      }
      dev->kbdfeed = NULL;
  }

  #ifdef DEBUG
  fprintf(stderr, "nxagentFreeKeyboardDeviceData: Freed device data.\n");
  #endif

  return 1;
}

#if XKB

int ProcXkbInhibited(register ClientPtr client)
{
  unsigned char majorop;
  unsigned char minorop;

  #ifdef TEST
  fprintf(stderr, "ProcXkbInhibited: Called.\n");
  #endif

  majorop = ((xReq *)client->requestBuffer)->reqType;

  #ifdef PANIC
  if (majorop != (unsigned char)nxagentXkbWrapper.base)
  {
    fprintf(stderr, "ProcXkbInhibited: MAJOROP is [%d] but should be [%d].\n",
            majorop, nxagentXkbWrapper.base);
  }
  #endif

  minorop = *((unsigned char *) client->requestBuffer + 1);

  #ifdef TEST
  fprintf(stderr, "ProcXkbInhibited: MAJOROP is [%d] MINOROP is [%d].\n",
              majorop, minorop);
  #endif

  switch (minorop)
  {
    case X_kbLatchLockState:
    case X_kbSetControls:
    case X_kbSetCompatMap:
    case X_kbSetIndicatorMap:
    case X_kbSetNamedIndicator:
    case X_kbSetNames:
    case X_kbSetGeometry:
    case X_kbSetDebuggingFlags:
    case X_kbSetMap:
    {
      return client->noClientException;
    }
    case X_kbGetKbdByName:
    {
      return BadAccess;
    }
    case X_kbBell:
    case X_kbGetCompatMap:
    case X_kbGetControls:
    case X_kbGetDeviceInfo:
    case X_kbGetGeometry:
    case X_kbGetIndicatorMap:
    case X_kbGetIndicatorState:
    case X_kbGetMap:
    case X_kbGetNamedIndicator:
    case X_kbGetNames:
    case X_kbGetState:
    case X_kbListComponents:
    case X_kbPerClientFlags:
    case X_kbSelectEvents:
    case X_kbSetDeviceInfo:
    case X_kbUseExtension:
    {
      return (client->swapped ? nxagentXkbWrapper.SProcXkbDispatchBackup(client) :
                  nxagentXkbWrapper.ProcXkbDispatchBackup(client));
    }
    default:
    {
      /* Just make sure that it works in case xkb gets extended in future  */
      return BadImplementation;
    }
  }
}

void nxagentInitXkbWrapper(void)
{
  ExtensionEntry * extension;

  #ifdef TEST
  fprintf(stderr, "nxagentInitXkbWrapper: Called.\n");
  #endif

  if (!nxagentOption(InhibitXkb))
  {
    #ifdef TEST
    fprintf(stderr, "nxagentInitXkbWrapper: Nothing to do.\n");
    #endif

    return;
  }

  memset(&nxagentXkbWrapper, 0, sizeof(XkbWrapperRec));

  if ((extension = CheckExtension("XKEYBOARD")))
  {
    nxagentXkbWrapper.base = extension -> base;
    nxagentXkbWrapper.eventBase = extension -> eventBase;
    nxagentXkbWrapper.errorBase = extension -> errorBase;
    nxagentXkbWrapper.ProcXkbDispatchBackup  = NULL;
    nxagentXkbWrapper.SProcXkbDispatchBackup = NULL;

    #ifdef TEST
    fprintf(stderr, "nxagentInitXkbWrapper: base [%d] eventBase [%d] errorBase [%d].\n",
                extension -> base, extension -> eventBase, extension -> errorBase);
    #endif
  }
  else
  {
    nxagentXkbWrapper.base = -1;

    #ifdef TEST
    fprintf(stderr, "nxagentInitXkbWrapper: XKEYBOARD extension not found.\n");
    #endif
  }
}

void nxagentDisableXkbExtension(void)
{  
  #ifdef TEST
  fprintf(stderr, "nxagentDisableXkbExtension: Called.\n");
  #endif

  if (nxagentXkbWrapper.base > 0)
  {
    if (!nxagentXkbWrapper.ProcXkbDispatchBackup)
    {
      nxagentXkbWrapper.ProcXkbDispatchBackup = ProcVector[nxagentXkbWrapper.base];

      ProcVector[nxagentXkbWrapper.base] = ProcXkbInhibited;
    }
    #ifdef TEST
    else
    {
      fprintf(stderr, "nxagentDisableXkbExtension: Nothing to be done for ProcXkbDispatch.\n");
    }
    #endif

    if (!nxagentXkbWrapper.SProcXkbDispatchBackup)
    {
      nxagentXkbWrapper.SProcXkbDispatchBackup = SwappedProcVector[nxagentXkbWrapper.base];

      SwappedProcVector[nxagentXkbWrapper.base] = ProcXkbInhibited;
    }
    #ifdef TEST
    else
    {
      fprintf(stderr, "nxagentDisableXkbExtension: Nothing to be done for SProcXkbDispatch.\n");
    }
    #endif
  }
}

void nxagentEnableXkbExtension(void)
{
  #ifdef TEST
  fprintf(stderr, "nxagentEnableXkbExtension: Called.\n");
  #endif

  if (nxagentXkbWrapper.base > 0)
  {
    if (nxagentXkbWrapper.ProcXkbDispatchBackup)
    {
      ProcVector[nxagentXkbWrapper.base] = nxagentXkbWrapper.ProcXkbDispatchBackup;

      nxagentXkbWrapper.ProcXkbDispatchBackup = NULL;
    }
    #ifdef TEST
    else
    {
      fprintf(stderr, "nxagentEnableXkbExtension: Nothing to be done for ProcXkbDispatch.\n");
    }
    #endif

    if (nxagentXkbWrapper.SProcXkbDispatchBackup)
    {
      SwappedProcVector[nxagentXkbWrapper.base] = nxagentXkbWrapper.SProcXkbDispatchBackup;

      nxagentXkbWrapper.SProcXkbDispatchBackup = NULL;
    }
    #ifdef TEST
    else
    {
      fprintf(stderr, "nxagentEnableXkbExtension: Nothing to be done for SProcXkbDispatch.\n");
    }
    #endif
  }
}

/*
  from nxagent-3.0.0-88 changelog:

  - Fixed TR10D01539. Some XKEYBOARD requests are disabled if the option
  'keyboard' has value 'query'. This locks the initial keyboard map.
  Enabling/disabling of XKEYBOARD requests is done at run time.

  - Added -noxkblock command line option enabling the XKEYBOARD requests
  even if the option 'keyboard' value is 'query'.
*/
void nxagentTuneXkbWrapper(void)
{
  if (!nxagentOption(InhibitXkb))
  {
    #ifdef TEST
    fprintf(stderr, "nxagentTuneXkbWrapper: Nothing to do.\n");
    #endif

    return;
  }

  if (nxagentKeyboard && strcmp(nxagentKeyboard, "query") == 0)
  {
    nxagentDisableXkbExtension();
  }
  else
  {
    nxagentEnableXkbExtension();
  }
}

void nxagentXkbClearNames(void)
{
  free(nxagentRemoteRules); nxagentRemoteRules = NULL;
  free(nxagentRemoteModel); nxagentRemoteModel = NULL;
  free(nxagentRemoteLayout); nxagentRemoteLayout = NULL;
  free(nxagentRemoteVariant); nxagentRemoteVariant = NULL;
  free(nxagentRemoteOptions); nxagentRemoteOptions = NULL;
}

static void nxagentXkbGetNames(void)
{
  Atom atom;
  #ifdef _XSERVER64
  Atom64 type;
  #else
  Atom type;
  #endif
  int format;
  unsigned long n;
  unsigned long after;
  char *data;
  char *name;
  Status result;

  if (nxagentRemoteRules)
    return;

  atom = XInternAtom(nxagentDisplay, "_XKB_RULES_NAMES", 1);

  if (atom == 0)
  {
    return;
  }

  data = name = NULL;

  result = XGetWindowProperty(nxagentDisplay, DefaultRootWindow(nxagentDisplay),
                                  atom, 0, 256, 0, XA_STRING, &type, &format,
                                      &n, &after, (unsigned char **)&data);

  if (result != Success || !data)
  {
    return;
  }

  if ((after > 0) || (type != XA_STRING) || (format != 8))
  {
    if (data)
    {
      XFree(data);
      return;
    }
  }

  name = data;

  if (name < data + n)
  {
    nxagentRemoteRules = strdup(name);
    name += strlen(name) + 1;
  }

  if (name < data + n)
  {
    nxagentRemoteModel = strdup(name);
    name += strlen(name) + 1;
  }

  if (name < data + n)
  {
    nxagentRemoteLayout = strdup(name);
    name += strlen(name) + 1;
  }

  if (name < data + n)
  {
    nxagentRemoteVariant = strdup(name);
    name += strlen(name) + 1;
  }

  if (name < data + n)
  {
    nxagentRemoteOptions = strdup(name);
    name += strlen(name) + 1;
  }

  XFree(data);

  return;
}

static void writeKeyboardfileData(FILE *out, char *rules, char *model, char *layout, char *variant, char *options)
{
  /*
    How to set "empty" values with setxkbmap, result of trial and error:
    - model and layout: empty strings are accepted by setxkbmap.
    - rules: setxkbmap will fail if rules is an empty string
      (code will intercept in an earlier stage in that case)
    - variant: the variant line must be omitted completely.
    - options: prepend value with "," to override, otherwise options will be added.
  */
  fprintf(out, "rules=\"%s\"\n", rules);
  fprintf(out, "model=\"%s\"\n", model ? model : "");
  fprintf(out, "layout=\"%s\"\n", layout ? layout : "");
  if (variant && variant[0] != '\0')
    fprintf(out, "variant=\"%s\"\n", variant);
  fprintf(out, "options=\",%s\"\n", options ? options : "");
}

static char* getKeyboardFilePath(void)
{
  char *keyboard_file_path = NULL;
  char *sessionpath = nxagentGetSessionPath();
  if (sessionpath)
  {
    if ((asprintf(&keyboard_file_path, "%s/keyboard", sessionpath) == -1))
    {
      free(sessionpath);
      FatalError("malloc for keyboard file path failed.");
    }
    free(sessionpath);
  }
  else
  {
    fprintf(stderr, "Warning: Failed to determine keyboard file path: SessionPath not defined\n");
  }
  return keyboard_file_path;
}

static void nxagentWriteKeyboardDir(void)
{
  char *keyboard_file_path = getKeyboardFilePath();

  if (keyboard_file_path)
  {
    /*
     * special case: if rules is NULL create a directory insteas of
     * a file. This is the defined method to disable x2gosetkeyboard.
     */
    if (mkdir(keyboard_file_path, 0555) < 0)
    {
      int save_err = errno;
      fprintf(stderr, "Warning: Failed to create keyboard blocking directory '%s': %s\n", keyboard_file_path, strerror(save_err));
    }
    else
    {
      fprintf(stderr, "Info: keyboard blocking directory created: '%s'\n", keyboard_file_path);
    }
    free(keyboard_file_path);
  }
}

static void nxagentWriteKeyboardFile(char *rules, char *model, char *layout, char *variant, char *options)
{
  if (rules && rules[0] != '\0')
  {
    #ifdef DEBUG
    writeKeyboardfileData(stderr, rules, model, layout, variant, options);
    #endif

    char *keyboard_file_path = getKeyboardFilePath();

    if (keyboard_file_path)
    {
      FILE *keyboard_file;
      if ((keyboard_file = fopen(keyboard_file_path, "w")))
      {
        writeKeyboardfileData(keyboard_file, rules, model, layout, variant, options);
        fclose(keyboard_file);
        fprintf(stderr, "Info: keyboard file created: '%s'\n", keyboard_file_path);
      }
      else
      {
        int save_err = errno;
        fprintf(stderr, "Error: keyboard file not created: %s\n", strerror(save_err));
      }
      free(keyboard_file_path);
    }
  }
}

void nxagentKeycodeConversionSetup(void)
{
  nxagentKeycodeConversion = False;

  if (nxagentXkbInfo.Opcode == -1)
    return;

  if (nxagentOption(KeycodeConversion) == KeycodeConversionOff)
  {
    fprintf(stderr, "Info: Keycode conversion is off\n");
  }
  else if (nxagentOption(KeycodeConversion) == KeycodeConversionOn)
  {
    fprintf(stderr, "Info: Keycode conversion is on\n");
    nxagentKeycodeConversion = True;
  }
  else
  {
    if (nxagentRemoteRules && nxagentRemoteModel &&
        (strcmp(nxagentRemoteRules, "evdev") == 0 ||
         strcmp(nxagentRemoteModel, "evdev") == 0))
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: Activating KeyCode conversion.\n", __func__);
      #endif

      fprintf(stderr, "Info: Keycode conversion auto-determined as on\n");
      nxagentKeycodeConversion = True;
    }
    else
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: Deactivating KeyCode conversion.\n", __func__);
      #endif

      fprintf(stderr, "Info: Keycode conversion auto-determined as off\n");
    }
  }
}

Bool nxagentGetRemoteXkbExtension(void)
{
  Bool result;

  nxagentXkbInfo.Opcode = nxagentXkbInfo.EventBase = nxagentXkbInfo.ErrorBase = nxagentXkbInfo.MajorVersion = nxagentXkbInfo.MinorVersion = -1;
  nxagentXkbClearNames();

  if ((result = XkbQueryExtension(nxagentDisplay,
                                 &nxagentXkbInfo.Opcode,
                                 &nxagentXkbInfo.EventBase,
                                 &nxagentXkbInfo.ErrorBase,
                                 &nxagentXkbInfo.MajorVersion,
                                 &nxagentXkbInfo.MinorVersion)))
  {
    nxagentXkbGetNames();
  }
  #ifdef WARNING
  else
  {
    fprintf(stderr, "%s: WARNING! Failed to query XKB extension.\n", __func__);
  }
  #endif

  return result;
}
#endif /* XKB */