File: screen.c

package info (click to toggle)
brltty 5.6-10~bpo9+1
  • links: PTS, VCS
  • area: main
  • in suites: stretch-backports
  • size: 25,116 kB
  • sloc: ansic: 117,871; sh: 6,590; java: 4,785; xml: 3,451; makefile: 1,973; tcl: 1,499; awk: 611; ml: 293; python: 250; lisp: 52
file content (1548 lines) | stat: -rw-r--r-- 46,558 bytes parent folder | download | duplicates (3)
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
/*
 * BRLTTY - A background process providing access to the console screen (when in
 *          text mode) for a blind person using a refreshable braille display.
 *
 * Copyright (C) 1995-2018 by The BRLTTY Developers.
 *
 * BRLTTY comes with ABSOLUTELY NO WARRANTY.
 *
 * This is free software, placed under the terms of the
 * GNU Lesser General Public License, as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any
 * later version. Please see the file LICENSE-LGPL for details.
 *
 * Web Page: http://brltty.com/
 *
 * This software is maintained by Dave Mielke <dave@mielke.cc>.
 */

#include "prologue.h"

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <locale.h>

#ifdef HAVE_ATSPI_GET_A11Y_BUS
#include <atspi/atspi.h>
#endif

#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif /* HAVE_LANGINFO_H */

#ifdef __MINGW32__
#include "win_pthread.h"
#else /* __MINGW32__ */
#include <semaphore.h>
#endif /* __MINGW32__ */

#include <dbus/dbus.h>
#define SPI2_DBUS_INTERFACE		"org.a11y.atspi"
#define SPI2_DBUS_INTERFACE_REG		SPI2_DBUS_INTERFACE".Registry"
#define SPI2_DBUS_PATH_REG		"/org/a11y/atspi/registry"
#define SPI2_DBUS_PATH_ROOT		"/org/a11y/atspi/accessible/root"
#define SPI2_DBUS_PATH_DEC		SPI2_DBUS_PATH_REG "/deviceeventcontroller"
#define SPI2_DBUS_INTERFACE_DEC		SPI2_DBUS_INTERFACE".DeviceEventController"
#define SPI2_DBUS_INTERFACE_DEL		SPI2_DBUS_INTERFACE".DeviceEventListener"
#define SPI2_DBUS_INTERFACE_EVENT	SPI2_DBUS_INTERFACE".Event"
#define SPI2_DBUS_INTERFACE_TREE	SPI2_DBUS_INTERFACE".Tree"
#define SPI2_DBUS_INTERFACE_TEXT	SPI2_DBUS_INTERFACE".Text"
#define SPI2_DBUS_INTERFACE_ACCESSIBLE	SPI2_DBUS_INTERFACE".Accessible"
#define FREEDESKTOP_DBUS_INTERFACE	"org.freedesktop.DBus"
#define FREEDESKTOP_DBUS_INTERFACE_PROP	FREEDESKTOP_DBUS_INTERFACE".Properties"


#define ATSPI_STATE_ACTIVE 1
#define ATSPI_STATE_FOCUSED 12

#ifdef HAVE_X11_KEYSYM_H
#include <X11/keysym.h>
#endif /* HAVE_X11_KEYSYM_H */

#include "log.h"
#include "parse.h"
#include "thread.h"
#include "brl_cmds.h"
#include "charset.h"
#include "async_io.h"
#include "async_alarm.h"
#include "async_event.h"

typedef enum {
  PARM_RELEASE,
  PARM_TYPE
} ScreenParameters;
#define SCRPARMS "release", "type"

#include "scr_driver.h"

typedef enum {
  TYPE_TEXT,
  TYPE_TERMINAL,
  TYPE_ALL,
  TYPE_COUNT
} TypeValue;

static unsigned int releaseScreen;
static unsigned char typeFlags[TYPE_COUNT];

static char *curSender;
static char *curPath;

static long curNumRows, curNumCols;
static wchar_t **curRows;
static long *curRowLengths;
static long curCaret,curPosX,curPosY;

static DBusConnection *bus = NULL;

static int updated;

/* having our own implementation is much more independant on locales */

typedef struct {
  int remaining;
  wint_t current;
} my_mbstate_t;

static my_mbstate_t internal;

static size_t my_mbrtowc(wchar_t *pwc, const char *s, size_t n, my_mbstate_t *ps) {
  const unsigned char *c = (const unsigned char *) s;
  int read = 0;
  if (!c) {
    if (ps->remaining) {
      errno = EILSEQ;
      return (size_t)(-1);
    }
    return 0;
  }

  if (n && !ps->remaining) {
    /* initial state */
    if (!(*c&0x80)) {
      /* most frequent case: ascii */
      if (pwc)
	*pwc = *c;
      if (!*c)
	return 0;
      return 1;
    } else if (!(*c&0x40)) {
      /* utf-8 char continuation, shouldn't happen with remaining == 0 ! */
      goto error;
    } else {
      /* new utf-8 char, get remaining chars */
      read = 1;
      if (!(*c&0x20)) {
	ps->remaining = 1;
	ps->current = *c&((1<<5)-1);
      } else if (!(*c&0x10)) {
	ps->remaining = 2;
	ps->current = *c&((1<<4)-1);
      } else if (!(*c&0x08)) {
	ps->remaining = 3;
	ps->current = *c&((1<<3)-1);
      } else if (!(*c&0x04)) {
	ps->remaining = 4;
	ps->current = *c&((1<<2)-1);
      } else if (!(*c&0x02)) {
	ps->remaining = 5;
	ps->current = *c&((1<<1)-1);
      } else
	/* 0xff and 0xfe are not allowed */
	goto error;
      c++;
    }
  }
  /* looking for continuation chars */
  while (n-read) {
    if ((*c&0xc0) != 0X80)
      /* not continuation char, error ! */
      goto error;
    /* utf-8 char continuation */
    ps->current = (ps->current<<6) | (*c&((1<<6)-1));
    read++;
    if (!(--ps->remaining)) {
      if (pwc)
	*pwc = ps->current;
      if (!ps->current)
	/* shouldn't coded this way, but well... */
	return 0;
      return read;
    }
    c++;
  }
  return (size_t)(-2);
error:
  errno = EILSEQ;
  return (size_t)(-1);
}

static size_t my_mbsrtowcs(wchar_t *dest, const char **src, size_t len, my_mbstate_t *ps) {
  int put = 0;
  size_t skip;
  wchar_t buf,*bufp;

  if (!ps) ps = &internal;
  if (dest)
    bufp = dest;
  else
    bufp = &buf;

  while (len-put || !dest) {
    skip = my_mbrtowc(bufp, *src, 6, ps);
    switch (skip) {
      case (size_t)(-2): errno = EILSEQ; /* shouldn't happen ! */
      case (size_t)(-1): return (size_t)(-1);
      case 0: *src = NULL; return put;
    }
    *src += skip;
    if (dest) bufp++;
    put++;
  }
  return put;
}

static size_t my_mbrlen(const char *s, size_t n, my_mbstate_t *ps) {
  return my_mbrtowc(NULL, s, n, ps?ps:&internal);
}

static size_t my_mbslen(const char *s, size_t n) {
  my_mbstate_t ps;
  size_t ret=0;
  size_t eaten;
  memset(&ps,0,sizeof(ps));
  while(n) {
    if ((ssize_t)(eaten = my_mbrlen(s,n,&ps))<0)
      return eaten;
    if (!(eaten)) return ret;
    s+=eaten;
    n-=eaten;
    ret++;
  }
  return ret;
}

static void addRows(long pos, long num) {
  curNumRows += num;
  curRows = realloc(curRows,curNumRows*sizeof(*curRows));
  curRowLengths = realloc(curRowLengths,curNumRows*sizeof(*curRowLengths));
  memmove(curRows      +pos+num,curRows      +pos,(curNumRows-(pos+num))*sizeof(*curRows));
  memmove(curRowLengths+pos+num,curRowLengths+pos,(curNumRows-(pos+num))*sizeof(*curRowLengths));
}

static void delRows(long pos, long num) {
  long y;
  for (y=pos;y<pos+num;y++)
    free(curRows[y]);
  memmove(curRows      +pos,curRows      +pos+num,(curNumRows-(pos+num))*sizeof(*curRows));
  memmove(curRowLengths+pos,curRowLengths+pos+num,(curNumRows-(pos+num))*sizeof(*curRowLengths));
  curNumRows -= num;
  curRows = realloc(curRows,curNumRows*sizeof(*curRows));
  curRowLengths = realloc(curRowLengths,curNumRows*sizeof(*curRowLengths));
}

static int
processParameters_AtSpi2Screen (char **parameters) {
  releaseScreen = 1;
  {
    const char *parameter = parameters[PARM_RELEASE];

    if (*parameter) {
      if (!validateYesNo(&releaseScreen, parameter)) {
        logMessage(LOG_WARNING, "invalid release screen setting: %s", parameter);
      }
    }
  }

  typeFlags[TYPE_TEXT] = 1;
  typeFlags[TYPE_TERMINAL] = 1;
  typeFlags[TYPE_ALL] = 0;
  {
    const char *parameter = parameters[PARM_TYPE];

    if (*parameter) {
      int count;
      char **types = splitString(parameter, '+', &count);

      if (types) {
        static const char *const choices[] = {
          [TYPE_TEXT] = "text",
          [TYPE_TERMINAL] = "terminal",
          [TYPE_ALL] = "all",
          [TYPE_COUNT] = NULL
        };

        for (unsigned int index=0; index<TYPE_COUNT; index+=1) {
          typeFlags[index] = 0;
        }

        for (unsigned int index=0; index<count; index+=1) {
          const char *type = types[index];
          unsigned int choice;

          if (validateChoice(&choice, type, choices)) {
            if ((choice == TYPE_ALL) && (index > 0)) {
              logMessage(LOG_WARNING, "widget type is mutually exclusive: %s", type);
            } else if (typeFlags[choice] || typeFlags[TYPE_ALL]) {
              logMessage(LOG_WARNING, "widget type specified more than once: %s", type);
            } else {
              typeFlags[choice] = 1;
            }
          } else {
            logMessage(LOG_WARNING, "%s: %s", "invalid widget type", type);
          }
        }

        deallocateStrings(types);
      }
    }
  }

  return 1;
}

/* Creates a method call message */
static DBusMessage *
new_method_call(const char *sender, const char *path, const char *interface, const char *method)
{
  DBusError error;
  DBusMessage *msg;

  dbus_error_init(&error);
  msg = dbus_message_new_method_call(sender, path, interface, method);
  if (dbus_error_is_set(&error)) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "error while making %s message: %s %s", method, error.name, error.message);

    dbus_error_free(&error);
    return NULL;
  }
  if (!msg) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "no memory while making %s message", method);
    return NULL;
  }
  return msg;
}

/* Sends a method call message, and returns the reply, if any. This unrefs the message.  */
static DBusMessage *
send_with_reply_and_block(DBusConnection *bus, DBusMessage *msg, int timeout_ms, const char *doing)
{
  DBusError error;
  DBusMessage *reply;

  dbus_error_init(&error);
  reply = dbus_connection_send_with_reply_and_block(bus, msg, timeout_ms, &error);
  dbus_message_unref(msg);
  if (dbus_error_is_set(&error)) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "error while %s: %s %s", doing, error.name, error.message);
    dbus_error_free(&error);
    return NULL;
  }
  if (!reply) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "timeout while %s", doing);
    return NULL;
  }
  if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "error while %s", doing);
    dbus_message_unref(reply);
    return NULL;
  }
  return reply;
}

static void findPosition(long position, long *px, long *py) {
  long offset=0, newoffset, x, y;
  /* XXX: I don't know what they do with necessary combining accents */
  for (y=0; y<curNumRows; y++) {
    if ((newoffset = offset + curRowLengths[y]) > position)
      break;
    offset = newoffset;
  }
  if (y==curNumRows) {
    if (!curNumRows) {
      y = 0;
      x = 0;
    } else {
      /* this _can_ happen, when deleting while caret is at the end of the
       * terminal: caret position is only updated afterwards... In the
       * meanwhile, keep caret at the end of last line. */
      y = curNumRows-1;
      x = curRowLengths[y];
    }
  } else
    x = position-offset;
  *px = x;
  *py = y;
}

static void caretPosition(long caret) {
  findPosition(caret,&curPosX,&curPosY);
  curCaret = caret;
}

static void finiTerm(void) {
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "end of term %s:%s",curSender,curPath);
  free(curSender);
  curSender = NULL;
  free(curPath);
  curPath = NULL;
  curPosX = curPosY = 0;
  free(curRows);
  curRows = NULL;
  curNumCols = curNumRows = 0;
}

/* Get the role of an AT-SPI2 object */
static char *getRole(const char *sender, const char *path) {
  const char *text;
  char *res = NULL;
  DBusMessage *msg, *reply;
  DBusMessageIter iter;

  msg = new_method_call(sender, path, SPI2_DBUS_INTERFACE_ACCESSIBLE, "GetRoleName");
  if (!msg)
    return NULL;
  reply = send_with_reply_and_block(bus, msg, 1000, "getting role");
  if (!reply)
    return NULL;

  dbus_message_iter_init(reply, &iter);
  if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "GetRoleName didn't return a string but '%c'", dbus_message_iter_get_arg_type(&iter));
    goto out;
  }
  dbus_message_iter_get_basic(&iter, &text);
  res = strdup(text);

out:
  dbus_message_unref(reply);
  return res;
}

/* Get the text of an AT-SPI2 object */
static char *getText(const char *sender, const char *path) {
  const char *text;
  char *res = NULL;
  DBusMessage *msg, *reply;
  dbus_int32_t begin = 0;
  dbus_int32_t end = -1;
  DBusMessageIter iter;

  msg = new_method_call(sender, path, SPI2_DBUS_INTERFACE_TEXT, "GetText");
  if (!msg)
    return NULL;
  dbus_message_append_args(msg, DBUS_TYPE_INT32, &begin, DBUS_TYPE_INT32, &end, DBUS_TYPE_INVALID);
  reply = send_with_reply_and_block(bus, msg, 1000, "getting text");
  if (!reply)
    return NULL;

  dbus_message_iter_init(reply, &iter);
  if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "GetText didn't return a string but '%c'", dbus_message_iter_get_arg_type(&iter));
    goto out;
  }
  dbus_message_iter_get_basic(&iter, &text);
  res = strdup(text);

out:
  dbus_message_unref(reply);
  return res;
}

/* Get the caret of an AT-SPI2 object */
static dbus_int32_t getCaret(const char *sender, const char *path) {
  dbus_int32_t res = -1;
  DBusMessage *msg, *reply = NULL;
  const char *interface = SPI2_DBUS_INTERFACE_TEXT;
  const char *property = "CaretOffset";
  DBusMessageIter iter, iter_variant;

  msg = new_method_call(sender, path, FREEDESKTOP_DBUS_INTERFACE_PROP, "Get");
  if (!msg)
    return -1;
  dbus_message_append_args(msg, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID);
  reply = send_with_reply_and_block(bus, msg, 1000, "getting caret");
  if (!reply)
    return -1;

  dbus_message_iter_init(reply, &iter);
  if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "getText didn't return a variant but '%c'", dbus_message_iter_get_arg_type(&iter));
    goto out;
  }
  dbus_message_iter_recurse(&iter, &iter_variant);
  if (dbus_message_iter_get_arg_type(&iter_variant) != DBUS_TYPE_INT32) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "getText didn't return an int32 but '%c'", dbus_message_iter_get_arg_type(&iter_variant));
    goto out;
  }
  dbus_message_iter_get_basic(&iter_variant, &res);
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "Got caret %d", res);

out:
  dbus_message_unref(reply);
  return res;
}

/* Switched to a new terminal, restart from scratch */
static void restartTerm(const char *sender, const char *path) {
  char *c,*d;
  const char *e;
  long i,len;
  char *text;

  if (curPath)
    finiTerm();

  text = getText(sender, path);
  if (!text)
    return;

  curSender = strdup(sender);
  curPath = strdup(path);
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "new term %s:%s with text %s",curSender,curPath, text);

  if (curRows) {
    for (i=0;i<curNumRows;i++)
      free(curRows[i]);
    free(curRows);
  }
  curNumRows = 0;
  free(curRowLengths);
  c = text;
  while (*c) {
    curNumRows++;
    if (!(c = strchr(c,'\n')))
      break;
    c++;
  }
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "%ld rows",curNumRows);
  curRows = malloc(curNumRows * sizeof(*curRows));
  curRowLengths = malloc(curNumRows * sizeof(*curRowLengths));
  i = 0;
  curNumCols = 0;
  for (c = text; *c; c = d+1) {
    d = strchr(c,'\n');
    if (d)
      *d = 0;
    e = c;
    curRowLengths[i] = (len = my_mbsrtowcs(NULL,&e,0,NULL)) + (d != NULL);
    if (len > curNumCols)
      curNumCols = len;
    else if (len < 0) {
      if (len==-2)
	logMessage(LOG_ERR,"unterminated sequence %s",c);
      else if (len==-1)
	logSystemError("mbrlen");
      curRowLengths[i] = (len = -1) + (d != NULL);
    }
    curRows[i] = malloc((len + (d!=NULL)) * sizeof(*curRows[i]));
    e = c;
    my_mbsrtowcs(curRows[i],&e,len,NULL);
    if (d)
      curRows[i][len]='\n';
    else
      break;
    i++;
  }
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "%ld cols",curNumCols);
  caretPosition(getCaret(sender, path));
  free(text);
}

/* Switched to a new object, check whether we want to read it, and if so, restart with it */
static void tryRestartTerm(const char *sender, const char *path) {
  char *role = getRole(sender, path);
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "state changed focus to role %s", role);
  if (typeFlags[TYPE_ALL] ||
      (role && typeFlags[TYPE_TEXT] && (strcmp(role, "text") == 0)) ||
      (role && typeFlags[TYPE_TERMINAL] && (strcmp(role, "terminal") == 0))) {
    restartTerm(sender, path);
  } else {
    if (curPath)
      finiTerm();
  }
  free(role);
}

/* Get the state of an object */
static dbus_uint32_t *getState(const char *sender, const char *path)
{
  DBusMessage *msg, *reply;
  DBusMessageIter iter, iter_array;
  dbus_uint32_t *states, *ret = NULL;
  int count;

  msg = new_method_call(sender, path, SPI2_DBUS_INTERFACE_ACCESSIBLE, "GetState");
  if (!msg)
    return NULL;
  reply = send_with_reply_and_block(bus, msg, 1000, "getting state");
  if (!reply)
    return NULL;

  if (strcmp (dbus_message_get_signature (reply), "au") != 0)
  {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "unexpected signature %s while getting active state", dbus_message_get_signature(reply));
    goto out;
  }
  dbus_message_iter_init (reply, &iter);
  dbus_message_iter_recurse (&iter, &iter_array);
  dbus_message_iter_get_fixed_array (&iter_array, &states, &count);
  if (count != 2)
  {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "unexpected signature %s while getting active state", dbus_message_get_signature(reply));
    goto out;
  }
  ret = malloc(sizeof(*ret) * count);
  memcpy(ret, states, sizeof(*ret) * count);

out:
  dbus_message_unref(reply);
  return ret;
}

/* Check whether an ancestor of this object is active */
static int checkActiveParent(const char *sender, const char *path) {
  DBusMessage *msg, *reply;
  DBusMessageIter iter, iter_variant, iter_struct;
  int res = 0;
  const char *interface = SPI2_DBUS_INTERFACE_ACCESSIBLE;
  const char *property = "Parent";
  dbus_uint32_t *states;

  msg = new_method_call(sender, path, FREEDESKTOP_DBUS_INTERFACE_PROP, "Get");
  if (!msg)
    return 0;
  dbus_message_append_args(msg, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID);
  reply = send_with_reply_and_block(bus, msg, 1000, "checking active object");
  if (!reply)
    return 0;

  if (strcmp (dbus_message_get_signature (reply), "v") != 0)
  {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "unexpected signature %s while checking active object", dbus_message_get_signature(reply));
    goto out;
  }

  dbus_message_iter_init (reply, &iter);
  dbus_message_iter_recurse (&iter, &iter_variant);
  dbus_message_iter_recurse (&iter_variant, &iter_struct);
  dbus_message_iter_get_basic (&iter_struct, &sender);
  dbus_message_iter_next (&iter_struct);
  dbus_message_iter_get_basic (&iter_struct, &path);

  states = getState(sender, path);
  if (states) {
    res = (states[0] & (1<<ATSPI_STATE_ACTIVE)) != 0 || checkActiveParent(sender, path);
    free(states);
  } else {
    res = 0;
  }

out:
  dbus_message_unref(reply);
  return res;
}

/* Check whether this object is the focused object (which is way faster than
 * browsing all objects of the desktop) */
static int reinitTerm(const char *sender, const char *path) {
  dbus_uint32_t *states = getState(sender, path);
  int active = 0;

  if (!states)
    return 0;

  /* Whether this widget is active */
  active = (states[0] & (1<<ATSPI_STATE_ACTIVE)) != 0;

  if (states[0] & (1<<ATSPI_STATE_FOCUSED)) {
    free(states);
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "%s %s is focused!", sender, path);
    /* This widget is focused */
    if (active) {
      /* And it is active, we are done.  */
      tryRestartTerm(sender, path);
      return 1;
    } else {
      /* Check that a parent is active.  */
      return checkActiveParent(sender, path);
    }
  }

  free(states);
  return 0;
}

/* Try to find an active object among children of the given object */

/* We need to take care of bogus applications which have children loops, so we
 * need to compare newly found children with the list of ancestors */
struct pathList {
  const char *sender;
  const char *path;
  struct pathList *prev;
  int loop;
};
static int findTerm(const char *sender, const char *path, int active, int depth, struct pathList *list);
static int recurseFindTerm(const char *sender, const char *path, int active, int depth, struct pathList *list) {
  DBusMessage *msg, *reply;
  DBusMessageIter iter, iter_array, iter_struct;
  int res = 0;

  msg = new_method_call(sender, path, SPI2_DBUS_INTERFACE_ACCESSIBLE, "GetChildren");
  if (!msg)
    return 0;
  reply = send_with_reply_and_block(bus, msg, 1000, "getting active object");
  if (!reply)
    return 0;

  if (strcmp (dbus_message_get_signature (reply), "a(so)") != 0)
  {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "unexpected signature %s while getting active object", dbus_message_get_signature(reply));
    goto out;
  }
  dbus_message_iter_init(reply, &iter);
  dbus_message_iter_recurse (&iter, &iter_array);
  while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
  {
    const char *childsender, *childpath;
    struct pathList *cur;

    dbus_message_iter_recurse (&iter_array, &iter_struct);
    dbus_message_iter_get_basic (&iter_struct, &childsender);
    dbus_message_iter_next (&iter_struct);
    dbus_message_iter_get_basic (&iter_struct, &childpath);

    /* Make sure that the child is not the same as an ancestor, to avoid
     * recursing indefinitely.  */
    for (cur = list; cur; cur = cur->prev)
      if (!strcmp(childsender, cur->sender) && !strcmp(childpath, cur->path))
      {
	/* Loop detected, avoid continuing looking at this part of the tree
	which is not actually a tree! */
	cur->loop = 1;
	break;
      }
    if (! cur)
    {
      struct pathList me = {
	.sender = sender,
	.path = path,
	.prev = list,
      };
      if (findTerm(childsender, childpath, active, depth, &me))
      {
	res = 1;
	goto out;
      }
      if (me.loop) {
        /* There is a loop up to us.  Avoid continuing looking here which may
         * entail an exponential number of lookups. */
	break;
      }
    }

    dbus_message_iter_next (&iter_array);
  }

out:
  dbus_message_unref(reply);
  return res;
}

/* Test whether this object is active, and if not recurse in its children */
static int findTerm(const char *sender, const char *path, int active, int depth, struct pathList *list) {
  dbus_uint32_t *states = getState(sender, path);

  if (!states)
    return 0;

  if (states[0] & (1<<ATSPI_STATE_ACTIVE))
    /* This application is active */
    active = 1;

  if (states[0] & (1<<ATSPI_STATE_FOCUSED) && active)
  {
    /* And this widget is focused */
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "%s %s is focused!", sender, path);
    free(states);
    tryRestartTerm(sender, path);
    return 1;
  }

  free(states);
  return recurseFindTerm(sender, path, active, depth+1, list);
}

/* Find out currently focused terminal, starting from registry */
static void initTerm(void) {
  recurseFindTerm(SPI2_DBUS_INTERFACE_REG, SPI2_DBUS_PATH_ROOT, 0, 0, NULL);
}

/* Handle incoming events */
static void AtSpi2HandleEvent(const char *interface, DBusMessage *message)
{
  DBusMessageIter iter, iter_variant;
  const char *detail;
  dbus_int32_t detail1, detail2;
  const char *member = dbus_message_get_member(message);
  const char *sender = dbus_message_get_sender(message);
  const char *path = dbus_message_get_path(message);
  int StateChanged_focused;

  dbus_message_iter_init(message, &iter);

  if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_STRUCT) {
    /* skip struct */
    dbus_message_iter_next(&iter);
  }

  if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "message detail not a string but '%c'", dbus_message_iter_get_arg_type(&iter));
    return;
  }
  dbus_message_iter_get_basic(&iter, &detail);

  dbus_message_iter_next(&iter);
  if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INT32) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "message detail1 not an int32 but '%c'", dbus_message_iter_get_arg_type(&iter));
    return;
  }
  dbus_message_iter_get_basic(&iter, &detail1);

  dbus_message_iter_next(&iter);
  if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INT32) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "message detail2 not an int32 but '%c'", dbus_message_iter_get_arg_type(&iter));
    return;
  }
  dbus_message_iter_get_basic(&iter, &detail2);

  dbus_message_iter_next(&iter);
  if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "message detail2 not a variant but '%c'", dbus_message_iter_get_arg_type(&iter));
    return;
  }
  dbus_message_iter_recurse(&iter, &iter_variant);

  StateChanged_focused =
       !strcmp(interface, "Object")
    && !strcmp(member, "StateChanged")
    && !strcmp(detail, "focused");

  if (StateChanged_focused && !detail1) {
    if (curSender && !strcmp(sender, curSender) && !strcmp(path, curPath))
      finiTerm();
  } else if (!strcmp(interface,"Focus") || (StateChanged_focused && detail1)) {
    tryRestartTerm(sender, path);
  } else if (!strcmp(interface, "Object") && !strcmp(member, "TextCaretMoved")) {
    if (!curSender || strcmp(sender, curSender) || strcmp(path, curPath)) return;
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "caret move to %d", detail1);
    caretPosition(detail1);
  } else if (!strcmp(interface, "Object") && !strcmp(member, "TextChanged") && !strcmp(detail, "delete")) {
    long x,y,toDelete = detail2;
    const char *deleted;
    long length = 0, toCopy;
    long downTo; /* line that will provide what will follow x */
    if (!curSender || strcmp(sender, curSender) || strcmp(path, curPath)) return;
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "delete %d from %d",detail2,detail1);
    findPosition(detail1,&x,&y);
    if (dbus_message_iter_get_arg_type(&iter_variant) != DBUS_TYPE_STRING) {
      logMessage(LOG_CATEGORY(SCREEN_DRIVER),
                 "ergl, not string but '%c'", dbus_message_iter_get_arg_type(&iter_variant));
      return;
    }
    dbus_message_iter_get_basic(&iter_variant, &deleted);
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "'%s'",deleted);
    downTo = y;
    if (downTo < curNumRows)
      length = curRowLengths[downTo];
    while (x+toDelete >= length) {
      downTo++;
      if (downTo <= curNumRows - 1)
	length += curRowLengths[downTo];
      else {
	/* imaginary extra line doesn't provide more length, and shouldn't need to ! */
	if (x+toDelete > length) {
	  logMessage(LOG_ERR,"deleting past end of text !");
	  /* discarding */
	  toDelete = length - x;
	}
	break; /* deleting up to end */
      }
    }
    if (length-toDelete>0) {
      /* still something on line y */
      if (y!=downTo) {
	curRowLengths[y] = length-toDelete;
	curRows[y]=realloc(curRows[y],curRowLengths[y]*sizeof(*curRows[y]));
      }
      if ((toCopy = length-toDelete-x))
	memmove(curRows[y]+x,curRows[downTo]+curRowLengths[downTo]-toCopy,toCopy*sizeof(*curRows[downTo]));
      if (y==downTo) {
	curRowLengths[y] = length-toDelete;
	curRows[y]=realloc(curRows[y],curRowLengths[y]*sizeof(*curRows[y]));
      }
    } else {
      /* kills this line as well ! */
      y--;
    }
    if (downTo>=curNumRows)
      /* imaginary extra lines don't need to be deleted */
      downTo=curNumRows-1;
    delRows(y+1,downTo-y);
    caretPosition(curCaret);
  } else if (!strcmp(interface, "Object") && !strcmp(member, "TextChanged") && !strcmp(detail, "insert")) {
    long len=detail2,semilen,x,y;
    const char *added;
    const char *adding,*c;
    if (!curSender || strcmp(sender, curSender) || strcmp(path, curPath)) return;
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "insert %d from %d",detail2,detail1);
    findPosition(detail1,&x,&y);
    if (dbus_message_iter_get_arg_type(&iter_variant) != DBUS_TYPE_STRING) {
      logMessage(LOG_CATEGORY(SCREEN_DRIVER),
                 "ergl, not string but '%c'", dbus_message_iter_get_arg_type(&iter_variant));
      return;
    }
    dbus_message_iter_get_basic(&iter_variant, &added);
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "'%s'",added);
    adding = c = added;
    if (x && (c = strchr(adding,'\n'))) {
      /* splitting line */
      addRows(y,1);
      semilen=my_mbslen(adding,c+1-adding);
      curRowLengths[y]=x+semilen;
      if (x+semilen-1>curNumCols)
	curNumCols=x+semilen-1;

      /* copy beginning */
      curRows[y]=malloc(curRowLengths[y]*sizeof(*curRows[y]));
      memcpy(curRows[y],curRows[y+1],x*sizeof(*curRows[y]));
      /* add */
      my_mbsrtowcs(curRows[y]+x,&adding,semilen,NULL);
      len-=semilen;
      adding=c+1;
      /* shift end */
      curRowLengths[y+1]-=x;
      memmove(curRows[y+1],curRows[y+1]+x,curRowLengths[y+1]*sizeof(*curRows[y+1]));
      x=0;
      y++;
    }
    while ((c = strchr(adding,'\n'))) {
      /* adding lines */
      addRows(y,1);
      semilen=my_mbslen(adding,c+1-adding);
      curRowLengths[y]=semilen;
      if (semilen-1>curNumCols)
	curNumCols=semilen-1;
      curRows[y]=malloc(semilen*sizeof(*curRows[y]));
      my_mbsrtowcs(curRows[y],&adding,semilen,NULL);
      len-=semilen;
      adding=c+1;
      y++;
    }
    if (len) {
      /* still length to add on the line following it */
      if (y==curNumRows) {
	/* It won't insert ending \n yet */
	addRows(y,1);
	curRows[y]=NULL;
	curRowLengths[y]=0;
      }
      curRowLengths[y] += len;
      curRows[y]=realloc(curRows[y],curRowLengths[y]*sizeof(*curRows[y]));
      memmove(curRows[y]+x+len,curRows[y]+x,(curRowLengths[y]-(x+len))*sizeof(*curRows[y]));
      my_mbsrtowcs(curRows[y]+x,&adding,len,NULL);
      if (curRowLengths[y]-(curRows[y][curRowLengths[y]-1]=='\n')>curNumCols)
	curNumCols=curRowLengths[y]-(curRows[y][curRowLengths[y]-1]=='\n');
    }
    caretPosition(curCaret);
  } else {
    return;
  }
  updated = 1;
}

static DBusHandlerResult AtSpi2Filter(DBusConnection *connection, DBusMessage *message, void *user_data)
{
  int type = dbus_message_get_type(message);
  const char *interface = dbus_message_get_interface(message);
  const char *member = dbus_message_get_member(message);

  if (type == DBUS_MESSAGE_TYPE_SIGNAL) {
    if (!strncmp(interface, SPI2_DBUS_INTERFACE_EVENT".", strlen(SPI2_DBUS_INTERFACE_EVENT"."))) {
      AtSpi2HandleEvent(interface + strlen(SPI2_DBUS_INTERFACE_EVENT"."), message);
    } else if (!strcmp(interface, DBUS_INTERFACE_LOCAL) &&
               !strcmp(member, "Disconnected")) {
      logMessage(LOG_CATEGORY(SCREEN_DRIVER),
                 "DBus disconnected signal, shutting down");
#ifdef SIGTERM
      raise(SIGTERM);
#endif
#ifdef SIGINT
      raise(SIGINT);
#endif
    } else {
      logMessage(LOG_CATEGORY(SCREEN_DRIVER),
                 "unknown signal: Intf:%s Msg:%s", interface, member);
    }
  } else {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "unknown message: Type:%d Intf:%s Msg:%s", type, interface, member);
  }

  return DBUS_HANDLER_RESULT_HANDLED;
}

/* Integration of DBus watches with brltty monitors */

struct a2Watch
{
  AsyncHandle input_monitor;
  AsyncHandle output_monitor;
  DBusWatch *watch;
};

int a2ProcessWatch(const AsyncMonitorCallbackParameters *parameters, int flags)
{
  struct a2Watch *a2Watch = parameters->data;
  DBusWatch *watch = a2Watch->watch;
  /* Read/Write on socket */
  dbus_watch_handle(watch, parameters->error?DBUS_WATCH_ERROR:flags);
  /* And process messages */
  while (dbus_connection_dispatch(bus) != DBUS_DISPATCH_COMPLETE)
    ;
  if (updated)
  {
    updated = 0;
    mainScreenUpdated();
  }
  return dbus_watch_get_enabled(watch);
}

ASYNC_MONITOR_CALLBACK(a2ProcessInput) {
  if (a2ProcessWatch(parameters, DBUS_WATCH_READABLE)) return 1;

  struct a2Watch *a2Watch = parameters->data;
  asyncDiscardHandle(a2Watch->input_monitor);
  a2Watch->input_monitor = NULL;
  return 0;
}

ASYNC_MONITOR_CALLBACK(a2ProcessOutput) {
  if (a2ProcessWatch(parameters, DBUS_WATCH_WRITABLE)) return 1;

  struct a2Watch *a2Watch = parameters->data;
  asyncDiscardHandle(a2Watch->output_monitor);
  a2Watch->output_monitor = NULL;
  return 0;
}

dbus_bool_t a2AddWatch(DBusWatch *watch, void *data)
{
  struct a2Watch *a2Watch = calloc(1, sizeof(*a2Watch));
  a2Watch->watch = watch;
  int flags = dbus_watch_get_flags(watch);
  if (dbus_watch_get_enabled(watch))
  {
    if (flags & DBUS_WATCH_READABLE)
      asyncMonitorFileInput(&a2Watch->input_monitor, dbus_watch_get_unix_fd(watch), a2ProcessInput, a2Watch);
    if (flags & DBUS_WATCH_WRITABLE)
      asyncMonitorFileOutput(&a2Watch->output_monitor, dbus_watch_get_unix_fd(watch), a2ProcessOutput, a2Watch);
  }
  dbus_watch_set_data(watch, a2Watch, NULL);
  return TRUE;
}

void a2RemoveWatch(DBusWatch *watch, void *data)
{
  struct a2Watch *a2Watch = dbus_watch_get_data(watch);
  dbus_watch_set_data(watch, NULL, NULL);
  if (a2Watch->input_monitor)
    asyncCancelRequest(a2Watch->input_monitor);
  if (a2Watch->output_monitor)
    asyncCancelRequest(a2Watch->output_monitor);
  free(a2Watch);
}

void a2WatchToggled(DBusWatch *watch, void *data)
{
  if (dbus_watch_get_enabled(watch)) {
    if (!dbus_watch_get_data(watch))
      a2AddWatch(watch, data);
  } else {
    if (dbus_watch_get_data(watch))
      a2RemoveWatch(watch, data);
  }
}

/* Integration of DBus timeouts with brltty monitors */

struct a2Timeout
{
  AsyncHandle monitor;
  DBusTimeout *timeout;
};

ASYNC_ALARM_CALLBACK(a2ProcessTimeout)
{
  struct a2Timeout *a2Timeout = parameters->data;
  DBusTimeout *timeout = a2Timeout->timeout;
  /* Process timeout */
  dbus_timeout_handle(timeout);
  /* And process messages */
  while (dbus_connection_dispatch(bus) != DBUS_DISPATCH_COMPLETE)
    ;
  if (updated)
  {
    updated = 0;
    mainScreenUpdated();
  }
  asyncDiscardHandle(a2Timeout->monitor);
  a2Timeout->monitor = NULL;
  if (dbus_timeout_get_enabled(timeout))
    /* Still enabled, requeue it */
    asyncNewRelativeAlarm(&a2Timeout->monitor, dbus_timeout_get_interval(timeout), a2ProcessTimeout, a2Timeout);
}

dbus_bool_t a2AddTimeout(DBusTimeout *timeout, void *data)
{
  struct a2Timeout *a2Timeout = calloc(1, sizeof(*a2Timeout));
  a2Timeout->timeout = timeout;
  if (dbus_timeout_get_enabled(timeout))
    asyncNewRelativeAlarm(&a2Timeout->monitor, dbus_timeout_get_interval(timeout), a2ProcessTimeout, a2Timeout);
  dbus_timeout_set_data(timeout, a2Timeout, NULL);
  return TRUE;
}

void a2RemoveTimeout(DBusTimeout *timeout, void *data)
{
  struct a2Timeout *a2Timeout = dbus_timeout_get_data(timeout);
  dbus_timeout_set_data(timeout, NULL, NULL);
  if (a2Timeout->monitor)
    asyncCancelRequest(a2Timeout->monitor);
  free(a2Timeout);
}

void a2TimeoutToggled(DBusTimeout *timeout, void *data)
{
  if (dbus_timeout_get_enabled(timeout)) {
    if (!dbus_timeout_get_data(timeout))
      a2AddTimeout(timeout, data);
  } else {
    if (dbus_timeout_get_data(timeout))
      a2RemoveTimeout(timeout, data);
  }
}

/* Driver construction / destruction */

static int addWatch(const char *message, const char *event) {
  DBusError error;
  DBusMessage *msg, *reply;

  dbus_error_init(&error);
  dbus_bus_add_match(bus, message, &error);
  if (dbus_error_is_set(&error)) {
    logMessage(LOG_ERR, "error while adding watch %s: %s %s", message, error.name, error.message);
    dbus_error_free(&error);
    return 0;
  }
 
  if (!event)
    return 1;

  /* Register as event listener. */
  msg = new_method_call(SPI2_DBUS_INTERFACE_REG, SPI2_DBUS_PATH_REG, SPI2_DBUS_INTERFACE_REG, "RegisterEvent");
  if (!msg)
    return 0;
  dbus_message_append_args(msg, DBUS_TYPE_STRING, &event, DBUS_TYPE_INVALID);
  reply = send_with_reply_and_block(bus, msg, 1000, "registering listener");
  if (!reply)
    return 0;

  dbus_message_unref(reply);
  return 1;
}

static int
addWatches (void) {
  typedef struct {
    const char *message;
    const char *event;
  } WatchEntry;

  static const WatchEntry watchTable[] = {
    { .message = "type='method_call',interface='"SPI2_DBUS_INTERFACE_TREE"'",
      .event = NULL
    },

    { .message = "type='signal',interface='"SPI2_DBUS_INTERFACE_EVENT".Focus'",
      .event = "focus"
    },

    { .message = "type='signal',interface='"SPI2_DBUS_INTERFACE_EVENT".Object'",
      .event = "object"
    },

    { .message = "type='signal',interface='"SPI2_DBUS_INTERFACE_EVENT".Object',member='ChildrenChanged'",
      .event = "object:childrenchanged"
    },

    { .message = "type='signal',interface='"SPI2_DBUS_INTERFACE_EVENT".Object',member='TextChanged'",
      .event = "object:textchanged"
    },

    { .message = "type='signal',interface='"SPI2_DBUS_INTERFACE_EVENT".Object',member='TextCaretMoved'",
      .event = "object:textcaretmoved"
    },

    { .message = "type='signal',interface='"SPI2_DBUS_INTERFACE_EVENT".Object',member='StateChanged'",
      .event = "object:statechanged"
    },

    { .message = NULL }
  };

  for (const WatchEntry *watch=watchTable; watch->message; watch+=1) {
    if (!addWatch(watch->message, watch->event)) return 0;
  }

  return 1;
}

static int
construct_AtSpi2Screen (void) {
  DBusError error;

  dbus_error_init(&error);
#ifdef HAVE_ATSPI_GET_A11Y_BUS
  bus = atspi_get_a11y_bus();
  if (!bus)
#endif
  {
    bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
    if (dbus_error_is_set(&error)) {
      logMessage(LOG_ERR, "can't get dbus session bus: %s %s", error.name, error.message);
      dbus_error_free(&error);
      goto noBus;
    }
  }

  if (!bus) {
    logMessage(LOG_ERR, "can't get dbus session bus");
    goto noBus;
  }

  if (!dbus_connection_add_filter(bus, AtSpi2Filter, NULL, NULL)) goto noConnection;
  if (!addWatches()) goto noWatches;

  if (!curPath) {
    initTerm();
  } else if (!reinitTerm(curSender, curPath)) {
    logMessage(LOG_CATEGORY(SCREEN_DRIVER),
               "caching failed, restarting from scratch");
    initTerm();
  }

  dbus_connection_set_watch_functions(bus, a2AddWatch, a2RemoveWatch, a2WatchToggled, NULL, NULL);
  dbus_connection_set_timeout_functions(bus, a2AddTimeout, a2RemoveTimeout, a2TimeoutToggled, NULL, NULL);

  logMessage(LOG_CATEGORY(SCREEN_DRIVER), "SPI2 initialized");
  return 1;

noWatches:

noConnection:
  dbus_connection_unref(bus);

noBus:
  return 0;
}

static void
destruct_AtSpi2Screen (void) {
  dbus_connection_remove_filter(bus, AtSpi2Filter, NULL);
  dbus_connection_close(bus);
  dbus_connection_unref(bus);
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "SPI2 stopped");
}

static int
selectVirtualTerminal_AtSpi2Screen (int vt) {
  return 0;
}

static int
switchVirtualTerminal_AtSpi2Screen (int vt) {
  return 0;
}

static int
currentVirtualTerminal_AtSpi2Screen (void) {
  return (curPath || !releaseScreen)? 0: SCR_NO_VT;
}

static const char nonatspi [] = "not an AT-SPI2 text widget";

static int
poll_AtSpi2Screen (void)
{
  return 0;
}

ASYNC_EVENT_CALLBACK(AtSpi2ScreenUpdated) {
  mainScreenUpdated();
}

static int
refresh_AtSpi2Screen (void)
{
  return 1;
}

static void
describe_AtSpi2Screen (ScreenDescription *description) {
  if (curPath) {
    description->cols = curPosX>=curNumCols?curPosX+1:curNumCols;
    description->rows = curNumRows?curNumRows:1;
    description->posx = curPosX;
    description->posy = curPosY;
  } else {
    const char *message = nonatspi;
    if (releaseScreen) description->unreadable = message;

    description->rows = 1;
    description->cols = strlen(message);
    description->posx = 0;
    description->posy = 0;
  }

  description->number = currentVirtualTerminal_AtSpi2Screen();
}

static int
readCharacters_AtSpi2Screen (const ScreenBox *box, ScreenCharacter *buffer) {
  clearScreenCharacters(buffer, (box->height * box->width));

  if (!curPath) {
    setScreenMessage(box, buffer, nonatspi);
    return 1;
  }

  if (!curNumCols || !curNumRows) return 0;
  short cols = (curPosX >= curNumCols)? (curPosX + 1): curNumCols;
  if (!validateScreenBox(box, cols, curNumRows)) return 0;

  for (unsigned int y=0; y<box->height; y+=1) {
    if (curRowLengths[box->top+y]) {
      for (unsigned int x=0; x<box->width; x+=1) {
        if (box->left+x < curRowLengths[box->top+y] - (curRows[box->top+y][curRowLengths[box->top+y]-1]=='\n')) {
          buffer[y*box->width+x].text = curRows[box->top+y][box->left+x];
        }
      }
    }
  }

  return 1;
}

enum key_type_e {
  PRESS,
  RELEASE,
  PRESSRELEASE,
  SYM
};

static int
AtSpi2GenerateKeyboardEvent (dbus_uint32_t keysym, enum key_type_e key_type)
{
  DBusMessage *msg, *reply;
  char *s = "";

  msg = new_method_call(SPI2_DBUS_INTERFACE_REG, SPI2_DBUS_PATH_DEC, SPI2_DBUS_INTERFACE_DEC, "GenerateKeyboardEvent");
  if (!msg)
    return 0;
  dbus_message_append_args(msg, DBUS_TYPE_INT32, &keysym, DBUS_TYPE_STRING, &s, DBUS_TYPE_UINT32, &key_type, DBUS_TYPE_INVALID);
  reply = send_with_reply_and_block(bus, msg, 1000, "generating keyboard event");
  if (!reply)
    return 0;

  return 1;
}

static int
insertKey_AtSpi2Screen (ScreenKey key) {
  long keysym;
  int modMeta=0, modControl=0;

  setScreenKeyModifiers(&key, SCR_KEY_CONTROL);

  if (isSpecialKey(key)) {
    switch (key & SCR_KEY_CHAR_MASK) {
#ifdef HAVE_X11_KEYSYM_H
      case SCR_KEY_ENTER:         keysym = XK_KP_Enter;  break;
      case SCR_KEY_TAB:           keysym = XK_Tab;       break;
      case SCR_KEY_BACKSPACE:     keysym = XK_BackSpace; break;
      case SCR_KEY_ESCAPE:        keysym = XK_Escape;    break;
      case SCR_KEY_CURSOR_LEFT:   keysym = XK_Left;      break;
      case SCR_KEY_CURSOR_RIGHT:  keysym = XK_Right;     break;
      case SCR_KEY_CURSOR_UP:     keysym = XK_Up;        break;
      case SCR_KEY_CURSOR_DOWN:   keysym = XK_Down;      break;
      case SCR_KEY_PAGE_UP:       keysym = XK_Page_Up;   break;
      case SCR_KEY_PAGE_DOWN:     keysym = XK_Page_Down; break;
      case SCR_KEY_HOME:          keysym = XK_Home;      break;
      case SCR_KEY_END:           keysym = XK_End;       break;
      case SCR_KEY_INSERT:        keysym = XK_Insert;    break;
      case SCR_KEY_DELETE:        keysym = XK_Delete;    break;
      case SCR_KEY_FUNCTION + 0:  keysym = XK_F1;        break;
      case SCR_KEY_FUNCTION + 1:  keysym = XK_F2;        break;
      case SCR_KEY_FUNCTION + 2:  keysym = XK_F3;        break;
      case SCR_KEY_FUNCTION + 3:  keysym = XK_F4;        break;
      case SCR_KEY_FUNCTION + 4:  keysym = XK_F5;        break;
      case SCR_KEY_FUNCTION + 5:  keysym = XK_F6;        break;
      case SCR_KEY_FUNCTION + 6:  keysym = XK_F7;        break;
      case SCR_KEY_FUNCTION + 7:  keysym = XK_F8;        break;
      case SCR_KEY_FUNCTION + 8:  keysym = XK_F9;        break;
      case SCR_KEY_FUNCTION + 9:  keysym = XK_F10;       break;
      case SCR_KEY_FUNCTION + 10: keysym = XK_F11;       break;
      case SCR_KEY_FUNCTION + 11: keysym = XK_F12;       break;
      case SCR_KEY_FUNCTION + 12: keysym = XK_F13;       break;
      case SCR_KEY_FUNCTION + 13: keysym = XK_F14;       break;
      case SCR_KEY_FUNCTION + 14: keysym = XK_F15;       break;
      case SCR_KEY_FUNCTION + 15: keysym = XK_F16;       break;
      case SCR_KEY_FUNCTION + 16: keysym = XK_F17;       break;
      case SCR_KEY_FUNCTION + 17: keysym = XK_F18;       break;
      case SCR_KEY_FUNCTION + 18: keysym = XK_F19;       break;
      case SCR_KEY_FUNCTION + 19: keysym = XK_F20;       break;
      case SCR_KEY_FUNCTION + 20: keysym = XK_F21;       break;
      case SCR_KEY_FUNCTION + 21: keysym = XK_F22;       break;
      case SCR_KEY_FUNCTION + 22: keysym = XK_F23;       break;
      case SCR_KEY_FUNCTION + 23: keysym = XK_F24;       break;
      case SCR_KEY_FUNCTION + 24: keysym = XK_F25;       break;
      case SCR_KEY_FUNCTION + 25: keysym = XK_F26;       break;
      case SCR_KEY_FUNCTION + 26: keysym = XK_F27;       break;
      case SCR_KEY_FUNCTION + 27: keysym = XK_F28;       break;
      case SCR_KEY_FUNCTION + 28: keysym = XK_F29;       break;
      case SCR_KEY_FUNCTION + 29: keysym = XK_F30;       break;
      case SCR_KEY_FUNCTION + 30: keysym = XK_F31;       break;
      case SCR_KEY_FUNCTION + 31: keysym = XK_F32;       break;
      case SCR_KEY_FUNCTION + 32: keysym = XK_F33;       break;
      case SCR_KEY_FUNCTION + 33: keysym = XK_F34;       break;
      case SCR_KEY_FUNCTION + 34: keysym = XK_F35;       break;
#else /* HAVE_X11_KEYSYM_H */
#warning insertion of non-character key presses not supported by this build - check that X11 protocol headers have been installed
#endif /* HAVE_X11_KEYSYM_H */
      default: logMessage(LOG_WARNING, "key not insertable: %04X", key); return 0;
    }
  } else {
    wchar_t wc;

    if (key & SCR_KEY_ALT_LEFT) {
      key &= ~SCR_KEY_ALT_LEFT;
      modMeta = 1;
    }

    if (key & SCR_KEY_CONTROL) {
      key &= ~SCR_KEY_CONTROL;
      modControl = 1;
    }

    wc = key & SCR_KEY_CHAR_MASK;
    if (wc < 0x100)
      keysym = wc; /* latin1 character */
    else
      keysym = 0x1000000 | wc;
  }
  logMessage(LOG_CATEGORY(SCREEN_DRIVER),
             "inserting key: %04X -> %s%s%ld",
             key,
             (modMeta? "meta ": ""),
             (modControl? "control ": ""),
             keysym);

  {
    int ok = 0;

#ifdef HAVE_X11_KEYSYM_H
    if (!modMeta || AtSpi2GenerateKeyboardEvent(XK_Meta_L,PRESS)) {
      if (!modControl || AtSpi2GenerateKeyboardEvent(XK_Control_L,PRESS)) {
#endif /* HAVE_X11_KEYSYM_H */

        if (AtSpi2GenerateKeyboardEvent(keysym,SYM)) {
          ok = 1;
        } else {
          logMessage(LOG_WARNING, "key insertion failed.");
        }

#ifdef HAVE_X11_KEYSYM_H
        if (modControl && !AtSpi2GenerateKeyboardEvent(XK_Control_L,RELEASE)) {
          logMessage(LOG_WARNING, "control release failed.");
          ok = 0;
        }
      } else {
        logMessage(LOG_WARNING, "control press failed.");
      }

      if (modMeta && !AtSpi2GenerateKeyboardEvent(XK_Meta_L,RELEASE)) {
        logMessage(LOG_WARNING, "meta release failed.");
        ok = 0;
      }
    } else {
      logMessage(LOG_WARNING, "meta press failed.");
    }
#endif /* HAVE_X11_KEYSYM_H */

    return ok;
  }
}

static void
scr_initialize (MainScreen *main) {
  initializeRealScreen(main);
  main->base.poll = poll_AtSpi2Screen;
  main->base.refresh = refresh_AtSpi2Screen;
  main->base.describe = describe_AtSpi2Screen;
  main->base.readCharacters = readCharacters_AtSpi2Screen;
  main->base.insertKey = insertKey_AtSpi2Screen;
  main->base.selectVirtualTerminal = selectVirtualTerminal_AtSpi2Screen;
  main->base.switchVirtualTerminal = switchVirtualTerminal_AtSpi2Screen;
  main->base.currentVirtualTerminal = currentVirtualTerminal_AtSpi2Screen;
  main->processParameters = processParameters_AtSpi2Screen;
  main->construct = construct_AtSpi2Screen;
  main->destruct = destruct_AtSpi2Screen;
}