File: display.c

package info (click to toggle)
twin 0.4.0-4
  • links: PTS
  • area: main
  • in suites: woody
  • size: 3,804 kB
  • ctags: 23,904
  • sloc: ansic: 61,860; cpp: 1,023; makefile: 777; sh: 552; lex: 302; yacc: 231
file content (1392 lines) | stat: -rw-r--r-- 35,149 bytes parent folder | download | duplicates (2)
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
/*
 *  display.c  -- connect to a running twin and register as a display
 *
 *  Copyright (C) 2000-2001 by Massimiliano Ghilardi
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 */

/*
 * this is basically a chopped down version of twin,
 * with the minimum required features to startup a display driver,
 * plus libTw code to talk to twin, register on it as a special display,
 * and forward messages and commands between the display driver and twin.
 */

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <signal.h>

#include "twin.h"
#include "hw.h"
#include "hw_private.h"
#include "common.h"
#include "fdlist.h"
#include "version.h"

#include "Tw/Tw.h"
#include "Tw/Twerrno.h"
#include "Tw/Twstat.h"

/* HW specific headers */

#ifdef CONF_HW_X11
# include "HW/hw_X11.h"
#endif

#ifdef CONF_HW_TWIN
# include "HW/hw_twin.h"
#endif

#ifdef CONF_HW_TTY
# include "HW/hw_tty.h"
#endif

#ifdef CONF_HW_GGI
# include "HW/hw_ggi.h"
#endif




#ifdef CONF__MODULES

# ifdef LIBDIR
#  define DIR_LIB_TWIN_MODULES_ LIBDIR "/twin/modules/"
# else
#  define DIR_LIB_TWIN_MODULES_ "./"
# endif

static CONST byte *conf_destdir_lib_twin_modules_ = DIR_LIB_TWIN_MODULES_;

#endif /* CONF__MODULES */



static CONST byte *MYname;

static dat TryDisplayWidth, TryDisplayHeight;
static byte ValidVideo;

CONST byte *TWDisplay, *origTWDisplay, *origTERM;

byte nullMIME[TW_MAX_MIMELEN];

udat ErrNo;
byte CONST * ErrStr;

#define L 0x55
#define M 0xAA
#define H 0xFF

palette Palette[MAXCOL+1] = {
    /* the default colour table, for VGA+ colour systems */
    {0,0,0}, {0,0,M}, {0,M,0}, {0,M,M}, {M,0,0}, {M,0,M}, {M,M,0}, {M,M,M},
    {L,L,L}, {L,L,H}, {L,H,L}, {L,H,H}, {H,L,L}, {H,L,H}, {H,H,L}, {H,H,H}};

palette defaultPalette[MAXCOL+1] = {
    /* the default colour table, for VGA+ colour systems */
    {0,0,0}, {0,0,M}, {0,M,0}, {0,M,M}, {M,0,0}, {M,0,M}, {M,M,0}, {M,M,M},
    {L,L,L}, {L,L,H}, {L,H,L}, {L,H,H}, {H,L,L}, {H,L,H}, {H,H,L}, {H,H,H}};

#undef H
#undef M
#undef L

static fdlist FdList[5];
static uldat FdSize = 5, FdTop, FdBottom, FdWQueued;
#define LS      FdList[Slot]
#define ls      FdList[slot]

static fd_set save_rfds, save_wfds;
static int max_fds;

static tmsgport TMsgPort = NOID, THelper = NOID;
static byte MouseMotionN; /* non-zero to report also mouse motion events */

int (*OverrideSelect)(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) = select;

/*
 * first, utility functions
 */

void Quit(int status);

void NoOp(void) {
}
byte AlwaysFalse(void) {
    return FALSE;
}
byte AlwaysTrue(void) {
    return TRUE;
}
void *AlwaysNull(void) {
    return NULL;
}

void GainPrivileges(void) {
}
void RemotePidIsDead(pid_t pid) {
}

byte Error(udat Code_Error) {
    switch ((ErrNo = Code_Error)) {
      case NOMEMORY:
	ErrStr = "Out of memory!";
	break;
      case NOTABLES:
	ErrStr = "Internal tables full!";
	break;
      case SYSCALLERROR:
	ErrStr = strerror(errno);
	break;
      default:
	break;
    }
    return FALSE;
}

int printk(CONST byte *format, ...) {
    int i = 0;
#ifdef HAVE_VPRINTF
    va_list ap;
    va_start(ap, format);
    i = vfprintf(stderr, (CONST char *)format, ap);
    va_end(ap);
#endif
    return i;
}

int flushk(void) {
    return fflush(stderr);
}

static void OutOfMemory(void) {
    printk("twdisplay: Out of memory!\n");
}

byte *CloneStr(CONST byte *s) {
    byte *q;
    uldat len;
    
    if (s) {
	len = 1 + LenStr(s);
	if ((q = AllocMem(len)))
	    CopyMem(s, q, len);
	return q;
    }
    return NULL;
}

byte *CloneStrL(CONST byte *s, uldat len) {
    byte *q;
    
    if (s) {
	if ((q = AllocMem(len+1))) {
	    if (len)
		CopyMem(s, q, len);
	    q[len] = '\0';
	}
	return q;
    }
    return NULL;
}

INLINE uldat FdListGet(void) {
    if (FdBottom < FdSize)
	return FdBottom;
    return NOSLOT;
}

uldat RegisterRemote(int Fd, obj HandlerData, void *HandlerIO) {
    uldat Slot, j;
    
    if ((Slot = FdListGet()) == NOSLOT)
	return Slot;
    
    WriteMem(&LS, 0, sizeof(fdlist));
    
    LS.Fd = Fd;
    LS.pairSlot = NOSLOT;
    if ((LS.HandlerData = HandlerData))
	LS.HandlerIO.D = HandlerIO;
    else
	LS.HandlerIO.S = HandlerIO;
    LS.extern_couldntwrite = FALSE;
    
    if (FdTop <= Slot)
	FdTop = Slot + 1;
    for (j = FdBottom + 1; j < FdTop; j++)
	if (FdList[j].Fd == NOFD)
	    break;
    FdBottom = j;

    if (Fd >= 0) {
	FD_SET(Fd, &save_rfds);
	if (max_fds < Fd)
	    max_fds = Fd;
    }
    return Slot;
}

void UnRegisterRemote(uldat Slot) {
    /* not needed, we are going to quit anyway if this gets called */
}

void RemoteCouldntWrite(uldat Slot) {
    if (Slot == NOSLOT || Slot >= FdTop || LS.Fd == NOFD)
	return;
    if (LS.extern_couldntwrite == FALSE) {
	LS.extern_couldntwrite = TRUE;
	FdWQueued++;
    }
    FD_SET(LS.Fd, &save_wfds);
}

void RemoteCouldWrite(uldat Slot) {
    if (Slot == NOSLOT || Slot >= FdTop || LS.Fd == NOFD)
	return;
    if (LS.extern_couldntwrite == TRUE) {
	LS.extern_couldntwrite = FALSE;
	FdWQueued--;
    }
    FD_CLR(LS.Fd, &save_wfds);
}

static void RemoteEvent(int FdCount, fd_set *FdSet) {
    uldat Slot;
    int fd;
    for (Slot=0; Slot<FdTop && FdCount; Slot++) {
	if ((fd = LS.Fd) >= 0) {
	    if (FD_ISSET(fd, FdSet)) {
		FdCount--;
		if (LS.HandlerData)
		    LS.HandlerIO.D (fd, LS.HandlerData);
		else
		    LS.HandlerIO.S (fd, Slot);
	    }
	}
    }
}


#ifdef CONF__MODULES

#include <dlfcn.h>

static struct s_fn_module _FnModule = {
    module_magic, (uldat)sizeof(struct s_module), (uldat)1,
	(void *)NoOp, /* CreateModule */
	(void *)NoOp, /* InsertModule */
	(void *)NoOp, /* RemoveModule */
	(void *)NoOp, /* DeleteModule */
	NULL,	      /* Fn_Obj */
	(void *)NoOp, /* DlOpen	      */
	(void *)NoOp  /* DlClose      */
};

static struct s_module _Module = {
    module_magic,
	&_FnModule,
};

static module DlLoadAny(uldat len, byte *name) {
    module Module = &_Module;
    byte (*init_dl)(module);
    byte *_name;
    
    if ((Module->Name = CloneStrL(name, len)) &&
	(_name = AllocMem(len + strlen(conf_destdir_lib_twin_modules_) + 1))) {
	
	sprintf(_name, "%s%s", conf_destdir_lib_twin_modules_, Module->Name);

	if ((Module->Handle = dlopen(_name, RTLD_NOW|RTLD_GLOBAL)) &&
	    /*
	     * Module MUST have a InitModule function, as it needs to set
	     * Module->Private to its xxx_InitHW() startup code.
	     */
	    (init_dl = dlsym(Module->Handle, "InitModule")) &&
	    init_dl(Module))

	    return Module;
	else
	    ErrStr = dlerror();
    } else
	ErrStr = "Out of memory!";
    return (module)0;
}

static byte module_InitHW(void) {
    byte *name, *tmp;
    byte *(*InitD)(void);
    byte *arg = HW->Name;
    uldat len = HW->NameLen;
    module Module;

    if (!arg || len <= 4)
	return FALSE;
    
    arg += 4; len -= 4; /* skip "-hw=" */
    
    name = memchr(arg, '@', len);
    tmp = memchr(arg, ',', len);
    if (tmp && (!name || tmp < name))
	name = tmp;
    if (name)
	len = name - arg;
    
    if ((name = AllocMem(len + 10))) {
	sprintf(name, "HW/hw_%.*s.so", (int)len, arg);
			
	Module = DlLoadAny(len+9, name);
	
	FreeMem(name);
	    
	if (Module) {
	    printk("twdisplay: starting display driver module `HW/hw_%.*s.so'...\n", (int)len, arg);
	    
	    if ((InitD = Module->Private) && InitD()) {
		printk("twdisplay: ...module `HW/hw_%.*s.so' successfully started.\n", (int)len, arg);
		HW->Module = Module; Module->Used++;
		return TRUE;
	    }
	    /*Delete(Module);*/
	}
    } else
	ErrStr = "Out of memory!";

    if (Module) {
	printk("twdisplay: ...module `HW/hw_%.*s.so' failed to start.\n", (int)len, arg);
    } else
	printk("twdisplay: unable to load display driver module `HW/hw_%.*s.so' :\n"
		"      %s\n", (int)len, arg, ErrStr);
    
    return FALSE;
}

#endif /* CONF__MODULES */

static display_hw CreateDisplayHW(uldat len, CONST byte *name);
static byte InitDisplayHW(display_hw);
static void QuitDisplayHW(display_hw);

static struct s_fn_display_hw _FnDisplayHW = {
    display_hw_magic, (uldat)sizeof(struct s_display_hw), (uldat)1,
	(void *)NoOp, /* CreateDisplayHW */
	(void *)NoOp, /* InsertDisplayHW */
	(void *)NoOp, /* RemoveDisplayHW */
	(void *)NoOp, /* DeleteDisplayHW */
	(void *)NoOp, /* ChangeFieldDisplayHW */
	NULL,	      /* Fn_Obj */
	InitDisplayHW,
	QuitDisplayHW
};

static struct s_display_hw _HW = {
    display_hw_magic,
	&_FnDisplayHW,
};

#if defined(CONF_HW_X11) || defined(CONF_HW_TWIN) || defined(CONF_HW_TTY) || defined(CONF_HW_GGI)
static byte check4(byte *s, byte *arg) {
    if (arg && strncmp(s, arg, strlen(s))) {
	printk("twdisplay: `-hw=%s' given, skipping `-hw=%s' display driver.\n",
		arg, s);
	return FALSE;
    } else if (arg)
	printk("twdisplay: trying given `-hw=%s' display driver.\n", s);
    else
	printk("twdisplay: autoprobing `-hw=%s' display driver.\n", s);
    return TRUE;
}

static void fix4(byte *s, display_hw D_HW) {
    uldat len;
    if (!D_HW->NameLen) {
	if (D_HW->Name)
	    FreeMem(D_HW->Name), D_HW->Name = NULL;
	len = strlen(s) + 4;
	if ((D_HW->Name = AllocMem(len + 1))) {
	    sprintf(D_HW->Name, "-hw=%s", s);
	    D_HW->NameLen = len;
	}
    }
}
#endif /* defined(CONF_HW_X11) || defined(CONF_HW_TWIN) || defined(CONF_HW_TTY) || defined(CONF_HW_GGI) */

static void warn_NoHW(uldat len, char *arg, uldat tried) {
#ifdef CONF__MODULES
    if (!tried && !arg)
	printk("twdisplay: no display driver compiled into twdisplay.\n"
	       "      please run as `twdisplay [-twin@<TWDISPLAY>] -hw=<display>'\n");
    else
#endif
    {
	printk("twdisplay: All display drivers failed");
	if (arg)
	    printk(" for `-hw=%.*s\'", (int)len, arg);
	else
	    printk(".");
	printk("\n");
    }
}

static void UpdateFlagsHW(void) {
    if (!HW->Quitted) {
	NeedOldVideo = HW->FlagsHW & FlHWNeedOldVideo;
	ExpensiveFlushVideo = HW->FlagsHW & FlHWExpensiveFlushVideo;
	CanDragArea = !!HW->CanDragArea;
    }
}

/*
 * InitDisplayHW runs HW specific InitXXX() functions, starting from best setup
 * and falling back in case some of them fails.
 */
static byte InitDisplayHW(display_hw D_HW) {
    byte *arg = D_HW->Name;
    uldat tried = 0;
    byte success;

    SaveHW;
    SetHW(D_HW);

    D_HW->DisplayIsCTTY = D_HW->NeedHW = D_HW->FlagsHW = FALSE;
    
    if (arg && !strncmp(arg, "-hw=", 4))
	arg += 4;
    else
	arg = NULL;

    success =
#ifdef CONF_HW_X11
	(check4("X", arg) && (tried++, X11_InitHW()) && (fix4("X", D_HW), TRUE)) ||
#endif
#ifdef CONF_HW_TWIN
	(check4("twin", arg) && (tried++, TW_InitHW()) && (fix4("twin", D_HW), TRUE)) ||
#endif

#if 0 /* cannot use `-hw=display' inside twdisplay! */
	(check4("display", arg) && (tried++, display_InitHW()) && (fix4("display", D_HW), TRUE)) ||
#endif
	
#ifdef CONF_HW_TTY
	(check4("tty", arg) && (tried++, tty_InitHW()) && (fix4("tty", D_HW), TRUE)) ||
#endif
#ifdef CONF_HW_GGI
	(check4("ggi", arg) && (tried++, GGI_InitHW()) && (fix4("ggi", D_HW), TRUE)) ||
#endif
#ifdef CONF__MODULES
	module_InitHW() ||
#endif
	(warn_NoHW(arg ? D_HW->NameLen - 4 : 0, arg, tried), FALSE);

    if (success) {
	D_HW->Quitted = FALSE;
	if (!DisplayHWCTTY && D_HW->DisplayIsCTTY)
	    DisplayHWCTTY = D_HW;
	UpdateFlagsHW();
    }
    
    RestoreHW;

    return success;
}

static void QuitDisplayHW(display_hw D_HW) {
    if (D_HW && D_HW->QuitHW)
	HW = D_HW, D_HW->QuitHW();
}


static display_hw CreateDisplayHW(uldat NameLen, CONST byte *Name) {
    byte *newName = NULL;
    
    if (Name && (newName = CloneStrL(Name, NameLen))) {	
	HW = &_HW;
	HW->NameLen = NameLen;
	HW->Name = newName;
	HW->Module = NULL;
	HW->Quitted = TRUE;
	HW->AttachSlot = NOSLOT;
	/*
	 * ->Quitted will be set to FALSE only
	 * after DisplayHW->InitHW() has succeeded.
	 */
	return HW;
    }
    if (newName)
	FreeMem(newName);
    return (display_hw)0;
}

static byte IsValidHW(uldat len, CONST byte *arg) {
    CONST byte *slash = memchr(arg, '/', len), *at = memchr(arg, '@', len), *comma = memchr(arg, ',', len);
    if (slash && (!at || slash < at) && (!comma || slash < comma)) {
	printk("twdisplay: slash ('/') not allowed in display HW name: %.*s\n", (int)len, arg);
	return FALSE;
    }
    return TRUE;
}


static display_hw AttachDisplayHW(uldat len, CONST byte *arg, uldat slot, byte flags) {
    if ((len && len <= 4) || CmpMem("-hw=", arg, Min2(len,4))) {
	printk("twdisplay: specified `%.*s\' is not `-hw=<display>\'\n",
		(int)len, arg);
	return (display_hw)0;
    }
    
    if (IsValidHW(len, arg) && CreateDisplayHW(len, arg)) {
	HW->AttachSlot = slot;
	if (InitDisplayHW(HW))
	    return HW;
    }
    return (display_hw)0;
}


#if 0
/* not needed, server-side hw_display already does optimization for us */
INLINE void OptimizeChangedVideo(void) {
    uldat _start, start, _end, end;
    int i;
    
    for (i=0; i<DisplayHeight*2; i++) {
	start = (uldat)ChangedVideo[i>>1][!(i&1)][0];
	    
	if (start != (uldat)-1) {
	    
	    start += (i>>1) * DisplayWidth;
	    _start = start;

	    _end = end = (uldat)ChangedVideo[i>>1][!(i&1)][1] + (i>>1) * DisplayWidth;
		
	    while (start <= end && Video[start] == OldVideo[start])
		start++;
	    while (start <= end && Video[end] == OldVideo[end])
		end--;

	    if (start > end) {
		if (i&1) {
		    /*
		     * this is the first area, to make it empty
		     * copy the second on this.
		     */
		    if (ChangedVideo[i>>1][1][0] != -1) {
			ChangedVideo[i>>1][0][0] = ChangedVideo[i>>1][1][0];
			ChangedVideo[i>>1][0][1] = ChangedVideo[i>>1][1][1];
			ChangedVideo[i>>1][1][0] = -1;
		    } else
			ChangedVideo[i>>1][0][0] = -1;
		} else
		    ChangedVideo[i>>1][1][0] = -1;
		continue;
	    } else if (start > _start || end < _end) {
		ChangedVideo[i>>1][!(i&1)][0] += start - _start;
		ChangedVideo[i>>1][!(i&1)][1] -= _end - end;
	    }
	}
    }
}
#else
# define OptimizeChangedVideo() do { } while(0)
#endif

INLINE void SyncOldVideo(void) {
    uldat start, len;
    int i;

    if (ChangedVideoFlag) {
	for (i=0; i<DisplayHeight*2; i++) {
	    start = ChangedVideo[i>>1][i&1][0];
	    
	    if (start != -1) {
		len = ChangedVideo[i>>1][i&1][1] + 1 - start;
		start += (i>>1)*DisplayWidth;
		
		ChangedVideo[i>>1][i&1][0] = -1;
	    
		CopyMem(Video + start, OldVideo + start, len * sizeof(hwattr));
	    }
	}
    }
}

void FlushHW(void) {
    
    if (!ValidVideo)
	return;
    
    if (QueuedDrawArea2FullScreen) {
	QueuedDrawArea2FullScreen = FALSE;
	DirtyVideo(0, 0, DisplayWidth - 1, DisplayHeight - 1);
	ValidOldVideo = FALSE;
    } else if (HW->RedrawVideo) {
	DirtyVideo(HW->RedrawLeft, HW->RedrawUp, HW->RedrawRight, HW->RedrawDown);
	ValidOldVideo = FALSE;
    } else if (NeedOldVideo && ValidOldVideo)
	OptimizeChangedVideo();
    
    HW->FlushVideo();
    
    HW->RedrawVideo = FALSE;
    
    if (HW->NeedHW & NEEDFlushHW)
	HW->FlushHW();

    if (NeedHW & NEEDFlushStdout)
	fflush(stdout), NeedHW &= ~NEEDFlushStdout;
    
    SyncOldVideo();

    ChangedVideoFlag = FALSE;
    ValidOldVideo = TRUE;
}


void ResizeDisplayPrefer(display_hw D_HW) {
    SaveHW;
    SetHW(D_HW);
    D_HW->DetectSize(&TryDisplayWidth, &TryDisplayHeight);
    NeedHW |= NEEDResizeDisplay;
    RestoreHW;
}

static byte ReAllocVideo(dat Width, dat Height) {
    byte change = DisplayWidth != Width || DisplayHeight != Height;
    
    if (!NeedOldVideo && OldVideo) {
	FreeMem(OldVideo);
	OldVideo = NULL;
    } else if ((NeedOldVideo && !OldVideo) || change) {
	if (!(OldVideo = (hwattr *)ReAllocMem(OldVideo, Width*Height*sizeof(hwattr))) && Width && Height) {
	    OutOfMemory();
	    Quit(1);
	}
	ValidOldVideo = FALSE;
    }
    
    if (!Video || change) {
	DisplayWidth = Width;
	DisplayHeight = Height;
	
	if ((!(Video = (hwattr *)ReAllocMem(Video, DisplayWidth*DisplayHeight*sizeof(hwattr))) ||
	     !(ChangedVideo = (dat (*)[2][2])ReAllocMem(ChangedVideo, DisplayHeight*sizeof(dat)*4))) &&
	     DisplayWidth && DisplayHeight) {
	    
	    OutOfMemory();
	    Quit(1);
	}
	ValidVideo = FALSE;
	WriteMem(ChangedVideo, 0xff, DisplayHeight*sizeof(dat)*4);
    
    }
    return change;
}


/*
 * return TRUE if DisplayWidth or DisplayHeight were changed
 */
static byte ResizeDisplay(void) {
    byte change = FALSE;
    tmsg Tmsg;
    
    if (!TryDisplayWidth || !TryDisplayHeight)
	HW->DetectSize(&TryDisplayWidth, &TryDisplayHeight);
    
    HW->CheckResize(&TryDisplayWidth, &TryDisplayHeight);
    HW->Resize(TryDisplayWidth, TryDisplayHeight);

    change = ReAllocVideo(TryDisplayWidth, TryDisplayHeight);
    
    NeedHW &= ~NEEDResizeDisplay;

    TryDisplayWidth = TryDisplayHeight = 0;
    
    if (change && (Tmsg = TwCreateMsg(TW_MSG_DISPLAY, sizeof(struct s_tevent_display)))) {
	Tmsg->Event.EventDisplay.Code = TW_DPY_Resize;
	Tmsg->Event.EventDisplay.Len  = 0;
	Tmsg->Event.EventDisplay.X    = DisplayWidth;
	Tmsg->Event.EventDisplay.Y    = DisplayHeight;
	TwBlindSendMsg(THelper, Tmsg);
    }
    return change;
}

byte AllHWCanDragAreaNow(dat Left, dat Up, dat Rgt, dat Dwn, dat DstLeft, dat DstUp) {
    return (CanDragArea && HW->CanDragArea &&
	    HW->CanDragArea(Left, Up, Rgt, Dwn, DstLeft, DstUp));
}

void DragAreaHW(dat Left, dat Up, dat Rgt, dat Dwn, dat DstLeft, dat DstUp) {
    HW->DragArea(Left, Up, Rgt, Dwn, DstLeft, DstUp);
}

    
void SetPaletteHW(udat N, udat R, udat G, udat B) {
    if (N <= MAXCOL) {
	palette c = {R, G, B};
	if (CmpMem(&Palette[N], &c, sizeof(palette))) {
	    Palette[N] = c;
	    HW->SetPalette(N, R, G, B);
	}
    }
}

void ResetPaletteHW(void) {
    HW->ResetPalette();
}

static void HandleMsg(tmsg Msg) {
    tevent_display EventD;
    
    switch (Msg->Type) {
      case TW_MSG_SELECTION:
	/* should never happen */
	printk("\ntwdisplay: HandleMsg(): unexpected Selection Message from twin!\n");
	break;
      case TW_MSG_SELECTIONREQUEST:
#if 0
	printk("twdisplay: Selection Request from 0x%08x, owner is underlying HW\n", Msg->Event.EventSelectionRequest.Requestor);
#endif
	/* request selection from underlying HW */
	
	/*
	 * Just like in TwinSelectionGetOwner() : normally Requestor
	 * is a meaningful pointer; here it is just a libTw Id.
	 * Cast it to (obj) as expected by HW displays...
	 * we will cast it back when needed
	 */
	HW->HWSelectionRequest((obj)(Msg->Event.EventSelectionRequest.Requestor),
			       Msg->Event.EventSelectionRequest.ReqPrivate);
	break;
      case TW_MSG_SELECTIONNOTIFY:
#if 0
	printk("twdisplay: Selection Notify to underlying HW\n");
#endif
	/* notify selection to underlying HW */
	HW->HWSelectionNotify(Msg->Event.EventSelectionNotify.ReqPrivate,
			      Msg->Event.EventSelectionNotify.Magic,
			      Msg->Event.EventSelectionNotify.MIME,
			      Msg->Event.EventSelectionNotify.Len,
			      Msg->Event.EventSelectionNotify.Data);
	break;
      case TW_MSG_DISPLAY:
	EventD = &Msg->Event.EventDisplay;
	switch (EventD->Code) {
	  case TW_DPY_DrawHWAttr:
	    if (EventD->Len /= sizeof(hwattr)) {
		if (EventD->X + EventD->Len > DisplayWidth || EventD->Y >= DisplayHeight) {
		    /*
		     * in a perfect world this should not happen, 
		     * but with our asyncronous display size negotiation,
		     * it actually can.
		     */

		    if (EventD->Y < DisplayHeight && EventD->X < DisplayWidth)
			EventD->Len = DisplayWidth - EventD->X;
		    else
			break;
		}
		DirtyVideo(EventD->X, EventD->Y, EventD->X + EventD->Len - 1, EventD->Y);
		CopyMem(EventD->Data, &Video[EventD->X + EventD->Y * DisplayWidth], EventD->Len * sizeof(hwattr));
	    }
	    break;
	  case TW_DPY_FlushHW:
	    ValidVideo = TRUE;
	    FlushHW();
	    break;
	  case TW_DPY_SetCursorType:
	    if (EventD->Len == sizeof(uldat))
		SetCursorType(*(uldat *)EventD->Data);
	    break;
	  case TW_DPY_MoveToXY:
	    MoveToXY(EventD->X, EventD->Y);
	    break;
	  case TW_DPY_Resize:
	    /*
	     * twin told us the new display size.
	     * don't detect/check anything, just apply it
	     * (if it is meaningful and different from current)
	     */
	    if (EventD->X != DisplayWidth || EventD->Y != DisplayHeight) {
		HW->Resize(EventD->X, EventD->Y);
		ReAllocVideo(EventD->X, EventD->Y);
	    }
	    break;
	  case TW_DPY_SelectionExport:
	    NeedHW |= NEEDSelectionExport;
	    break;
	  case TW_DPY_DragArea:
#define c ((udat *)EventD->Data)
	    if (EventD->Len == 4*sizeof(udat))
		DragArea(EventD->X, EventD->Y, c[0], c[1], c[2], c[3]);
#undef c
	    break;
	  case TW_DPY_Beep:
	    HW->Beep();
	    break;
	  case TW_DPY_Configure:
	    if (EventD->X == HW_MOUSEMOTIONEVENTS)
		MouseMotionN = EventD->Y > 0;
	    HW->Configure(EventD->X, EventD->Y == -1, EventD->Y);
	    break;
	  case TW_DPY_SetPalette:
#define c ((udat *)EventD->Data)
	    if (EventD->Len == 3*sizeof(udat))
		HW->SetPalette(EventD->X, c[0], c[1], c[2]);
#undef c
	    break;
	  case TW_DPY_ResetPalette:
	    HW->ResetPalette();
	    break;
	  case TW_DPY_Helper:
	    THelper = *(uldat *)EventD->Data;
	    break;
	  case TW_DPY_Quit:
	    Quit(0);
	    break;
	  default:
	    break;
	}
    }
}

static void SocketIO(void) {
    tmsg Msg;
    while ((Msg = TwReadMsg(FALSE)))
	HandleMsg(Msg);
}

void SelectionExport(void) {
    HW->HWSelectionExport();
    NeedHW &= ~NEEDSelectionExport;
}

/* HW back-end function: get selection owner */

/*
 * In the same function in twin server, this returns a meaningful pointer.
 * Here, it returns just an Id coming from libTw.
 * Cheat and cast to to (obj), since the underlying display HW code
 * treats it as opaque. We will cast it back to (uldat) when needed.
 */
obj TwinSelectionGetOwner(void) {
    return (void *)TwGetOwnerSelection();
}

/* HW back-end function: set selection owner */
void TwinSelectionSetOwner(obj Owner, time_t Time, frac_t Frac) {
    tmsg Msg;

    if ((Msg=TwCreateMsg(TW_MSG_SELECTIONCLEAR, sizeof(tevent_common)))) {
	TwBlindSendMsg(THelper, Msg);
    }
}

/* HW back-end function: notify selection */
void TwinSelectionNotify(obj Requestor, uldat ReqPrivate, uldat Magic, CONST byte MIME[MAX_MIMELEN],
			    uldat Len, CONST byte *Data) {
    if (!MIME)
	MIME = nullMIME;
#if 0
    printk("twdisplay: Selection Notify to 0x%08x\n", (uldat)Requestor);
#endif
    /* cast back Requestor from fake (obj) to its original (uldat) */
    TwNotifySelection((uldat)Requestor, ReqPrivate, Magic, MIME, Len, Data);
}

/* HW back-end function: request selection */
void TwinSelectionRequest(obj Requestor, uldat ReqPrivate, obj Owner) {
#if 0
    printk("twdisplay: Selection Request from 0x%08x, Owner is 0x%08x\n", (uldat)Requestor, (uldat)Owner);
#endif
    /* cast back Owner from the fake (obj) to (uldat) */
    TwRequestSelection((uldat)Owner, ReqPrivate);
}

static byte StdAddEventMouse(udat CodeMsg, udat Code, dat MouseX, dat MouseY) {
    tevent_mouse Event;
    tmsg Msg;

    if (HW->FlagsHW & FlHWNoInput)
	return TRUE;

    if ((Msg=TwCreateMsg(CodeMsg, sizeof(event_mouse)))) {
	Event = &Msg->Event.EventMouse;

	Event->Code = Code;
	Event->ShiftFlags = (udat)0;
	Event->X = MouseX;
	Event->Y = MouseY;
	
	TwBlindSendMsg(THelper, Msg);
	return TRUE;
    }
    return FALSE;
}

byte MouseEventCommon(dat x, dat y, dat dx, dat dy, udat Buttons) {
    dat prev_x, prev_y;
    udat OldButtons;
    mouse_state *OldState;
    udat result;
    byte ret = TRUE;
     
    OldState=&HW->MouseState;
    OldButtons=OldState->keys;
    prev_x = OldState->x;
    prev_y = OldState->y;

    x = Max2(x, 0); x = Min2(x, DisplayWidth - 1);
    OldState->delta_x = x == 0 ? Min2(dx, 0) : x == DisplayWidth - 1 ? Max2(dx, 0) : 0;

    y = Max2(y, 0); y = Min2(y, DisplayHeight - 1);
    OldState->delta_y = y == 0 ? Min2(dy, 0) : y == DisplayHeight - 1 ? Max2(dy, 0) : 0;
	
    if (x != prev_x || y != prev_y)
	HW->FlagsHW |= FlHWChangedMouseFlag;

    OldState->x = x;
    OldState->y = y;
    
    OldState->keys=Buttons;
    
    if (Buttons != OldButtons || ((MouseMotionN || OldButtons) && (x != prev_x || y != prev_y))) {
	
	if (MouseMotionN && !OldButtons && (x != prev_x || y != prev_y)) {
	    if (!StdAddEventMouse(TW_MSG_WIDGET_MOUSE, MOTION_MOUSE, x, y))
		ret = FALSE;
	} else if (OldButtons && (x != prev_x || y != prev_y)) {
	    if (!StdAddEventMouse(TW_MSG_WIDGET_MOUSE, DRAG_MOUSE | OldButtons, x, y))
		ret = FALSE;
	}
	if ((Buttons & HOLD_LEFT) != (OldButtons & HOLD_LEFT)) {
	    result = (Buttons & HOLD_LEFT ? DOWN_LEFT : RELEASE_LEFT) | (OldButtons &= ~HOLD_LEFT);
	    OldButtons |= Buttons & HOLD_LEFT;
	    if (!StdAddEventMouse(TW_MSG_WIDGET_MOUSE, result, x, y))
		ret = FALSE;
	}
	if ((Buttons & HOLD_MIDDLE) != (OldButtons & HOLD_MIDDLE)) {
	    result = (Buttons & HOLD_MIDDLE ? DOWN_MIDDLE : RELEASE_MIDDLE) | (OldButtons &= ~HOLD_MIDDLE);
	    OldButtons |= Buttons & HOLD_MIDDLE;
	    if (!StdAddEventMouse(TW_MSG_WIDGET_MOUSE, result, x, y))
		ret = FALSE;
	}
	if ((Buttons & HOLD_RIGHT) != (OldButtons & HOLD_RIGHT)) {
	    result = (Buttons & HOLD_RIGHT ? DOWN_RIGHT : RELEASE_RIGHT) | (OldButtons &= ~HOLD_RIGHT);
	    OldButtons |= Buttons & HOLD_RIGHT;
	    if (!StdAddEventMouse(TW_MSG_WIDGET_MOUSE, result, x, y))
		ret = FALSE;
	}
    }
    return ret;
}

byte KeyboardEventCommon(udat Code, udat ShiftFlags, udat Len, CONST byte *Seq) {
    tevent_keyboard Event;
    tmsg Msg;

    if (HW->FlagsHW & FlHWNoInput)
	return TRUE;

    if ((Msg=TwCreateMsg(TW_MSG_WIDGET_KEY, Len + sizeof(event_keyboard)))) {
	Event = &Msg->Event.EventKeyboard;
	    
	Event->Code = Code;
	Event->ShiftFlags = ShiftFlags;
	Event->SeqLen = Len;
	CopyMem(Seq, Event->AsciiSeq, Len);
	Event->AsciiSeq[Len] = '\0'; /* terminate string with \0 */
	
	TwBlindSendMsg(THelper, Msg);
	return TRUE;
    }
    return FALSE;
}

static void MainLoop(int Fd) {
    struct timeval sel_timeout, *this_timeout;
    fd_set read_fds, write_fds, *pwrite_fds;
    uldat err, detail;
    int sys_errno, num_fds;
    
    for (;;) {
	if (GotSignals)
	    HandleSignals();
	
	if (NeedHW & NEEDResizeDisplay)
	    ResizeDisplay();
	
	if (NeedHW & NEEDSelectionExport)
	    SelectionExport();

	/*
	 * don't FlushHW() unconditionalluy here,
	 * as it gets called syncronously
	 * with the main twin from HandleEvent()...
	 * just update what is needed.
	 */
	if (HW->RedrawVideo)
	    FlushHW();
	else {
	    HW->UpdateMouseAndCursor();

	    if (HW->NeedHW & NEEDFlushHW)
		HW->FlushHW();
	    if (NeedHW & NEEDFlushStdout)
		fflush(stdout), NeedHW &= ~NEEDFlushStdout;
	}
	
	read_fds = save_rfds;
	
	if (!FdWQueued)
	    pwrite_fds = NULL;
	else {
	    write_fds = save_wfds;
	    pwrite_fds = &write_fds;
	}
	
	if (!TwFlush())
	    break;
	
	if (TwPendingMsg()) {
	    /*
	     * messages can arrive during Tw* function calls,
	     * so the FD_ISSET() test alone does not suffice.
	     */
	    sel_timeout.tv_sec = sel_timeout.tv_usec = 0;
	    this_timeout = &sel_timeout;
	} else
	    this_timeout = NULL;

	if (NeedHW & NEEDPanicHW)
	    break;

	num_fds = OverrideSelect(max_fds+1, &read_fds, pwrite_fds, NULL, this_timeout);

	if (num_fds < 0 && errno != EINTR)
	    /* ach, problem. */
	    break;

	if ((num_fds > 0 && FD_ISSET(Fd, &read_fds)) || TwPendingMsg()) {
	    /*
	     * messages can arrive during Tw* function calls,
	     * so the FD_ISSET() test alone does not suffice.
	     */
	    FD_CLR(Fd, &read_fds);
	    num_fds--;
	    SocketIO();
	}
	if (num_fds > 0)
	    RemoteEvent(num_fds, &read_fds);
    }

    if (NeedHW & NEEDPanicHW)
	Quit(0);
    
    if (num_fds < 0 && errno != EINTR) {
	QuitDisplayHW(HW);
	printk("twdisplay: select(): %s\n", strerror(errno));
	exit(1);
    }
    if (TwInPanic()) {
	err = TwErrno;
	detail = TwErrnoDetail;
    	QuitDisplayHW(HW);
	printk("%s: libTw error: %s%s\n", MYname,
		TwStrError(err), TwStrErrorDetail(err, detail));
	exit(1);
    }
    err = TwErrno;
    detail = TwErrnoDetail;
    sys_errno = errno;
    QuitDisplayHW(HW);
    printk("%s: shouldn't happen! Please report:\n"
	    "\tlibTw TwErrno: %d(%d),\t%s%s\n"
	    "\tsystem  errno: %d,\t%s\n", MYname,
	    err, detail, TwStrError(err), TwStrErrorDetail(err, detail),
	    sys_errno, strerror(sys_errno));
    exit(1);
}

dat GetDisplayWidth(void) {
    return DisplayWidth;
}
dat GetDisplayHeight(void) {
    return DisplayHeight;
}


static void Usage(void) {
    fputs("Usage: twdisplay [OPTIONS] -hw=<display> [...]\n"
	  "Currently known options: \n"
	  " -h, -help               display this help and exit\n"
	  " -V, -version            output version information and exit\n"
	  " -s, -share              allow multiple simultaneous displays (default)\n"
	  " -x, -excl               request exclusive display - detach all others\n"
	  " -v                      verbose output (default)\n"
	  " -q                      quiet - don't report messages from twin server\n"
	  " -f                      force running even with wrong protocol version\n"
	  " -twin@<TWDISPLAY>       specify server to contact instead of $TWDISPLAY\n"
	  " -hw=<display>[,options] start the given display\n"
	  "Currently known display methods: \n"
	  "\tX[@<XDISPLAY>]\n"
	  "\ttwin[@<TWDISPLAY>]\n"
	  "\ttty[@<tty device>]\n"
	  "\tggi[@<ggi display>]\n", stdout);
}

static void TryUsage(CONST char *opt) {
    if (opt)
	fprintf(stdout, "twdisplay: unknown option `%s'\n", opt);
    fputs("           try `twdisplay -help' for usage summary.\n", stdout);
}

static void ShowVersion(void) {
    fputs("twdisplay " TWIN_VERSION_STR " with socket protocol "
	  TW_PROTOCOL_VERSION_STR "\n", stdout);
}

static byte VersionsMatch(byte force) {
    uldat cv = TW_PROTOCOL_VERSION, lv = TwLibraryVersion(), sv = TwServerVersion();
	
    if (lv != sv || lv != cv) {
	printk("twdisplay: %s: socket protocol version mismatch!%s\n"
		"           client is %d.%d.%d, library is %d.%d.%d, server is %d.%d.%d\n",
		(force ? "warning" : "fatal"), (force ? " (ignored)" : ""),
		TWVER_MAJOR(cv), TWVER_MINOR(cv), TWVER_PATCH(cv),
		TWVER_MAJOR(lv), TWVER_MINOR(lv), TWVER_PATCH(lv),
		TWVER_MAJOR(sv), TWVER_MINOR(sv), TWVER_PATCH(sv));
	return FALSE;
    }
    return TRUE;
}

TW_DECL_MAGIC(display_magic);

int main(int argc, char *argv[]) {
    byte flags = TW_ATTACH_HW_REDIRECT, force = 0;
    byte *dpy = NULL, *arg = NULL, *tty = ttyname(0);
    byte ret = 0, ourtty = 0;
    byte *s;
    TW_CONST byte *buff;
    uldat chunk;
    int Fd;
    
    MYname = argv[0];
    
    while (*++argv) {
	if (!strcmp(*argv, "-V") || !strcmp(*argv, "-version")) {
	    ShowVersion();
	    return 0;
	} else if (!strcmp(*argv, "-h") || !strcmp(*argv, "-help")) {
	    Usage();
	    return 0;
	} else if (!strcmp(*argv, "-x") || !strcmp(*argv, "-excl"))
	    flags |= TW_ATTACH_HW_EXCLUSIVE;
	else if (!strcmp(*argv, "-s") || !strcmp(*argv, "-share"))
	    flags &= ~TW_ATTACH_HW_EXCLUSIVE;
	else if (!strcmp(*argv, "-v"))
	    flags |= TW_ATTACH_HW_REDIRECT;
	else if (!strcmp(*argv, "-q"))
	    flags &= ~TW_ATTACH_HW_REDIRECT;
	else if (!strcmp(*argv, "-f"))
	    force = 1;
	else if (!strncmp(*argv, "-twin@", 6))
	    dpy = *argv + 6;
	else if (!strncmp(*argv, "-hw=", 4)) {
	    if (!strncmp(*argv+4, "display", 7)) {
		printk("%s: argument `-hw=display' is for internal use only.\n", MYname);
		TryUsage(NULL);
		return 1;
	    }
	    if (!strncmp(*argv+4, "tty", 3)) {
		buff = *argv + 7;
		s = strchr(buff, ',');
		if (s) *s = '\0';
		
		if (!*buff)
		    /* attach twin to our tty */
		    ourtty = 1;
		else if (*buff == '@' && buff[1]) {
		    if (buff[1] == '-') {
			/*
			 * using server tty makes no sense for twdisplay
			 */
			printk("%s: `%s' makes sense only with twattach.\n", MYname, *argv);
			return 1;
		    } else if (tty) {
			if (!strcmp(buff+1, tty))
			    /* attach twin to our tty */
			    ourtty = 1;
		    } else {
			printk("%s: ttyname() failed: cannot find controlling tty!\n", MYname);
			return 1;
		    }
		} else {
		    printk("%s: malformed display hw `%s'\n", MYname, *argv);
		    return 1;
		}

		if (s) *s = ',';
		else s = "";
		
		if (ourtty) {
		    buff = getenv("TERM");
		    if (!buff) buff = "";
		    
		    arg = malloc(strlen(tty) + 9 + strlen(s) + (buff ? 6 + strlen(buff) : 0));
		    
		    sprintf(arg, "-hw=tty%s%s%s", (buff ? (byte *)",TERM=" : buff), buff, s);
		} else
		    arg = *argv;
	    } else if ((*argv)[4])
		arg = *argv;
	    else {
		TryUsage(*argv);
		return 1;
	    }
	} else {
	    TryUsage(*argv);
	    return 1;
	}
    }
    
    if (!arg) {
	Usage();
	return 1;
    }

#ifdef CONF__ALLOC
    /* do this as soon as possible */
    if (!InitAlloc()) {
	fputs("twin: InitAlloc() failed: internal error!\n", stderr);
	return 1;
    }
#endif
    
    TWDisplay = origTWDisplay = CloneStr(dpy ? dpy : (byte *)getenv("TWDISPLAY"));
    origTERM = CloneStr(getenv("TERM"));

    InitSignals();
    InitTtysave();
    
#ifdef CONF__ALLOC
    TwConfigMalloc(AllocMem, ReAllocMem, FreeMem);
#endif

    if (TwCheckMagic(display_magic) && TwOpen(TWDisplay)) do {
	byte *buf;
	
	if (!VersionsMatch(force)) {
	    if (!force) {
		printk("twdisplay: Aborting. Use option `-f' to ignore versions check.\n");
		TwClose();
		return 1;
	    }
	}

	if (RegisterRemote(Fd = TwConnectionFd(), NULL, NoOp) == NOSLOT) {
	    TwClose();
	    OutOfMemory();
	    return 1;
	}
	    
	if (!(TMsgPort = TwCreateMsgPort(9, "twdisplay", 0, 0, 0)))
	    break;

	DisplayWidth = TryDisplayWidth = TwGetDisplayWidth();
	DisplayHeight = TryDisplayHeight = TwGetDisplayHeight();

	if (!(HW = AttachDisplayHW(strlen(arg), arg, NOSLOT, 0))) {
	    TwClose();
	    return 1;
	}
	if (!(buf = AllocMem(HW->NameLen + 80))) {
	    QuitDisplayHW(HW);
	    TwClose();
	    OutOfMemory();
	    return 1;
	}
	
	sprintf(buf, "-hw=display@(%.*s),x=%d,y=%d%s%s%s", (int)HW->NameLen, HW->Name,
		(int)HW->X, (int)HW->Y, HW->CanResize ? ",resize" : "",
		/* CanDragArea */ TRUE ? ",drag" : "", ExpensiveFlushVideo ? ",slow" : "");
	
	TwAttachHW(strlen(buf), buf, flags);
	TwFlush();
	
	flags &= TW_ATTACH_HW_REDIRECT;
	
	if (flags)
	    printk("reported messages ...\n");
	
	for (;;) {
	    buff = TwAttachGetReply(&chunk);
	    if (buff <= (byte *)2) {
		ret = (byte)(size_t)buff;
		break;
	    } else if (buff == (byte *)-1)
		/* libTw panic */
		break;

	    printk("  %.*s", (int)chunk, buff);
	}
	flushk();
	
	if (TwInPanic())
	    break;

	if (ourtty) {
	    fputs("\033[2J", stdout);
	    fflush(stdout);
	}

	
	/*
	 * twin waits this before grabbing the display...
	 * so we can fflush(stdout) to show all messages
	 * *BEFORE* twin draws on (eventually) the same tty
	 */
	TwAttachConfirm();

	ResizeDisplay();
	
	if (flags && !ourtty) {
	    if (ret)
		printk("... ok, twin successfully attached.\n");
	    else
		printk("... ach, twin failed to attach.\n");
	    flushk();
	}
	if (ret == 2)
	    /*
	     * twin told us to stay and sit on the display
	     * until it is quitted.
	     */
	    MainLoop(Fd);
	else if (ret)
	    printk("%s: twin said we can quit... strange!\n", MYname);
	
	Quit(!ret);
    } while (0);
    
    printk("%s: libTw error: %s%s\n", MYname,
	    TwStrError(TwErrno), TwStrErrorDetail(TwErrno, TwErrnoDetail));
    return 1;
}

void Quit(int status) {
    QuitDisplayHW(HW);
    if (status < 0)
	return; /* give control back to signal handler */
    exit(status);
}