File: x_retrieve.c

package info (click to toggle)
plotutils 2.4.1-11
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 11,676 kB
  • ctags: 6,967
  • sloc: ansic: 76,305; sh: 15,172; cpp: 12,403; yacc: 2,604; makefile: 888; lex: 144
file content (1404 lines) | stat: -rw-r--r-- 50,380 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
/* This file contains the Plotter-specific _retrieve_font method, which is
   called when the font_name, font_size, and textangle fields of the
   current drawing state have been filled in.  It retrieves the specified
   font, and fills in the true_font_name, true_font_size, font_type,
   typeface_index, font_index, font_ascent, font_descent, font_cap_height,
   and font_is_iso8859_1 fields of the drawing state.  It is called by
   _set_font, which in turn is called by the API functions alabel() and
   flabelwidth(). */

/* This version is for XDrawablePlotters (and XPlotters).  It also fills in
   the x_font_pixmatrix and x_native_positioning fields of the drawing
   state, which are X-specific. */

/* We retrieve the font from the X server, or from a local cache of
   XFontStruct's.  We run through various possibilities: first we try to
   interpret `name' as the name of a PS font in libplot's font database
   (e.g. "Times-Roman"), for which we necessarily have a base XLFD name
   (e.g., "times-medium-r-normal", then as a base XLFD name not in our
   database (e.g. "utopia-medium-r-normal"), then as a non-XLFD font name
   (e.g., "fixed" or "vtsingle").  If none of these succeeds, then we try
   to retrieve a default X font instead.  That the default font may be
   different from the requested font is one reason why the true_font_name
   field, when filled in, may be different from the font_name field.

   The `true_font_size' field is a bit difficult to compute for an X font.
   Ideally it would be a minimum interline spacing, because that is what
   must be returned (in user units) by fontname(), fontsize, and
   textangle().  But even for non-rotated, non-sheared fonts, there are
   several possibilities for this: (1) the so-called pixel size (which can
   be extracted only if the font has an XLFD name, or if the font has a
   PIXEL_SIZE or POINT_SIZE property), (2) the sum of the `logical'
   font_ascent and font_descent (from the font structure), (3) the sum of
   the maximum (over characters) ascent and the maximum descent, (4) the
   sum of the cap height and the maximum descender length (which may both
   be difficult to extract), etc.

   I decided to use (1).  The analogue for affinely transformed fonts is
   easy to compute (from the pixel matrix).  However, for old non-XLFD (and
   hence non-rotated, non-sheared) fonts, there is the possibility that the
   PIXEL_SIZE property may not be available.  For such fonts, the
   POINT_SIZE and RESOLUTION_Y properties are used to compute it.  If they
   also are not available, we fall back on definition (2).

   The {font_ascent,font_descent} fields of the drawing state are important
   for vertical positioning.  For modern XLFD fonts at least, we obtain
   them from the RAW_ASCENT and RAW_DESCENT properties.  The
   font_cap_height field is harder.  See comments in the code. */

/* NOTE: _x_retrieve_font() and the routines that it calls now keep careful
   track of which elements of the X11R6-style font pixel matrix, if any,
   are zero.  This is because the true font size, as supplied by the X
   server, may not be quite the size we request.  If a font with pixel
   matrix containing one or more zeroes is requested from the X server,
   what comes back may have the zeroes replaced by absurdly small
   quantities (e.g. 4e-311).  Believe it or not, floating point numbers
   that small cannot be manipulated arithmetically on a DEC Alpha.  If you
   try, you get a SIGFPE and a program crash!  We make sure that our
   internal representation for the returned font pixel matrix sets such
   elements to zero (exactly).  This problem was first noticed when `graph'
   on a DEC Alpha crashed when trying to plot a y-axis label (rotated 90
   degrees, so two of the four elements of the pixel matrix were zero). */

#include "sys-defines.h"
#include "extern.h"
#include "g_her_metr.h"

/* max length user-level font name we'll accept; this may be either an XLFD
   base name (a string with exactly three hyphens in it), or something else
   (an alias, a pre-XLFD font name, etc.). */
#define MAX_USER_FONT_NAME_LENGTH 200

/* length of buffer for constructing an X font name; must be large enough
   to handle XFLD template, user-level font name */
#define MAX_FONT_NAME_LENGTH 255

/* An XLFD template, with holes into which we can punch the base name (a
   string with exactly three hyphens in it) and the integer size in terms
   of pixels */
static const char * const _xlfd_template = "-*-%s-*-%d-*-*-*-*-*-*-*";

/* An XLFD template for an affinely transformed font, with holes for the
   base name and for four dimensions in terms of pixels.  Supported as of
   X11R6.  (And by HP for several years before that?) */
static const char * const _xlfd_template_with_scaling = "-*-%s-*-[%s %s %s %s]-*-*-*-*-*-*-*";

/* length of buffer for constructing an X11R6-style list-of-charset-ranges
   string, e.g. "[32 48_57 65_90]" would represent the non-contiguous set
   of characters [ 0-9A-Z]. */
#define MAX_CHARSET_SUBSET_LIST_LENGTH 767

#define NUM_XLFD_FIELDS 14
#define FIELD_FOUNDRY 0
#define FIELD_FAMILY 1
#define FIELD_WEIGHT 2
#define FIELD_SLANT 3
#define FIELD_SET_WIDTH 4
#define FIELD_ADDITIONAL_STYLE 5
#define FIELD_PIXELS 6
#define FIELD_POINTS 7
#define FIELD_HORIZONTAL_RESOLUTION 8
#define FIELD_VERTICAL_RESOLUTION 9
#define FIELD_SPACING 10
#define FIELD_AVERAGE_WIDTH 11
#define FIELD_CHARACTER_SET_MAJOR 12
#define FIELD_CHARACTER_SET_MINOR 13 /* in X11R6 may include char subset too */

/* forward references */
static bool _is_a_subset ____P((unsigned char set1[32], unsigned char set2[32]));
static char *_xlfd_field ____P ((const char *name, int field));
static void _parse_pixmatrix ____P ((const char *pixel_string, double d[4], bool *x_native_positioning, bool is_zero[4]));
static void _print_bitvector ____P ((unsigned char v[32], char *s));
static void _string_to_bitvector ____P ((const unsigned char *s, unsigned char v[8], bool include_X));

/* _x_retrieve_font() attempts to retrieve an X font specified by a triple,
   namely {name, size, rotation}.  Three possible interpretations are
   tried, in order.

   1. `name' is taken to be an alias for an XLFD base name, as listed in
   our table in g_fontdb.c.  (Aliases for the 35 standard font names appear
   there).  E.g., name="times-roman" or "Times-Roman".

   2. `name' is taken to be an XLFD base name (no aliasing), of the form
   foundry-family-weight-slant-width, with exactly four hyphens.  E.g.,
   name="bitstream-courier-medium-r-normal".  NOT YET IMPLEMENTED.

   3. `name' is taken to be an XLFD base name (no aliasing), of the form
   family-weight-slant-width, with exactly three hyphens.  E.g.,
   name="grotesk-bold-r-normal", or "times-medium-r-normal".

   4. `name' is taken to be a full X font name, in which case `size' and
   `rotation' are ignored.  E.g.,
   name="-schumacher-clean-medium-r-normal--6-60-75-75-c-50-iso8859-1" or
   name="vtbold".  This option is really to support old (pre-XLFD) fonts,
   such as "vtbold".

   If an X font is successfully retrieved (which will set the fields
   true_font_size, font_ascent, font_descent, and font_iso8859_1 of the
   drawing state, and the X-specific fields x_font_struct,
   x_font_pixmatrix, and x_native_positioning too), then this function sets
   font_type (F_POSTSCRIPT in case 1, F_OTHER in cases 2, 3 and 4) and
   returns true.  If a font is not successfully retrieved, this function
   returns false.

   typeface_index and font_index are also set in case 1.  In the other
   cases (F_OTHER) it's hardly worth it to set them, since switching to
   other fonts, except for a symbol font (`font #0') won't be supported.
   See g_cntrlify.c. */

bool
#ifdef _HAVE_PROTOS
_x_retrieve_font (S___(Plotter *_plotter))
#else
_x_retrieve_font (S___(_plotter))
     S___(Plotter *_plotter;)
#endif
{
  const char *name, *true_name = ""; /* keep compiler happy */
  double size, rotation;
  bool is_zero[4];		/* pixel matrix el.s are zero? (see above) */
  bool matched_builtin = false;	/* font name matches name of a font in db? */
  bool success;			/* font retrieved from cache or server? */
  const char *name_p;
  const char *x_name = NULL, *x_name_alt = NULL; /* from our font tables */
  double user_size;		/* font size in user units */
  int i, hyphen_count;
  int typeface_index = 0, font_index = 0; /* from our database of fonts */
  int font_type = F_POSTSCRIPT; /* from our database of fonts */

  name = _plotter->drawstate->font_name;
  size = _plotter->drawstate->font_size;
  rotation = _plotter->drawstate->text_rotation;  

#ifdef DEBUG
	  fprintf (stderr, "_x_retrieve_font(): name=\"%s\", size=%g, rotation=%g\n", 
		   name, size, rotation);
#endif

  if (strlen (name) > MAX_USER_FONT_NAME_LENGTH) /* avoid buffer overflow */
    return false;

  if (size == 0.0)		/* don't try to retrieve zero-size fonts */
    return false;

  user_size = size;		/* user units */

  /* Search null-terminated table of recognized PS fonts, in g_fontdb.c,
     for a name matching the passed name.  We support either PS-style names
     (e.g. "Times-Roman") or shortened XLFD-style names
     (e.g. "times-medium-r-normal").  Alternative versions of latter are
     supported because some X servers use "zapfdingbats" instead of "itc
     zapf dingbats", etc. */
  i = -1;
  while (_ps_font_info[++i].ps_name) /* array ends in NULL */
    {
      if ((strcasecmp (_ps_font_info[i].ps_name, name) == 0)
	  /* check alternative ps font name if any */
	  || (_ps_font_info[i].ps_name_alt
	      && strcasecmp (_ps_font_info[i].ps_name_alt, name) == 0)
	  /* check 2nd alternative ps font name if any */
	  || (_ps_font_info[i].ps_name_alt2
	      && strcasecmp (_ps_font_info[i].ps_name_alt2, name) == 0)
	  /* check X font name */
	  || (strcasecmp (_ps_font_info[i].x_name, name) == 0)
	  /* check alternative X font name if any */
	  || (_ps_font_info[i].x_name_alt
	      && strcasecmp (_ps_font_info[i].x_name_alt, name) == 0))
	break;
    }
  
  if (_ps_font_info[i].ps_name)	/* matched name of a PS font in database */
    {
      matched_builtin = true;
      true_name = _ps_font_info[i].ps_name;
      x_name = _ps_font_info[i].x_name;
      x_name_alt = _ps_font_info[i].x_name_alt;
      font_type = F_POSTSCRIPT;
      typeface_index = _ps_font_info[i].typeface_index;
      font_index = _ps_font_info[i].font_index;
    }

#ifdef USE_LJ_FONTS_IN_X
  if (matched_builtin == false)	/* PS match failed, so try PCL fonts too */
    {
      i = -1;
      while (_pcl_font_info[++i].ps_name) /* array ends in NULL */
	{
	  if ((strcasecmp (_pcl_font_info[i].ps_name, name) == 0)
	      /* check alternative ps font name if any */
	      || (_pcl_font_info[i].ps_name_alt
		  && strcasecmp (_pcl_font_info[i].ps_name_alt, name) == 0)
	      /* check X font name */
	      || (strcasecmp (_pcl_font_info[i].x_name, name) == 0))
	    break;
	}
  
      if (_pcl_font_info[i].ps_name) /* matched name of a PCL font in db */
	{
	  matched_builtin = true;
	  true_name = _pcl_font_info[i].ps_name;
	  x_name = _pcl_font_info[i].x_name;
	  x_name_alt = NULL;
	  font_type = F_PCL;
	  typeface_index = _pcl_font_info[i].typeface_index;
	  font_index = _pcl_font_info[i].font_index;
	}
    }
#endif /* USE_LJ_FONTS_IN_X */

  if (matched_builtin)
    {
      /* user passed the name of a PS or PCL font in libplot's database */
      success = _x_select_xlfd_font_carefully (R___(_plotter) x_name, x_name_alt, user_size, rotation);

      if (success)
	/* we've retrieved an X font version of a font in our internal
           database, and have filled in X-specific fields; good */
	{
	  free ((char *)_plotter->drawstate->true_font_name);
	  _plotter->drawstate->true_font_name = 
	    (const char *)_plot_xmalloc (strlen (true_name) + 1);
	  strcpy ((char *)_plotter->drawstate->true_font_name, true_name);

	  _plotter->drawstate->font_type = font_type;
	  _plotter->drawstate->typeface_index = typeface_index;
	  _plotter->drawstate->font_index = font_index;

#ifdef DEBUG
	  fprintf (stderr, "_x_retrieve_font(): retrieved \"%s\" as \"%s\", type=%d\n", name, _plotter->drawstate->true_font_name, _plotter->drawstate->font_type);
#endif
	  return true;
	}
    }
  
  /* User-specified font name didn't match either of the names of any PS
     [or PCL] font in libplot's database, so first consider possibility
     that it's an XLFD base name for some other X font
     (e.g. "utopia-medium-r-normal"), with exactly three hyphens. */
  name_p = name;
  hyphen_count = 0;
  while (*name_p)
    hyphen_count += (*name_p++ == '-' ? 1 : 0);

  if (hyphen_count == 3)
    /* treat as base of an XLFD name */
    {
      success = _x_select_xlfd_font_carefully (R___(_plotter) name, NULL, user_size, rotation);

      if (success)
	/* we've retrieved a scalable X font that isn't one of the fonts in
           the libplot database */
	{
	  free ((char *)_plotter->drawstate->true_font_name);
	  _plotter->drawstate->true_font_name = 
	    (const char *)_plot_xmalloc (strlen (name) + 1);
	  strcpy ((char *)_plotter->drawstate->true_font_name, name);

	  _plotter->drawstate->font_type = F_OTHER;
	  /* these two fields are irrelevant because we don't support
	     switching among user-defined fonts */
	  _plotter->drawstate->typeface_index = 0;
	  _plotter->drawstate->font_index = 1;

#ifdef DEBUG
	  fprintf (stderr, "_x_retrieve_font(): retrieved \"%s\" as \"%s\", type=%d\n", name, _plotter->drawstate->true_font_name, _plotter->drawstate->font_type);
#endif
	  return true;
	}  
    }
  
  /* User-passed name didn't have exactly 3 hyphens, so try treating it as
     a full X fontname; ignore size.  This a kludge, needed to support
     pre-XLFD fonts, e.g. "vtsingle", and aliases for XLFD fonts,
     e.g. "fixed".  Most of the latter are really pre-XLFD names. */
  
  /* We don't do this unless the desired text rotation is zero, since
     pre-XLFD fonts all have rotation 0.  Also we insist that the
     user->device coordinate scaling should preserve coordinate axes, have
     the same scaling factors in both directions, and not involve a
     reflection. */

  if ((rotation == (double)0.0) 
      && _plotter->drawstate->transform.axes_preserved 
      && _plotter->drawstate->transform.uniform 
      && _plotter->drawstate->transform.nonreflection
      && _plotter->drawstate->transform.m[0] > 0.0)
    {
      /* don't assume that any elements of pixel matrix are zero (user
	 perhaps could have passed us a bizarre font name containing an
	 explicit pixel matrix?) */
      is_zero[0] = is_zero[3] = false;
      is_zero[1] = is_zero[2] = false;

      /* try to retrieve font from server or cache list */
      success = _x_select_font_carefully (R___(_plotter)
					  name, is_zero, 
					  _plotter->drawstate->x_label);
      if (success)
	/* we've retrieved a presumably non-scalable X font that isn't one
           of the fonts in the libplot database */
	{
	  free ((char *)_plotter->drawstate->true_font_name);
	  _plotter->drawstate->true_font_name = 
	    (const char *)_plot_xmalloc (strlen (name) + 1);
	  strcpy ((char *)_plotter->drawstate->true_font_name, name);

	  _plotter->drawstate->font_type = F_OTHER;
	  _plotter->drawstate->x_native_positioning = true;
	  /* these two fields are irrelevant because we don't support
	     switching among `other' fonts */
	  _plotter->drawstate->typeface_index = 0;
	  _plotter->drawstate->font_index = 1;

#ifdef DEBUG
	  fprintf (stderr, "_x_retrieve_font(): retrieved \"%s\" as \"%s\", type=%d\n", name, _plotter->drawstate->true_font_name, _plotter->drawstate->font_type);
#endif
	  return true;
	}
    }
  
  /* couldn't retrieve a matching X font; failure */
#ifdef DEBUG
	  fprintf (stderr, "_x_retrieve_font(): FAILURE, couldn't retrieve \"%s\"\n", name);
#endif
  return false;
}

/* A helper function that x_retrieve_font() above uses.  It constructs a
   full XLFD font name from one or two possible prefixes, such as
   "helvetica-medium-r-normal", and attempts to retrieve each of them. */

bool
#ifdef _HAVE_PROTOS
_x_select_xlfd_font_carefully (R___(Plotter *_plotter) const char *x_name, const char *x_name_alt, double user_size, double rotation)
#else
_x_select_xlfd_font_carefully (R___(_plotter) x_name, x_name_alt, user_size, rotation)
     S___(Plotter *_plotter;)
     const char *x_name, *x_name_alt;
     double user_size, rotation;
#endif
{
  char *x_name_buf;		/* buffer for creating font name */
  bool is_zero[4];		/* pixel matrix el.s are zero? */
  bool success = false;

  /* prepare buffer for font name assemblage */
  x_name_buf = (char *)_plot_xmalloc ((MAX_FONT_NAME_LENGTH + 1) * sizeof (char));

  /* Build full XLFD name of font, computing pixel matrix values if we have
     something other than an unrotated, uniformly scaled font. */
  if ((rotation == (double)0.0) 
      && _plotter->drawstate->transform.axes_preserved 
      && _plotter->drawstate->transform.uniform
      && _plotter->drawstate->transform.nonreflection
      && _plotter->drawstate->transform.m[0] > 0.0)
    /* case 1: zero text rotation, uniformly scaled */
    {
      int size_in_pixels;
      
      size_in_pixels = 
	IROUND(_plotter->drawstate->transform.m[0] * user_size);
      
      /* if integer size in terms of pixels is zero, bail */
      if (size_in_pixels == 0)
	{
	  free (x_name_buf);
	  return false;
	}
      
      /* no text rotation, pixel matrix will be diagonal */
      is_zero[0] = is_zero[3] = false;
      is_zero[1] = is_zero[2] = true;
      
      /* punch size into template, try to retrieve font from server or
	 cache list */
      sprintf (x_name_buf, _xlfd_template, x_name, size_in_pixels);
      success = _x_select_font_carefully (R___(_plotter)
					  x_name_buf, is_zero, 
					  _plotter->drawstate->x_label);
      if (success == false && x_name_alt)
	/* alternative X font name was supplied, so try it */
	{
	  sprintf (x_name_buf, _xlfd_template, x_name_alt, size_in_pixels);
	  success = _x_select_font_carefully (R___(_plotter)
					      x_name_buf, is_zero, 
					      _plotter->drawstate->x_label);
	}
    }
  else
    /* case 2: nonzero font rotation, or non-uniform scaling */
    {
      double rot[4];		/* font rotation matrix */
      double pm[4];		/* pixel matrix */
      char a[4][256];		/* ascii representation */
      char *p;
      int k;
      
      rot[0] = cos (M_PI * rotation / 180.0);
      rot[1] = sin (M_PI * rotation / 180.0);
      rot[2] = - sin (M_PI * rotation / 180.0);
      rot[3] = cos (M_PI * rotation / 180.0);

      /* pixel matrix: product of text rotation matrix, and
	 transformation from user to device coordinates; note flipped-y
	 convention affecting _plotter->drawstate->transform.m[1] and
	 _plotter->drawstate->transform.m[3].  A factor user_size is
	 also included; see below. */
      pm[0] =  (rot[0] * _plotter->drawstate->transform.m[0] 
		+ rot[1] * _plotter->drawstate->transform.m[2]);
      pm[1] =  - (rot[0] * _plotter->drawstate->transform.m[1] 
		  + rot[1] * _plotter->drawstate->transform.m[3]);
      pm[2] =  (rot[2] * _plotter->drawstate->transform.m[0] 
		+ rot[3] * _plotter->drawstate->transform.m[2]);
      pm[3] =  - (rot[2] * _plotter->drawstate->transform.m[1] 
		  + rot[3] * _plotter->drawstate->transform.m[3]);
      
      /* don't attempt to retrieve zero-size fonts */
      if (pm[0] == 0.0 && pm[1] == 0.0 && pm[2] == 0.0 && pm[3] == 0.0)
	{
	  free (x_name_buf);
	  return false;
	}
      
      /* ascii entries in pixel matrix string */
      for (k = 0; k < 4; k++)
	{
	  sprintf (a[k], "%f", user_size * pm[k]);
	  /* test whether pixel matrix elements are zero, to the
	     precision supported by %f (6 significant digits) */
	  if (strcmp (a[k], "0.000000") == 0
	      || strcmp (a[k], "-0.000000") == 0)
	    is_zero[k] = true;
	  else 
	    is_zero[k] = false;
	}
      
      /* convert minus signs to tildes */
      for (k = 0; k < 4; k++)
	for (p = a[k]; *p; p++)
	  if (*p == '-')
	    *p = '~';
      
      /* punch size into template, try to retrieve font from server or
	 cache list */
      sprintf (x_name_buf, _xlfd_template_with_scaling,
	       x_name, a[0], a[1], a[2], a[3]);
      success = _x_select_font_carefully (R___(_plotter)
					  x_name_buf, is_zero, 
					  _plotter->drawstate->x_label);
      if (success == false && x_name_alt)
	/* alternative X font name was supplied, so try it */
	{
	  sprintf (x_name_buf, _xlfd_template_with_scaling,
		   x_name_alt, a[0], a[1], a[2], a[3]);
	  success = _x_select_font_carefully (R___(_plotter)
					      x_name_buf, is_zero, 
					      _plotter->drawstate->x_label);
	}
    }

  return success;
}

/* _x_select_font_carefully() is a wrapper around _x_select_font() below.
   It attempts to retrieve a font (with charset subsetting) from the X
   server or the font cache.  The charset subset (if any) is specified by a
   string.  NULL means that we are only retrieving the font to look at its
   metrics, so we attempt to retrieve a singleton subset consisting of the
   space character, " ".  If a valid string is supplied, we attempt to
   retrieve a subset that will allow the string to be rendered.  In both
   cases, in the event of failure we attempt a complete retrieval of the
   font (as would be needed on a pre-X11R6 server, for example). */

bool
#ifdef _HAVE_PROTOS
_x_select_font_carefully (R___(Plotter *_plotter) const char *name, bool is_zero[4], const unsigned char *s)
#else
_x_select_font_carefully (R___(_plotter) name, is_zero, s)
     S___(Plotter *_plotter;)
     const char *name;
     bool is_zero[4];
     const unsigned char *s;
#endif
{
  bool success;
  
  if (s == NULL)
    /* need metrics only */
    s = (const unsigned char *)" ";

  /* Following #ifdef requested by Georgy Salnikov <sge@nmr.nioch.nsc.ru>,
     to fix a problem with XFree86-3.2.  If an XLFD font name ends in
     *-*[32], i.e. font contains only a single space, the X server reports
     an error retrieving the font, and the client exits.  The bug does not
     surface in XFree86-3.3, or in Solaris-2.4 or Irix-5.3.  Retrieving the
     entire font is what he recommends. */

  /* This bug fix is now presumed obsolete, since we now always include the
     character `X' in the subset of the character set that we retrieve,
     since we wish to compute the cap height of the font.  I.e., we no
     longer retrieve fonts consisting of a single space character. */

#ifdef XFREE86_FONTNAME_BUG_FIX
  {
    bool replace_space = true;
    const unsigned char *t = s;
    
    while (*t)
      if (*t++ != ' ')
	{
	  replace_space = false;
	  break;
	}
    if (replace_space)
      s = NULL;
  }
#endif

  success = _x_select_font (R___(_plotter) name, is_zero, s);
  if (s != NULL && success == false)
    /* request entire font */
    success = _x_select_font (R___(_plotter) name, is_zero, NULL);
  
  return success;
}

/* _x_select_font() attempts to retrieve a specified X font by (1) checking
   the list of fonts previously retrieved with XLoadQueryFont(), and (2) if
   the font is not in the list, calling XLoadQueryFont.  X11R6-style
   charset subsetting is supported (subsetting may be specified by passing
   a non-NULL pointer to a string).  If retrieval succeeds, i.e. we obtain
   an XFontStruct, we call _x_set_font_dimensions() to fill in the
   true_font_size, x_font_pixmatrix, font_ascent, font_descent,
   font_cap_height, x_native_positioning, and font_is_iso8859_1 fields of
   the drawing state.  We don't set the font in the GC used for drawing
   though (for that, see x_text.c). */

/* Note: if subsetting, we always include the character `X' in the subset.
   This is a bit of a kludge.  Generally, rasterizing and retrieving `X' is
   the only way we can compute the cap height; see comments below in
   _x_set_font_dimensions().  We have some backup code in that function
   which will automatically set the cap height to 0.75 times the font
   ascent, if `X' isn't present in the retrieved font. */

bool
#ifdef _HAVE_PROTOS
_x_select_font (R___(Plotter *_plotter) const char *name, bool is_zero[4], const unsigned char *s)
#else
_x_select_font (R___(_plotter) name, is_zero, s)
     S___(Plotter *_plotter;)
     const char *name;
     bool is_zero[4];
     const unsigned char *s;
#endif
{
  plFontRecord *fptr;
  bool subsetting = (s == NULL ? false : true);
  bool found = false;
  unsigned char bitvec[32];

#ifdef DEBUG
  fprintf (stderr, "_x_select_font (name=\"%s\", subset=\"%s\")\n", 
	   name, (const char *)s ? (const char *)s : "(null)");
#endif

  if (subsetting)
    /* construct 256-bit vector specifying charset subset; final arg `true'
       requests that the character `X' be included (we use it for
       retrieving the font's cap height) */
    _string_to_bitvector (s, bitvec, true);

  /* attempt to find font in cache list */
  for (fptr = _plotter->x_fontlist; fptr; fptr = fptr->next)
    if (strcmp (name, fptr->name) == 0)
      {
	if ((subsetting && fptr->subset
	       && _is_a_subset (bitvec, fptr->subset_vector))
	    || (subsetting && (fptr->subset == false))
	    || (subsetting == false && fptr->subset == false))
	  {
	    found = true;
	    _plotter->drawstate->x_font_struct = fptr->x_font_struct;
	    break;
	  }
      }

  if (found == false)
    /* no record, try to retrieve font from X server */
    {
      char *tmpname, *tmpname_perm, *_charset_subset_list = NULL;
      int extra = 0;
      plFontRecord *record = 
	(plFontRecord *)_plot_xmalloc (sizeof (plFontRecord));

      if (subsetting)
	{
	  _charset_subset_list = 
	    (char *)_plot_xmalloc ((MAX_CHARSET_SUBSET_LIST_LENGTH + 1) * sizeof (char));
	  _print_bitvector (bitvec, _charset_subset_list);
	  extra = strlen (_charset_subset_list);
	}
      tmpname_perm = (char *)_plot_xmalloc (1 + strlen (name));
      strcpy (tmpname_perm, name);
      tmpname = (char *)_plot_xmalloc (1 + strlen (name) + extra);
      strcpy (tmpname, name);
      if (subsetting)
	{
	  /* append X11R6 list-of-ranges to name to be sent to server */
	  strcat (tmpname, _charset_subset_list);
	  free (_charset_subset_list);
	}

#ifdef DEBUG
      fprintf (stderr, "_x_select_font(): trying to invoke XLoadQueryFont on \"%s\"\n", tmpname);
#endif

      _plotter->drawstate->x_font_struct = 
	XLoadQueryFont (_plotter->x_dpy, tmpname);
      free (tmpname);
      
      /* Whether successfully retrieved or not, add a record of this font
	 to cache list.  (If retrieval failed, recorded x_font_struct will
	 be NULL.) */
      record->name = tmpname_perm; /* stored name doesn't include subset */
      record->x_font_struct = _plotter->drawstate->x_font_struct;
      record->subset = subsetting;
      if (subsetting)
	memcpy (record->subset_vector, bitvec, 32 * sizeof (unsigned char));
      record->next = _plotter->x_fontlist;
      _plotter->x_fontlist = record;

      if (_plotter->drawstate->x_font_struct)
	/* successfully retrieved a font from the server */
	{
#ifdef DEBUG
	  fprintf (stderr, "_x_select_font(): loaded font \"%s\"\n", name);
#endif	  
	  /* fill in abovementioned six fields of the drawing state */
	  _x_set_font_dimensions (R___(_plotter) is_zero);
	  /* copy these six fields into the record in the cache */
	  record->true_font_size = _plotter->drawstate->true_font_size;
	  record->font_pixmatrix[0] = _plotter->drawstate->x_font_pixmatrix[0];
	  record->font_pixmatrix[1] = _plotter->drawstate->x_font_pixmatrix[1];
	  record->font_pixmatrix[2] = _plotter->drawstate->x_font_pixmatrix[2];
	  record->font_pixmatrix[3] = _plotter->drawstate->x_font_pixmatrix[3];
	  record->font_cap_height = _plotter->drawstate->font_cap_height;
	  record->font_ascent = _plotter->drawstate->font_ascent;
	  record->font_descent = _plotter->drawstate->font_descent;
	  record->native_positioning = _plotter->drawstate->x_native_positioning;
	  record->font_is_iso8859_1 = _plotter->drawstate->font_is_iso8859_1;

	  return true;		/* X font selected */
	}
      else
	/* couldn't find font either in cache or on server */
	{
#ifdef DEBUG
	  fprintf (stderr, "_x_select_font(): failed to load font \"%s\"\n", name);
#endif	  
	  return false;
	}
    }
  else
    /* record for font was found in cache */
    {
      if (_plotter->drawstate->x_font_struct) 
	/* font record was a genuine one */
	{
#ifdef DEBUG
	  fprintf (stderr, "_x_select_font(): found in cache: \"%s\"\n", name);
#endif
	  /* copy abovementioned six fields from cached font record */
	  _plotter->drawstate->true_font_size = fptr->true_font_size;
	  _plotter->drawstate->x_font_pixmatrix[0] = fptr->font_pixmatrix[0];  
	  _plotter->drawstate->x_font_pixmatrix[1] = fptr->font_pixmatrix[1];
	  _plotter->drawstate->x_font_pixmatrix[2] = fptr->font_pixmatrix[2];
	  _plotter->drawstate->x_font_pixmatrix[3] = fptr->font_pixmatrix[3];
	  _plotter->drawstate->font_cap_height = fptr->font_cap_height;
	  _plotter->drawstate->font_ascent = fptr->font_ascent;
	  _plotter->drawstate->font_descent = fptr->font_descent;
	  _plotter->drawstate->x_native_positioning = fptr->native_positioning;
	  _plotter->drawstate->font_is_iso8859_1 = fptr->font_is_iso8859_1;

	  return true;		/* X font selected */
	}
      else
	{
#ifdef DEBUG
	  fprintf (stderr, "_x_select_font(): found in cache: NULL record for \"%s\"\n", name);
#endif
	  /* we don't have a font; previous retrieval attempt failed */
	  return false;		/* X font not selected */
	}	  
    }  
}

/* _x_set_font_dimensions() is called when an X font has been retrieved and
   an XFontStruct placed in the x_font_struct field of the
   _plotter->drawstate structure.  It attempts to compute and fill in
   several other fields.  This includes (1) the `true_font_size' field
   (essentially pixel size, see comments at head of file, transformed from
   the device frame to the user frame; it's what will be returned by
   e.g. the fontsize() operation), (2) the `pixmatrix' field, and (3) the
   `x_native_positioning' field.

   If the font has a server-returned XLFD name, i.e., a FONT property that
   is an official XLFD string, the pixel size and pixel matrix are
   extracted from it; if not, we try to extract (or compute) the PIXEL_SIZE
   property of the font.  Only if we fail at this do we punt, and fill in
   the `true_font_size' field from the font height (i.e. font ascent + font
   descent) provided by the XFontStruct.  The `x_native_positioning' field
   is set if the pixel matrix is proportional to the identity matrix.

   We also fill in (4) the `font_ascent' field, (5) the `font_descent'
   field, and (6) the `font_cap_height' field.  Either they are taken from
   properties, or they are computed from the `x_font_struct' field.  We
   fill in (7) the `font_is_iso8859_1' field too.

   If the font doesn't have an XLFD name, various kludges are used. */

void
#ifdef _HAVE_PROTOS
_x_set_font_dimensions(R___(Plotter *_plotter) bool is_zero[4])
#else
_x_set_font_dimensions(R___(_plotter) is_zero)
     S___(Plotter *_plotter;)
     bool is_zero[4];
#endif
{
  unsigned long retval;
  char *name, *pixel_field;
  double size;
  char *charset_major_field, *charset_minor_field;
  XFontStruct *x_font_struct = _plotter->drawstate->x_font_struct;

#ifdef DEBUG2
  {
    int i;

    for (i = 0; i < x_font_struct->n_properties; i++)
      fprintf (stderr, "\tproperty %s [atom %lu] is %ld\n", 
	       XGetAtomName(_plotter->x_dpy, 
			    x_font_struct->properties[i].name),
	       x_font_struct->properties[i].name,
	       x_font_struct->properties[i].card32);
  }    
#endif

  if (XGetFontProperty (x_font_struct, XA_FONT, &retval))
    /* this font has a FONT property, as any well behaved font should */
    {
      /* Extract relevant fields from this property (i.e. from X server's
	 idea of the font name).  This will work if it's an XLFD name. */
      name = XGetAtomName(_plotter->x_dpy, retval); 
      /* N.B. it's here that the bogus tiny entries ("4e-311") can show up */

#ifdef DEBUG
      fprintf (stderr, "_x_set_font_dimensions(): FONT property is \"%s\"\n", name);
#endif
      pixel_field = _xlfd_field (name, FIELD_PIXELS);
      charset_major_field = _xlfd_field (name, FIELD_CHARACTER_SET_MAJOR);
      charset_minor_field = _xlfd_field (name, FIELD_CHARACTER_SET_MINOR);
      XFree (name);

      /* determine whether font encoding is ISO-Latin-1 */
      if ((charset_major_field != NULL) && (charset_minor_field != NULL)
	  && strcasecmp (charset_major_field, "iso8859") == 0
	  && charset_minor_field[0] == (char)'1')
	_plotter->drawstate->font_is_iso8859_1 = true;
      else
	_plotter->drawstate->font_is_iso8859_1 = false;

      if (charset_major_field)
	free (charset_major_field);
      if (charset_minor_field)
	free (charset_minor_field);

      if (pixel_field != NULL)	
	/* font presumably has an XLFD name, since it has a pixel field */
	{
	  /* extract x_font_pixmatrix, x_native_positioning from the pixel
             field; keep track of which elements of pixmatrix should be
             exactly zero */
	  _parse_pixmatrix (pixel_field, 
			    _plotter->drawstate->x_font_pixmatrix, 
			    &(_plotter->drawstate->x_native_positioning),
			    is_zero);
	  free (pixel_field);
	  
	  /* compute true_font_size from the pixmatrix */
	  {
	    double sx, sy;
	    double ux, uy;
	    
	    /* (sx, sy) is a sort of minimum inter-line displacement
               vector, in the device frame (i.e. in terms of pixel coors) */
	    sx = _plotter->drawstate->x_font_pixmatrix[2];
	    sy = - _plotter->drawstate->x_font_pixmatrix[3];	  

	    /* (ux, uy) is the same, in the user frame; it should be
	       perpendicular to the escapement vector, the angle of which
	       the user specifies with textangle() */
	    ux = XUV (sx, sy);
	    uy = YUV (sx, sy);

	    /* `true_font_size' is length of this vector, in user frame */
	    _plotter->drawstate->true_font_size = sqrt (ux*ux + uy*uy);
	  }
	  
	  /* Try to fill in the font_{descent,ascent,cap_height} fields by
	     retrieving the RAW_DESCENT, RAW_ASCENT, RAW_CAP_HEIGHT
	     properties of the font.  (``What descent, ascent, and
	     cap_height would be for a 1000-pixel untransformed font''.)
	     If they don't exist, this must be an XLFD font without a
	     matrix pixmatrix (hence no rotation).  So in that case we get
	     the descent and ascent from the XFontStruct, instead.  The
	     RAW_CAP_HEIGHT property seems seldom to be supplied; we get it
	     from the ascent of the `X' character, which we assume to
	     exist.

	     These fields are used only for computing vertical offsets when
	     plotting label strings. */
	  {
	    Atom raw_descent_atom, raw_ascent_atom, raw_cap_height_atom;
	    bool descent_success, ascent_success, cap_height_success;
	    unsigned long font_raw_descent, font_raw_ascent, font_raw_cap_height;
	    
	    raw_descent_atom = XInternAtom (_plotter->x_dpy, 
					    "RAW_DESCENT", false);
	    raw_ascent_atom = XInternAtom (_plotter->x_dpy, 
					   "RAW_ASCENT", false);
	    raw_cap_height_atom = XInternAtom (_plotter->x_dpy, 
					       "RAW_CAP_HEIGHT", false);
	    
	    descent_success = 
	      XGetFontProperty (x_font_struct, 
				raw_descent_atom, 
				&font_raw_descent) ? true : false;
	    
	    ascent_success = 
	      XGetFontProperty (x_font_struct, 
				raw_ascent_atom, 
				&font_raw_ascent) ? true : false;
	    cap_height_success = 
	      XGetFontProperty (x_font_struct, 
				raw_cap_height_atom, 
				&font_raw_cap_height) ? true : false;

#ifdef DEBUG2
	    if (descent_success)
	      fprintf (stderr, "RAW_DESCENT property is \"%lu\"\n", 
		       font_raw_descent);
	    else
	      fprintf (stderr, "RAW_DESCENT property does not exist\n");
	    if (ascent_success)
	      fprintf (stderr, "RAW_ASCENT property is \"%lu\"\n", 
		       font_raw_ascent);
	    else
	      fprintf (stderr, "RAW_ASCENT property does not exist\n");
#endif

	    /* If no success, this must be a pre-X11R6 font of some kind
	       (so we can assume the transformation from user coordinates
	       to device coordinates is a multiple of the identity [?]).
	       So we get the descent and ascent from the XFontStruct and
	       inverse-transform them to `1000-pixel font units', assuming
	       that the pixel matrix is a multiple of the identity. */

	    if (!descent_success)
	      /* no RAW_DESCENT property, take descent from XFontStruct */
	      {
		font_raw_descent 
		  = IROUND(1000.0 * x_font_struct->descent 
			   / _plotter->drawstate->x_font_pixmatrix[3]);
#ifdef DEBUG2
		fprintf (stderr, "kludged RAW_DESCENT property is \"%lu\", from %d\n", 
			 font_raw_descent, x_font_struct->descent);
#endif		
	      }

	    if (!ascent_success)
	      /* no RAW_ASCENT property, take ascent from XFontStruct */
	      {
		font_raw_ascent 
		  = IROUND(1000.0 * x_font_struct->ascent 
			   / _plotter->drawstate->x_font_pixmatrix[3]);
#ifdef DEBUG2
		fprintf (stderr, "kludged RAW_ASCENT property is \"%lu\", from %d\n", 
			 font_raw_ascent, x_font_struct->ascent);
#endif		
	      }

	    if (!cap_height_success)
	      /* This one is much harder.  The RAW_CAP_HEIGHT property
		 seems seldom to be supplied, so we can't be sure that if
		 it isn't, the pixmatrix is a multiple of the identity.  If
		 the pixmatrix isn't a multiple of the identity, our
		 alternative approach (taking the cap height from the
		 ascent of the `X' character, if it's available) won't
		 work.  So in that case we punt: we declare the cap height
		 to be 75% of the font ascent. */
	      {

		if ('X' >= x_font_struct->min_char_or_byte2
		    && 'X' <= x_font_struct->max_char_or_byte2)
		  /* have `X' in the font */
		  {
		    int X = 'X' - x_font_struct->min_char_or_byte2;

		    if (is_zero[1] && is_zero[2] &&
			_plotter->drawstate->x_font_pixmatrix[3] != 0.0)
		      /* user frame->device frame preserves axes, etc. */
		      {
			/* two possibilities, depending on whether or not
			   map reverses the y coordinate */
			if (_plotter->drawstate->x_font_pixmatrix[3] > 0.0)
			  {
			    if (x_font_struct->per_char)
			      font_raw_cap_height
				= IROUND(1000.0 * x_font_struct->per_char[X].ascent
					 / _plotter->drawstate->x_font_pixmatrix[3]);
			    else
			      font_raw_cap_height
				= IROUND(1000.0 * x_font_struct->min_bounds.ascent
					 / _plotter->drawstate->x_font_pixmatrix[3]);
			  }
			else
			  {
			    if (x_font_struct->per_char)
			      font_raw_cap_height
				= - IROUND(1000.0 * x_font_struct->per_char[X].descent
					   / _plotter->drawstate->x_font_pixmatrix[3]);
			    else
			      font_raw_cap_height
				= - IROUND(1000.0 * x_font_struct->min_bounds.descent
					   / _plotter->drawstate->x_font_pixmatrix[3]);
			  }
		      }
		    else
		      /* coordinate axes not preserved, so define our
			 kludged RAW_CAP_HEIGHT to equal (3/4) of
			 RAW_ASCENT (what else could we do?) */
		      font_raw_cap_height = IROUND(0.75 * font_raw_ascent);
		  }
		else
		  /* don't have the letter `X' in the font, so define our
		     kludged RAW_CAP_HEIGHT to equal (3/4) of RAW_ASCENT
		     (what else can we do?) */
		  font_raw_cap_height = IROUND(0.75 * font_raw_ascent);
#ifdef DEBUG2
		fprintf (stderr, "kludged RAW_CAP_HEIGHT property is \"%lu\"\n", 
			 font_raw_cap_height);
#endif		
	      }

	    /* copy all 3 metrics into drawing state */
	    _plotter->drawstate->font_ascent 
	      = ((double)font_raw_ascent / 1000.0) * _plotter->drawstate->true_font_size;
	    _plotter->drawstate->font_descent
	      = ((double)font_raw_descent / 1000.0) * _plotter->drawstate->true_font_size;
	    _plotter->drawstate->font_cap_height
	      = ((double)font_raw_cap_height / 1000.0) * _plotter->drawstate->true_font_size;
	  }

	  /* we've set all fields, so we can return */
	  return;
	}
    }
  else
    {
#ifdef DEBUG2
      fprintf (stderr, "FONT property does not exist\n");
#endif
    }
  
  /* if we reached here, font doesn't have an XLFD name (so no pixel size
     field, and hence no rotation), or there's no FONT property at all (a
     bad situation) */

  _plotter->drawstate->font_is_iso8859_1 = false;

  {
    Atom pixel_size_atom;
    
    pixel_size_atom = XInternAtom (_plotter->x_dpy, "PIXEL_SIZE", false);
    if (XGetFontProperty (x_font_struct, pixel_size_atom, &retval))
      /* there's a PIXEL_SIZE property, so use it to compute font size */
      {
#ifdef DEBUG2
	fprintf (stderr, "PIXEL_SIZE property is \"%lu\"\n", retval);
#endif	
	size = (double)retval;
      }
    else
      /* no PIXEL_SIZE, so try to compute size from POINT_SIZE and
	 RESOLUTION_Y properties */
      {
	Atom resolution_y_atom;
	unsigned long point_size, resolution_y;
	
#ifdef DEBUG2
	fprintf (stderr, "PIXEL_SIZE property does not exist\n");
#endif
	resolution_y_atom = XInternAtom (_plotter->x_dpy, "RESOLUTION_Y", false);
	if (XGetFontProperty (x_font_struct, XA_POINT_SIZE, &point_size)
	    && (XGetFontProperty (x_font_struct, 
				  resolution_y_atom, &resolution_y)))
	  {
#ifdef DEBUG2
	    fprintf (stderr, "POINT_SIZE property is \"%lu\"\n", 
		     point_size);
	    fprintf (stderr, "RESOLUTION_Y property is \"%lu\"\n", 
		     resolution_y);
#endif	
	    size = (double)point_size * (double)resolution_y / 722.7;
	  }
	else 
	  /* we can't compute the font size legitimately, so punt: estimate
	     it from the XFontStruct (may not be reliable) */
	  {
#ifdef DEBUG2
	    fprintf (stderr, "POINT_SIZE and/or RESOLUTION_Y properties do not exist\n");
#endif
	    size = (double)(x_font_struct->ascent + x_font_struct->descent);
	  }
      }

    /* now that the font size is known, handcraft a pixmatrix for this
       (presumed) pre-XLFD font, as if it were an XLFD font */
    _plotter->drawstate->x_font_pixmatrix[0] = size;
    _plotter->drawstate->x_font_pixmatrix[1] = 0.0;
    _plotter->drawstate->x_font_pixmatrix[2] = 0.0;
    _plotter->drawstate->x_font_pixmatrix[3] = size;

    {
      double ux, uy;
      
      /* (ux, uy) is a sort of minimum inter-line displacement vector, in
	 the user frame */
      ux = XUV (0.0, size);
      uy = YUV (0.0, size);
      
      /* the true_font_size field is the length of this vector */
      _plotter->drawstate->true_font_size = sqrt(ux*ux + uy*uy);
    }
    
    /* for non-XLFD fonts, we use these alternative definitions (kludges)
       for the descent and ascent drawing state fields */
    _plotter->drawstate->font_descent 
      = (_plotter->drawstate->true_font_size 
	 * x_font_struct->descent 
	 / _plotter->drawstate->x_font_pixmatrix[3]);
    
    _plotter->drawstate->font_ascent 
      = (_plotter->drawstate->true_font_size 
	 * x_font_struct->ascent 
	 / _plotter->drawstate->x_font_pixmatrix[3]);

    _plotter->drawstate->font_cap_height
      = (_plotter->drawstate->true_font_size 
	 * x_font_struct->per_char['X'-x_font_struct->min_char_or_byte2].ascent
	 / _plotter->drawstate->x_font_pixmatrix[3]);
  }
}

/* Extract a field from an XLFD name string, by number, and return it, via
   a call to malloc.  If `name' doesn't appear to be an XLFD name, NULL is
   returned. */

static char *
#ifdef _HAVE_PROTOS
_xlfd_field(const char *name, int field)
#else
_xlfd_field(name, field)
     const char *name;
     int field;
#endif
{
  const char *p;
  const char *fields[NUM_XLFD_FIELDS];
  char *retstring;
  int len[NUM_XLFD_FIELDS];
  int i, n, m;
  /* split into fields at hyphens */
  for (p = name, i = 0, n = 0, m = 0; 
       *p && (i < NUM_XLFD_FIELDS); 
       p++, n++, m++)
    {
      if (*p == '-')
	{
	  if (i > 0)
	    len[i-1] = n;
	  n = 0;
	  fields[i++] = p;
	}
    }
  if (i < NUM_XLFD_FIELDS)
    return NULL;

  len[NUM_XLFD_FIELDS - 1] = strlen (name) - (m - 1); /* final field exhausts string */

  /* for len[] and fields[], each field includes initial hyphen */
  retstring = (char *)_plot_xmalloc (len[field] * sizeof(char));
  strncpy (retstring, fields[field] + 1, 
	   (unsigned int)(len[field] - 1)); /* skip initial - */
  retstring[len[field] - 1] = '\0';
  
  return retstring;
}     

/* _parse_pixmatrix() parses a string (the pixel string from an XLFD font
   name).  If the string is a scalar pixel size, the parsed pixel matrix
   (stored in d[]) is defined to be [size 0.0 0.0 size].  If the string is
   an actual pixel matrix, its four elements are copied into d[].

   This routine also sets the x_native_positioning field, depending on
   whether or not the pixel size was a scalar.  In the scalar case, native
   X11 positioning for characters within a string may be used; in the
   non-scalar case, it may not.

   It's in this routine that we use the advisory is_zero[] array, which is
   passed down from several levels above.  If any element of the pixel
   matrix is, or should be, quite close to zero, we set it to zero exactly.
   This works around the problem that silly, tiny floating point numbers
   (e.g., 4e-311) passed back from some X servers are so small they can't
   be manipulated arithmetically on DEC Alphas. */

static void
#ifdef _HAVE_PROTOS
_parse_pixmatrix(const char *pixel_string, double d[4], bool *x_native_positioning, bool is_zero[4]) 
#else
_parse_pixmatrix(pixel_string, d, x_native_positioning, is_zero) 
     const char *pixel_string; 
     double d[4]; 
     bool *x_native_positioning; 
     bool is_zero[4];
#endif
{ 
  int len, i;
  char *s[4];
  
  len = strlen (pixel_string);
  for (i = 0; i < 4; i++)
    s[i] = (char *)_plot_xcalloc (1, (len + 1) * sizeof(char));
  sscanf (pixel_string, "[ %s %s %s %s ]", s[0], s[1], s[2], s[3]);

  if (*(s[0]) && *(s[1]) && *(s[2]) && *(s[3]))
    /* if we got four nonempty strings, good... */
    {
      int j;
      
      for (j = 0; j < 4; j++)
	{
	  char *p;
	  
	  /* convert all hyphens to minuses */
	  for (p = s[j]; *p; p++)
	    if (*p == '~')
	      *p = '-';

	  /* convert strings to doubles */
	  if (is_zero[j])
	    /* set to zero _exactly_, no matter what the server says */
	    d[j] = 0.0;
	  else
	    sscanf (s[j], "%lf", &(d[j]));
	  *x_native_positioning = false;
	}
    }

  /* otherwise parse pixel field as a scalar integer size */
  else
    {
      int size;
      
      sscanf (pixel_string, "%d", &size);
      d[0] = (double)size;
      d[1] = 0.0;
      d[2] = 0.0;
      d[3] = (double)size;
      *x_native_positioning = true;
    }
  
  for (i = 0; i < 4; i++)
    free (s[i]);

  return;
}

/* This prepares a bit vector (length 256 bits, i.e. 32 bytes) indicating
   which characters in the range 1..255 are used in a string.  Final
   argument `include_X', if true, requests the character `X' should be
   included, even if it isn't present in the string.  `X' is special
   because we use it to retrieve the cap height. */

static void
#ifdef _HAVE_PROTOS
_string_to_bitvector (const unsigned char *s, unsigned char v[32], bool include_X)
#else
_string_to_bitvector (s, v, include_X)
     const unsigned char *s;
     unsigned char v[32];
     bool include_X;
#endif
{
  unsigned char c;
  unsigned int i, j;
  int k;

  for (k = 0; k < 32; k++)
    v[k] = 0;

  if (include_X)
    {
      c = 'X';
      i = c / 8;
      j = c % 8;
      v[i] |= (1 << j);
    }

  while ((c = *s) != (unsigned char)'\0')
    {
      i = c / 8;
      j = c % 8;
#ifdef DEBUG2
      fprintf (stderr, "saw char %d (i.e. %c), stored as %d,%d\n", c, c, i, j);
#endif
      v[i] |= (1 << j);
      s++;
    }
}

/* This writes a bitvector as a string, in the form used in X11R6-style
   charset subsetting.  Each range of chars may require the writing of up
   to 8 bytes, e.g. " 160_180". The list of ranges is contained within
   brackets. */

static void
#ifdef _HAVE_PROTOS
_print_bitvector (unsigned char v[32], char *s)
#else
_print_bitvector (s, v)
     unsigned char v[32];
     char *s;
#endif
{
  int i, num_ranges_output = 0, num_chars_output = 0;
  int start_of_range = 0;
  bool used;
  bool in_range = false;
  
  *s++ = '[';
  for (i = 0; i <= 256; i++)
    {
      if (i == 256)
	used = false;
      else
	used = (v[i / 8] & (1 << (i % 8))) ? true : false;

#ifdef DEBUG2
      if (used)
	fprintf (stderr, "stored char %d (i.e. %c), from %d,%d\n", i, i, i/8, i%8);
#endif

      if (used && in_range == false)
	/* begin new range */
	{
	  start_of_range = i;
	  in_range = true;
	}
      else if (used == false && in_range)
	/* end of range, so output the range */
	{
	  int hundreds, tens, ones;
	  bool hundreds_output;

	  if (num_chars_output > MAX_CHARSET_SUBSET_LIST_LENGTH - 8)
	    break;		/* abort to avoid buffer overrun */

	  if (num_ranges_output > 0)
	    /* use space as separator */
	    {
	      *s++ = ' ';
	      num_chars_output++;
	    }
	  
#ifdef DEBUG2
	  fprintf (stderr, "outputting character range %d..%d, i.e. %c..%c\n",
		   start_of_range, i-1, start_of_range, i-1);
#endif
	  if (start_of_range < (i - 1))
	    /* have a genuine range, start..(i-1), not a singleton */
	    {
	      /* output start of range, followed by underscore */
	      hundreds = start_of_range / 100;
	      tens = (start_of_range - hundreds * 100) / 10;
	      ones = start_of_range % 10;
	      hundreds_output = false;
	      if (hundreds > 0)
		{
		  *s++ = (char)'0' + hundreds;
		  hundreds_output = true;
		  num_chars_output++;
		}
	      if (hundreds_output || tens > 0)
		{
		  *s++ = (char)'0' + tens;
		  num_chars_output++;
		}
	      *s++ = (char)'0' + ones;
	      num_chars_output++;
	      *s++ = (char)'_';
	      num_chars_output++;	      
	    }

	  /* output end of range, which is i-1 */
	  hundreds = (i-1) / 100;
	  tens = ((i-1) - hundreds * 100) / 10;
	  ones = (i-1) % 10;
	  hundreds_output = false;
	  if (hundreds > 0)
	    {
	      *s++ = (char)'0' + hundreds;
	      hundreds_output = true;
	      num_chars_output++;
	    }
	  if (hundreds_output || tens > 0)
	    {
	      *s++ = (char)'0' + tens;
	      num_chars_output++;
	    }
	  *s++ = (char)'0' + ones;
	  num_chars_output++;

	  /* no longer in range */
	  in_range = false;
	  num_ranges_output++;
	}
    }
  *s++ = ']';
  /* add final null */
  *s = '\0';
}

static bool
#ifdef _HAVE_PROTOS
_is_a_subset (unsigned char set1[32], unsigned char set2[32])
#else
_is_a_subset (set1, set2)
     unsigned char set1[32];
     unsigned char set2[32];
#endif
{
  int i;
  bool retval = true;
  
  for (i = 0; i < 32; i++)
    if (set1[i] & ~(set2[i]))
      {
	retval = false;
	break;
      }

  return retval;
}