File: XmPgplot.c

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

/* Motif pgplot widget class implementation */

#include <Xm/XmP.h>
#include <X11/StringDefs.h>
#include <Xm/ScrolledW.h>
#include <Xm/ScrollBar.h>
#include <X11/keysym.h>

#include <stdio.h>
#include <stdlib.h>

#ifndef convex
#include <string.h>
#endif

/*
 * VAX VMS includes etc..
 */
#ifdef VMS
#include <descrip.h>
#include <ssdef.h>
typedef struct dsc$descriptor_s VMS_string;
#define VMS_STRING(dsc, string) \
  dsc.dsc$w_length = strlen(string); \
  dsc.dsc$b_dtype = DSC$K_DTYPE_T; \
  dsc.dsc$b_class = DSC$K_CLASS_S; \
  dsc.dsc$a_pointer = string;
#endif

/*
 * Allow xmdriv to be calleable by FORTRAN using the two commonest
 * calling conventions. Both conventions append length arguments for
 * each FORTRAN string at the end of the argument list, and convert the
 * name to lower-case, but one post-pends an underscore to the function
 * name (PG_PPU) while the other doesn't. Note the VMS is handled
 * separately below. For other calling conventions you must write a
 * C wrapper routine to call xmdriv() or xmdriv_().
 */
#ifdef PG_PPU
#define XMDRIV xmdriv_
#else
#define XMDRIV xmdriv
#endif

#include "XmPgplotP.h"

/*
 * Define the default attributes of the widget.
 */
#define XMP_MIN_WIDTH 64     /* Minimum width (pixels) */
#define XMP_MIN_HEIGHT 64    /* Minimum height (pixels) */
#define XMP_DEF_WIDTH 256    /* Default width (pixels) */
#define XMP_DEF_HEIGHT 256   /* Default height (pixels) */
#define XMP_MIN_COLORS 2     /* Min number of colors per colormap */
#define XMP_DEF_COLORS 100   /* Default number of colors to try for */
#define XMP_MAX_COLORS 255   /* Max number of colors per colormap */
#define XMP_DEF_MARGIN 20    /* The number of pixels to assign to the margin */
#define XMP_DEF_SHARE 0      /* Default to allocating shared colors */

/*
 * Specify the name to prefix errors with.
 */
#define XMP_IDENT "PgplotWidget"

static void xmp_GetDefaultHighlightColor(Widget widget, int offset,
					 XrmValue *value);
static void xmp_GetDefaultBackgroundColor(Widget widget, int offset,
					  XrmValue *value);
static void xmp_GetDefaultForegroundColor(Widget widget, int offset,
					  XrmValue *value);
/*
 * Define all the X resources that are to be understood by the
 * widget.
 */
static XtResource resources[] = {
  {
    XmpNminColors,
    XmpCMinColors,
    XtRInt,
    sizeof(int),
    XtOffsetOf(XmPgplotRec, pgplot.min_colors),
    XtRImmediate,
    (XtPointer) XMP_MIN_COLORS
  },
  {
    XmpNmaxColors,
    XmpCMaxColors,
    XtRInt,
    sizeof(int),
    XtOffsetOf(XmPgplotRec, pgplot.max_colors),
    XtRImmediate,
    (XtPointer) XMP_DEF_COLORS
  },
  {
    XmNvisual,
    XmCVisual,
#if XmVersion <= 1001
    XtRVisual,
#else
    XmRVisual,
#endif
    sizeof(Visual *),
    XtOffsetOf(XmPgplotRec, pgplot.visual),
    XtRImmediate,
    (XtPointer) CopyFromParent
  },
  {
    XmNresizeCallback,
    XmCCallback, XmRCallback, sizeof(XtCallbackList),
    XtOffsetOf(XmPgplotRec, pgplot.resize_callback),
    XmRImmediate, (XtPointer) NULL
  },
  {
    XmNhighlightColor,
    XmCHighlightColor,
    XmRPixel, 
    sizeof(Pixel),
    XtOffsetOf(XmPgplotRec, primitive.highlight_color),
    XmRCallProc, (XtPointer) xmp_GetDefaultHighlightColor
  },
  {
    XmNbackground,
    XmCBackground,
    XmRPixel, 
    sizeof(Pixel),
    XtOffsetOf(XmPgplotRec, core.background_pixel),
    XmRCallProc, (XtPointer) xmp_GetDefaultBackgroundColor
  },
  {
    XmNforeground,
    XmCForeground,
    XmRPixel, 
    sizeof(Pixel),
    XtOffsetOf(XmPgplotRec, primitive.foreground),
    XmRCallProc, (XtPointer) xmp_GetDefaultForegroundColor
  },
  {
    XmpNpadX,
    XmpCPadX,
    XtRDimension,
    sizeof(Dimension),
    XtOffsetOf(XmPgplotRec, pgplot.pad_x),
    XtRImmediate,
    (XtPointer) XMP_DEF_MARGIN
  },
  {
    XmpNpadY,
    XmpCPadY,
    XtRDimension,
    sizeof(Dimension),
    XtOffsetOf(XmPgplotRec, pgplot.pad_y),
    XtRImmediate,
    (XtPointer) XMP_DEF_MARGIN
  },
  {
    XmpNshare,
    XmpCShare,
    XtRBoolean,
    sizeof(Boolean),
    XtOffsetOf(XmPgplotRec, pgplot.share),
    XtRImmediate,
    (XtPointer) XMP_DEF_SHARE
  },
};

/*
 * Declare class method functions.
 */
static void xmp_ClassPartInit(WidgetClass w);
static void xmp_Initialize(Widget request, Widget new_w, 
				     ArgList args, Cardinal *num_args);
static void xmp_Realize(Widget widget, XtValueMask *mask, 
				  XSetWindowAttributes *attributes);
static void xmp_Resize(Widget widget);
static void xmp_Destroy(Widget widget);
static void xmp_Expose(Widget widget, XEvent *event, Region region);
static Boolean xmp_SetValues(Widget old_widget, Widget req_widget, 
				       Widget new_widget, 
				       ArgList args, Cardinal *num_args);
static XtGeometryResult xmp_Query_Geometry(Widget widget, 
					    XtWidgetGeometry *request, 
					    XtWidgetGeometry *reply);
static void XmpDestroyParentCallback(Widget w, 
                              XtPointer client_data, XtPointer call_data);

/*
 * Actions and their default translations should go here.
 * Note that specifying NULL for for the core.tm_table class
 * field results in the Motif Primitive initialization function
 * not augmenting the table with its keyboard traversal translations.
 * Thus we must supply a translation table, even if it is empty.
 */
static char default_translations[] = "";

/*
 * Define the Motif Pgplot class shared context descriptor.
 */
externaldef(xmpgplotclassrec) XmPgplotClassRec xmPgplotClassRec = {

  { /* core_class fields */
    /* superclass         */    (WidgetClass) &xmPrimitiveClassRec,
    /* class_name         */    "XmPgplot",
    /* widget_size        */    sizeof(XmPgplotRec),
    /* class_initialize   */    NULL,
    /* class_part_initiali*/    xmp_ClassPartInit,
    /* class_inited       */    FALSE,
    /* initialize         */    xmp_Initialize,
    /* initialize_hook    */    NULL,
    /* realize            */    xmp_Realize,
    /* actions            */    NULL,
    /* num_actions        */    0,
    /* resources          */    resources,
    /* num_resources      */    XtNumber(resources),
    /* xrm_class          */    NULLQUARK,
    /* compress_motion    */    TRUE,
    /* compress_exposure  */    XtExposeCompressMultiple,
    /* compress_enterleave*/    TRUE,
    /* visible_interest   */    FALSE,
    /* destroy            */    xmp_Destroy,
    /* resize             */    xmp_Resize,
    /* expose             */    xmp_Expose,
    /* set_values         */    xmp_SetValues,
    /* set_values_hook    */    NULL,
    /* set_values_almost  */    XtInheritSetValuesAlmost,
    /* get_values_hook    */    NULL,
    /* accept_focus       */    NULL,
    /* version            */    XtVersion,
    /* callback_private   */    NULL,
    /* tm_table           */    default_translations,
    /* query_geometry     */    xmp_Query_Geometry,
    /* display accel      */    XtInheritDisplayAccelerator,
    /* extension          */    NULL
  },

  { /* primitive_class fields       */
    /* border_highlight   */    (XtWidgetProc) _XtInherit,
    /* border_unhighlight */    (XtWidgetProc) _XtInherit,
    /* translations       */    XtInheritTranslations,
    /* arm_and_activate   */    NULL,
    /* syn resources      */    NULL,
    /* num get_resources  */    0,
    /* extension          */    NULL
   },

   { /* Pgplot class fields */
     /* widget_id_counter   */  0,
     /* active_widgets      */  {NULL},
     /* free_widgets        */  {NULL},
     /* Extension           */  NULL
   }
};

/*
 * Declare a global class pointer for use in XtCreateManagedWidget
 * calls.
 */
externaldef(xmpgplotwidgetclass) WidgetClass xmPgplotWidgetClass = (WidgetClass) &xmPgplotClassRec;

/*
 * Private functions.
 */
static void xmp_abort(XmPgplotPart *xmp, char *msg);
static XmPgplotWidget xmp_open_widget(char *name);
static XmPgplotWidget xmp_close_widget(char *name);
static void xmp_update_scroll_bars(XmPgplotWidget w);
static void xmp_update_clip(XmPgplotWidget w);
static void xmp_NewPixmap(PgxWin *pgx, unsigned width, 
				    unsigned height);
static void xmp_scroll_callback(Widget widget, 
					  XtPointer client_data, 
					  XtPointer call_data);
static void xmp_CursorHandler(Widget widget, XtPointer client_data, 
			      XEvent *event, Boolean *cont);
static int xmp_ArmCursor(XmPgplotWidget w, int mode, float xref, 
			   float yref, XtCallbackProc callback, void *client_data);
static int xmp_DisarmCursor(XmPgplotWidget w);
static int xmp_new_visual(XmPgplotWidget w);
static int xmp_WorldToPixel(XmPgplotWidget w, float wx, float wy,
			    int *px, int *py);
static int xmp_PixelToWorld(XmPgplotWidget w, int px, int py,
			    float *wx, float *wy);

/* Enumerate the PGPLOT class widget lists */

#define XMP_ACTIVE_WIDGETS 1
#define XMP_FREE_WIDGETS 2

static XmPgplotList *xmp_WidgetList(int type);

static XmPgplotWidget xmp_FindWidgetByName(char *name, int type, 
						     XmPgplotWidget *prev);
static XmPgplotWidget xmp_FindWidgetByID(int xmslct_id, int type, 
						   XmPgplotWidget *prev);

static XmPgplotWidget xmp_RemoveWidget(char *name, int type);
static XmPgplotWidget xmp_PrependWidget(XmPgplotWidget w, int type);
static XmPgplotWidget xmp_CurrentWidget(char *context);

/*.......................................................................
 * This is called once to initialize the PGPLOT part of the widget class
 * structure when the first widget instance of this type is created.
 *
 * Input:
 *  w   WidgetClass   The class record to be initialized.
 */
static void xmp_ClassPartInit(WidgetClass w)
{
  XmPgplotWidgetClass class = (XmPgplotWidgetClass) w;
  XmPgplotClassPart *pgplot = &class->pgplot_class;
  pgplot->widget_id_counter = 0;
  pgplot->active_widgets.head = NULL;
  pgplot->free_widgets.head = NULL;
  pgplot->extension = NULL;
  return;
}

/*.......................................................................
 * This is called to check resource derived defaults and initialize
 * a PGPLOT widget instance.
 *
 * Input:
 *  request    Widget   The instance widget type with the resource values
 *                      requested by the client.
 *  new_w      Widget   The resulting instance widget with allowed
 *                      resource values.
 *  args      ArgList   The widget-creation argument list used to override
 *                      default values.
 *  num_args Cardinal   The number of arguments in args.
 */
static void xmp_Initialize(Widget request, Widget new_w, ArgList args,
			     Cardinal *num_args)
{
  XmPgplotWidget w = (XmPgplotWidget) new_w;
  XmPgplotPart *xmp = &w->pgplot;
/*
 * Initialize the private attributes.
 */
  xmp->next = NULL;
  xmp->xmslct_id = xmPgplotClassRec.pgplot_class.widget_id_counter++;
  xmp->pgslct_id = 0;  /* This is filled in by the first select-plot opcode */
  xmp->device = NULL;
  xmp->app = XtWidgetToApplicationContext(new_w);
  xmp->scroll.is_scrolled = 0;
  xmp->scroll.w_hbar = NULL;
  xmp->scroll.w_vbar = NULL;
  xmp->scroll.width = 0;
  xmp->scroll.height = 0;
  xmp->scroll.x = 0;
  xmp->scroll.y = 0;
  xmp->input.mask = 0;
  xmp->input.callback = 0;
  xmp->input.client_data = NULL;
  xmp->bg.red = xmp->bg.green = xmp->bg.blue = 0;
  xmp->fg.red = xmp->fg.green = xmp->fg.blue = 65535;
  xmp->pgx = NULL;
/*
 * Record the RGB values of the default background and foreground
 * colors.
 */
  XtVaGetValues(new_w,
	XtVaTypedArg, XmNbackground, XmRColor, &xmp->bg, sizeof(xmp->bg),
	XtVaTypedArg, XmNforeground, XmRColor, &xmp->fg, sizeof(xmp->fg),
	NULL);
/*
 * Allocate the PGPLOT-window context descriptor.
 */
  xmp->pgx = new_PgxWin(XtDisplay(new_w), 
			XScreenNumberOfScreen(XtScreen(new_w)), (void *) w,
			XtName(new_w), 0, xmp_NewPixmap);
  if(!xmp->pgx)
    xmp_abort(xmp, NULL);
/*
 * Compose a sample PGPLOT device-specification for use in opening this
 * widget to PGPLOT.
 */
  xmp->device = (char *) malloc(sizeof(char) *
			(strlen(xmp->pgx->name) + 1 + strlen(XMP_DEVICE) + 1));
  if(!xmp->device)
    xmp_abort(xmp, "Insufficient memory.\n");
  sprintf(xmp->device, "%s/%s", xmp->pgx->name, XMP_DEVICE);
/*
 * Check the widget size.
 */
  if(w->core.width==0)
    w->core.width = XMP_DEF_WIDTH;
  if(w->core.height==0)
    w->core.height = XMP_DEF_HEIGHT;
  if(w->core.width < XMP_MIN_WIDTH)
    w->core.width = XMP_MIN_WIDTH;
  if(w->core.height < XMP_MIN_HEIGHT)
    w->core.height = XMP_MIN_HEIGHT;
/*
 * Check color resources.
 */
  if(xmp->min_colors < XMP_MIN_COLORS)
    xmp->min_colors = XMP_MIN_COLORS;
  if(xmp->max_colors > XMP_MAX_COLORS)
    xmp->max_colors = XMP_MAX_COLORS;
/*
 * See if the parent widget is a scrolled window.
 */
  if(XtIsSubclass(XtParent(new_w), xmScrolledWindowWidgetClass)) {
    Widget w_scroll = XtParent(new_w);
    XmpScroll *scroll = &xmp->scroll;
    scroll->is_scrolled = 1;
    scroll->width = w->core.width;
    scroll->height = w->core.height;
    scroll->w_hbar = XtVaCreateManagedWidget("hbar", xmScrollBarWidgetClass,
					  w_scroll,
					  XmNorientation, XmHORIZONTAL,
					  XmNminimum, 0,
					  XmNmaximum, scroll->width,
					  XmNsliderSize, scroll->width,
					  XmNpageIncrement, scroll->width,
					  XmNincrement, 1,
					  NULL);
    XtAddCallback(scroll->w_hbar, XmNvalueChangedCallback, xmp_scroll_callback,
		  w);
    XtAddCallback(scroll->w_hbar, XmNdragCallback, xmp_scroll_callback, w);
    scroll->w_vbar = XtVaCreateManagedWidget("vbar", xmScrollBarWidgetClass,
					  w_scroll,
					  XmNorientation, XmVERTICAL,
					  XmNminimum, 0,
					  XmNmaximum, scroll->height,
					  XmNsliderSize, scroll->height,
					  XmNpageIncrement, scroll->height,
					  XmNincrement, 1,
					  NULL);
    XtAddCallback(scroll->w_vbar, XmNvalueChangedCallback, xmp_scroll_callback,
		  w);
    XtAddCallback(scroll->w_vbar, XmNdragCallback, xmp_scroll_callback, w);
    XmScrolledWindowSetAreas(w_scroll, scroll->w_hbar, scroll->w_vbar, new_w);
  };
  return;
}

/*.......................................................................
 * Create and clear the window of a PGPLOT widget instance.
 *
 * Input:
 *  widget             Widget   The widget to be realized.
 *  mask          XtValueMask * The bit-mask that specifies which
 *                              attributes have been set in 'attr'.
 *  attr XSetWindowAttributes * The container of the pre-set window
 *                              attributes specified in 'mask'.
 */
static void xmp_Realize(Widget widget, XtValueMask *mask,
		    XSetWindowAttributes *attr)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
  XmPgplotPart *xmp = &w->pgplot;
  PgxWin *pgx = xmp->pgx;
/*
 * Get a visual and colormap for the window if necessary.
 */
  if(!pgx->color) {
    if(!xmp->share && xmp_new_visual(w))  /* If requested try private first */
      xmp->share = 1;
    if(xmp->share && xmp_new_visual(w)) { /* Try for shared colors */
      fprintf(stderr,
      "%s: There are insufficient colors, so black and white will be used.\n",
       XMP_IDENT);
      if(!pgx_bw_visual(pgx))
	xmp_abort(xmp, "No colors.\n");
    };
  };
/*
 * Keep the resource-value record of the chosen visual and colormap
 * in sync with the values in pgx->color.
 */
  xmp->visual = pgx->color->vi->visual;
  w->core.colormap = pgx->color->cmap;
/*
 * Reset the background and foreground colors to match the current
 * X resource values.
 */
  pgx_set_background(pgx, &xmp->bg);
  pgx_set_foreground(pgx, &xmp->fg);
/*
 * The window attributes passed to this function are based on
 * attributes stored in the core record of the widget instance.
 * By default these attributes (set by X resources) cause the
 * new window to inherit colormap, depth, etc.. from the parent
 * window. Since the call to pgx_new_visual() may have invalidated this
 * we need to install new values. This involves both updating the
 * window attributes to be passed to XtCreateWindow() and modifying
 * the X resources of the core part of the instance structure.
 *
 * It is important to remember that the border and background pixmaps
 * need to be changed to avoid mismatches between their depths and the
 * depth of our chosen visual. To avoid such conflicts we will make sure
 * that pixmaps are not used and substitute solid colors.
 */
/*
 * Add and remove appropriate window attributes.
 */
  *mask |= CWDontPropagate | CWBackPixel | CWBorderPixel | CWColormap;
  *mask &= ~(CWBackPixmap | CWBorderPixmap);
  attr->do_not_propagate_mask = ButtonPressMask | ButtonReleaseMask |
    KeyPressMask | KeyReleaseMask;
  attr->background_pixel = xmp->pgx->color->pixel[0];
  attr->border_pixel = xmp->pgx->color->pixel[0];
  attr->colormap = w->core.colormap;
/*
 * Record the new attributes in the core part of the instance record.
 */
  XtVaSetValues(widget,
		XmNbackground, xmp->pgx->color->pixel[0],
		XmNborderColor, xmp->pgx->color->pixel[0],
		XmNdepth, xmp->pgx->color->vi->depth,
		NULL);
/*
 * Create the window.
 */
  XtCreateWindow(widget, InputOutput, xmp->visual, *mask, attr);
  pgx->window = XtWindow(widget);
/*
 * Create and initialize a graphical context descriptor. This is where
 * Line widths, line styles, fill styles, plot color etc.. are
 * recorded.
 */
  {
    XGCValues gcv;
    gcv.graphics_exposures = False;
    pgx_start_error_watch(pgx);
    pgx->expose_gc = XCreateGC(pgx->display, pgx->window, (unsigned long)
			       (GCGraphicsExposures), &gcv);
    if(pgx_end_error_watch(pgx) || pgx->expose_gc==NULL)
      xmp_abort(xmp, "Failed to allocate a graphical context.\n");
  };
/*
 * If the widget has scroll-bars make sure that they agree with the
 * window.
 */
  xmp_update_scroll_bars(w);
  xmp_update_clip(w);
/*
 * Prepend the new widget to the list of unassigned widgets to be
 * used by pgbeg().
 */
  xmp_PrependWidget(w, XMP_FREE_WIDGETS);
  return;
}

/*.......................................................................
 * PGPLOT Widget destructor function.
 *
 * Input:
 *  widget    Widget   The widget whose resources are to be released.
 */
static void xmp_Destroy(Widget widget)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
  XmPgplotPart *xmp = &w->pgplot;
  PgxWin *pgx = xmp->pgx;
/*
 * Remove the device from the appropriate list of PGPLOT Motif widgets.
 */
  xmp_RemoveWidget(pgx->name, pgx->state ? XMP_ACTIVE_WIDGETS : XMP_FREE_WIDGETS);
/*
 * Delete the window context descriptor.
 */
  xmp->pgx = del_PgxWin(pgx);
  return;
}

/*.......................................................................
 * PGPLOT Widget resize function.
 *
 * Input:
 *  widget    Widget   The widget that is being resized.
 */
static void xmp_Resize(Widget widget)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
  xmp_update_clip(w);
  if(XtIsRealized(widget)) {
    w->pgplot.scroll.x = 0;
    w->pgplot.scroll.y = 0;
    xmp_update_scroll_bars(w);
    XtCallCallbackList(widget, w->pgplot.resize_callback, (XtPointer *)0);
  };
}

/*.......................................................................
 * The expose-event handler for PGPLOT widgets.
 *
 * Input:
 *  widget   Widget   The widget that is to be re-drawn.
 *  event    XEvent   The expose event that invoked the callback.
 *  region   Region   The area to be re-drawn.
 */
static void xmp_Expose(Widget widget, XEvent *event, Region region)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
  XmPgplotPart *xmp = &w->pgplot;
  XmPgplotWidgetClass class = (XmPgplotWidgetClass) XtClass(widget);
  PgxWin *pgx = xmp->pgx;
/*
 * Re-draw highlight border.
 */
  if(w->primitive.highlighted) {
    class->primitive_class.border_highlight(widget);
  } else {
    class->primitive_class.border_unhighlight(widget);
  };
  pgx_expose(pgx, event);
  return;
}

/*.......................................................................
 * This function is called whenever one or more resource values are
 * changed, to give the widget a chance to re-configure itself to
 * reflect the new values.
 *
 * Input:
 *  old_widget Widget   A copy of the widget before the change was made.
 *  req_widget Widget   The same as new_w but with the resources evaluated
 *                      by the superclasses.
 *  new_widget Widget   The widget with the new values in place. This
 *                      is also the output widget so changes made to
 *                      this widget will be in the final widget.
 *  args      ArgList   The resource argument list responsible for the
 *                      changes.
 *  num_args Cardinal * The number of arguments in args.
 * Output:
 *  return    Boolean   Return True if the widget needs to be re-displayed,
 *                      or False if not.
 */
static Boolean xmp_SetValues(Widget old_widget, Widget req_widget,
			     Widget new_widget,
			     ArgList args, Cardinal *num_args)
{
  XmPgplotWidget old_w = (XmPgplotWidget) old_widget;
  XmPgplotWidget new_w = (XmPgplotWidget) new_widget;
  XmPgplotPart *old_xmp = &old_w->pgplot;
  XmPgplotPart *new_xmp = &new_w->pgplot;
  Bool redisplay_needed = False;
/*
 * Changes to color resources won't be seen once the widget is
 * realized. Warn the application writer.
 */
  if(new_xmp->min_colors != old_xmp->min_colors ||
     new_xmp->max_colors != old_xmp->max_colors ||
     new_xmp->share != old_xmp->share ||
     new_w->core.colormap != old_w->core.colormap ||
     new_xmp->visual != old_xmp->visual) {
    if(XtIsRealized(new_widget))
      XtWarning("XtSetValues (XmPgplot): Too late to change color settings.\n");
    new_xmp->min_colors = old_xmp->min_colors;
    new_xmp->max_colors = old_xmp->max_colors;
    new_xmp->share = old_xmp->share;
    new_w->core.colormap = old_w->core.colormap;
    new_xmp->visual = old_xmp->visual;
  };
/*
 * If the highlight border-thickness changed update the window
 * clip region to exclude the border from future pgxwin graphics.
 */
  if(new_w->primitive.highlight_thickness !=
     old_w->primitive.highlight_thickness) {
    xmp_update_clip(new_w);
    redisplay_needed = True;
  };
/*
 * If the background or foreground colors changed, convert them to
 * RGB values and instantiate the new definitions. Note that keeping
 * and using RGB values rather than the pixel value is important
 * because we may not yet have created the window or its final colormap,
 * in which case the pixel will correspond to the wrong colormap. The
 * RGB values are used hereafter by xmp_open_widget().
 */
  if(new_w->core.background_pixel != old_w->core.background_pixel) {
    XColor *bg = &new_xmp->bg;
    XtVaGetValues(new_widget,
		  XtVaTypedArg, XmNbackground, XmRColor, bg, sizeof(*bg),
		  NULL);
    pgx_set_background(new_xmp->pgx, bg);
  };
  if(new_w->primitive.foreground != old_w->primitive.foreground) {
    XColor *fg = &new_xmp->fg;
    XtVaGetValues(new_widget,
		  XtVaTypedArg, XmNforeground, XmRColor, fg, sizeof(*fg),
		  NULL);
    pgx_set_foreground(new_xmp->pgx, fg);
  };
/*
 * Change the margins?
 */
  if(new_xmp->pad_x != old_xmp->pad_x || new_xmp->pad_y != old_xmp->pad_y)
    pgx_set_margin(new_xmp->pgx, new_xmp->pad_x, new_xmp->pad_y);
  return redisplay_needed;
}

/*.......................................................................
 * Whenever the parent widget wishes to resize a PGPLOT widget, this
 * function is called to give the widget a chance to veto or otherwise
 * modify the requested new geometry.
 *
 * Input:
 *  widget             Widget   The widget wrt which the geometry change
 *                              pertains.
 *  request  XtWidgetGeometry * The requested widget geometry.
 * Input/Output:
 *  reply    XtWidgetGeometry * The returned allowed widget geometry.
 * Output:
 *  return   XtGeometryResult   Return status from:
 *                               XtGeometryYes 
 *                                 The requested geometry is acceptible.
 *                               XtGeometryAlmost
 *                                 An acceptible revision of the requested
 *                                 geometry has been encoded in *reply.
 *                               XtGeometryNo
 *                                 The requested geometry is identical
 *                                 to the existing geometry.
 */
static XtGeometryResult xmp_Query_Geometry(Widget widget,
					   XtWidgetGeometry *request,
					   XtWidgetGeometry *reply)
{
/*
 * Tell the parent which attributes we are interested in
 * and set them to their current values until otherwise
 * requested.
 */
  reply->request_mode = CWWidth | CWHeight;
  reply->width = widget->core.width;
  reply->height = widget->core.height;
/*
 * Check the requested width.
 */
  if(request->request_mode & CWWidth) {
    reply->width = request->width < XMP_MIN_WIDTH ? XMP_MIN_WIDTH :
      request->width;
  };
/*
 * Check the requested height.
 */
  if(request->request_mode & CWHeight) {
    reply->height = request->height < XMP_MIN_HEIGHT ? XMP_MIN_HEIGHT :
      request->height;
  };
/*
 * Determine the appropriate reply.
 */
  if((request->request_mode & (CWWidth | CWHeight)) == (CWWidth | CWHeight) &&
     request->width == reply->width &&
     request->height == reply->height)
    return XtGeometryYes;
  else if(reply->width == widget->core.width &&
	  reply->height == widget->core.height)
    return XtGeometryNo;
  else
    return XtGeometryAlmost;
}

/*.......................................................................
 * This function is called to abort the application after a fatal
 * error occurs. It doesn't return.
 *
 * Input:
 *  xmp   XmPgplotPart *  The PGPLOT part of the widget instance structure.
 *  msg           char *  An error message to abort with, or NULL.
 */
static void xmp_abort(XmPgplotPart *xmp, char *msg)
{
  XtAppError(xmp->app, msg ? msg : "Aborting");
}

/*.......................................................................
 * Find an inactive PGPLOT widget of a given name, open it to PGPLOT,
 * and move it to the head of the active list of widgets.
 *
 * Input:
 *  name         char *  The name of the widget to be opened.
 * Output:
 *  w  XmPgplotWidget    The selected widget, or NULL on error.
 */
static XmPgplotWidget xmp_open_widget(char *name)
{
  XmPgplotWidget w; /* The PGPLOT widget to be opened */
/*
 * Remove the named widget from the free-widget list.
 */
  w = xmp_RemoveWidget(name, XMP_FREE_WIDGETS);
  if(!w) {
    fprintf(stderr, "%s: Request to open non-existent widget (%s).\n",
	    XMP_IDENT, name ? name : "(null)");
    return NULL;
  };
/*
 * Pre-pend the widget to the active list.
 */
  xmp_PrependWidget(w, XMP_ACTIVE_WIDGETS);
/*
 * Open the connection to the PgxWin library.
 */
  pgx_open(w->pgplot.pgx);
  if(!w->pgplot.pgx->state)
    xmp_close_widget(name);
/*
 * Reset the background and foreground colors to match the current
 * X resource values.
 */
  pgx_set_background(w->pgplot.pgx, &w->pgplot.bg);
  pgx_set_foreground(w->pgplot.pgx, &w->pgplot.fg);
/*
 * Allow for margins.
 */
  pgx_set_margin(w->pgplot.pgx, w->pgplot.pad_x, w->pgplot.pad_y);
/*
 * Reset its scroll-bars.
 */
  xmp_update_scroll_bars(w);
  return w;
}

/*.......................................................................
 * Find an active PGPLOT widget of a given name, close it to PGPLOT and
 * move it to the head of the inactive list of widgets.
 *
 * Input:
 *  name             char *  The name of the widget.
 * Output:
 *  return XmPgplotWidget    The selected widget, or NULL if not found.
 */
static XmPgplotWidget xmp_close_widget(char *name)
{
  XmPgplotWidget w;
/*
 * Remove the widget from the active list.
 */
  w = xmp_RemoveWidget(name, XMP_ACTIVE_WIDGETS);
  if(!w) {
    fprintf(stderr, "%s: Request to close non-existent widget (%s).\n",
	    XMP_IDENT, name ? name : "(null)");
    return NULL;
  };
/*
 * Remove cursor handler.
 */
  xmp_DisarmCursor(w);
/*
 * Close the connection to the PgxWin library.
 */
  pgx_close(w->pgplot.pgx);
/*
 * Invalidate the pgslct() id. The next time that the widget is opened
 * to PGPLOT a different value will likely be used.
 */
  w->pgplot.pgslct_id = 0;
/*
 * Prepend the widget to the free list.
 */
  xmp_PrependWidget(w, XMP_FREE_WIDGETS);
  return w;
}

/*.......................................................................
 * Lookup a widget by name from a given list of widgets.
 *
 * Input:
 *  name             char * The name of the widget.
 *  type              int   The enumerated name of the list to search,
 *                          from:
 *                            XMP_ACTIVE_WIDGETS
 *                            XMP_FREE_WIDGETS
 * Output:
 *  prev   XmPgplotWidget * *prev will either be NULL if the widget
 *                          was at the head of the list, or be the
 *                          widget in the list that immediately precedes
 *                          the specified widget.
 *  return XmPgplotWidget   The located widget, or NULL if not found.
 */
static XmPgplotWidget xmp_FindWidgetByName(char *name, int type,
					   XmPgplotWidget *prev)
{
  XmPgplotList *widget_list; /* The list to be searched */
  widget_list = xmp_WidgetList(type);
  if(widget_list && name) {
    XmPgplotWidget last = NULL;
    XmPgplotWidget node = widget_list->head;
    for( ; node; last = node, node = node->pgplot.next) {
      if(strcmp(node->pgplot.pgx->name, name)==0) {
	if(prev)
	  *prev = last;
	return node;
      };
    };
  };
/*
 * Widget not found.
 */
  if(prev)
    *prev = NULL;
  return NULL;
}

/*.......................................................................
 * Lookup a widget by its PGPLOT id from a given list of widgets.
 *
 * Input:
 *  xmslct_id         int   The number used by PGPLOT to select the
 *                          device.
 *  type              int   The enumerated name of the list to search,
 *                          from:
 *                            XMP_ACTIVE_WIDGETS
 *                            XMP_FREE_WIDGETS
 * Output:
 *  prev   XmPgplotWidget * *prev will either be NULL if the widget
 *                          was at the head of the list, or be the
 *                          widget in the list that immediately precedes
 *                          the specified widget.
 *  return XmPgplotWidget   The located widget, or NULL if not found.
 */
static XmPgplotWidget xmp_FindWidgetByID(int xmslct_id, int type,
					   XmPgplotWidget *prev)
{
  XmPgplotList *widget_list; /* The list to be searched */
  widget_list = xmp_WidgetList(type);
  if(widget_list) {
    XmPgplotWidget last = NULL;
    XmPgplotWidget node = widget_list->head;
    for( ; node; last = node, node = node->pgplot.next) {
      if(xmslct_id == node->pgplot.xmslct_id) {
	if(prev)
	  *prev = last;
	return node;
      };
    };
  };
/*
 * Widget not found.
 */
  if(prev)
    *prev = NULL;
  return NULL;
}

/*.......................................................................
 * Lookup one of the PGPLOT class widget lists by its enumerated type.
 *
 * Input:
 *  type            int   The enumerated name of the list, from:
 *                          XMP_ACTIVE_WIDGETS
 *                          XMP_FREE_WIDGETS
 * Output:
 *  return XmPgplotList * The widget list, or NULL if not recognized.
 */
static XmPgplotList *xmp_WidgetList(int type)
{
  switch(type) {
  case XMP_ACTIVE_WIDGETS:
    return &xmPgplotClassRec.pgplot_class.active_widgets;
  case XMP_FREE_WIDGETS:
    return &xmPgplotClassRec.pgplot_class.free_widgets;
  default:
    fprintf(stderr, "xmp_WidgetList: No such list.\n");
  };
  return NULL;
}

/*.......................................................................
 * Remove a given widget from one of the PGPLOT class widget lists.
 *
 * Input:
 *  name             char * The name of the widget to be removed from
 *                          the list.
 *  type              int   The enumerated name of the list from which to
 *                          remove the widget, from:
 *                            XMP_ACTIVE_WIDGETS
 *                            XMP_FREE_WIDGETS
 * Output:
 *  return XmPgplotWidget   The removed widget, or NULL if not found.
 */
static XmPgplotWidget xmp_RemoveWidget(char *name, int type)
{
  XmPgplotList *widget_list; /* The list to remove the widget from */
  XmPgplotWidget w = NULL;   /* The widget being removed */
  XmPgplotWidget prev;       /* The widget preceding w in the list */
/*
 * Get the widget list.
 */
  widget_list = xmp_WidgetList(type);
  if(widget_list) {
    w = xmp_FindWidgetByName(name, type, &prev);
    if(w) {
      if(prev) {
	prev->pgplot.next = w->pgplot.next;
      } else {
	widget_list->head = w->pgplot.next;
      };
      w->pgplot.next = NULL;
    };
  };
  return w;
}

/*.......................................................................
 * Prepend a PGPLOT widget to a given PGPLOT class widget list.
 *
 * Input:
 *  w      XmPgplotWidget   The widget to add to the list.
 *  type              int   The enumerated name of the list to add to,
 *                          from:
 *                            XMP_ACTIVE_WIDGETS
 *                            XMP_FREE_WIDGETS
 * Output:
 *  return XmPgplotWidget   The added widget (the same as w), or NULL
 *                          on error.
 */
static XmPgplotWidget xmp_PrependWidget(XmPgplotWidget w, int type)
{
  XmPgplotList *widget_list;  /* The list to prepend the widget to */
/*
 * Get the widget list.
 */
  widget_list = xmp_WidgetList(type);
  if(widget_list) {
    w->pgplot.next = widget_list->head;
    widget_list->head = w;
  };
  return w;
}

/*.......................................................................
 * Return the currently selected PGPLOT device.
 *
 * Input:
 *  context           char * If no XmPgplot device is currently selected
 *                           and context!=NULL then, an error message of
 *                           the form printf("%s: ...\n", context) will
 *                           be written to stderr reporting that no
 *                           device is open.
 * Output:
 *  return  XmPgplotWidget   The currently selected PGPLOT device, or
 *                           NULL if no device is currently selected.
 */
static XmPgplotWidget xmp_CurrentWidget(char *context)
{
  XmPgplotWidget w = xmPgplotClassRec.pgplot_class.active_widgets.head;
  if(w) {
/*
 * We need a window.
 */
    if(!XtIsRealized((Widget)w)) {
      if(context) {
	fprintf(stderr, "%s: PGPLOT widget \"%s\" is not realized.\n",
		context, w->pgplot.pgx->name);
      };
      w = NULL;
    };
  } else {
    if(context)
      fprintf(stderr, "%s: No /xm device is currently selected.\n", context);
  };
  return w;
}

/*.......................................................................
 * This is the only external entry point to the /xm device driver.
 * It is called by PGPLOT to open, perform operations on, return
 * information about and close /xmotif windows.
 *
 * Input:
 *  ifunc   int *  The PGPLOT operation code to be executed.
 * Input/output:
 *  rbuf  float *  A general buffer for input/output of float values.
 *  nbuf    int *  Where relevant this is used to return the number of
 *                 elements in rbuf[]. Also used on input to specify
 *                 number of pixels in the line-of-pixels primitive.
 *  chr    char *  A general buffer for string I/O.
 *  lchr    int *  Where relevant this is used to send and return the
 *                 number of significant characters in chr.
 * Input:
 *  len     int    Added to the call line by the FORTRAN compiler.
 *                 This contains the declared size of chr[].  
 */
#ifdef VMS
void xmdriv(ifunc, rbuf, nbuf, chrdsc, lchr)
     int *ifunc;
     float rbuf[];
     int *nbuf;
     struct dsc$descriptor_s *chrdsc; /* VMS FORTRAN string descriptor */
     int *lchr;
{
  int len = chrdsc->dsc$w_length;
  char *chr = chrdsc->dsc$a_pointer;
#else
void XMDRIV(ifunc, rbuf, nbuf, chr, lchr, len)
 int   *ifunc, *nbuf, *lchr;
 int   len;
 float rbuf[];
 char  *chr;
{
#endif
/*
 * Get the active widget if there is one.
 */
  XmPgplotWidget w = xmp_CurrentWidget(NULL);
  XmPgplotPart *xmp = w ? &w->pgplot : NULL;
  PgxWin *pgx = xmp ? xmp->pgx : NULL;
  int i;
/*
 * Flush buffered opcodes.
 */
  pgx_pre_opcode(pgx, *ifunc);
/*
 * Branch on the specified PGPLOT opcode.
 */
  switch(*ifunc) {

/*--- IFUNC=1, Return device name ---------------------------------------*/

  case 1:
    {
      char *dev_name = "XMOTIF (X window widget_name/xm)";
      strncpy(chr, dev_name, len);
      *lchr = strlen(dev_name);
      for(i = *lchr; i < len; i++)
	chr[i] = ' ';
    };
    break;

/*--- IFUNC=2, Return physical min and max for plot device, and range
               of color indices -----------------------------------------*/
  case 2:
    rbuf[0] = 0.0;
    rbuf[1] = -1.0;  /* Report no effective max plot width */
    rbuf[2] = 0.0;
    rbuf[3] = -1.0;  /* Report no effective max plot height */
    rbuf[4] = 0.0;
    rbuf[5] = (pgx && !pgx->bad_device) ? pgx->color->ncol-1 : 1;
    *nbuf = 6;
    break;

/*--- IFUNC=3, Return device resolution ---------------------------------*/

  case 3:
    pgx_get_resolution(pgx, &rbuf[0], &rbuf[1]);
    rbuf[2] = 1.0;		/* Device coordinates per pixel */
    *nbuf = 3;
    break;

/*--- IFUNC=4, Return misc device info ----------------------------------*/

  case 4:
    chr[0] = 'I'; /* Interactive device */
    chr[1] = 'X'; /* Cursor is available and opcode 27 is desired */
    chr[2] = 'N'; /* No dashed lines */
    chr[3] = 'A'; /* Area fill available */
    chr[4] = 'T'; /* Thick lines */
    chr[5] = 'R'; /* Rectangle fill available */
    chr[6] = 'P'; /* Line of pixels available */
    chr[7] = 'N'; /* Don't prompt on pgend */
    chr[8] = 'Y'; /* Can return color representation */
    chr[9] = 'N'; /* Not used */
    chr[10]= 'S'; /* Area-scroll available */
    *lchr = 11;
    break;

/*--- IFUNC=5, Return default file name ---------------------------------*/

  case 5:
    chr[0] = '\0';  /* Default name is "" */
    *lchr = 0;
    break;

/*--- IFUNC=6, Return default physical size of plot ---------------------*/

  case 6:
    pgx_def_size(pgx, XMP_DEF_WIDTH, XMP_DEF_HEIGHT, rbuf, nbuf);
    break;

/*--- IFUNC=7, Return misc defaults -------------------------------------*/

  case 7:
    rbuf[0] = 1.0;
    *nbuf = 1;
    break;

/*--- IFUNC=8, Select plot ----------------------------------------------*/

  case 8:
    {
      XmPgplotWidget new_w = xmp_FindWidgetByID((int)(rbuf[1]+0.5),
						XMP_ACTIVE_WIDGETS, NULL);
      if(new_w) {
	new_w->pgplot.pgslct_id = (int) (rbuf[0]+0.5);
	xmp_RemoveWidget(new_w->pgplot.pgx->name, XMP_ACTIVE_WIDGETS);
	xmp_PrependWidget(new_w, XMP_ACTIVE_WIDGETS);
      } else {
	fprintf(stderr, "%s: [Select plot] No such open device.\n", XMP_IDENT);
      };
    };
    break;

/*--- IFUNC=9, Open workstation -----------------------------------------*/

  case 9:
/*
 * Assign the returned device unit number and success indicator.
 * Assume failure to open until the workstation is open.
 */
    rbuf[0] = rbuf[1] = 0.0;
    *nbuf = 2;
/*
 * Prepare the display name.
 */
    if(*lchr >= len) {
      fprintf(stderr, "%s: Widget name too long.\n", XMP_IDENT);
      return;
    } else {
      chr[*lchr] = '\0';
    };
/*
 * Get the requested widget from the free widget list.
 */
    w = xmp_open_widget(chr);
    if(!w)
      return;
    rbuf[0] = w->pgplot.xmslct_id; /* The number used to select this device */
    rbuf[1] = 1.0;
    *nbuf = 2;
    break;

/*--- IFUNC=10, Close workstation ---------------------------------------*/

  case 10:
/*
 * Remove the device from the list of open devices.
 */
    if(pgx)
      xmp_close_widget(pgx->name);
    break;

/*--- IFUNC=11, Begin picture -------------------------------------------*/

  case 11:
    pgx_begin_picture(pgx, rbuf);
    break;

/*--- IFUNC=12, Draw line -----------------------------------------------*/

  case 12:
    pgx_draw_line(pgx, rbuf);
    break;

/*--- IFUNC=13, Draw dot ------------------------------------------------*/

  case 13:
    pgx_draw_dot(pgx, rbuf);
    break;

/*--- IFUNC=14, End picture ---------------------------------------------*/

  case 14:
    break;

/*--- IFUNC=15, Select color index --------------------------------------*/

  case 15:
    pgx_set_ci(pgx, (int) (rbuf[0] + 0.5));
    break;

/*--- IFUNC=16, Flush buffer. -------------------------------------------*/

  case 16:
    pgx_flush(pgx);
    break;

/*--- IFUNC=17, Read cursor. --------------------------------------------*/

  case 17:
    if(w) {
      xmp_DisarmCursor(w);
      if(!XtIsManaged((Widget)w))
	XtManageChild((Widget)w);
    };
    pgx_read_cursor(pgx, rbuf, chr, nbuf, lchr);
    break;

/*--- IFUNC=18, Erase alpha screen. -------------------------------------*/
  /* (Not implemented: no alpha screen) */
  case 18:
    break;

/*--- IFUNC=19, Set line style. -----------------------------------------*/
  /* (Not implemented: should not be called) */
  case 19:
    break;

/*--- IFUNC=20, Polygon fill. -------------------------------------------*/

  case 20:
    pgx_poly_fill(pgx, rbuf);
    break;

/*--- IFUNC=21, Set color representation. -------------------------------*/

  case 21:
    pgx_set_rgb(pgx, (int)(rbuf[0]+0.5), rbuf[1],rbuf[2],rbuf[3]);
    break;

/*--- IFUNC=22, Set line width. -----------------------------------------*/

  case 22:
    pgx_set_lw(pgx, rbuf[0]);
    break;

/*--- IFUNC=23, Escape --------------------------------------------------*/
    /* (Not implemented: ignored) */
  case 23:
    break;

/*--- IFUNC=24, Rectangle Fill. -----------------------------------------*/

  case 24:
    pgx_rect_fill(pgx, rbuf);
    break;

/*--- IFUNC=25, ---------------------------------------------------------*/
  /* (Not implemented: ignored) */
  case 25:
    break;

/*--- IFUNC=26, Line of pixels ------------------------------------------*/

  case 26:
    pgx_pix_line(pgx, rbuf, nbuf);
    break;

/*--- IFUNC=27, World-coordinate scaling --------------------------------*/

  case 27:
    pgx_set_world(pgx, rbuf);
    break;

/*--- IFUNC=29, Query color representation ------------------------------*/
  case 29:
    pgx_get_rgb(pgx, rbuf, nbuf);
    break;

/*--- IFUNC=30, Scroll rectangle ----------------------------------------*/
  case 30:
    pgx_scroll_rect(pgx, rbuf);
    break;

/*--- IFUNC=?, ----------------------------------------------------------*/

  default:
    fprintf(stderr, "%s: Ignoring unimplemented opcode=%d.\n",
	    XMP_IDENT, *ifunc);
    *nbuf = -1;
    break;
  };
  return;
}

/*.......................................................................
 * This function is called upon by the pgxwin toolkit whenever the
 * pixmap used as backing store needs to be resized.
 *
 * Input:
 *  pgx      PgxWin *   The pgxwin toolkit context descriptor.
 *  width  unsigned     The desired new pixmap width.
 *  height unsigned     The desired new pixmap height.
 */
static void xmp_NewPixmap(PgxWin *pgx, unsigned width, unsigned height)
{
  XmPgplotWidget w = (XmPgplotWidget) pgx->context;
/*
 * Record the requested dimensions then hand the job of allocating the
 * pixmap back to the pgxwin toolkit.
 */
  w->pgplot.scroll.width = width;
  w->pgplot.scroll.height = height;
  w->pgplot.scroll.x = 0;
  w->pgplot.scroll.y = 0;
  xmp_update_scroll_bars(w);
  pgx_new_pixmap(pgx, width, height);
  return;
}

/*.......................................................................
 * Whenever the size of a pixmap and/or window of a PGPLOT winget are
 * changed, this function should be called to adjust scroll bars if the
 * parent is a scrolled window widget.
 *
 * Input:
 *  w     XmPgplotWidget   The pgplot widget instance.
 */
static void xmp_update_scroll_bars(XmPgplotWidget w)
{
  if(w->pgplot.scroll.is_scrolled) {
    XmPgplotPart *xmp = &w->pgplot;
    XmpScroll *scroll = &xmp->scroll;
/*
 * Ensure that the scroll area has a finite size.
 */
    if(scroll->width < 1)
      scroll->width = 1;
    if(scroll->height < 1)
      scroll->height = 1;
/*
 * Update the horizontal scroll-bar.
 */
    XtVaSetValues(xmp->scroll.w_hbar,
		  XmNsliderSize, w->core.width,
		  XmNpageIncrement, w->core.width,
		  XmNmaximum, scroll->width > w->core.width ?
		              scroll->width : w->core.width,
		  XmNvalue, scroll->x / scroll->width,
		  NULL);
/*
 * Update the vertical scroll-bar.
 */
    XtVaSetValues(xmp->scroll.w_vbar,
		  XmNsliderSize, w->core.height,
		  XmNpageIncrement, w->core.height,
		  XmNmaximum, scroll->height > w->core.height ?
		              scroll->height : w->core.height,
		  XmNvalue, scroll->y / scroll->height,
		  NULL);
/*
 * Tell pgplot about the current scroll and pan values.
 */
    pgx_scroll(xmp->pgx, scroll->x, scroll->y);
  };
  return;
}

/*.......................................................................
 * This function is called whenever a scrollbar of a parent scrolled
 * window widget is moved.
 */
static void xmp_scroll_callback(Widget widget, XtPointer client_data,
				XtPointer call_data)
{
  XmScrollBarCallbackStruct *bar = (XmScrollBarCallbackStruct *) call_data;
  XmPgplotWidget w = (XmPgplotWidget) client_data;
  XmPgplotPart *xmp = &w->pgplot;
  XmpScroll *scroll = &xmp->scroll;
/*
 * Determine which scroll-bar was responsible for this call.
 */
  if(widget == scroll->w_hbar) {
    scroll->x = bar->value;
  } else if(widget == scroll->w_vbar) {
    scroll->y = bar->value;
  };
/*
 * Scroll the pixmap.
 */
  pgx_scroll(xmp->pgx, xmp->scroll.x, xmp->scroll.y);
  return;
}

/*.......................................................................
 * This function provides an asynchronous alternative to pgband() and
 * pgcurs(). It creates an event handler which ensures that the X cursor
 * is augmented with selected rubber-band graphics when visible, and
 * which calls a specified user cursor-input callback when the user
 * presses a key or button over the window. As with pgband() all
 * specified and reported coordinates are world coordinates. The
 * cursor is automatically disarmed in xmdriv() if the pgband() opcode
 * is invoked. It is also disarmed when the pgplot close-workstation
 * opcode is invoked.
 *
 * Input:
 *  widget       Widget   The PGPLOT widget to connect a cursor to.
 *  mode            int   The type of cursor augmentation (see XmPgplot.h).
 *  xref,yref     float   The world-coordinate reference point for band-type
 *                        cursors.
 *  callback XtCallbackProc The callback function to call when input events
 *                        are received.
 *  client_data    void * Client-specific data to be sent to the callback
 *                        function.
 * Output:
 *  return          int   0 - OK.
 *                        1 - Error.
 */
int xmp_arm_cursor(Widget widget, int mode, float xref, float yref,
		    XtCallbackProc callback, void *client_data)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
/*
 * Check the arguments.
 */
  if(!widget) {
    fprintf(stderr, "xmp_arm_cursor: NULL widget.\n");
    return 1;
  };
/*
 * Make sure that the widget is currently open to PGPLOT.
 */
  if(w->pgplot.pgslct_id == 0) {
    fprintf(stderr, "xmp_arm_cursor: The widget is not open to PGPLOT.\n");
    return 1;
  };
/*
 * Delegate the work to an internal function.
 */
  return xmp_ArmCursor(w, mode, xref, yref, callback, client_data);
}

/*.......................................................................
 * Erase the cursor, remove input callbacks and remove the cursor
 * event handler.
 *
 * Input:
 *  widget     Widget   The PGPLOT widget to disconnect the cursor from.
 * Output:
 *  return        int   0 - OK.
 *                      1 - Error.
 */
int xmp_disarm_cursor(Widget widget)
{
  if(!widget) {
    fprintf(stderr, "xmp_disarm_cursor: NULL widget intercepted.\n");
    return 1;
  };
  return xmp_DisarmCursor((XmPgplotWidget)widget);
}

/*.......................................................................
 * This is the cursor event handler registered by xmp_arm_cursor().
 */
static void xmp_CursorHandler(Widget widget, XtPointer client_data,
			      XEvent *event, Boolean *cont)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
  XmPgplotPart *xmp = &w->pgplot;
  PgxWin *pgx = xmp->pgx;
  float rbuf[2];
  char key;
/*
 * Perform input-focus management?
 */
  if(XmIsTraversable(widget)) {
/*
 * Allow Motif Tab-group traversal by ignoring all Tab-key groups.
 */
    if(event->type == KeyPress && XLookupKeysym(&event->xkey, 0) == XK_Tab)
      return;
/*
 * If the event that we are responding to is a button press and
 * the widget doesn't currently have keyboard input focus, turn
 * keyboard focus on and discard the button press.
 */
    if(event->type == ButtonPress && !w->primitive.have_traversal &&
       _XmGetFocusPolicy(widget) == XmEXPLICIT) {
      XmProcessTraversal(widget, XmTRAVERSE_CURRENT);
      return;
    };
  };
/*
 * Handle the event.
 */
  if(pgx_cursor_event(pgx, event, rbuf, &key) && xmp->input.callback) {
    XmpCursorCallbackStruct call_data;
    pgx_dev2world(pgx, rbuf);
    call_data.x = rbuf[0];
    call_data.y = rbuf[1];
    call_data.key = key;
    (*xmp->input.callback)(widget, (XtPointer) xmp->input.client_data,
			   (XtPointer) &call_data);
  };
/*
 * Handle errors.
 */
  if(pgx->bad_device) {
    *cont = False;
    xmp_DisarmCursor(w);
  } else {
    *cont = True;
  };
  return;
}

/*.......................................................................
 * The private work-horse function of xmp_arm_cursor(). Note that
 * this function takes an XmPgplotWidget argument whereas xmp_arm_cursor()
 * takes a generic Widget argument.
 *
 * Input:
 *  w    XmPgplotWidget   The PGPLOT widget to connect a cursor to.
 *  mode            int   The type of cursor augmentation (see XmPgplot.h).
 *  xref,yref     float   The world-coordinate reference point for band-type
 *                        cursors.
 *  callback XtCallbackProc The callback function to call when input events
 *                        are received, or 0 if keyboard and button
 *                        events are to be handled externally.
 *  client_data    void * Client-specific data to be sent to the callback
 *                        function.
 * Output:
 *  return          int   0 - OK.
 *                        1 - Error.
 */
static int xmp_ArmCursor(XmPgplotWidget w, int mode, float xref, float yref,
			 XtCallbackProc callback, void *client_data)
{
  Widget widget = (Widget) w;
  XmPgplotPart *xmp = &w->pgplot;
  PgxWin *pgx = xmp->pgx;
  float rbuf[2];
/*
 * Remove any existing cursor.
 */
  xmp_DisarmCursor(w);
/*
 * Convert xref, yref from world coordinates to device coordinates.
 */
  rbuf[0] = xref;
  rbuf[1] = yref;
  pgx_world2dev(pgx, rbuf);
/*
 * Raise the cursor.
 */
  if(pgx_set_cursor(pgx, -1, mode, 0, rbuf, rbuf))
    return 1;
/*
 * If the pointer is currently in the window, record its position
 * and draw the cursor.
 */
  if(pgx_locate_cursor(pgx))
    pgx_draw_cursor(pgx);
/*
 * Assemble the cursor-hander event-mask.
 */
  xmp->input.mask = EnterWindowMask | LeaveWindowMask | PointerMotionMask;
/*
 * Only select for keyboard and button input if a callback was
 * provided.
 */
  if(callback)
    xmp->input.mask |= KeyPressMask | ButtonPressMask;
/*
 * Record the callback and its data.
 */
  xmp->input.callback = callback;
  xmp->input.client_data = client_data;
/*
 * Register an event handler to handle asychronous cursor input.
 */
  XtAddEventHandler(widget, xmp->input.mask, False, xmp_CursorHandler,
		    (XtPointer) 0);
/*
 * Make sure that the widget is visible.
 */
  if(!XtIsManaged(widget))
    XtManageChild(widget);
  return 0;
}

/*.......................................................................
 * The private work-horse function of xmp_disarm_cursor(). Note that
 * this function takes an XmPgplotWidget argument whereas
 * xmp_disarm_cursor() takes a generic Widget argument.
 *
 *  w  XmPgplotWidget   The widget to disconnect the cursor from.
 * Output:
 *  return        int   0 - OK.
 *                      1 - Error.
 */
static int xmp_DisarmCursor(XmPgplotWidget w)
{
  if(w) {
    XmPgplotPart *xmp = &w->pgplot;
    PgxWin *pgx = xmp->pgx;
/*
 * Do nothing if the cursor is inactive.
 */
    if(xmp->input.mask == NoEventMask)
      return 0;
/*
 * Remove the current event handler.
 */
    XtRemoveEventHandler((Widget) w, xmp->input.mask, False,
			 xmp_CursorHandler, (XtPointer) 0);
/*
 * Remove the callback function and its data.
 */
    xmp->input.callback = 0;
    xmp->input.client_data = NULL;
/*
 * Erase the cursor.
 */
    if(pgx_erase_cursor(pgx) ||
       pgx_set_cursor(pgx, 0, PGX_NORM_CURSOR, 0, NULL, NULL))
      return 1;
  };
  return 0;
}

/*.......................................................................
 * Get the visual and colormap for a new window as specified by X
 * resource values.
 *
 * Input:
 *  w    XmPgplotWidget   The PGPLOT widget.
 * Output:
 *  return          int   0 - OK.
 *                        1 - Error.
 */
static int xmp_new_visual(XmPgplotWidget w)
{
  XmPgplotPart *xmp = &w->pgplot;
  PgxWin *pgx = xmp->pgx;
/*
 * Allocate colors from parent visual and colormap?
 */
  if(xmp->visual == CopyFromParent || w->core.colormap == CopyFromParent) {
/*
 * Find the first parent widget that has a window.
 */
    Widget parent = (Widget) w;
    do {
      parent = XtParent(parent);
    } while(parent && XtWindow(parent)==None);
    if(!parent) {
      fprintf(stderr, "xmp_new_visual: No parent window found.\n");
      return 1;
    };
/*
 * Locate the visual and colormap of the parent and allocate colors from them.
 */
    if(!pgx_window_visual(pgx, XtWindow(parent), xmp->min_colors,
			  xmp->max_colors, xmp->share))
      return 1;
  }
/*
 * Allocate colors from a specified colormap and visual.
 */
  else {
    if(!pgx_adopt_visual(pgx, XVisualIDFromVisual(xmp->visual),
			 w->core.colormap, xmp->min_colors, xmp->max_colors,
			 xmp->share))
      return 1;
  };
/*
 * Record what kind of colors were actually allocated.
 */
  xmp->share = xmp->pgx->color->readonly;
  return 0;
}

/*.......................................................................
 * Return an unambiguous PGPLOT device-specification that can be used
 * as the FILE argument of cpgbeg() to open a given PGPLOT widget.
 *
 * Input:
 *  widget  Widget   The PGPLOT widget to return a device string for.
 * Output:
 *  return    char * The PGPLOT device-specication. Note that the returned
 *                   string is owned by the widget driver and must not be
 *                   free()d or overwritten.
 */
char *xmp_device_name(Widget widget)
{
  if(!widget || XtClass(widget) != xmPgplotWidgetClass) {
    fprintf(stderr, "xmp_device_name: Not a Motif PGPLOT widget.\n");
    return "/null";
  };
  return ((XmPgplotWidget) widget)->pgplot.device;
}

/*.......................................................................
 * Return the pgslct_id of the given widget. This can then be used with
 * the cpgslct() function to select the widget as the currently
 * active widget.
 *
 * Input:
 *  widget  Widget   The PGPLOT widget to return a device string for.
 * Output:
 *  return     int   The PGPLOT device-id. This will be 0 if the widget
 *                   is not currently open to PGPLOT.
 */
int xmp_device_id(Widget widget)
{
  if(!widget || XtClass(widget) != xmPgplotWidgetClass) {
    fprintf(stderr, "xmp_device_id: Not a Motif PGPLOT widget.\n");
    return 0;
  } else {
    XmPgplotWidget w = (XmPgplotWidget) widget;
    if(w->pgplot.pgslct_id <= 0) {
      fprintf(stderr,
      "xmp_device_id: The specified widget is not currently open to PGPLOT.\n");
    };
    return w->pgplot.pgslct_id;
  };
}

/*.......................................................................
 * The following is a convenience none-variadic function for creating
 * a PGPLOT widget. Note that XtManageChild() should be applied to the
 * returned widget.
 *
 * Input:
 *  parent     Widget    The parent widget to adopt.
 *  name         char *  The name to give the widget.
 *  arglist   ArgList    A list of X resources.
 *  argcount Cardinal    The number of X resources.
 * Output:
 *  return     Widget    The new PGPLOT widget.
 */
Widget XmCreatePgplot(Widget parent, char *name, ArgList arglist,
		      Cardinal argcount)
{
  return XtCreateWidget(name, xmPgplotWidgetClass, parent, arglist, argcount);
}

/*.......................................................................
 * The following is a convenience none-variadic function for creating
 * a PGPLOT widget with scroll-bars. Note that XtManageChild() should
 * be applied to the returned widget if you want the PGPLOT window to
 * fit exactly within the ScrollBar widget area.
 *
 * Input:
 *  parent     Widget    The parent widget to adopt.
 *  name         char *  The name to give the widget.
 *  arglist   ArgList    A list of X resources.
 *  argcount Cardinal    The number of X resources.
 * Output:
 *  return     Widget    The new PGPLOT widget.
 */
Widget XmCreateScrolledPgplot(Widget parent, char *name, ArgList arglist,
		      Cardinal argcount)
{
  char *scroll_name;     /* The name to give the scroll-bar widget */
  ArgList scroll_args;   /* The scroll-bar resource argument list */
  Cardinal scroll_count; /* The number of defined entries in scroll_args */
  Widget scroll_w;       /* The ScrollBar widget */
  Widget pgplot_w;       /* The PGPLOT widget */
  int i;
/*
 * We need to create a name for the scrolled window. Follow the
 * convention used by the Motif Text Widget of appending "SW" to the
 * existing name.
 */
  scroll_name = (char *) XtMalloc(sizeof(char) * strlen(name) + 3);
  sprintf(scroll_name, "%sSW", name);
/*
 * We need to construct a resource assignment list for the
 * ScrollBar widget. This is done by copying the input argument list
 * and appending some standard ScrollBar resources.
 */
  scroll_args = (ArgList) XtMalloc(sizeof(Arg) * (argcount + 4));
/*
 * Copy the input argument list.
 */
  scroll_count = 0;
  for(i=0; i<argcount; i++) {
    scroll_args[scroll_count].name = arglist[i].name;
    scroll_args[scroll_count].value = arglist[i].value;
    scroll_count++;
  };
/*
 * Append ScrollBar specific arguments.
 */
  XtSetArg (scroll_args[scroll_count], XmNscrollingPolicy,
	    (XtArgVal )XmAPPLICATION_DEFINED); scroll_count++;
  XtSetArg (scroll_args[scroll_count], XmNvisualPolicy,
	    (XtArgVal )XmVARIABLE); scroll_count++;
  XtSetArg (scroll_args[scroll_count], XmNscrollBarDisplayPolicy,
	    (XtArgVal )XmSTATIC); scroll_count++;
  XtSetArg (scroll_args[scroll_count], XmNshadowThickness, (XtArgVal ) 0); scroll_count++;
/*
 * Create the ScrollBar widget.
 */
  scroll_w = XtCreateManagedWidget(scroll_name, xmScrolledWindowWidgetClass,
				   parent, scroll_args, scroll_count);
/*
 * Reclaim redundant resources.
 */
  XtFree((char *) scroll_name);
  XtFree((char *) scroll_args);
/*
 * Create the PGPLOT widget with the ScrollBar widget as its parent.
 */
  pgplot_w = XtCreateWidget(name, xmPgplotWidgetClass, scroll_w, arglist,
			    argcount);
/*
 * Arrange that when the PGPLOT widget gets destroyed, so does its
 * parent ScrollBar widget.
 */
  XtAddCallback(pgplot_w, XmNdestroyCallback, XmpDestroyParentCallback, NULL);
/*
 * Finished. Return the PGPLOT widget (not the ScrollBar widget).
 */
  return pgplot_w;
}

/*.......................................................................
 * This is the callback used to destroy the ScrollBar parent of a widget.
 */
static void XmpDestroyParentCallback(Widget w, XtPointer client_data, XtPointer call_data)
{
  if(w)
    XtDestroyWidget(XtParent(w));
}

/*.......................................................................
 * Update the clip-area of the window to prevent pgxwin functions from
 * drawing over the highlight-borders.
 *
 * Input:
 *  w     XmPgplotWidget   The pgplot widget instance.
 */
static void xmp_update_clip(XmPgplotWidget w)
{
  (void) pgx_update_clip(w->pgplot.pgx, 1, w->core.width, w->core.height,
			 w->primitive.highlight_thickness);
}

/*.......................................................................
 * This function is a XtResourceDefaultProc function used to return
 * the default highlight color. It is used to initialize the
 * XmNhighlightColor resource.
 */
static void xmp_GetDefaultHighlightColor(Widget widget, int offset,
					XrmValue *value)
{
  static Pixel pixel;
  pixel = WhitePixel(XtDisplay(widget),XScreenNumberOfScreen(XtScreen(widget)));
  value->addr = (XtPointer) &pixel;
}
/*.......................................................................
 * This function is a XtResourceDefaultProc function used to return
 * the default background color. It is used to initialize the
 * XmNbackground resource.
 */
static void xmp_GetDefaultBackgroundColor(Widget widget, int offset,
					  XrmValue *value)
{
  static Pixel pixel;
  pixel = BlackPixel(XtDisplay(widget),XScreenNumberOfScreen(XtScreen(widget)));
  value->addr = (XtPointer) &pixel;
}
/*.......................................................................
 * This function is a XtResourceDefaultProc function used to return
 * the default foreground color. It is used to initialize the
 * XmNforeground resource.
 */
static void xmp_GetDefaultForegroundColor(Widget widget, int offset,
					  XrmValue *value)
{
  static Pixel pixel;
  pixel = WhitePixel(XtDisplay(widget),XScreenNumberOfScreen(XtScreen(widget)));
  value->addr = (XtPointer) &pixel;
}

/*.......................................................................
 * This is an application-level utility function for converting from
 * PGPLOT world coordinates to X-window pixel coordinates.
 *
 * Input:
 *  widget  Widget    The PGPLOT widget whose coordinates are to be
 *                    converted.
 *  wx, wy   float    The PGPLOT world coordinates to be converted.
 * Output:
 *  px, py     int *  On output, *px and *py will be assigned with the
 *                    X-window pixel coordinates that correspond to wx,wy.
 *  return     int    0 - OK.
 *                    1 - Error.
 */
int xmp_world_to_pixel(Widget widget, float wx, float wy, int *px, int *py)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
/*
 * Check the arguments.
 */
  if(!widget) {
    fprintf(stderr, "xmp_world_to_pixel: NULL widget.\n");
    return 1;
  };
/*
 * Delegate the conversion to an internal function.
 */
  return xmp_WorldToPixel(w, wx, wy, px, py);
}

/*.......................................................................
 * This is an application-level utility function for converting from
 * X-window pixel coordinates to PGPLOT world coordinates.
 *
 * Input:
 *  widget  Widget    The PGPLOT widget whose coordinates are to be
 *                    converted.
 *  px, py     int *  The X-window pixel coordinates to be converted.
 * Output:
 *  wx, wy   float *  On output, *wx and *wy will be assigned with the
 *                    PGPLOT world coordinates that correspond to px,py.
 *  return     int    0 - OK.
 *                    1 - Error.
 */
int xmp_pixel_to_world(Widget widget, int px, int py, float *wx, float *wy)
{
  XmPgplotWidget w = (XmPgplotWidget) widget;
/*
 * Check the arguments.
 */
  if(!widget) {
    fprintf(stderr, "xmp_pixel_to_world: NULL widget.\n");
    return 1;
  };
/*
 * Delegate the conversion to an internal function.
 */
  return xmp_PixelToWorld(w, px, py, wx, wy);
}

/*.......................................................................
 * This is an internal function for converting from X-window pixel
 * coordinates to PGPLOT world coordinates.
 *
 * Input:
 *  w  XmPgplotWidget   The widget whose coordinates are to be converted.
 *  px, py        int * The X-window pixel coordinates to be converted.
 * Output:
 *  wx, wy      float * On output, *wx and *wy will be assigned with the
 *                      PGPLOT world coordinates that correspond to px,py.
 *  return        int    0 - OK.
 *                       1 - Error.
 */
static int xmp_PixelToWorld(XmPgplotWidget w, int px, int py,
			    float *wx, float *wy)
{
  PgxWin *pgx = w->pgplot.pgx;
  float rbuf[2];
/*
 * Convert the specified pixel coordinates to world coordinates.
 */
  pgx_win2dev(pgx, px, py, rbuf);
  pgx_dev2world(pgx, rbuf);
/*
 * Assign the return values if possible.
 */
  if(wx) *wx = rbuf[0];
  if(wy) *wy = rbuf[1];
  return 0;
}

/*.......................................................................
 * This is an internal function for converting from PGPLOT world
 * coordinates to X-window pixel coordinates.
 *
 * Input:
 *  w  XmPgplotWidget   The widget whose coordinates are to be converted.
 *  wx, wy      float   The PGPLOT world coordinates to be converted.
 * Output:
 *  px, py       int *  On output, *px and *py will be assigned with the
 *                      X-window pixel coordinates that correspond to wx,wy.
 *  return        int   0 - OK.
 *                      1 - Error.
 */
static int xmp_WorldToPixel(XmPgplotWidget w, float wx, float wy,
			    int *px, int *py)
{
  PgxWin *pgx = w->pgplot.pgx;
  float rbuf[2];
/*
 * Convert the world coordinate to pixel coordinates.
 */
  rbuf[0] = wx;
  rbuf[1] = wy;
  pgx_world2dev(pgx, rbuf);
  pgx_dev2win(pgx, rbuf, px, py);
  return 0;
}