summaryrefslogtreecommitdiff
path: root/lib/encoding.c
blob: 432da4e60e4ffb91a2e1ae3a639263c576091e59 (plain)
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
/*
 * encodings.c
 *
 * definition of the char encodings used
 * Copyright (c) 1988-1993 Miguel Santana
 * Copyright (c) 1995-1999 Akim Demaille, Miguel Santana
 */

/*
 * This file is part of a2ps.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include "encoding.h"
#include "routines.h"
#include "jobs.h"
#include "message.h"
#include "pathwalk.h"
#include "pair_ht.h"
#include "fonts.h"
#include "xobstack.h"
#include "dsc.h"
#include "getshline.h"
#include "document.h"
#include "quotearg.h"
#include "strverscmp.h"

/* Suffix of the Encoding Description Files */
#define EDF_SUFFIX ".edf"


/* FIXME: THe comment is no longer exact
  Dealing with the encodings is a long and painful work.

  There are many things to be done, in as short time as possible.
  The big problem is to associate an array of the width of the
  characters for a given font in a given encoding (two keys).

  a2ps first loads the prologue definitions.  In that file, there are
  lines such as:

  %Face: Plain Courier
  /p {
  false UL
  false BX
  fc setfont
  Show
  } bind def

  By this line, it is requested to encode the font Courier, which
  will be used through the name fc.  One of the problems is that for
  instance Courier does not suppport Latin2 encoding and other.
  Then we define some substitution, related to each encoding.  As
  an example, in latin2.edf, there is the subsitution Courier->
  Courier-Ogonkify.

  So we must be carreful to separate various instanciation of the fonts
  (fc) from one encoding to another.  This is done through ps dictionaries.
  fc is define in latin1dict, latin2dict, with different encodings.  It
  works very well with the ps interpreters: there are no problems
  to encounter later, when using these dictionaries.

  Still, building them is painful if one wants to stay open.

  One may ask: << Why not
   %Face: Plain Courier
  /p {
  false UL
  false BX
  FontPlain setfont		%% Here is the difference
  Show
  >>
  The answer is that in that case if two faces use the same base
  font, them we use twice the memory we need.

  One may reply: << Why not
  %Face: Plain Courier
  /p {
  false UL
  false BX
  FontCourier setfont		%% Here is the difference
  Show
  >>
  The problem is then when somebody wants to use a separate Courier
  instance, with another size, in a header.  Then there should be two
  different FontCourier. Too bad.

  It gets even worse when one knows that all this cannot be resolved
  with the subsitution, since these are known _after_ the prologue
  is loaded.  And I don't want any more cross-references between
  prologues and encodings.

  So the decision, not great, but the easier, will be the second one,
  the one which uses too much memory:

  %Face: Plain Courier
  /p {
  false UL
  false BX
  FontPlain setfont		%% Here is the difference
  Show
  >>

  because it is the most open solution.  Especially if the prologue
  makes use of some other faces (in the headers for instance).
*/

/************************************************************************/
/*			encoding.map handling				*/
/************************************************************************/
/*
  These entries allow to define several aliases for a single encoding.
  This is extremely useful for instance when a2ps-the-prog parse a mail
  and finds tags that define the charset to use.  It could read 8859-1,
  or ISO-8859-1 or iso-8859-1 though the user would like latin1.

  The scheme, of course, should be much more general than just skipping
  ISO|iso-8859, since it is even _wrong_ for, say, latin5 (8859-9)

  From an implementation point of view, it is nothing but a double
  strings hash table (cf. pair_ht.[ch]).
 */
struct pair_htable *
encodings_map_new (void)
{
  return pair_table_new ();
}

void
encodings_map_free (struct pair_htable * table)
{
  pair_table_free (table);
}

/*
 * What is the KEY corresponding to ALIAS?
 */
static char *
encodings_map_resolve_alias (struct pair_htable * encodings_map,
			     const char * alias)
{
  return pair_get (encodings_map, alias);
}

/*
 * Read a sheets map file
 */
static int
load_encodings_map (struct a2ps_job * job, const char *file)
{
  return pair_table_load (job->encodings_map, file);
}

/*
 * Read the encodings.map file
 */
int
load_main_encodings_map (struct a2ps_job * job)
{
  char * file;

  /* System's */
  file = xpw_find_file (job->common.path, "encoding.map", NULL);
  load_encodings_map (job, file);
  if (msg_test (msg_enc))
    {
      fprintf (stderr, "Read encoding.map:\n");
      pair_table_list_long (job->encodings_map, stderr);
    }
  free (file);
  return 1;
}

/************************************************************************/
/*		     	wx handling					*/
/************************************************************************/
static inline unsigned int *
wx_new (void)
{
  int i;
  unsigned int *res = XMALLOC (unsigned int, 256);

  for (i = 0 ; i < 256 ; i++)
    res [i] = 0;

  return res;
}

static void
wx_self_print (unsigned int * wx, FILE * stream)
{
  int j;

  if (wx)
    for (j = 0 ; j < 256 ; j += 8)
      fprintf (stream,
	       "%3d: %04u %04u %04u %04u %04u %04u %04u %04u\n", j,
	       wx [j + 0], wx [j + 1], wx [j + 2], wx [j + 3],
	       wx [j + 4], wx [j + 5], wx [j + 6], wx [j + 7]);
  else
    fputs ("<No WX defined>\n", stream);
}


/************************************************************************/
/*		     fonts entries handling				*/
/************************************************************************/
/*
  Font entries are hashed, but they will be used only at
  initialization: the first thing to do will be to associate
  the font's to the face which uses this font.

  But it is not yet known.  First we read the information on the
  encoding required (which allows us to discover that for instance
  Courier is _not_ to use with Latin2 (use Courier-Ogonki), and
  later, reading the PS prologue, we will learn what face uses
  what font.  At this moment we will associate the font's wx to the
  face.
*/

/*
 * For a font (actually encoding for a given char set)
 * it wx.
 */
struct font_entry {
  char * key;		/* eg. Courier-Ogonki 				*/
  int used;		/* If used, need to be dump in the PS		*/
  int reencode;		/* E.g. Symbol is not to reencode		*/
  unsigned int * wx;	/* Not an array, because some fonts may
			 * share their wx (Courier familly for instance	*/
};

static unsigned long
font_entry_hash_1 (struct font_entry * entry)
{
  return_STRING_HASH_1 (entry->key);
}

static unsigned long
font_entry_hash_2 (struct font_entry * entry)
{
  return_STRING_HASH_2 (entry->key);
}

static int
font_entry_hash_cmp (struct font_entry * x, struct font_entry * y)
{
  return_STRING_COMPARE (x->key, y->key);
}

static int
font_entry_hash_qcmp (struct font_entry ** x, struct font_entry ** y)
{
  return_STRING_COMPARE ((*x)->key, (*y)->key);
}

/*
 * We make a copy of the name, but not of the array
 */
static inline struct font_entry *
font_entry_new (const char * name, unsigned int * wx)
{
  NEW (struct font_entry, res);
  res->key = xstrdup (name);
  res->used = false;
  res->wx = wx;
  return res;
}

/*
 * Free the memory used
 */
static inline void
font_entry_free (struct font_entry * item)
{
  free (item->key);
  free (item);
}

static void
font_entry_self_print (struct font_entry * entry, FILE * stream)
{
  fprintf (stream, "***** %s ***** (%s, %s) ",
	   entry->key,
	   entry->used ? "used" : "not used",
	   entry->reencode ? "to share between encodings" : "reencode");
  wx_self_print (entry->wx, stream);
}

/************************************************************************/
/*		     fonts entries hash table handling			*/
/************************************************************************/
static struct hash_table_s *
font_table_new (void)
{
  struct hash_table_s * res;

  res = XMALLOC (hash_table, 1);
  hash_init (res, 32,
	     (hash_func_t) font_entry_hash_1,
	     (hash_func_t) font_entry_hash_2,
	     (hash_cmp_func_t) font_entry_hash_cmp);
  return res;
}

static void
font_table_free (struct hash_table_s * table)
{
  hash_free (table, (hash_map_func_t) font_entry_free);
  free (table);
}

static void
font_table_self_print (struct hash_table_s * table, FILE * stream)
{
  int i;
  struct font_entry ** entries;
  entries = (struct font_entry **)
    hash_dump (table, NULL,
	       (hash_cmp_func_t) font_entry_hash_qcmp);

  for (i = 0 ; entries[i] ; i++)
    font_entry_self_print (entries [i], stream);
  putc ('\n', stream);
  free (entries);
}

/*
 * We make a copy of the name, but not of the array
 */
static inline void
font_entry_add (struct hash_table_s * table,
		const char * name, unsigned int * wx)
{
  hash_insert (table, font_entry_new (name, wx));
}

static inline struct font_entry *
font_entry_get (struct hash_table_s * table, const char * name)
{
  struct font_entry token, * item;
  token.key = (char *) name;
  item = (struct font_entry *) hash_find_item (table, &token);
  return item;
}

static unsigned int *
font_entry_get_wx (struct hash_table_s * table,
		   const char * name)
{
  return font_entry_get (table, name)->wx;
}

static int
font_entry_exists (struct hash_table_s * table, const char * name)
{
  return font_entry_get (table, name) != NULL;
}

static int
font_entry_is_used (struct hash_table_s * table, const char * name)
{
  return font_entry_get (table, name)->used;
}

static void
font_entry_set_used (struct hash_table_s * table, const char * name)
{
  font_entry_get (table, name)->used = true;
}

/************************************************************************/
/*		     encodings entries handling				*/
/************************************************************************/
/*
 * Association of suffixes rules, and corresponding style sheet
 * (The hashing is upon `alias')
 */
struct slantfont_info {
  char * name;
  char * src;
  float ratio;
};

struct encoding {
  char * key;			/* e.g. latin1			*/
  char * name;			/* e.g. ISO Latin 1		*/
  int    composite_flag;		/* flag for composite font	*/
  uchar * documentation;		/* Useful pieces of text	*/

  char * default_font;		/* When a font can't be used
				   define the font to use	*/
  struct pair_htable * substitutes;	/* e.g. in latin2, don't use
					 * Courier, but Courier-Ogonki	*/
  struct pair_htable * composite;

  struct slantfont_info     slantfont[NB_FACES];

  char * vector[256];	/* Define the char set			*/
  struct darray * font_names_used;
				/* E.g. Courier has been used, but
				 * Actually Courier_Ogonki is the real
				 * font used (cf infra)			*/
  struct hash_table_s * fonts;	/* Contains cells that are
				 * 1. name of font, 2. int wx[256] 	*/
  unsigned int * faces_wx[NB_FACES];

  unsigned int   composite_wx[NB_FACES];     /* fixed length font width */
  float          composite_ratio[NB_FACES];  /* size ratio of additonal and original font */
};

/*
 * Create an encoding, reading its associated file.wx
 */
static struct encoding *
encoding_new (const char * key)
{
  int i;

  NEW (struct encoding, res);

  res->key = xstrdup (key);
  res->name = NULL;
  res->default_font = NULL;
  res->documentation = NULL;
  res->composite_flag = false;

  /* Vector will be set by setup */
  res->substitutes = pair_table_new ();
  res->composite = pair_table_new ();
  res->slantfont[0].name = NULL;
  res->font_names_used = da_new ("List of font names", 10,
				 da_linear, 10,
				 (da_print_func_t) da_str_print,
				 (da_cmp_func_t) da_str_cmp);
  res->fonts = font_table_new ();
  for (i = 0 ; i < NB_FACES ; i++)
    res->faces_wx [i] = NULL;
  for (i = 0 ; base_faces [i] != -1 ; i++)
    res->faces_wx [base_faces [i]] = wx_new ();
  return res;
}

static void
encoding_free (struct encoding * encoding)
{
  int i;

  XFREE (encoding->key);
  XFREE (encoding->name);
  XFREE (encoding->default_font);
  XFREE (encoding->documentation);

  for (i = 0 ; i < 256 ; i++)
    free (encoding->vector [i]);

  pair_table_free (encoding->substitutes);
  da_free (encoding->font_names_used, (da_map_func_t) free);
  font_table_free (encoding->fonts);

  for (i = 0 ; base_faces [i] != -1 ; i++)
    free (encoding->faces_wx [base_faces [i]]);
  free (encoding);
}

/*
 * Add a subsitution in the current encoding
 */
static void
encoding_add_font_substitute (struct encoding * encoding,
			      const char * orig, const char * subs)
{
  pair_add (encoding->substitutes, orig, subs);
}

/*
 * Add a composite font in the current encoding
 */
static void
encoding_add_composite_font (struct encoding * encoding,
			      const char * orig, const char * subs,
			      int wx, float ratio)
{
  encoding->composite_flag = true;
  pair_add2 (encoding->composite, orig, subs, wx, ratio);
}

/*
 * Add a composite font in the current encoding
 */
static void
encoding_add_slant_font (struct encoding * encoding,
			 const char * new, const char * src,
			 float ratio)
{
  static num =  0;
  encoding->slantfont[num].name = strdup(new);
  encoding->slantfont[num].src  = strdup(src);
  encoding->slantfont[num].ratio = ratio;
  encoding->slantfont[num+1].name = NULL;
  num++;
}

/*
 * When FONT_NAME is used with ENCODING, return the
 * real font name to use (e.g., in latin2, Courier-Ogonki
 * should be returned when asked for Courier).
 *
 * Actually, now FONT_NAME can be a `,' separated list
 * of fonts desired, in decreasing order of preference
 */
const char *
encoding_resolve_font_substitute (struct a2ps_job * job,
				  struct encoding * encoding,
				  const char * font_list)
{
  const char * res = NULL;
  char * font_list_copy;
  char * font_name;

  astrcpy (font_list_copy, font_list);
  font_name = strtok (font_list_copy, ",<>;");

  do
    {
      /* Find if there is a substitute for that font */
      res = pair_get (encoding->substitutes, font_name);
      if (!res)
	/* No. Check if this font is supported */
	if (font_exists (job, font_name))
	  /* Avoid returning sth alloca'd */
	  res = xstrdup (font_name);
    }
  while (!res && (font_name = strtok (NULL, ",<>;")));

  /* We've found nothing interesting.  Last chance is the default
   * font */
  if (!res)
    {
      if (encoding->default_font)
	res = encoding->default_font;
      else
	error (1, 0, "Cannot find font %s, nor any substitute",
	       font_name);
    }

  message (msg_enc,
	   (stderr, "In encoding %s, composite font for %s is resolved as %s\n",
	    encoding->key, font_name, res));
  return res;
}

/*
 * Get composite font size and ratio
 */
static int
composite_font_info_get_wx(struct a2ps_job * job,
			   struct encoding * encoding,
			   const char * font_list)
{
  int wx= -1;
  char * font_list_copy;
  char * font_name;
  astrcpy (font_list_copy, font_list);
  font_name = strtok (font_list_copy, ",<>;");

  wx = pair_get_wx (encoding->composite, font_name);
  if (wx<0)
      wx = pair_get_wx (encoding->composite, "default_composite__");

  return wx;
}

static float
composite_font_info_get_ratio(struct a2ps_job * job,
			      struct encoding * encoding,
			      const char * font_list)
{
  float ratio= -1;
  char * font_list_copy;
  char * font_name;

  astrcpy (font_list_copy, font_list);
  font_name = strtok (font_list_copy, ",<>;");

  ratio = pair_get_ratio (encoding->composite, font_name);
  if (ratio<0)
      ratio = pair_get_ratio (encoding->composite, "default_composite__");
  return ratio;
}

const char *
encoding_resolve_composite_font (struct a2ps_job * job,
				  struct encoding * encoding,
				  const char * font_list)
{
  const char * res = NULL;
  char * font_list_copy;
  char * font_name;

  astrcpy (font_list_copy, font_list);
  font_name = strtok (font_list_copy, ",<>;");

  /* Find if there is a substitute for that font */
  res = pair_get (encoding->composite, font_name);

  /* We've found nothing interesting.  Last chance is the default
   * font */
  if (!res)
    {
      res = pair_get (encoding->composite, "default_composite__");

      if (!res)
	error (1, 0, "Cannot find font %s, nor any composite font",
	       font_name);
    }
  
  message (msg_enc,
	   (stderr, "In encoding %s, font %s is resolved as %s\n",
	    encoding->key, font_name, res));
  return res;
}

/*
 * Read of *.edf file, given its path
 */
#define GET_TOKEN(from) (strtok ((from), " \t\n"))
#define GET_LINE_TOKEN(from) (strtok ((from), "\n"))
#define CHECK_TOKEN()                                                   \
  if (token2 == NULL)                                                   \
    error_at_line (1, 0, fname, firstline,				\
		   _("missing argument for `%s'"), quotearg (token));

static void
load_encoding_description_file (a2ps_job * job,
				struct encoding * encoding)
{
  FILE * stream;
  char * buf = NULL;
  char * fname;
  size_t bufsiz = 0;
  char * token, * token2;
  int firstline = 0, lastline = 0;
  static int first_time = 1;
  static struct obstack documentation_stack;

  if (first_time)
    {
      /* Initialize the obstack we use to record the docuementation
       * lines */
      first_time = 0;
      obstack_init (&documentation_stack);
    }

  message (msg_enc,
	   (stderr, "Loading encoding file `%s.edf'\n", encoding->key));
  fname = xpw_find_file (job->common.path, encoding->key, ".edf");
  stream = xrfopen (fname);

  while (getshline_numbered (&firstline, &lastline,
			     &buf, &bufsiz, stream) != -1)
    {
      token = GET_TOKEN (buf);

      if (!token)
	/* Blank line */
	continue;

      if (strequ (token, "Vector:"))
	{
	  int c = 0;
	  char buf2 [256];

	  while (c < 256)
	    {
	      if (!fgets (buf2, sizeof (buf2), stream))
		error_at_line (1, 0, fname, firstline,
			       _("missing argument for `%s'"), "`Vector:'");
	      lastline++;
	      token = GET_TOKEN (buf2);
	      encoding->vector [c++] = xstrdup (token);
	      while ((token2 = GET_TOKEN (NULL)))
		encoding->vector [c++] = xstrdup (token2);
	  }
	}
      else if (strequ (token, "Name:"))
	{
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  encoding->name = xstrdup (token2);
	}
      else if (strequ (token, "Default:"))
	{
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  encoding->default_font = xstrdup (token2);
	}
      else if (strequ (token, "Documentation"))
	{
	  char * documentation;
	  char buf2 [BUFSIZ];
	  size_t read_length;

	  /* We don't use getshline, because we do want the
	   * ``empty'' lines to be kept: they separate the
	   * paragraphs */
	  while (fgets (buf2, sizeof(buf2), stream)
		 && !strprefix ("EndDocumentation", buf2))
	    {
	      read_length = strlen (buf2);
	      if (read_length < sizeof (buf2))
		lastline++;
	      /* Grow the obstack with the doc content */
	      obstack_grow (&documentation_stack, buf2, read_length);
	    }
	  if (!strprefix ("EndDocumentation", buf2))
	    error (1, 0, fname, firstline,
		   _("missing argument for `%s'"), "`Documentation'");
	  /* Finish the obstack, and store in the encoding entry */
	  obstack_1grow (&documentation_stack, '\0');
	  documentation =
	    (char *) obstack_finish (&documentation_stack);
	  obstack_free (&documentation_stack, documentation);
	  encoding->documentation = xustrdup (documentation);
    	}
      else if (strequ (token, "Substitute:"))
	{
	  char * orig, * subs;

	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  orig = token2;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  subs = token2;
	  encoding_add_font_substitute (encoding, orig, subs);
	}
      else if (strequ (token, "DefaultComposite:"))
	{
	  char * orig, * subs;
	  int wx;
	  float ratio;

	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  subs = token2;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  wx = (int)atof(token2)*1000;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  ratio = atof(token2);
	  encoding_add_composite_font(encoding, "default_composite__",
				      subs, wx, ratio);
	}
      else if (strequ (token, "Composite:"))
	{
	  char * orig, * subs;
	  int wx;
	  float ratio;

	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  orig = token2;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  subs = token2;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  wx = (int)atof(token2)*1000;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  ratio = atof(token2);
	  encoding_add_composite_font(encoding, orig, subs, wx, ratio);
	}
      else if (strequ (token, "SlantFont:"))
	{
	  char * new, * src;
	  float ratio;
	  unsigned int num;

	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  new = token2;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  src = token2;
	  token2 = GET_TOKEN (NULL);
	  CHECK_TOKEN ();
	  ratio = atof(token2);
	  for (num = 0 ; encoding->slantfont[num].name ; num ++ );
	  if (num > sizeof encoding->slantfont - 1){
	      error_at_line (1, 0, fname, firstline,
			   _("too many slant font: `%s'"), new);
	  }
	  encoding_add_slant_font(encoding, new, src, ratio);
	}
      else
        error_at_line (1, 0, fname, firstline,
                       _("invalid option `%s'"), quotearg (token));

    }
  fclose (stream);
  free (buf);
  free (fname);
}

/*
 * Used by --list-encodings
 */
static void
encoding_print_signature (struct encoding * item, FILE * stream)
{
  int i, title_len;

  title_len = (strlen (" ()")
	       + strlen (item->name)
	       + strlen (item->key));
  fprintf (stream, "%s (%s)\n", item->name, item->key);
  for (i = 0 ; i < title_len ; i++)
    putc ('-', stream);
  putc ('\n', stream);

  documentation_print_plain (item->documentation, "%s", stream);
}

/*
 * Output the correct setup of ENCODING
 */
static void
encoding_output_ps_vector (struct a2ps_job * job,
			   struct encoding * encoding)
{
  int c;

  output (job->ps_encodings, "%%%%BeginResource: encoding %sEncoding\n",
	  encoding->name);
  output (job->ps_encodings, "/%sEncoding [",
	  encoding->name);
  for (c = 0 ; c < 256 ; c++)
    {
      if (!(c % 8))
	output_char (job->ps_encodings, '\n');
      output (job->ps_encodings, "/%s ", encoding->vector [c]);
    }
  output (job->ps_encodings, "\n] def\n");
  output (job->ps_encodings, "%%%%EndResource\n");
}

/*
 * Used for very verbose reports
 */
void
encoding_self_print (struct encoding * item, FILE * stream)
{
  int c;

  encoding_print_signature (item, stream);

  if (! IS_EMPTY (item->default_font))
    fprintf (stream, "Default font is `%s'\n", item->default_font);

  fprintf (stream, "Substitution of fonts:\n");
  pair_table_list_long (item->substitutes, stream);
  fprintf (stream, "Name of fonts used (before substitution):\n");
  da_self_print (item->font_names_used, stream);

  fprintf (stream, "Encoding array:");
  for (c = 0 ; c < 256 ; c++)
    {
      if (!(c % 8))
	putc ('\n', stream);
      fprintf (stream, "%-10s ", item->vector [c]);
    }
  putc ('\n', stream);

  fprintf (stream, "Fonts:\n");
  font_table_self_print (item->fonts, stream);
  if (msg_test (msg_enc))
    {
      enum face_e face;
      int i;
      fprintf (stream, "Faces:\n");
      for (i = 0 ; base_faces [i] != -1 ; i++)
	{
	  face = base_faces [i];
	  fprintf (stream, "Face %s (%d)\n", face_to_string (face), face);
	  wx_self_print (item->faces_wx [face], stream);
	}
    }
}

/*
 * Return the name of ENC
 */
const char *
encoding_get_name (struct encoding * enc)
{
  return enc->name;
}

/*
 * Return the key of ENC
 */
const char *
encoding_get_key (struct encoding * enc)
{
  return enc->key;
}

int
encoding_char_exists (struct encoding * enc,
			    enum face_e face, uchar c)
{
  return enc->faces_wx[face][c];
}

/*
 * Return the flag of composite flag
 */
int
encoding_get_composite_flag (struct encoding * enc)
{
  return enc->composite_flag;
}

/*
 * Prepare the environment (a dictionary) for the support
 * of ENCODING, dump it into STREAM.
 *
 * This routine is called at the end of the whole job, while
 * undiverting, so that everything we need to know is known.
 */
static void
dump_encoding_setup (FILE * stream,
		     struct a2ps_job * job,
		     struct encoding * encoding)
{
  size_t i, nb;
  size_t ns;
  const char * real_font_name;		/* After subsitution	*/
  char ** font_names = (char **) encoding->font_names_used->content;


  /* How many fonts are there? */
  da_qsort (encoding->font_names_used);
  da_unique (encoding->font_names_used, (da_map_func_t) free);

  /* We do not want to reencode the fonts that should not be
   * reencoded */
  for (i = 0 ; i < encoding->font_names_used->len ; i++)
    {
      real_font_name = encoding_resolve_font_substitute (job, encoding,
							 font_names [i]);
      if (!font_is_to_reencode (job, real_font_name))
	da_remove_at (encoding->font_names_used, i, (da_map_func_t) free);
    }

  /* The number of fonts that, finally, have to be encoded
   * in the current ENCODING	*/
  nb = encoding->font_names_used->len;

  /* The number of slant fonts */
  for (i= 0, ns=0 ; encoding->slantfont[i].name ; i++ )
      ns++;

  /* Create the dictionary and fill it */
  fprintf (stream, "%% Dictionary for %s support\n",
	  encoding->name);
  fprintf (stream, "/%sdict %d dict begin\n", encoding->key,
	   (encoding->composite_flag == true)? nb+nb+ns:nb+ns);
  for (i = 0 ; i < nb ; i++)
    fprintf (stream, "  /f%s %sEncoding /%s reencode_font\n",
	     font_names [i],
	     encoding->name,
	     encoding_resolve_font_substitute (job, encoding, font_names [i]));

  /* Slant font setting */
  for (i = 0 ; encoding->slantfont[i].name ; i++ )
    fprintf (stream, "  /%s /%s %f slantfont  definefont pop\n",
	     encoding->slantfont[i].name,
	     encoding->slantfont[i].src,
	     encoding->slantfont[i].ratio);

  /*
   * Composite font setting.
   * If kanji font size is larger than alphabet character, 
   * set base font size to kanji charactor size.
   */
  if (encoding->composite_flag == true) {
    for (i = 0 ; i < nb ; i++)
      fprintf (stream, "  /f%s /f%s /%s %f %f false  compositefont "
	               "%f scalefont def\n",
	       font_names [i],
	       font_names [i],
	       encoding_resolve_composite_font (job, encoding, font_names [i]),
	       encoding->composite_ratio[i],
	       (encoding->composite_ratio[i] > 1.0)?
	       0: (1-encoding->composite_ratio[i])/2.0,
	       (encoding->composite_ratio[i] > 1.0)?
	       1.0/encoding->composite_ratio[i]: 1.0 );
  }
  fputs ("currentdict end def\n", stream);
}

/************************************************************************/
/*		     encodings hash table handling			*/
/************************************************************************/
/*
 * 1. hash table service routines on cells
 */
static unsigned long
encoding_hash_1 (struct encoding * entry)
{
  return_STRING_HASH_1 (entry->key);
}

static unsigned long
encoding_hash_2 (struct encoding * entry)
{
  return_STRING_HASH_2 (entry->key);
}

static int
encoding_hash_cmp (struct encoding * x, struct encoding * y)
{
  return_STRING_COMPARE (x->key, y->key);
}

static int
encoding_hash_qcmp (struct encoding ** x,
			  struct encoding ** y)
{
  return_STRING_COMPARE ((*x)->key, (*y)->key);
}

/*
 * 2. Hash table routines
 */
struct hash_table_s *
encodings_table_new (void)
{
  struct hash_table_s * res;

  res = XMALLOC (hash_table, 1);
  hash_init (res, 32,
	     (hash_func_t) encoding_hash_1,
	     (hash_func_t) encoding_hash_2,
	     (hash_cmp_func_t) encoding_hash_cmp);
  return res;
}

/*
 * Free the table and content
 */
void
encodings_table_free (struct hash_table_s * table)
{
  hash_free (table, (hash_map_func_t) encoding_free);
  free (table);
}

/*
 * Create an encoding, reading its associated file.edf
 */
static void
encoding_setup (struct a2ps_job * job,
		      struct encoding * encoding)
{
  char * cp;

  load_encoding_description_file (job, encoding);
  switch (job->output_format)
    {
    case ps:
    case eps:     /* Producing PostScript */
      /* FIXME: Remove this
       * Include its encoding definition */
      /* This, too, should be handled by the pseudo PDD files */
      cp = ALLOCA (char, strlen (encoding->name) + strlen ("Encoding") + 1);
      sprintf (cp, "%sEncoding", encoding->name);

      add_supplied_resource (job, "encoding", cp);
      encoding_output_ps_vector (job, encoding);
      break;
    }
}

/*
 * Add an encoding in the hash table,
 * Reading its associated file.edf
 */
static void
encoding_add (struct a2ps_job * job, const char * key)
{
  struct encoding * encoding;

  encoding = encoding_new (key);
  encoding_setup (job, encoding);

  /* If yet the association between faces and fonts is known,
   * get the WX per face */
  if (face_eo_font_is_set (job))
    encoding_build_faces_wx (job, encoding);
  if (msg_test (msg_enc))
    encoding_self_print (encoding, stderr);
  hash_insert (job->encodings, encoding);
}

void
encoding_add_font_name_used (struct encoding * encoding,
				   const char * name)
{
  da_append (encoding->font_names_used, xstrdup (name));
}

/*
 * Make an encoding do the association between the fonts
 * and the faces, so that the faces can be immediately used when
 * looking for the wx.
 *
 * The resolution of substitution for the fonts must be done here too,
 * because it depends on the encoding.
 */
void
encoding_build_faces_wx (a2ps_job * job, struct encoding * encoding)
{
  int i;
  enum face_e face;
  const char * true_font_name;

  for (i = 0 ; base_faces [i] != -1 ; i++)
    {
      face = base_faces [i];
      encoding_add_font_name_used (encoding,
				   job->face_eo_font [face]);
      /* E.g. in Latin 2, don't use Courier but Courier-Ogonki */
      true_font_name =
	encoding_resolve_font_substitute (job, encoding,
					  job->face_eo_font [face]);
      /* Get the wx related to the FACE */
      font_info_get_wx_for_vector (job,
				   true_font_name,
				   encoding->vector,
				   encoding->faces_wx [face]);

      if (encoding->composite_flag)
	{
	  encoding->composite_ratio[i] =
	    composite_font_info_get_ratio(job, encoding, 
					  job->face_eo_font [face]);

	  encoding->composite_wx[i] =
	    composite_font_info_get_wx(job, encoding, 
				       job->face_eo_font [face]);

	  /* If kanji font size is larger than alphabet character, 
	     fit kanji charactor size to base font size */
	  if (encoding->composite_ratio[i] < 1.0)
	      encoding->composite_wx[i] *= encoding->composite_ratio[i]; 
	}
    }
}

/*
 * Retreive an encoding
 */
static struct encoding *
encoding_get (struct a2ps_job * job, const char * key)
{
  struct encoding token, *res;

  token.key = (char *) key;
  res = (struct encoding *) hash_find_item (job->encodings, &token);

  if (!res)
    {	/* The encoding has never been read yet */
      encoding_add (job, key);
      res = (struct encoding *) hash_find_item (job->encodings, &token);
    }
  return res;
}

/*
 * Return the encoding and NULL if none
 */
struct encoding *
get_encoding_by_alias (struct a2ps_job * job, char * alias)
{
  const char * key;

  key = encodings_map_resolve_alias (job->encodings_map, strlower (alias));
  if (key)
    return encoding_get (job, key);
  else
    /* This is not a valid alias */
    return NULL;
}

/*
 * Prepare all the encodings used.  This is easy: there
 * are all the members of JOB->encodings
 */
void
dump_encodings_setup (FILE * stream,
		      struct a2ps_job * job)
{
  int i;
  struct encoding ** encodings;

  /* Get the list of the encodings */
  encodings = (struct encoding **)
    hash_dump (job->encodings, NULL,
	       (hash_cmp_func_t) encoding_hash_qcmp);

  for (i = 0 ; encodings [i] ; i++)
    dump_encoding_setup (stream, job, encodings [i]);

  free (encodings);
}

/************************************************************************/
/*		     Computing the width of a char/string		*/
/************************************************************************/
/*
 *	Returns the WX of a char (including M- and ^)
 */
unsigned int
char_WX (a2ps_job * job, uchar c)
{
#define _WX_(char)  (job->encoding->faces_wx[job->status->face][(int) char])
  unsigned int wx = _WX_(c);

  /* Only printable characters have a positive wx */
  if (wx)
    return wx;

  switch (job->unprintable_format)
    {
    case hexa:
      {
	char buf [3];
	sprintf (buf, "%02x", c);
	return _WX_ ('\\') + _WX_('x') + _WX_ (buf[0]) + _WX_ (buf[1]);
      }

    case octal:
      {
	char buf [4];
	sprintf (buf, "%03o", c);
	return (_WX_ ('\\')
		+ _WX_ (buf [0]) + _WX_ (buf [1]) + _WX_ (buf [2]));
      }

    case space:
      return _WX_(' ');

    case question_mark:
      return _WX_('?');

    case caret:
      if (0177 < c)
	{
	  wx += _WX_('M') + _WX_('-');
	  c &= 0177;
	}
      if (c == 0177)
	wx += _WX_('^') + _WX_('?');
      else if (c < ' ')
	wx += _WX_ ('^') + _WX_ (c + '@');
      else
	wx += _WX_ (c);
      return wx;

    case Emacs:
      if (0177 < c)
	{
	  wx += _WX_('M') + _WX_('-');
	  c &= 0177;
	}
      if (c == 0177)
	wx += _WX_('C') + _WX_('-') + _WX_('?');
      else if (c < ' ')
	wx += _WX_('C') + _WX_('-') + _WX_ (c + '@');
      else
	wx += _WX_ (c);
      return wx;

    default:
      abort ();
    }

  return 0;	/* For -Wall */
}

unsigned int
char_composite_WX (a2ps_job * job, uchar c)
{
  return (job->encoding->composite_wx[job->status->face]/
	  job->encoding->composite_ratio[job->status->face]);
}

/*
 *	Returns the WX of a string (including M- and ^)
 */
unsigned int
string_WX (a2ps_job * job, uchar * string)
{
  unsigned int result=0;

  for (/* skip */; *string ; string ++)
    result += char_WX(job, *string);

  return result;
}

/*
 * Use this encoding now
 */
void
set_encoding (struct a2ps_job * job, struct encoding * enc)
{
  job->encoding = enc;
}

/* Compare names with strverscmp, so that latin 15 is after latin 2.  */

static int
da_encoding_name_cmp (char * key1, char * key2, struct a2ps_job * job)
{
  return strverscmp ((char *) encoding_get (job, key1)->name,
		     (char *) encoding_get (job, key2)->name);
}

/*
 * Report the known encodings for --list-features
 */
void
list_encodings_short (a2ps_job * job, FILE * stream)
{
  fputs (_("Known Encodings"), stream);
  putc ('\n', stream);
  pw_lister_on_suffix (stream, job->common.path, EDF_SUFFIX);
}

/*
 * Report the known encodings for --list-encodings
 */
void
list_encodings_long (a2ps_job * job, FILE * stream)
{
  struct darray * entries;
  struct encoding * encoding;
  size_t i;

  entries = pw_glob_on_suffix (job->common.path, EDF_SUFFIX);

  /* We want them to be in order of the names, not keys */
  da_qsort_with_arg (entries,
		     (da_cmp_arg_func_t) da_encoding_name_cmp, job);

  fputs (_("Known Encodings"), stream);
  putc ('\n', stream);

  for (i = 0 ; i < entries->len ; i++)
    {
      /* Don't forget to cut the suffix */
      encoding = encoding_get (job, entries->content[i]);
      encoding_print_signature (encoding, stream);
      putc ('\n', stream);
    }
  da_free (entries, (da_map_func_t) free);
}
/************************************************************************/
/*		Report in Texinfo format				*/
/************************************************************************/
/*
 * Print a short signature (i.e., name, comments)
 * In texinfo format
 */
static void
encoding_texinfo_print_signature (struct encoding * encoding,
					FILE * stream)
{
  fprintf (stream, "@deftp {Encoding} {%s} (@file{%s.edf})\n",
	   encoding->name, encoding->key);

  documentation_print_texinfo (encoding->documentation, "%s", stream);
  fputs ("@end deftp\n\n", stream);
}

/*
 * Report the known encodings for --list-encodings
 */
void
list_texinfo_encodings_long (a2ps_job * job, FILE * stream)
{
  struct darray * entries;
  struct encoding * encoding;
  unsigned int i;

  entries = pw_glob_on_suffix (job->common.path, EDF_SUFFIX);

  /* We want them to be in order of the names, not keys */
  da_qsort_with_arg (entries,
		     (da_cmp_arg_func_t) da_encoding_name_cmp, job);

  fputs ("The known encodings are:\n", stream);

  for (i = 0 ; i < entries->len ; i++)
    {
      /* Don't forget to cut the suffix */
      encoding = encoding_get (job, entries->content[i]);
      encoding_texinfo_print_signature (encoding, stream);
    }
  da_free (entries, (da_map_func_t) free);
}