File: window.c

package info (click to toggle)
grafix 1.6-5
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,156 kB
  • ctags: 1,962
  • sloc: ansic: 20,183; makefile: 186; sh: 3
file content (1509 lines) | stat: -rw-r--r-- 51,159 bytes parent folder | download
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
// window.c : basic source file for the Grafix package
// the "GNU Public Lincense" policy applies to all programs of this package
// (c) Wolfgang Koehler, wolf@first.gmd.de, Dec. 1994 - Nov. 1995
//     Kiefernring 15
//     14478 Potsdam, Germany
//     0331-863238

#pragma implementation

#include <assert.h>
#include <unistd.h>
#include "window.h"

#include "X11/Xutil.h"
#include "X11/cursorfont.h"

#include "eventnames.h" // from Xlib Manual

void error(char* fmt, ...) {
  va_list args; va_start(args,fmt); 
  fprintf(stderr,"fatal error: "); 
  vfprintf(stderr, fmt, args);
  fprintf(stderr,"\n");
  va_end(args);
  _exit(1); // exit(1) results in seg fault !
}

// linked list with pair (XID, window *)
class xlist {
public:
  unsigned XW; // the XWindow ID = Win member of window
  window *tw;  // the this pointer of associated window
  xlist *next;
  // constructor pushes a new entry in front of the rest list
  xlist(unsigned XW, window *tw, xlist *rest) : XW(XW), tw(tw) { next = rest; }
};

// hash table mechanism used to map XWindow IDs to window pointers
// is needed to get a fast and flexible even handling
// implemented as a vector of xlist* (xltab)
// which is indexed with (WID % TABSIZE)
// each index is a simple linked list that stores the this pointer
// of the associated window 

// class for hash table with xlist entries
// constructor takes tabsize as argument; but size should not matter 
// unless we have really huge numbers of windows (event handling could be slow)
// public methods : xhadd, xhget, xhdel
class xhash {
  xlist **xltab; // the actual hash table
  unsigned tabsize;
  unsigned Wind(unsigned Win) { return (Win % tabsize); }
public:
  xhash(unsigned size) : tabsize(size) {
    xltab = new xlist* [tabsize];
    for (unsigned i = 0; i < tabsize; i++) xltab[i] = NULL;
  }
  ~xhash() { delete[] xltab; }

  // add a new entry in the hash table
  void xhadd(unsigned Win, window *tw) {
    // printf(" new win %x %p\n",Win,tw);
    xltab[Wind(Win)] = new xlist(Win, tw, xltab[Wind(Win)]);
  }
  
  // get the xlist pointer for Win
  xlist *xhget(unsigned Win) { 
    xlist *xptr;
    for (xptr = xltab[Wind(Win)]; xptr; xptr = xptr->next)
      if (xptr->XW == Win) break;
    return xptr; // returns NULL if not found (usually deleted)
  }

  // delete the entry in the hash table : remove the cell by relinking
  void xhdel(unsigned Win) { 
    // printf("delete %x \n",Win);
    xlist *xptr,*xxp = NULL; // the previous xlist pointer (points to -> xptr)
    for (xptr = xltab[Wind(Win)]; xptr; xptr = xptr->next) {
      if (xptr->XW == Win) break; xxp = xptr;
    }
    if (xxp) xxp->next = xptr->next; // relink the list (exclude xptr)
    else xltab[Wind(Win)] = xptr->next; // it was the first entry to remove
    delete (xptr); // the deleted entry 
  }
  // only for tests : read the hash table
  xlist *xhread(int i) { return (xltab[i]); }

};

static xhash *xhatab; // the one and only xhash table for event handling
  
// eg. for menu_bars : make place for picture in the Name-string !
char * ext_string(char * Name) { 
  // printf("%s %d -> ",Name,strlen(Name)); fflush(stdout);
  char * nn = new char[strlen(Name) + 3]; // delete not needed, marginal
  sprintf(nn," %s ",Name); 
  return nn; // _Name_
}

Display * display;
int screen;
GC gc_copy, gc_but_xor, gc_clear, gc_inv, gc_rubber; // some often used gcs
XFontStruct * fixed_fn;       // and fonts
Cursor watch_cursor;
Cursor text_cursor;  // for edit_windows
Cursor hs_cursor, vs_cursor; // special cursors for scrollbars

unsigned depth;
unsigned black, white, Red, Green, Blue, Yellow, Violet;

// convinience functions
GC CreateGC(unsigned long mask, XGCValues * gcv)
{ return XCreateGC(display, DefaultRootWindow(display), mask, gcv); }

// set default gc for line drawing etc.
void set_color(unsigned long color) {
   static XGCValues values; 
   values.foreground = color;
   XChangeGC(display,gc_copy, GCForeground, &values);
}

Colormap def_cmap;

int alloc_color(unsigned red, unsigned green, unsigned blue) {
  // allocation of a cmap-entry for given color -> returns pixel-value
  // -1 failure : no free entry
  XColor col = { 0, red, green, blue };
  if (XAllocColor(display,def_cmap,&col) == 0) {   
    printf(" Warning : Color map full (%x,%x,%x) \n",red,green,blue); 
    return(-1); }
  return col.pixel;
}

int alloc_named_color(char *colname) {
  XColor col;
  if (XAllocNamedColor(display,def_cmap,colname,&col,&col) == 0) 
    error(" Color map full"); 
  return col.pixel;
}

// the GCs for the button-representation
GC button_fg_gc, button_br_gc, button_lw_gc; 
int button_fg_pix, button_br_pix, button_lw_pix; // the button colors

Bool True_Color_Visual; // only for TrueColor -> no XAllocColorCells will work

// init global used screen values
void init_globals(char * DISP) { 
  if (DISP == NULL) DISP = getenv("DISPLAY");
  display = XOpenDisplay(DISP);   
  if (display == NULL) error("cannot open display '%s'",DISP);

  Visual *visual = DefaultVisual(display,screen);
  int cl = visual->c_class;
  True_Color_Visual = (cl == TrueColor);
  // printf("Visual Class = %d  True_Col = %d\n",cl,  True_Color_Visual );
  
  screen = DefaultScreen(display);    
  depth = XDefaultDepth(display,screen);
  def_cmap = DefaultColormap(display,screen);
  black = BlackPixel(display,screen);
  white = WhitePixel(display,screen);
  Red = alloc_color(0xffff,0,0); 
  Green = alloc_color(0,0xffff,0);
  Blue = alloc_color(0,0,0xffff);
  Violet = alloc_color(0xe000,0,0xe000);
  Yellow = alloc_color(0xd000,0xd000,0);
  button_fg_pix = alloc_color(0x6180,0xa290,0xc300); // buttons inner part 
  button_br_pix = alloc_color(0x8a20,0xe380,0xffff); // bright rim
  button_lw_pix = alloc_color(0x30c0,0x5144,0x6180); // dark rim

  XGCValues gcv; gcv.function = GXcopy ;     
  gcv.foreground = black; gcv.background = white; 
  gc_copy = CreateGC(GCFunction | GCForeground , &gcv);
  
  gcv.foreground = button_fg_pix ^ black; 
  gcv.function = GXxor;
  gc_but_xor = CreateGC(GCFunction | GCForeground , &gcv); 
  // for xor-ing with button color (used in edit_window) 

  gcv.function = GXcopy; 
  gc_clear= CreateGC(GCFunction, &gcv);
  // use white as *background* for clear !!!
  // should be changed to custom color !
  XSetForeground(display, gc_clear, white);
  
  gcv.function = GXinvert;
  gc_inv = CreateGC(GCFunction, &gcv);

 //XGCValues={function,plane_mask,foreground,background,linewidth,linestyle,..}
  XGCValues val_rubber = { GXinvert, AllPlanes,0,0,2, LineOnOffDash}; 

  // rubberband for temp. coordinate lines
  gc_rubber= CreateGC(GCFunction | GCPlaneMask | GCLineWidth | GCLineStyle, 
		      &val_rubber); 

  fixed_fn = XLoadQueryFont(display,"fixed");
  XSetFont(display, gc_copy, fixed_fn->fid); // default font 

  XGCValues values;
  values.foreground = button_fg_pix;
  button_fg_gc = CreateGC(GCForeground, &values);
  values.foreground = button_br_pix;
  button_br_gc =  CreateGC(GCForeground, &values);
  values.foreground = button_lw_pix;
  button_lw_gc =  CreateGC(GCForeground, &values);

  watch_cursor = XCreateFontCursor(display,XC_watch);
  text_cursor = XCreateFontCursor(display,XC_xterm);
  hs_cursor = XCreateFontCursor(display, XC_sb_h_double_arrow); 
  vs_cursor = XCreateFontCursor(display, XC_sb_v_double_arrow); 

}

#define TABSIZE 100 // the tabsize is really arbitrary ( > 0)
// if you think the buttons react too slowly you could increase this 
 
window::window(char * DISP) { // constructor for root window
  init_globals(DISP);
  width = DisplayWidth(display,screen);
  height = DisplayHeight(display,screen);
  Win = DefaultRootWindow(display);  
  children = NULL; // own children List = empty
  parentw = NULL; // has no parent
  xhatab = new xhash(TABSIZE);  
  xhatab->xhadd(Win,this); // for safety reasons ; should not be needed
  // printf(" root Window %x %d %d \n",Win, width, height);
};

int debug_create = False; // not defined in window.h (private)

window::window(window & parent, int w, int h, int x, int y, int bw) { 
  width = (w ? w : parent.width) - 2*bw;
  height = (h ? h : parent.height) - 2*bw;
  border_width = bw;
  parentw = &parent;
  hidden = CB_info = is_mapped =  False;
  mainw = parent.mainw; // simply pass through
  children = NULL; // own children List = empty

  parent.add_child(this,x,y);
  dhlp = 0;
  type = SimpleType;
  Win = XCreateSimpleWindow(display, parent.Win, x,y, width, height, border_width,black,white); 
 
  if (debug_create) printf(" Window %lx %d %d \n",Win,width, height);
  
  gc = gc_copy; // default gc
  text_gc = gc_copy; // gc for DrawString, PlaceText; temoprarily changed

  xhatab->xhadd(Win,this); // set hash table entry

  //  default mask, modified by subclasses if needed
  selection_mask =  StructureNotifyMask | ExposureMask ;
};
  
// to update children list (and possibly fit the parent geometry) :
void window::add_child(window *ch, int x, int y) { 
  children = new win_list(ch,x,y,children);
}

void window::remove_child(window *chrem) { // remove from my children list
  win_list *chpp = NULL, *chp;
  for (chp = children; chp; chp = chp->next) {
    if (chrem == chp->child) break; chpp = chp;
  } 
  assert(chp); // loop completed -> child not in parent list, 
  // this should never happen, else list is corrupted
  
  // now re-link the pointers in the children list : 
  if (chpp) chpp->next = chp->next; else children = chp->next;
  delete (chp); // delete old win_list structure
}

window root_window; // **** definition ****

void safe_delete(window *w) { // delete only, if not yet deleted !
  // look children list of root_window -> only main_windows are catched !
  for (win_list *ch = root_window.children; ch; ch = ch->next) 
    if (ch->child == w) { delete (w); return; }
}

Bool debug_delete = False; // debugging printf for destructors

window::~window() {
  if (debug_delete) printf("destr %lx %p\n",Win,this); 

  xhatab->xhdel(Win);  // remove from the hash table

  // correct new version (11/95) :
  // first : search parents child list for my own entry and remove it
  if (this != &root_window) // for root parentw is not defined
    parentw->remove_child(this);

  // now delete my own children :
  // *** attn : this is called recursively ***
  // ie. the list - itself - is destructed from the children 
  // via above mechanism; after this it must be empty !
  for (win_list *ch = children; ch;) { 
    win_list *next = ch->next; // store here because ch is deleted implicitely
    delete (ch->child); 
    ch = next;
  }
  assert(children == NULL); // list must be empty now !!

  if (debug_delete && this == &root_window) {
    for (int i= 0; i < TABSIZE ; i++) printf("%p ",xhatab->xhread(i));
    printf("\n");
  } 
}

void window::Map() { 
  is_mapped = true;
  if (hidden) return; 
  draw_interior();  
  XMapWindow(display, Win);
}

/* remarks to ResizeRequest : 
   if the bit in the SelectMask is set the window manager does no further
   process XResizeRequestEvents because they are managed from 
   application window !
*/
void window::Realize() {  
  // printf("Realize %x %d %d\n",Win,width,height);
  XSelectInput(display, Win, selection_mask);
  Map(); // the proper sequence (Select, Map) is essential !!
};

void window::Unmap() { is_mapped = false; XUnmapWindow(display,Win); };

int window::map_state() { // returns : IsUnmapped, IsUnviewable, IsViewable 
  XWindowAttributes watt;
  XGetWindowAttributes(display,Win,&watt);
  return watt.map_state;
}

// to toggle mapping state : if mapped -> Unmap (avv) ; return new map state
Bool window::toggle_map() {
  Bool state = (map_state() == IsViewable);
  if (state) Unmap(); else Map(); 
  return !state; // it switched
}

// Realize the whole Window tree from this root
void window::RealizeChildren() { 
  Realize();
  for (win_list *cc = children; cc; cc = cc->next) { 
    window *ch = cc->child;
    ch->RealizeChildren();
  }
}

void window::set_backing_store() {
  XSetWindowAttributes attr; attr.backing_store = WhenMapped;
  XChangeWindowAttributes(display,Win,CWBackingStore,&attr);
}

void window::set_save_under() {
  XSetWindowAttributes attr; attr.save_under = TRUE;
  XChangeWindowAttributes(display,Win,CWSaveUnder,&attr);
}

void window::clear() { 
  XFillRectangle(display, Win, gc_clear, 0,0,width,height); 
}

int window::DrawString(int x, int y, char * string) { 
  int n = strlen(string);
  XDrawString(display,Win,text_gc,x,y, string, n);
  return n;
}

int window::printw(int x, int y, char* fmt, ...) {
  va_list args; va_start(args,fmt); 
  char str[1000]; 
  vsprintf(str, fmt, args);
  int n = DrawString(x,y,str);
  va_end(args);
  return n;
}

void window::PlaceText(char * string, int x, int y, XFontStruct * fn) { 
  XSetFont(display, text_gc, fn->fid);
  int tw = XTextWidth(fn, string, strlen(string));   
  int th = fn->ascent; // + fn->descent;
  if (x == 0) x = (eff_width() - tw) / 2;  // horizontal centred
  if (y == 0) y = (height + th) / 2; // vertical centred
  DrawString(x,y,string); 
  XSetFont(display, text_gc, fixed_fn->fid);
}

void window::line(int x0, int y0, int x1, int y1) { 
  XDrawLine(display, Win, gc_copy, x0, y0, x1, y1); 
}

void window::DrawPoint(int x, int y) { XDrawPoint(display, Win, gc_copy, x, y); }

#include "helper.c"

void window::Expose_CB(XExposeEvent ev) { 
  if (CB_info) 
    printf("expose %d %d %d %d %d\n",ev.count,ev.x,ev.y,ev.width,ev.height);
  if (ev.count == 0) redraw();
}

/* definitions from /usr/include/X11/X.h : 
   see -> eventnames.h 
   KeyPress		2   KeyRelease		3
   ButtonPress		4   ButtonRelease	5
   MotionNotify		6   EnterNotify		7
   LeaveNotify		8   FocusIn		9
   FocusOut		10  KeymapNotify	11
   Expose		12  GraphicsExpose	13
   NoExpose		14  VisibilityNotify	15
   CreateNotify		16  DestroyNotify	17
   UnmapNotify		18  MapNotify		19
   MapRequest		20  ReparentNotify	21
   ConfigureNotify	22  ConfigureRequest	23
   GravityNotify	24  ResizeRequest	25
   CirculateNotify	26  CirculateRequest	27
   PropertyNotify	28  SelectionClear	29
   SelectionRequest	30  SelectionNotify	31
   ColormapNotify	32  ClientMessage	33
   MappingNotify	34  LASTEvent		35
*/


// the main callback function manages call of proper event handler
void window::CallBack(XEvent &event) { 
  if (CB_info) printf("Event %s (%d) in Win %lx\n",event_names[event.type],
		      event.type,event.xany.window);
  if (hidden) return;
  
  switch (event.type) { 
    case ButtonPress:    
        BPress_CB(event.xbutton); // allgemeiner BPress-handler, zB. buttons   
	switch (event.xbutton.button) {
	  case 1: BPress_1_CB(event.xbutton); break;
	  case 3: BPress_3_CB(event.xbutton); break;
	}
        break;
    case ButtonRelease:
        BRelease_CB(event.xbutton); break;
    case EnterNotify: 
	Enter_CB(event.xcrossing); break;
    case LeaveNotify:
	Leave_CB(event.xcrossing); break;
    case Expose:
	Expose_CB(event.xexpose); break;
    case KeyPress:
	KeyPress_CB(event.xkey);  break;
    case MotionNotify: 
	Motion_CB(event.xmotion); break;
    case ConfigureNotify:
        Configure_CB(event.xconfigure); break;
    case ClientMessage:
	ClientMsg_CB(event.xclient); break;
    default: break;
   }; 
}

void window::WatchCursor() { // set main window to watch
  XDefineCursor(display,mainw->Win,watch_cursor); 
  XFlush(display);
  //  watch_main = mainw;
}

void window::ResetCursor() { // temporarily set, in event-loop reset
  XUndefineCursor(display,mainw->Win);
}

// static float xf_res,yf_res; // resize-factors: either global (in CB) or 
// computed locally inside resize itself

void window::resize(int w, int h) {
  // printf("resize %x: w,h = %d %d (%d %d)\n",Win,w,h,width,height); 
  if (width == w && height == h) return; // evtl. only move Events
  float xf_res = float(w)/width, yf_res = float(h)/height;
  width = w; height = h;  
  XResizeWindow(display,Win,w,h);
  win_list *ch = children; 
  while (ch) { 
    window * cw = ch->child;
    int xn = irint(xf_res * ch->x), yn = irint(yf_res * ch->y);
    ch->x = xn; ch->y = yn;  // new x,y - coordinatec of the child-window
    XMoveWindow(display,cw->Win, xn, yn);
    cw->resize(irint(xf_res * cw->width), irint(yf_res * cw->height)); 
    ch = ch->next; 
  } 
} 

void window::frame3d(GC left_top, GC right_bot) {
  rect3d(Win, 0, 0, width-1, height-1, left_top,right_bot);
}

// ##################     main_window class    ###########################
#include "icon.h"

main_window *top_main = 0; // used to handle client messages : 
/* it becomes the first created main_window
   for this window will the close button (from the window manager)
   exit the application. Other main_windows will only be unmapped
   Therefore the main application window should be created first
*/

main_window::main_window(char * WMName, int w, int h,int fix_pos,int x,int y) 
  : window(root_window, w, h, x, y, 0) { // no border
  mainw = this; // its me myself !
  name = WMName; // mainly for debugging used
  polling_mode = False;     // default : use XNextEvent in main_loop

  XStoreName(display, Win, WMName);  // set name in WM-frame

  Cursor main_cursor = XCreateFontCursor(display,XC_left_ptr);
  // printf("1.main %s %d\n", WMName, fix_pos);
  XDefineCursor(display, Win, main_cursor);
  set_icon(icon_bits,icon_width,icon_height);
  if (fix_pos > 0) { 
    XSizeHints sz_hints; 
    if (fix_pos == 2) {       
      x = (DisplayWidth(display,screen) - w)/2;
      y = (DisplayHeight(display,screen)- h)/2;  // centre window
    }
    XMoveWindow(display,Win, x, y); // XSetWMNormalHints doesnt work here ?!
    // the x,y-slots of sz_hints are ignored, only move works ! 
    sz_hints.flags = PPosition | USPosition;;
    XSetWMNormalHints(display,Win,&sz_hints);
  }
  // this protocoll is used from the window manager (mwm) when the 
  // close button is pushed (f.kill). If not set the whole application
  // is killed when any main window is closed !
  Atom p = XInternAtom(display,"WM_DELETE_WINDOW",0); 
  XSetWMProtocols(display,Win,&p,1);

  if (top_main == 0) top_main = this; // the first created should be the app.
}

// up to now only invoked from window manager upon "close"
void main_window::ClientMsg_CB(XClientMessageEvent) {
  if (this == top_main) exit(0); else Unmap();
}

main_window::~main_window() {
  XDestroyWindow(display,Win); // also destroys the Subwindows 
  if (debug_delete) printf("main_window '%s' -> ", name);
  // window::~window(); 
  // explicite destr. for basis class not needed
}

// only for popup windows : show them at given x,y : old version :
// 1. make it small before moving it, 2. realize, 3. move to x,y-position
// not quite convinient
// this version -> does not work !
void main_window::do_popup(int x , int y) { 
  XMoveWindow(display, Win, x,y); // -> does not work here
  RealizeChildren(); 
  // XMoveResizeWindow(display, Win, x, y, width, height); // -> too slow 
}
	
void main_window::Configure_CB(XConfigureEvent ev) {  
  // printf("config %d %d %d \n",ev.type,ev.width,ev.height);
  // xf_res = float(ev.width)/width; yf_res = float(ev.height)/height;
  resize(ev.width, ev.height); 
}

// the event loop :
// from the window-id the this-pointer of the window is computed (table)
// then the "CallBack" function invokes the virtual handler to the 
// corresponding derived class from window

void handle_event(XEvent &event) {
  if (event.type != MotionNotify) clear_help(); // if there is any open help window -> close it
  // but not for PointerMotion Events (scrollbar helps !)
  unsigned wid = event.xany.window;
  xlist *xw = xhatab->xhget(wid);
  if (xw) xw->tw->CallBack(event);
  // else : the window is deleted, but some events can occur nevertheless 
  // eg. LeaveNotify-Events (type = 8) 
}

// for event loop in polling_mode
static Bool predicate(Display *, XEvent *, char *) { return TRUE; } 

void main_window::main_loop() {
  exit_flag = False;
  RealizeChildren(); 
  while (1) { 
    XEvent event;   
    if (polling_mode) { // polling : used only for special applications
      if (! XCheckIfEvent(display,&event,predicate,"loop")) {
	polling_handler(); 
	continue;  // no event handling needed
      }
    } else XNextEvent(display, &event);
    handle_event(event);
    // in case of the queue has filled during handling -> flush events 
    while (XCheckMaskEvent(display, KeyPressMask | KeyReleaseMask 
			   | PointerMotionMask,&event));
    if (exit_flag) break; // is set by quit buttons
  }
  Unmap();
  // printf("main_loop exited\n");
}

void main_window::set_icon(char *ibits, int iwidth, int iheight) {
  // printf("set_icon %x %d %d %x %x\n",ibits,iwidth,iheight,display,Win); 
  Pixmap icon_pixmap = XCreateBitmapFromData(display,Win,ibits,iwidth,iheight);
  // printf("set_icon %x \n",icon_pixmap); 
  XWMHints *wm_hints = XAllocWMHints();
  // printf("set_icon %x \n",wm_hints); 
  wm_hints->icon_pixmap = icon_pixmap;
  wm_hints->flags = IconPixmapHint;

  XSetWMHints(display,Win,wm_hints);
  XFree((void *) wm_hints);
}

// ####################      pixmap_window    ############################

pixmap_window::pixmap_window(window & parent,int w,int h,int x,int y,int bw) : 
window(parent, w, h,x, y, bw) {
  pix = XCreatePixmap(display, Win, width, height, depth);
  clear();
}

pixmap_window::~pixmap_window() {
  XFreePixmap(display,pix);
}  

void pixmap_window::clear() { 
  XFillRectangle(display, pix, gc_clear, 0,0, width, height); 
}
 
void pixmap_window::Map() { 
  draw_interior(); 
  is_mapped = true;
  XCopyArea(display,pix, Win, gc_copy, 0, 0, width, height, 0, 0);
  XMapWindow(display, Win); 
}

int pixmap_window::DrawString(int x, int y, char * string) {
  int n = strlen(string);
  XDrawString(display,pix,gc_copy,x,y, string, n); 
  return n;
}

void pixmap_window::line(int x0, int y0, int x1, int y1) {
  XDrawLine(display, pix, gc_copy, x0, y0, x1, y1); }

void pixmap_window::DrawPoint(int x, int y) {
    XDrawPoint(display, pix, gc_copy, x, y); 
  }

void pixmap_window::Expose_CB(XExposeEvent ev) { 
  // restore the exposed area from pixmap onto screen
  XCopyArea(display, pix, Win,gc_copy,ev.x,ev.y,ev.width,ev.height,ev.x,ev.y);
}

void pixmap_window::resize(int w, int h) {
  // printf("resize %dx%d -> %dx%d\n",width,height,w,h);
  if (width == w && height == h) return; // evtl. nur move Events
  XFreePixmap(display,pix);
  pix = XCreatePixmap(display,Win,w,h,depth);
  window::resize(w,h);
  clear(); // erst hier (braucht width, height !)
  Map();
}

// calculation of GCs for button colors, outside class definition, 
// since many buttons can use the same GC 
// give the brightest colors, the other 2 are set proportional
void color_GC(unsigned short r, unsigned short g, unsigned short b, GC3 *gc3) {
  int fg_pix = alloc_color(3*r/4,3*g/4,3*b/4); // inner part
  int br_pix = alloc_color(r,g,b); // bright rim
  int lw_pix = alloc_color(r/2,g/2,b/2); // dark rim
  XGCValues values;
  
  values.foreground = fg_pix;
  gc3->forgr = CreateGC(GCForeground, &values);
  values.foreground = br_pix;
  gc3->bright =  CreateGC(GCForeground, &values);
  values.foreground = lw_pix;
  gc3->dark =  CreateGC(GCForeground, &values);
}

// ****************** 3d-shapes ********  
// draw rectangle in 3d-look with two distinct GCs
// mode = up3d, flat3d (background pix), down3d
void rect3d(Window Win, short x, short y, short w, short h, GC left_top, GC right_bot) {
  int i, thickness = 2;  
  for (i = 0; i < thickness; i++) {
    short xa = x+i, ya = y+i, xe = x+w-i, ye = y+h-i ; 
    XPoint xp[5] = { {xa,ye}, {xa,ya}, {xe,ya}, {xe,ye}, {xa,ye}}; // short x,y
    XDrawLines(display,Win, left_top, xp, 3, CoordModeOrigin);
    XDrawLines(display,Win, right_bot, xp+2, 3, CoordModeOrigin);
  }
}

void set_gcs(int mode, GC& left_top, GC& right_bot) { // set GCs for mode
  switch (mode) { 
    case up3d:   left_top = button_br_gc; right_bot = button_lw_gc; break;
    case down3d: left_top = button_lw_gc; right_bot = button_br_gc; break;
    case flat3d: 
    default: left_top = button_fg_gc; right_bot = button_fg_gc; break;
  }
}

void rect3d(Window Win, int mode, short x, short y, short w, short h) {
  GC left_top, right_bot; // colors for both border parts
  set_gcs(mode, left_top, right_bot);
  rect3d(Win,x,y,w,h,left_top,right_bot);
}

// analog triangle, points downwards, x,y = left edge
// mode = up3d, flat3d (background pix), down3d
void tri3d_s(Window Win, int mode, short x, short y, short w, short h) {
  int i, thickness = 2;  
  GC left_top,right_bot; 
  switch (mode) { 
  case up3d:   left_top = button_br_gc; right_bot = button_lw_gc; break;
  case down3d: left_top = button_lw_gc; right_bot = button_br_gc; break;
  case flat3d: 
  default: left_top = button_fg_gc; right_bot = button_fg_gc; break;
  }
  for (i = 0; i < thickness; i++) {
    short xa = x+i, ya = y+i, xe = x+w-i, ye = y+h-i, xm = x+w/2; 
    XPoint xp[4] = { {xm,ye}, {xa,ya}, {xe,ya}, {xm,ye}}; 
    XDrawLines(display,Win, left_top, xp, 3, CoordModeOrigin); 
    XDrawLines(display,Win, right_bot, xp+2, 2, CoordModeOrigin);
  }
}

// plates are pseudo-3d-windows
plate::plate(window & parent, int w, int h, int x, int y,int mode3d)  
: window(parent, w, h, x, y, 0), mode3d(mode3d) { 
  selection_mask |= EnterWindowMask | LeaveWindowMask; 
  forgr = button_fg_gc; bright = button_br_gc; dark = button_lw_gc; // by default use light-blue
}
  
void plate::set_GC(struct GC3 *gc3) { // set other than the default light-blue
  forgr = gc3->forgr; bright = gc3->bright; dark = gc3->dark;
}
 
void plate::frame3d(int mode) {   
  GC left_top, right_bot; // colors for both border parts
  switch (mode) { 
    case up3d:   left_top = bright; right_bot = dark; break;
    case down3d: left_top = dark; right_bot = bright; break;
    case flat3d: default: left_top = right_bot = forgr; break;
  }
  window::frame3d(left_top, right_bot); 
}

void plate::redraw() {
  XFillRectangle(display,Win,forgr,0,0,width,height); 
  default_frame(); // virtual function !
}

// --------------------------- BUTTONS  -------------------------------
// ##################         button class      ###########################

void button::init_button(window *parent) {  
  in_pulldown = (parent->type == PulldownType);
  enabled = true; // by default
  selection_mask |= ButtonPressMask | ButtonReleaseMask;
} 

void button::redraw() {
  plate::redraw(); 
  PlaceText(Name);
  if (! enabled) for (int y=3; y < height-3; y +=3) // some lines with button color : dither
    XDrawLine(display,Win,forgr,3,y,width-3,y); 
}

button::~button() {
  if (debug_delete) printf("button '%s' -> ",Name); 
}

void button::BRelease_CB(XButtonEvent ev) { 
  if (ev.state & Button1Mask) { 
    if (enabled) BRelease_1_action(); 
    default_frame(); 
  }
}
// ##################      popup_button        #########################
// realize the popup menu when BPress (make it visibel) 
// if pressed again : make it unvisible 

void popup_button::BPress_1_CB(XButtonEvent ev) { 
  XWindowAttributes attr;
  XGetWindowAttributes(display,popup_menu->Win,&attr);
  if (attr.map_state == IsViewable) popup_menu->Unmap(); 
  else popup_menu->do_popup(ev.x_root + 10,ev.y_root + 20); 
}  

// ##################     help_button class    ############################

void help_button::make_popup(char *text[]) {
  // Berechnung der noetigen Windowgroesse fuer popup
 int ln, cols; 
 compute_text_size(text,cols,ln);
 popup_menu = new text_popup("help", 6*cols + 10, ln*15 + 30, text); 
 // leave room for OK button (bottom)!
}

// ##################   function_button class    ############################

function_button::function_button (window & parent, char * Name,  
                                 int w, int h, int x, int y, CB cb,  ...) : 
      button (parent, Name, w, h, x, y), callback(cb) {
    int i; va_list ap; va_start(ap,cb);
    for (i=0;i<10;i++) values[i] = va_arg(ap,void*);
    va_end(ap);
  }

function_button::function_button (menu_bar & parent, char * Name, CB cb, ...) :
  button (parent, Name), callback(cb) { 
    int i; va_list ap; va_start(ap,cb);
    for (i=0;i<10;i++) values[i] = va_arg(ap,void*);
    va_end(ap);
  }

// --------------  switch_button ------------------  
// a button with 2 states of display, which switch on click
// the 2. string should be <= the first (= initial)

void switch_dummy(void *) {} // default dummy fn : does nothing

switch_button::switch_button(menu_bar & parent, char *Name1, char *Name2, 
			     Bool *toggle,
		 VVP inf, void * toinf) : button(parent,Name1), toggle(toggle) 
{ callbck = inf; instptr = toinf; Narr[0] = Name1; Narr[1] = Name2; }

switch_button::switch_button(window & parent, char *Name1, char *Name2, Bool *toggle,
		 VVP inf, void * toinf, int w, int h, int x, int y) : 
		 button(parent,Name1,w,h,x,y) ,toggle(toggle) 
    { callbck = inf; instptr = toinf; Narr[0] = Name1; Narr[1] = Name2; }

void switch_button::switch_it() {
    *toggle = ! *toggle;  // switch
    Name = Narr[*toggle]; // use as index ! (0,1)
    redraw(); // display new string
    (*callbck)(instptr); 
  }
 
// ---------------------------- PULLDOWN --------------------------------

// ##################     pulldown_window class    #######################
// a window child from root_window, not yet visible, not managed from WM,
// position is determined from the button at popup time

pulldown_window::pulldown_window (int w, int h, int nb, button **rbp) : 
main_window("",w,h), nb(nb), rbp(rbp){
  XSetWindowAttributes attr; 
  attr.override_redirect = TRUE; attr.save_under = TRUE;
  XChangeWindowAttributes(display, Win, CWOverrideRedirect | CWSaveUnder, &attr);
  type = PulldownType;
  rold = NULL;
}
  
void pulldown_window::toggle(radio_button *rb) {
  if (rold) rold->status = False;
  // printf("%p %p %p\n",this,rold,rb);
  rold = rb; rb->status = True;
}

// maps pulldown window and handles X-pointer selection (only for local buttons!!)
void pulldown_window::handler(int x, int y) {  
  XMoveWindow(display, Win, x, y);
 
  RealizeChildren();
  XRaiseWindow(display,Win); 

  XUngrabPointer(display,CurrentTime); // to enable the pulldown menu
  // for (int i=0; i<nb; i++) printf("  %lx",rbp[i]->Win);
  // printf("\n");

  while (1) { 
    XEvent event;   
    XNextEvent(display, &event);
    
    unsigned wid = event.xany.window;
    for (int i=0; i<nb; i++) 
      if (wid == rbp[i]->Win) {
	xlist *xw = xhatab->xhget(wid);
	if (xw) xw->tw->CallBack(event); 
      }
    if (event.type == ButtonRelease) break;
  }
  Unmap();

}
// ##################     pulldown_button class    ########################
// map the window (menu) on root when button is activated (BPress)
// the window is mapped to absolute co-ordinates !

pulldown_button::pulldown_button (window & parent, pulldown_window * menu, 
				  char * Name, int w, int h, int x, int y) 
: button(parent, Name, w, h, x, y) { 
  pulldown_menu = menu; xright = 12; 
}

pulldown_button::pulldown_button(menu_bar & parent, pulldown_window * menu, 
				 char * Name) 
: button(parent, ext_string(Name)) { 
  pulldown_menu = menu; xright = 12; 

}

pulldown_button::pulldown_button (window & parent, pulldown_window * menu, 
				  char * Name, char ** help_text,
				  int w, int h, int x, int y) 
: button(parent, Name, help_text, w, h, x, y) 
         { pulldown_menu = menu; xright = 12;}
 
void pulldown_button::picture() { 
   int offs = (height-8)/2; 
   tri3d_s(Win,up3d, width-xright,offs,8,8);
}

// special cursor for pulldown menus 
Cursor pulldown_cursor = XCreateFontCursor(display,XC_right_ptr);

void pulldown_button::BPress_1_CB(XButtonEvent ev) { 
  int x, y; // *absolut*  position of pulldown menu
  // determine the absolute coord of mouse pointer
  x = ev.x_root - ev.x; // + (width-pulldown_menu->width)/2; horizontal centr.
  y = ev.y_root - ev.y + height + 1;

  pulldown_menu->handler(x,y);
  default_frame();
} 

// if w == 0 parent must be menu_bar -> use autoplacement
pulldown_button* make_radio_menu(window &parent, char *Name, char **list,
				 window * action_win,
				 int w, int h, int x, int y, int inival) {
  int wm, hm;      // size of pulldown_menu
  int nbuttons;   // number of buttons on pulldown
  char * value;
  // first parse blist to determine size of pulldown menu
  compute_text_size(list,wm,nbuttons);
  wm = 40 >? wm * 6 + 18;   //  6 = width of char
  hm = nbuttons * 20;       // 20 = height of button
  radio_button **rbp = new (radio_button*) [nbuttons];
  pulldown_window *pd_wi = new pulldown_window(wm,hm,nbuttons, (button**) rbp);
  pulldown_button *pd_bt = (w > 0) ? new pulldown_button(parent,pd_wi,Name,w,h,x,y) 
    : new pulldown_button((menu_bar&) parent, pd_wi, Name);

  for (int yp = 0, ind = 0; ind < nbuttons; ind++, yp += 20) { 
    value = *list++;
    radio_button *rb = rbp[ind] = 
      new radio_button(*pd_wi,Name,wm,20,0,yp,value, action_win);
    Bool status = (ind == inival);
    rb->status = status; // the first button is set True, others False
    if (status) pd_wi->toggle(rb);
  };
  return pd_bt;
}

pulldown_button* make_radio_menu(menu_bar &parent, char *Name, char **blist, window* action_win,
				 int inival) {
  pulldown_button* r_menu = make_radio_menu(parent, Name, blist, action_win, 0, 0, 0, 0, inival );
  return r_menu;
}

// analogous : with help popup
pulldown_button* make_radio_menu(window &parent, char *Name, char **list,
				 char** help_text, window* action_win,
				 int w, int h, int x, int y, int inival) {
  pulldown_button* r_menu = make_radio_menu(parent, Name, list, action_win, w, h, x, y, inival );
  r_menu->add_help(help_text);
  return r_menu;
}

// list : { {"button1", &callback1}, {"button2", &callback} }
pulldown_button * make_pulldown_menu(window &parent, char *Name, 
				     int nbuttons, struct but_cb list[],
				     int w, int h, int x, int y) {
  int wm = 0, hm;     // size of pulldown_menu
  int i;
  // first parse blist to determine size of pulldown menu
  for (i=0; i < nbuttons; i++) { 
    int ll;
    ll = strlen(list[i].bname); if (ll > wm) wm = ll;
  };
  wm = wm * 6 + 10 ;            //  6 = length of char
  hm = nbuttons * 20;           // 20 = height of button
  button **cbp = new (button*)[nbuttons];
  pulldown_window * pd = new pulldown_window(wm, hm,nbuttons,cbp);
  pulldown_button * pb;
  if (w > 0) pb = new pulldown_button(parent,pd,Name,w,h,x,y); else
     pb = new pulldown_button((menu_bar&) parent, pd, Name); 

  int yp = 0; 
  for (i=0; i < nbuttons; i++) { 
    cbp[i] = new callback_button(*pd,list[i].bname,list[i].cb,wm,20,0, yp);
    yp += 20;
  }
  return pb;
}


// ###################### text_popup #######################
text_popup::text_popup(char * WMName, int w, int h, char *text[]) :
main_window (WMName, w, h) { 
  pop_text = text; 
  new unmap_button (*this,"OK",50,20, (width-50)/2,height-23); 
  // a button to close the popup window
}

void text_popup::Expose_CB(XExposeEvent) { // write the text
    int ln = 0, y = 0; 
    while (pop_text[ln]) {   
      y+= 15;
      PlaceText(pop_text[ln++], 4, y);
    }
  }

// String-Arrays: char *x[] = {"xyzuvw","XXXX",...,0} 
// max length of a  string  && number of  strings 
void compute_text_size(char *text[], int &cols, int &lines) {
  int ll = 0;
  lines = 0; cols = 0;
  while (text[lines]) { 
    ll = strlen(text[lines++]);
    if (ll > cols) cols = ll;
    if (ll > 1000 || cols > 1000) error("text-array has no NULL-termination");
  }
}

// ##################### coord_window ##########################
coord_window::coord_window(window & parent, int w, int h, int x, int y, 
	                   int rxl, int rxr, int ryd, int ryu) :
    pixmap_window(parent,w,h,x,y), rxl(rxl), ryd(ryd) { 
    w_diff = rxr + rxl; h_diff = ryd + ryu; // the border minus
}

void coord_window::define_coord(double x1, double y1, double x2, double y2) {
  xl = x1; yd = y1; xr = x2; yu = y2;
  x0 = rxl; y0 = height - ryd; // Window-coordinates of origin
  w_eff = width - w_diff; h_eff = height - h_diff;
  xf = w_eff/(x2 - x1); yf = h_eff/(y2 - y1);
}

void coord_window::resize(int w, int h) {
  // compute parameters for new window size w*h
  x0 = rxl; y0 = h - ryd; // Window-coordinates of origin
  w_eff = w - w_diff; h_eff = h - h_diff;
  xf = w_eff/(xr - xl); yf = h_eff/(yu - yd);
  pixmap_window::resize(w,h);
}
 
// compute total window-coordinates from world-values
int coord_window::x_window(double x) { return x0 + (int)(xf * (x - xl) + .5); }
int coord_window::y_window(double y) { return y0 - (int)(yf * (y - yd) + .5); }

XPoint coord_window::p_window(double x, double y) { // returns same as XPoint
  XPoint temp = { x_window(x), y_window(y) };
  return temp;
}
   
// back transformation : window coords to world-values
double coord_window::x_org(int xw) { return (xw - x0)/xf + xl; }
double coord_window::y_org(int yw) { return (y0 - yw)/yf + yd; }

void coord_window::draw_coords() { wline(0,yd,0,yu); wline(xl,0,xr,0); }

void coord_window::x_ticks(double dx, int n) { 
  double xx; 
  if (xr < xl) dx = -dx; // failsafe
  int y = y_window(0.0);
  for (xx = xl; xx < xr; xx+= dx) { 
    int x = x_window(xx); line(x,y,x,y+2); 
    if (n-- == 0) break;
  } 
}
void coord_window::y_ticks(double dy, int n) { 
  int i; double yy = yd;
  if (yu < yd) dy = -dy;
  int x = x_window(0.0);
  for (i = 0; i < n; i++) { 
    int y = y_window(yy); line(x,y,x-2,y); 
    yy += dy; if (yy > yu) break;
  }
}
 
void coord_window::graph(int nx, double f[]) { 
  int i, x , y, xp = 0, yp = 0; 
  for (i=0; i<nx-1; i++) { 
    y = y_window(f[i]); x = x_window(i); 
    if (i > 0) line(xp, yp ,x, y);
    xp = x; yp = y; 
  }
}

//   ###########  system buttons && xwd_buttons ##########

void system_button::BPress_1_CB(XButtonEvent) { 
  printf("calling system('%s')\n",cmdline);
  system(cmdline);
}

void xwd_button::BPress_1_CB(XButtonEvent) { 
  char cmdline[200]; 
  sprintf(cmdline,"xwd -id 0x%lx %s",dumpw->Win, arg);
  printf("dump : calling system('%s')\n",cmdline);
  system(cmdline);
}

// ############################################################
//              SLIDERS &   SCROLLBARS

slider::slider(window &parent, int w, int h, int x, int y) : 
  plate (parent,w,h,x,y,up3d) { }

void slider::redraw() { // called from Expose_CB, not invoked from move !
  plate::redraw();
  line(width/2,0,width/2,height);
}

void pure_scrollbar::set_slider(int x) {
  bar = new slider(*this,sw,sh,x+2,sy); 
  xact = x;
}

void pure_scrollbar::init () { 
  sw = 19; sh = height-10; sy = 5; // start-values for slider
  xoff = sw/2+2; xmax = width-sw/2-2; xspan = xmax-xoff-1;
  set_backing_store(); // to avoid flickering of scrollbar when drawing slider
  selection_mask |= PointerMotionMask | ButtonPressMask; 
  nticks = 0; // default : no ticks
}

void pure_scrollbar::move(int x) { 
  if (x >= 0 && x <= xspan) { // the real value in intervall [0..xspan]
    XMoveWindow(display,bar->Win,x + xoff - sw/2,sy); 
  }  
}

void pure_scrollbar::move_cb(int x) {
 if (x >= 0 && x <= xspan) { // the real value in intervall [0..xspan]
    XMoveWindow(display,bar->Win,x + xoff - sw/2,sy); 
    callbck(x);
  }  
}

void pure_scrollbar::redraw() {   
  plate::redraw(); 
  line(xoff,height/2,xmax,height/2); // horizontal line
  // line(xoff,4,xoff,height-4); line(xmax,4,xmax,height-4)
  for (int i = 0; i < nticks; i++) { // only drawn if nticks > 0
    int x = xoff + (i+1)*(xmax-xoff)/(nticks+1);
    line(x,4,x,height-4);
  }
}

void pure_scrollbar::resize(int w, int h) {
  plate::resize(w,h);
  sw = bar->width; sy = (height - bar->height)/2;
  xoff = sw/2+2; xmax = width-sw/2-2; xspan = xmax-xoff-1;
} 

void display_window::set_text_mode(int mode) { 
  // mode 0 : clear, 1 : write
  text_gc = (mode) ? gc_copy : button_fg_gc;
} 
 
void scrollbar::init(window &parent, int w, int h, int x, int y, 
                     float minp, float maxp, float xstart) 
{  min = minp; max = (maxp) ? maxp : xspan; 
   factor = ((double) (max - min))/xspan; 
   set_slider( val_to_pix(xstart) );
   setval(xstart); // Anfangs-default
   disp_win = new display_window(parent,str,60,h,x+w-60,y,down3d);
 }

scrollbar::scrollbar(window &parent, void (*inf)(), int w, int h, 
		     int x, int y, float minp, float maxp, float xstart,
		     char *format) :
     pure_scrollbar (parent,pwidth(w),h,x,y), format(format) {
       init(parent,w,h,x,y,minp,maxp,xstart);
       to_inform = NULL;
       inffn.empty = inf;
  }
 
// 2. constructor :
scrollbar::scrollbar(window &parent, void (*inf)(void*), void * to_inf,
		     int w, int h, int x, int y, 
		     float minp, float maxp, float xstart, char *format) :
     pure_scrollbar (parent,pwidth(w),h,x,y), format(format) {
       init(parent,w,h,x,y,minp,maxp,xstart);
       to_inform = to_inf;
       inffn.vptr = inf;
  }
    
void scrollbar::display_val(float x) {   
  // quick clearing of the old display : overwrite with  background gc
  disp_win->set_text_mode(0); disp_win->draw_val();
  setval(x); // compute new display
  disp_win->set_text_mode(1); disp_win->draw_val(); // reset default gc !!! , new value
}

void scrollbar::callbck_val(float x) {  
  display_val(x);
  if (inffn.value) { if (to_inform) (*inffn.vptr)(to_inform); else (*inffn.empty)(); }
}

void scrollbar::resize(int w, int h) {
  pure_scrollbar::resize(w,h);  
  factor = ((double) (max - min))/xspan; 
}

// **** class tick_scrollbar ***** : scrollbar with ticks and numbers
// has fixed height (20 + 15 = 35) with ticks and value displays 
void tick_scrollbar::tickstr() { // compute tick strings
  char *stptr = strvec;
  for (int i=0; i < nticks+2; i++) {
    sprintf(stptr,format,i*(max-min)/(nticks+1)+min); valstr[i]= stptr;
    stptr += strlen(stptr)+1;
  }
}

tick_scrollbar::tick_scrollbar(window &parent, void (*inf)(void*), 
			       void *to_inf,
			       int w, int x, int y, int n_ticks, 
			       float minp, float maxp, float xstart, 
			       char *format) :
  scrollbar(parent, inf, to_inf, w, 20, x, y, minp, maxp, xstart, format) {   
    nticks = n_ticks;
    if (nticks > MAXTCKS) 
      error("too many ticks for scrollbar %d (max %d)", nticks,MAXTCKS);
    strvec = new char[(nticks+2)*12]; // room should suffice
    tickstr();
    for (int i = 0; i < nticks+2; i++) { 
      // windows to display numbers below ticks
      // int nl = strlen(valstr[i]);
      int xp = xoff + i*xspan/(nticks+1) ;
      valtxt[i] = new text_win(parent, valstr[i], 30, 15, x + xp - 15, y+20);
    }
  }

tick_scrollbar::~tick_scrollbar() { delete strvec; }

void tick_scrollbar::adapt(int maxp, int xstart) {
  max = maxp; factor = ((double) max - min)/xspan; 
  change(xstart); // set slider to xstart and displays value
  tickstr();
  for (int i = 0; i < nticks+2; i++) { // displays numbers below ticks
    valtxt[i]->clear(); valtxt[i]->redraw();
  }
}

// some aux fns
static void play_updated(play_scrollbar *psc) { psc->updated(); }
static void play_switch(play_scrollbar *psc) { psc->switch_play(); }

// **** class play_scrollbar ***
// a tick_scrollbar, that adds playback- and stepping buttons left and right  
play_scrollbar::play_scrollbar(window &parent, int w, int x, int y, 
			       int n_ticks, stepper *stp, int minp, int maxp, 
			       int xstart) 
: tick_scrollbar(parent, (VVP) &play_updated, (void*) this, w-2*(15+20), 
		 x+50, y, n_ticks, minp, maxp, xstart), stp(stp) {   
  new instance_button <play_scrollbar> // left
    (parent,"<", &play_scrollbar::step_bck, this, 15,20, x, y); 
    
  new instance_button <play_scrollbar> // left +15
    (parent,">", &play_scrollbar::step_fwd, this, 15, 20, x+15, y); 
  
  new switch_button(parent,">>","||",&play_mode, // left + 30
		    (VVP) &play_switch, (void*) this, 20, 20, x+30,y);
  new instance_button <play_scrollbar>  // right - 20
    (parent,"<<", &play_scrollbar::reset, this, 20, 20, x+w-20, y);
}

// ***************************************
// class "edit_window" for editing of strings, max 80 chars 
edit_window::edit_window(window &parent, char *str, int w,int h, int x, int y)
: plate(parent,w,h,x,y,down3d) { 
  strncpy(value,str,200);
  XDefineCursor(display,Win,text_cursor);
  cp = strlen(value); // set behind the string
  selection_mask |= KeyPressMask;
}

void edit_window::mark_cursor() { 
  XFillRectangle(display, Win, gc_but_xor, xs + 6*cp, 2, 6, 15);
}
void edit_window::Enter_CB(XCrossingEvent) { // frame3d(flat3d); 
  mark_cursor(); 
}
void edit_window::Leave_CB(XCrossingEvent) { // default_frame(); 
  mark_cursor(); 
}

void edit_window::redraw() {
  plate::redraw(); 
  xs = width - 6*strlen(value) - 10; 
  DrawString(xs,16,value);
}
  
void edit_window::del_char() { // clear chars left from cursor
  for (unsigned i = cp; i <= strlen(value); i++) value[i-1] = value[i];
  cp--;
}

void edit_window::ins_char(char x) { // insertion left
  for (int i = strlen(value); i >= cp; i--) value[i] = value[i-1];
  value[cp] = x; cp++;
}

void edit_window::KeyPress_CB(XKeyEvent ev) {
  mark_cursor();
  KeySym keysym = XLookupKeysym(&ev,ev.state & 1);
  switch(keysym) {
  case XK_Left: while (cp <= 0) ins_char(0x20); // fill with space
    cp -= 1; break;
  case XK_Right: if (cp < (int) strlen(value)) cp += 1; break;
  case XK_BackSpace: if (cp > 0) del_char(); break;
  case XK_Delete: if (cp > 0) del_char(); break;
  case XK_Escape: escape(); break;
  case XK_Return: enter(); break;               // Return = Enter
  default: 
    if ((keysym >= 0x20) && (keysym<= 0x7e)) // all ASCII-chars
      ins_char(keysym);
  }
  redraw();
  mark_cursor(); 
}

// class clock_win : public pixmap_window 
// class to display a simple analogue clock bound to an external time variable

clock_win::clock_win(window &parent, int *tptr,int w, int h, int x, int y) :
  pixmap_window(parent,w,h,x,y,0), tptr(tptr) { init(); }

// display a centered arrow with radius r
void clock_win::arrow(double phi, float r) {
  double c, s; 
  s = sin(phi); c = cos(phi);
  line(xc,yc, irint(xc + r*s), irint(yc - r*c));
}

void clock_win::draw_interior()  {
  int r = d/2;
  XDrawArc(display,pix,gc_copy,xc-r,yc-r,d,d,0,360*64);
  arrow(*tptr/3600.*2.0*3.1416, rm); // minutes arrow
  arrow(*tptr/86400.*4.0*3.1416, rh); // hours arrow
}
  
void clock_win::init() {
  xc = width/2; yc = height/2; 
  d = (width <? height) - 2; // minimum of width and height
  rh = d/3 - 2; rm = d/2 - 4;
  // printf(" %d %d %d %d %d\n",width,height,xc,yc,d);
}

void clock_win::resize(int w, int h) {
  pixmap_window::resize(w,h);
  init();
  redraw();
}

//  ************* twodim_input ***********
// a class used to get a twodim value from a mouse pointer driven slider

twodim_input::twodim_input(window &parent, int w, int h, int x, int y, 
			   int swp, int shp, void *vptr)
: plate (parent,w,h,x,y,down3d), vptr(vptr), sw(swp), sh(shp) { 
  set_backing_store(); 
  selection_mask |= PointerMotionMask | ButtonPressMask; 
  set_vars();  
  bar = new plate(*this,sw,sh,sx,sy,up3d);
  cbhook = NULL;
}  

void twodim_input::set_vars() {
  sx = 2; sy = 2; 
  yact = sy; xact = sx; 
  if (sh == 0) sh = height - 2*sy; // horiz. shifter : yspan = 0
  if (sw == 0) sw = width  - 2*sx; // vert . shifter : xspan = 0
  yspan = height - 2*sy - sh; 
  xspan = width - 2*sx - sw;
}

void twodim_input::move(int x, int y) { // called from Events
  set_slider(x - sx - sw/2,y - sy - sh/2);
}
void twodim_input::BPress_CB(XButtonEvent ev)  {
  switch (ev.button) {
  case 1: case 2: // all the same
  case 3: move(ev.x,ev.y); break;  
  }
}

void twodim_input::Motion_CB(XMotionEvent ev)  { 
  if (ev.state & (Button1Mask | Button2Mask | Button3Mask)) { 
    move(ev.x,ev.y); }
}

void twodim_input::set_slider(int x, int y)  {  // set slider y = 0..zspan
  // printf(" %d %d\n",x,y);
  y = MAX(0, MIN(yspan,y)); 
  x = MAX(0, MIN(xspan,x));     
  if (x != xact || y != yact) {
    xact = x; yact = y;
    XMoveWindow(display,bar->Win,x + sx ,y + sy); 
    if (cbhook) cbhook(vptr,this);
  }
}

// called from resize && others 
void twodim_input::slider_adapt(int swp,int shp) { // adaptate to new slider size
  sw = swp; sh = shp; 
  set_vars(); 
  bar->resize(sw,sh); set_slider(0,0);
} 


void twodim_input::resize(int w, int h)  {
  //    if (width == w && height == h) return; // only once
  width = w; height = h; 
  XResizeWindow(display,Win,width,height); 
  slider_adapt(sw,sh);
}

void twodim_input::configure(int w, int h, int swp, int shp, int x, int y)  { 
  resize(w,h);
  slider_adapt(swp,shp);
  XMoveWindow(display,Win,x,y);
  RealizeChildren(); // in case it was unmaped before
}


// scrolled_window has a virtual window which can be shifted with shifters
// arguments are : real width/height, virtual width/height
// (the first window with correct resizing)
// the virtual window must be derived from class virtual_window !!!

scrolled_window::scrolled_window(window &parent, int w, int h, int vw, int vh, 
				 int x, int y) 
: window(parent,w,h,x,y,0) {
  xp = yp = 0;
  hvirt = vh; wvirt = vw;
  hs = vs = 0; clip = 0;
  resize(w,h);
  virt_win =  0; // must be set later !!!
} 

void scrolled_window::cbhook(twodim_input *ts) {
  if (virt_win == 0) error("no virtual window bound");
  int x = ts->xact, y = ts->yact, xs = ts->xspan, ys = ts->yspan;
  // printf("hook %d %d\n",ts->xact,ts->yact);
  // transform slider-pos to shift values
  if (xs != 0) xp = -x*(wvirt - wvis)/xs; 
  // else vert.shifter: use old xp
  if (ys != 0) yp = -y*(hvirt - hvis)/ys;
  XMoveWindow(display,virt_win->Win,xp,yp);
}

static void scw_cbhook(scrolled_window* sc, twodim_input *td) {
  sc->cbhook(td);
}

void scrolled_window::resize(int w, int h) {
  // if (w == width && h == height) return;
  width = w; height = h;
  // printf("resize scrolled window %d %d %d %d\n",w,h,wvirt,hvirt);
  XResizeWindow(display,Win,w,h);
  int sz = 15; // shifter dim. (heigth or width)
  Bool horz_scr = (wvirt > w);
  if (horz_scr) h -= sz; // left room for horz_shifter (bottom) 
  Bool vert_scr = (hvirt > h); 
  if (vert_scr) w -= sz; // left room for shifter (right) 
  wvis = w; hvis = h;    // that is the region which is actually visible

  if (vert_scr) {
    int sh = (h-4) * h/hvirt; if (sh < 4) sh = 4; // else too small
    if (vs == 0) // create new 
      vs = new vertical_shifter(*this,sz,h,w,0,sh, (CBHOOK) &scw_cbhook, this);
    else vs->configure(sz,h,0,sh,w,0); 
  } else if (vs) XUnmapWindow(display,vs->Win);
  if (horz_scr) {
    int sw = (w-4) * w/wvirt; if (sw < 4) sw = 4; // else too small
    if (hs == 0) // create new 
      hs = new horizontal_shifter(*this,w,sz,0,h,sw, (CBHOOK) &scw_cbhook,this);
    else hs->configure(w,sz,sw,0,0,h); 
  } else if (hs) XUnmapWindow(display,hs->Win);
  
  if (clip == 0) clip = new window(*this,wvis, hvis, 0, 0); // clip window
  else XResizeWindow(display,clip->Win,wvis,hvis);
  // printf("%d %d %d %d %d %d\n",wvirt,hvirt,wvis,hvis,w,h);
}

horizontal_shifter::horizontal_shifter(window &parent, int w, int h, int x, 
				       int y, int sw, CBHOOK cbh, void *vptr) 
: twodim_input(parent,w,h,x,y,sw,0,vptr) { 
  cbhook = cbh; 
  XDefineCursor(display,Win,hs_cursor); 
}

vertical_shifter::vertical_shifter(window &parent, int w, int h, int x, int y, 
				   int sh, CBHOOK cbh, void *vptr) 
: twodim_input(parent,w,h,x,y,0,sh,vptr) { 
  cbhook = cbh; 
  XDefineCursor(display,Win,vs_cursor); 
}