summaryrefslogtreecommitdiff
path: root/pango/pangox.c
blob: 5021c9dc84fa33595f86bccfad7d87b0c37d9ad2 (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
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
/* pangox.c: Routines for handling X fonts
 *
 * Copyright (C) 1999 Red Hat Software
 * Copyright (C) 2000 SuSE Linux Ltd
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <string.h>
#include <stdlib.h>
#include <math.h>

#include <X11/Xlib.h>
#include "pangox.h"
#include "pango-utils.h"
#include "pangox-private.h"
#include "pango-intset.h"
#include "modules.h"

#define PANGO_X_UNKNOWN_FLAG 0x10000000

#define PANGO_LIGATURE_HACK_DEBUG

#include "config.h"

#define PANGO_TYPE_X_FONT              (pango_x_font_get_type ())
#define PANGO_X_FONT(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_X_FONT, PangoXFont))
#define PANGO_X_FONT_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), PANGO_TYPE_X_FONT, PangoXFontClass))
#define PANGO_X_IS_FONT(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_X_FONT))
#define PANGO_X_IS_FONT_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), PANGO_TYPE_X_FONT))
#define PANGO_X_FONT_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), PANGO_TYPE_X_FONT, PangoXFontClass))

typedef struct _PangoXFontClass   PangoXFontClass;
typedef struct _PangoXMetricsInfo PangoXMetricsInfo;
typedef struct _PangoXContextInfo PangoXContextInfo;
typedef struct _PangoXLigatureInfo   PangoXLigatureInfo;
typedef struct _PangoXLigatureSource PangoXLigatureSource;

#ifndef HAVE_STRTOK_R
/* This implementation of strtok_r comes from the GNU C library.
 * Copyright (C) 1991, 1996, 1997, 1998, 1999, 2001 Free Software Foundation, Inc.
 */
static char *
my_strtok_r (char       *s,
	     const char *delim,
	     char      **save_ptr)
{
  char *token;

  if (s == NULL)
    s = *save_ptr;

  /* Scan leading delimiters.  */
  s += strspn (s, delim);
  if (*s == '\0')
    {
      *save_ptr = s;
      return NULL;
    }

  /* Find the end of the token.  */
  token = s;
  s = strpbrk (token, delim);
  if (s == NULL)
    /* This token finishes the string.  */
    *save_ptr = token + strlen (token);
  else
    {
      /* Terminate the token and make *SAVE_PTR point past it.  */
      *s = '\0';
      *save_ptr = s + 1;
    }
  return token;
}
#else
#define my_strtok_r strtok_r
#endif /* HAVE_STRTOK_R */

static int
hex_to_integer (const char *s) 
{
  int a;
  char *end_ptr;
  
  if (!*s)
    return (gunichar)-1;

  a = strtol (s, &end_ptr, 16);
  if (*end_ptr)
    return (gunichar)-1;  /* Invalid characters in string */
    
  if (a <= 0 || a >= 0xffff)
    return (gunichar)-1; /* Character out of range */
  
  return a;
}

static PangoIntSet *
parse_gintset_spec (char *s) 
{
  char *m = NULL;
  PangoIntSet *set = pango_int_set_new ();
  s = my_strtok_r (s, ",", &m);
  while (s)
    {
      char *p = strchr (s, '-');
      if (!p) 
	{
	  int i = hex_to_integer (s);
	  if (i != -1)
	    pango_int_set_add (set, i);
	}
      else 
	{
	  int start, end;
	  *p = 0;
	  p++;
	  start = hex_to_integer (s);
	  end = hex_to_integer (p);
	  if (start != -1 && end != -1)
	    pango_int_set_add_range (set, start, end);
	}
      s = my_strtok_r (NULL, ",", &m);
    }
  return set;
}

struct _PangoXSubfontInfo
{
  char *xlfd;
  XFontStruct *font_struct;
  gboolean     is_1byte;
  int          range_byte1;
  int          range_byte2;
  
  /* hash table mapping setnames to PangoIntSets */
  GHashTable *ligature_sets;
   
  PangoXLigatureInfo *ligs;
  int n_ligs;
};

struct _PangoXMetricsInfo
{
  const char *sample_str;
  PangoFontMetrics *metrics;
};

struct _PangoXContextInfo
{
  PangoGetGCFunc  get_gc_func;
  PangoFreeGCFunc free_gc_func;
};

struct _PangoXFontClass
{
  PangoFontClass parent_class;
};

struct _PangoXLigatureSource
{
  gboolean is_set;
  union {
    PangoIntSet *set;
    gunichar glyph;
  } data;
};

struct _PangoXLigatureInfo 
{
  int n_source;
  PangoXLigatureSource *source;

  gunichar *dest;
  int n_dest;
};

static PangoFontClass *parent_class;	/* Parent class structure for PangoXFont */

static void pango_x_font_class_init (PangoXFontClass *class);
static void pango_x_font_init       (PangoXFont      *xfont);
static void pango_x_font_dispose    (GObject         *object);
static void pango_x_font_finalize   (GObject         *object);

static PangoFontDescription *pango_x_font_describe          (PangoFont        *font);
static PangoCoverage *       pango_x_font_get_coverage      (PangoFont        *font,
							     PangoLanguage    *language);
static PangoEngineShape *    pango_x_font_find_shaper       (PangoFont        *font,
							     PangoLanguage    *language,
							     guint32           ch);
static void                  pango_x_font_get_glyph_extents (PangoFont        *font,
							     PangoGlyph        glyph,
							     PangoRectangle   *ink_rect,
							     PangoRectangle   *logical_rect);
static PangoFontMetrics *    pango_x_font_get_metrics       (PangoFont        *font,
							     PangoLanguage    *language);

static PangoXSubfontInfo * pango_x_find_subfont    (PangoFont          *font,
						    PangoXSubfont       subfont_index);
static XCharStruct *       pango_x_get_per_char    (PangoFont          *font,
						    PangoXSubfontInfo  *subfont,
						    guint16             char_index);
static gboolean            pango_x_find_glyph      (PangoFont          *font,
						    PangoGlyph          glyph,
						    PangoXSubfontInfo **subfont_return,
						    XCharStruct       **charstruct_return);
static XFontStruct *       pango_x_get_font_struct (PangoFont          *font,
						    PangoXSubfontInfo  *info);

static void     pango_x_get_item_properties (PangoItem      *item,
					     PangoUnderline *uline,
					     PangoAttrColor *fg_color,
					     gboolean       *fg_set,
					     PangoAttrColor *bg_color,
					     gboolean       *bg_set);

static void font_struct_get_ligatures (PangoFontMap *map,
				       Display *display, 
				       XFontStruct *fs, 
				       PangoXSubfontInfo *info);

static inline PangoXSubfontInfo *
pango_x_find_subfont (PangoFont  *font,
		      PangoXSubfont subfont_index)
{
  PangoXFont *xfont = (PangoXFont *)font;
  
  if (subfont_index < 1 || subfont_index > xfont->n_subfonts)
    {
      g_warning ("Invalid subfont %d", subfont_index);
      return NULL;
    }
  
  return xfont->subfonts[subfont_index-1];
}

static void
pango_x_make_font_struct (PangoFont *font, PangoXSubfontInfo *info)
{
  PangoXFont *xfont = (PangoXFont *)font;
  PangoXFontCache *cache;

  cache = pango_x_font_map_get_font_cache (xfont->fontmap);
  
  info->font_struct = pango_x_font_cache_load (cache, info->xlfd);
  if (!info->font_struct)
    {
      g_warning ("Cannot load font for XLFD '%s\n", info->xlfd);

      /* Prevent a segfault, but probably not much more */
      info->font_struct = pango_x_font_cache_load (cache, "fixed");
    }
  
  info->is_1byte = (info->font_struct->min_byte1 == 0 && info->font_struct->max_byte1 == 0);
  info->range_byte1 = info->font_struct->max_byte1 - info->font_struct->min_byte1 + 1;
  info->range_byte2 = info->font_struct->max_char_or_byte2 - info->font_struct->min_char_or_byte2 + 1;
  font_struct_get_ligatures (xfont->fontmap, xfont->display, info->font_struct, info);
}

static inline XFontStruct *
pango_x_get_font_struct (PangoFont *font, PangoXSubfontInfo *info)
{
  if (!info->font_struct)
    pango_x_make_font_struct (font, info);
  
  return info->font_struct;
}

/**
 * pango_x_get_context:
 * @display: an X display (As returned by XOpenDisplay().)
 * 
 * Retrieves a #PangoContext appropriate for rendering with X fonts on the
 * given display.
 * 
 * Return value: the new #PangoContext.
 **/
PangoContext *
pango_x_get_context (Display *display)
{
  PangoContext *result;
  PangoXContextInfo *info;
  int i;
  static gboolean registered_modules = FALSE;
  
  g_return_val_if_fail (display != NULL, NULL);  
  
  if (!registered_modules)
    {
      registered_modules = TRUE;
      
      for (i = 0; _pango_included_x_modules[i].list; i++)
        pango_module_register (&_pango_included_x_modules[i]);
    }
  
  result = pango_context_new ();
  
  info = g_new (PangoXContextInfo, 1);
  info->get_gc_func = NULL;
  info->free_gc_func = NULL;
  g_object_set_qdata_full (G_OBJECT (result),
                           g_quark_from_static_string ("pango-x-info"),
                           info, (GDestroyNotify)g_free);
  
  pango_context_set_font_map (result, pango_x_font_map_for_display (display));

  return result;
}

/**
 * pango_x_context_set_funcs:
 * @context: a #PangoContext.
 * @get_gc_func: function called to create a new GC for a given color.
 * @free_gc_func: function called to free a GC created with @get_gc_func.
 * 
 * Sets the functions that will be used to get GC's in various colors when
 * rendering layouts with this context.
 **/
void
pango_x_context_set_funcs  (PangoContext     *context,
			    PangoGetGCFunc    get_gc_func,
			    PangoFreeGCFunc   free_gc_func)
{
  PangoXContextInfo *info;
  
  g_return_if_fail (context != NULL);

  info = g_object_get_qdata (G_OBJECT (context),
                             g_quark_from_static_string ("pango-x-info"));

  info->get_gc_func = get_gc_func;
  info->free_gc_func = free_gc_func;
}

static GType
pango_x_font_get_type (void)
{
  static GType object_type = 0;

  if (!object_type)
    {
      static const GTypeInfo object_info =
      {
        sizeof (PangoXFontClass),
        (GBaseInitFunc) NULL,
        (GBaseFinalizeFunc) NULL,
        (GClassInitFunc) pango_x_font_class_init,
        NULL,           /* class_finalize */
        NULL,           /* class_data */
        sizeof (PangoXFont),
        0,              /* n_preallocs */
        (GInstanceInitFunc) pango_x_font_init,
      };
      
      object_type = g_type_register_static (PANGO_TYPE_FONT,
                                            "PangoXFont",
                                            &object_info, 0);
    }
  
  return object_type;
}

static void 
pango_x_font_init (PangoXFont *xfont)
{
  xfont->subfonts_by_charset = g_hash_table_new (g_str_hash, g_str_equal);
  xfont->subfonts = g_new (PangoXSubfontInfo *, 1);

  xfont->n_subfonts = 0;
  xfont->max_subfonts = 1;

  xfont->metrics_by_lang = NULL;

  xfont->size = -1;
  xfont->xface = NULL;
}

static void
pango_x_font_class_init (PangoXFontClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);
  PangoFontClass *font_class = PANGO_FONT_CLASS (class);

  parent_class = g_type_class_peek_parent (class);
  
  object_class->finalize = pango_x_font_finalize;
  object_class->dispose = pango_x_font_dispose;
  
  font_class->describe = pango_x_font_describe;
  font_class->get_coverage = pango_x_font_get_coverage;
  font_class->find_shaper = pango_x_font_find_shaper;
  font_class->get_glyph_extents = pango_x_font_get_glyph_extents;
  font_class->get_metrics = pango_x_font_get_metrics;
}

PangoXFont *
pango_x_font_new (PangoFontMap *fontmap, const char *spec, int size)
{
  PangoXFont *result;

  g_return_val_if_fail (fontmap != NULL, NULL);
  g_return_val_if_fail (spec != NULL, NULL);

  result = (PangoXFont *)g_type_create_instance (PANGO_TYPE_X_FONT);
  
  result->fontmap = fontmap;
  g_object_ref (G_OBJECT (fontmap));
  result->display = pango_x_fontmap_get_display (fontmap);

  result->fonts = g_strsplit(spec, ",", -1);
  for (result->n_fonts = 0; result->fonts[result->n_fonts]; result->n_fonts++)
    ; /* Nothing */

  result->size = size;

  return result;
}

/**
 * pango_x_load_font:
 * @display: the X display.
 * @spec:    a comma-separated list of XLFD's.
 *
 * Loads up a logical font based on a "fontset" style text
 * specification. This is not remotely useful (Pango API's generally
 * work in terms of PangoFontDescription) and the result may not
 * work correctly in all circumstances. Use of this function should
 * be avoided.
 *
 * Returns a new #PangoFont.
 */
PangoFont *
pango_x_load_font (Display    *display,
		   const char *spec)
{
  PangoXFont *result;

  g_return_val_if_fail (display != NULL, NULL);
  g_return_val_if_fail (spec != NULL, NULL);
  
  result = pango_x_font_new (pango_x_font_map_for_display (display), spec, -1);

  return (PangoFont *)result;
}
 
/**
 * pango_x_render:
 * @display: the X display.
 * @d:       the drawable on which to draw string.
 * @gc:      the graphics context.
 * @font:    the font in which to draw the string.
 * @glyphs:  the glyph string to draw.
 * @x:       the x position of start of string (in pixels).
 * @y:       the y position of baseline (in pixels).
 *
 * Renders a #PangoGlyphString onto an X drawable.
 */
void 
pango_x_render  (Display           *display,
		 Drawable           d,
		 GC                 gc,
		 PangoFont         *font,
		 PangoGlyphString  *glyphs,
		 int                x, 
		 int                y)
{
  /* Slow initial implementation. For speed, it should really
   * collect the characters into runs, and draw multiple
   * characters with each XDrawString16 call.
   */
  Font old_fid = None;
  XFontStruct *fs;
  int i;
  int x_off = 0;

  g_return_if_fail (display != NULL);
  g_return_if_fail (glyphs != NULL);
  
  for (i=0; i<glyphs->num_glyphs; i++)
    {
      PangoGlyph glyph = glyphs->glyphs[i].glyph;
      int glyph_x = x + PANGO_PIXELS (x_off + glyphs->glyphs[i].geometry.x_offset);
      int glyph_y = y + PANGO_PIXELS (glyphs->glyphs[i].geometry.y_offset);

      /* Clip glyphs into the X coordinate range; we really
       * want to clip glyphs with an ink rect outside the
       * [0,32767] x [0,32767] rectangle but looking up
       * the ink rect here would be a noticeable speed hit.
       * This is close enough.
       */
      if (!(glyph &&
	    glyph_x >= -16384 && glyph_x <= 32767 &&
	    glyph_y >= -16384 && glyph_y <= 32767))
	goto next_glyph;
	      
      if (glyph & PANGO_X_UNKNOWN_FLAG)
        {
          PangoFontMetrics *metrics = pango_font_get_metrics (font, NULL);
          int x1, y1, x2, y2; /* rectangle the character should go inside. */
          int baseline;
          gunichar wc;
          
          x1 = glyph_x;
          y1 = glyph_y - PANGO_PIXELS (metrics->ascent);
          x2 = x1 + PANGO_PIXELS (glyphs->glyphs[i].geometry.width);
          y2 = y1 + PANGO_PIXELS (metrics->ascent + metrics->descent);
          baseline = glyph_y;
          
          wc = glyph & (~PANGO_X_UNKNOWN_FLAG);

          switch (wc)
            {
            case '\n':
            case '\r':
            case 0x2028: /* Line separator */
            case 0x2029: /* Paragraph separator */
              {
                /* Draw a carriage-return thingy */
                PangoRectangle up_stroke;
                PangoRectangle across_stroke;

		int stroke_thick = MAX ((y2 - y1) * 0.075, 1);
		int hborder = (x2 - x1) * 0.1;
		int arrow_height = 0.25 * (y2 - y1);
		int top_border = (y2 - y1) * 0.25;

		int arrow_x, arrow_width, tmp_height;

		/* Draw the arrow-head */

		tmp_height = (stroke_thick % 2 == 0) ? 2 : 1; /* Starting height */
		arrow_height = 2 * ((1 + arrow_height - tmp_height) / 2) + tmp_height; /* Force symmetry */
		arrow_width = 2 + arrow_height - tmp_height;

		for (arrow_x = x1 + hborder; arrow_x < x1 + hborder + arrow_width; arrow_x++)
		  {
                    XDrawLine (display, d, gc,
                               arrow_x,
			       baseline - stroke_thick + (stroke_thick - tmp_height) / 2,
                               arrow_x,
			       baseline - stroke_thick + (stroke_thick - tmp_height) / 2 + tmp_height - 1);
		    
		    if ((arrow_x - x1 - hborder) % 2 == 1)
		      tmp_height += 2;
		  }

                across_stroke.x = arrow_x;
                across_stroke.width = x2 - hborder - arrow_x - stroke_thick;
                across_stroke.y = baseline - stroke_thick;
                across_stroke.height = stroke_thick;

                XFillRectangle (display, d, gc,
                                across_stroke.x, across_stroke.y,
                                across_stroke.width, across_stroke.height);

		up_stroke.x = across_stroke.x + across_stroke.width;
		up_stroke.width = stroke_thick;
		up_stroke.y = y1 + top_border;
		up_stroke.height = baseline - up_stroke.y;

                XFillRectangle (display, d, gc,
                                up_stroke.x, up_stroke.y,
                                up_stroke.width, up_stroke.height);
              }
              break;

            default:

              /* Here we should draw the box-with-numbers as in the
               * Xft backend. The shaper never gives us a glyph that
               * activates this case at the moment though, so also
               * needs hacking.
               */
              
              break;
            }

	  pango_font_metrics_unref (metrics);
        }
      else
	{
	  guint16 index = PANGO_X_GLYPH_INDEX (glyph);
	  guint16 subfont_index = PANGO_X_GLYPH_SUBFONT (glyph);
	  PangoXSubfontInfo *subfont;
      
	  XChar2b c;
	  
	  subfont = pango_x_find_subfont (font, subfont_index);
	  if (subfont)
	    {
	      c.byte1 = index / 256;
	      c.byte2 = index % 256;
	      
	      fs = pango_x_get_font_struct (font, subfont);
	      if (!fs)
		continue;
	      
	      if (fs->fid != old_fid)
		{
		  XSetFont (display, gc, fs->fid);
		  old_fid = fs->fid;
		}
	      
	      XDrawString16 (display, d, gc,
			     glyph_x, glyph_y,
			     &c, 1);
	    }
	}

    next_glyph:
      x_off += glyphs->glyphs[i].geometry.width;
    }
}

static void
pango_x_font_get_glyph_extents  (PangoFont      *font,
				 PangoGlyph      glyph,
				 PangoRectangle *ink_rect,
				 PangoRectangle *logical_rect)
{
  XCharStruct *cs;
  PangoXSubfontInfo *subfont;

  if (glyph & PANGO_X_UNKNOWN_FLAG)
    {
      gunichar wc;
      
      wc = glyph & (~PANGO_X_UNKNOWN_FLAG);
          
      switch (wc)
        {
        case '\n':
        case '\r':
        case 0x2028: /* Line separator */
        case 0x2029: /* Paragraph separator */
          {
            /* Size of carriage-return thingy */
            PangoFontMetrics *metrics = pango_font_get_metrics (font, NULL);
            int w;

#define MAGIC_FACTOR 1.75
            
            w = metrics->approximate_char_width * MAGIC_FACTOR;
            
            if (ink_rect)
              {
                ink_rect->x = 0;
                ink_rect->width = w;
                ink_rect->y = - metrics->ascent;
                ink_rect->height = metrics->ascent + metrics->descent;
              }
            if (logical_rect)
              {
                logical_rect->x = 0;
                logical_rect->width = w;
                logical_rect->y = - metrics->ascent;
                logical_rect->height = metrics->ascent + metrics->descent;
              }

	    pango_font_metrics_unref (metrics);
          }
          break;
          
        default:
              
          break;
        }
    }
  else if (glyph && pango_x_find_glyph (font, glyph, &subfont, &cs))
    {
      if (ink_rect)
	{
	  ink_rect->x = PANGO_SCALE * cs->lbearing;
	  ink_rect->width = PANGO_SCALE * (cs->rbearing - cs->lbearing);
	  ink_rect->y = PANGO_SCALE * -cs->ascent;
	  ink_rect->height = PANGO_SCALE * (cs->ascent + cs->descent);
	}
      if (logical_rect)
	{
	  logical_rect->x = 0;
	  logical_rect->width = PANGO_SCALE * cs->width;
	  logical_rect->y = - PANGO_SCALE * subfont->font_struct->ascent;
	  logical_rect->height = PANGO_SCALE * (subfont->font_struct->ascent + subfont->font_struct->descent);
	}
    }
  else
    {
      if (ink_rect)
	{
	  ink_rect->x = 0;
	  ink_rect->width = 0;
	  ink_rect->y = 0;
	  ink_rect->height = 0;
	}
      if (logical_rect)
	{
	  logical_rect->x = 0;
	  logical_rect->width = 0;
	  logical_rect->y = 0;
	  logical_rect->height = 0;
	}
    }
}

static gboolean
get_int_prop (Atom         atom,
              XFontStruct *fs,
              int         *val)
{
  int i;

  *val = 0;
  
  i = 0;
  while (i < fs->n_properties)
    {
      if (fs->properties[i].name == atom)
        {
          *val = fs->properties[i].card32;
          return TRUE;
        }

      ++i;
    }

  return FALSE;
}

/* Call @func with each glyph resulting from shaping @string with each
 * glyph. This duplicates quite a bit of code from pango_itemize. This
 * function should die and we should simply add the ability to specify
 * particular fonts when itemizing.
 */
static void
itemize_string_foreach (PangoFont     *font,
			PangoLanguage *language,
			const char    *str,
			void         (*func) (PangoFont      *font,
					      PangoGlyphInfo *glyph_info,
					      gpointer        data),
			gpointer       data)
{
  const char *start, *p;
  PangoGlyphString *glyph_str = pango_glyph_string_new ();
  PangoEngineShape *shaper, *last_shaper;
  int last_level;
  gunichar *text_ucs4;
  long n_chars, i;
  guint8 *embedding_levels;
  PangoDirection base_dir = PANGO_DIRECTION_LTR;
  gboolean finished = FALSE;
  
  text_ucs4 = g_utf8_to_ucs4_fast (str, -1, &n_chars);
  if (!text_ucs4)
    return;

  embedding_levels = g_new (guint8, n_chars);
  pango_log2vis_get_embedding_levels (text_ucs4, n_chars, &base_dir,
				      embedding_levels);
  g_free (text_ucs4);

  last_shaper = NULL;
  last_level = 0;

  i = 0;
  p = start = str;
  while (*p || !finished)
    {
      gunichar wc;

      if (*p)
	{
	  wc = g_utf8_get_char (p);
	  shaper = pango_font_find_shaper (font, language, wc);
	}
      else
	{
	  finished = TRUE;
	  shaper = NULL;
	}
	  
      if (p > start && 
	  (finished ||
	   (shaper != last_shaper || last_level != embedding_levels[i])))
	{
	  PangoAnalysis analysis;
	  int j;

	  analysis.shape_engine = last_shaper;
	  analysis.lang_engine = NULL;
	  analysis.font = font;
	  analysis.language = language;
	  analysis.level = last_level;
	  analysis.extra_attrs = NULL;
	  
	  pango_shape (start, p - start, &analysis, glyph_str);

	  for (j = 0; j < glyph_str->num_glyphs; j++)
	    (*func) (font, &glyph_str->glyphs[j], data);
	  
	  start = p;
	}

      if (!finished)
	{
	  p = g_utf8_next_char (p);
	      
	  last_shaper = shaper;
	  last_level = embedding_levels[i];
	  i++;
        }
    }
  
  pango_glyph_string_free (glyph_str);
  g_free (embedding_levels);
}

/* Get composite font metrics for all subfonts in list
 */
static void
get_font_metrics_from_subfonts (PangoFont        *font,
				GSList           *subfonts,
				PangoFontMetrics *metrics)
{
  PangoXFont *xfont = (PangoXFont *)font;
  GSList *tmp_list = subfonts;
  gboolean first = TRUE;
  int total_avg_widths = 0;
  int n_avg_widths = 0;  
  Atom avg_width_atom;

  avg_width_atom = pango_x_fontmap_atom_from_name (xfont->fontmap,
                                                   "AVERAGE_WIDTH");
  
  metrics->ascent = 0;
  metrics->descent = 0;
  
  while (tmp_list)
    {
      PangoXSubfontInfo *subfont = pango_x_find_subfont (font, GPOINTER_TO_UINT (tmp_list->data));
      
      if (subfont)
	{
	  XFontStruct *fs = pango_x_get_font_struct (font, subfont);
          gint avg_width;
          
	  if (fs)
	    {
	      if (first)
		{
		  metrics->ascent = fs->ascent * PANGO_SCALE;
		  metrics->descent = fs->descent * PANGO_SCALE;
		  first = FALSE;
		}
	      else
		{
		  metrics->ascent = MAX (fs->ascent * PANGO_SCALE, metrics->ascent);
		  metrics->descent = MAX (fs->descent * PANGO_SCALE, metrics->descent);
		}
	    }

          if (get_int_prop (avg_width_atom, fs, &avg_width))
            {
              /* convert decipoints --> pango units.
               * Resolution is in (points * PANGO_SCALE) / pixel,
               * avg_width in decipoints.
               * We want pixels * PANGO_SCALE
               */

              /* Convert to points * PANGO_SCALE */
              avg_width *= PANGO_SCALE / (double) 10.0;
              /* Convert to pixels * PANGO_SCALE */
              avg_width *= (PANGO_SCALE / PANGO_X_FONT_MAP (PANGO_X_FONT (font)->fontmap)->resolution);
            }
          else
            {
              avg_width = PANGO_SCALE * ((fs->min_bounds.width + fs->max_bounds.width) / 2);
            }
          
          total_avg_widths += avg_width;
          n_avg_widths += 1;
	}
      else
	g_warning ("Invalid subfont %d in get_font_metrics_from_subfonts", GPOINTER_TO_UINT (tmp_list->data));
	  
      tmp_list = tmp_list->next;
    }

  /* This is pretty darn bogus. */
  if (n_avg_widths)
    metrics->approximate_char_width = total_avg_widths / n_avg_widths;
  else
    metrics->approximate_char_width = 10 * PANGO_SCALE;
}

void
get_subfonts_foreach (PangoFont      *font,
		      PangoGlyphInfo *glyph_info,
		      gpointer        data)
{
  GSList **subfonts = data;

  PangoXSubfont subfont = PANGO_X_GLYPH_SUBFONT (glyph_info->glyph);
  if (!g_slist_find (*subfonts, GUINT_TO_POINTER ((guint)subfont)))
    *subfonts = g_slist_prepend (*subfonts, GUINT_TO_POINTER ((guint)subfont));
}

/* Get composite font metrics for all subfonts resulting from shaping
 * string str with the given font
 */
static void
get_font_metrics_from_string (PangoFont        *font,
			      PangoLanguage    *language,
			      const char       *str,
			      PangoFontMetrics *metrics)
{
  GSList *subfonts = NULL;
  
  itemize_string_foreach (font, language, str, get_subfonts_foreach, &subfonts);
  get_font_metrics_from_subfonts (font, subfonts, metrics);
  g_slist_free (subfonts);
}

void
average_width_foreach (PangoFont      *font,
		       PangoGlyphInfo *glyph_info,
		       gpointer        data)
{
  int *width = data;

  *width += glyph_info->geometry.width;
}

/* Get composite font metrics for all subfonts resulting from shaping
 * string str with the given font
 */
static gdouble
get_total_width_for_string (PangoFont        *font,
			    PangoLanguage    *language,
			    const char       *str)
{
  int width = 0;
  
  itemize_string_foreach (font, language, str, average_width_foreach, &width);

  return width;
}

static PangoFontMetrics *
pango_x_font_get_metrics (PangoFont        *font,
			  PangoLanguage    *language)
{
  PangoXMetricsInfo *info = NULL; /* Quiet gcc */
  PangoXFont *xfont = (PangoXFont *)font;
  GSList *tmp_list;
      
  const char *sample_str = pango_language_get_sample_string (language);
  
  tmp_list = xfont->metrics_by_lang;
  while (tmp_list)
    {
      info = tmp_list->data;
      
      if (info->sample_str == sample_str)    /* We _don't_ need strcmp */
	break;

      tmp_list = tmp_list->next;
    }

  if (!tmp_list)
    {
      info = g_new (PangoXMetricsInfo, 1);
      info->sample_str = sample_str;
      info->metrics = pango_font_metrics_new ();

      xfont->metrics_by_lang = g_slist_prepend (xfont->metrics_by_lang, info);

      get_font_metrics_from_string (font, language, sample_str, info->metrics);

      info->metrics->approximate_digit_width = get_total_width_for_string (font, language, "0123456789") / 10;
    }
      
  return pango_font_metrics_ref (info->metrics);
}

/* Compare the tail of a to b */
static gboolean
match_end (char *a, char *b)
{
  size_t len_a = strlen (a);
  size_t len_b = strlen (b);

  if (len_b > len_a)
    return FALSE;
  else
    return (strcmp (a + len_a - len_b, b) == 0);
}

/* Substitute in a charset into an XLFD. Return the
 * (g_malloc'd) new name, or NULL if the XLFD cannot
 * match the charset
 */
static char *
name_for_charset (char *xlfd, char *charset)
{
  char *p;
  char *dash_charset = g_strconcat ("-", charset, NULL);
  char *result = NULL;
  int ndashes = 0;

  for (p = xlfd; *p; p++)
    if (*p == '-')
      ndashes++;
  
  if (ndashes == 14) /* Complete XLFD */
    {
      if (match_end (xlfd, "-*-*"))
	{
	  result = g_malloc (strlen (xlfd) - 4 + strlen (dash_charset) + 1);
	  strncpy (result, xlfd, strlen (xlfd) - 4);
	  strcpy (result + strlen (xlfd) - 4, dash_charset);
	}
      if (match_end (xlfd, dash_charset))
	result = g_strdup (xlfd);
    }
  else if (ndashes == 13)
    {
      if (match_end (xlfd, "-*"))
	{
	  result = g_malloc (strlen (xlfd) - 2 + strlen (dash_charset) + 1);
	  strncpy (result, xlfd, strlen (xlfd) - 2);
	  strcpy (result + strlen (xlfd) - 2, dash_charset);
	}
      if (match_end (xlfd, dash_charset))
	result = g_strdup (xlfd);
    }
  else
    {
      if (match_end (xlfd, "*"))
	{
	  result = g_malloc (strlen (xlfd) + strlen (dash_charset) + 1);
	  strcpy (result, xlfd);
	  strcpy (result + strlen (xlfd), dash_charset);
	}
      if (match_end (xlfd, dash_charset))
	result = g_strdup (xlfd);
    }

  g_free (dash_charset);
  return result;
}

static PangoXSubfont
pango_x_insert_subfont (PangoFont *font, const char *xlfd)
{
  PangoXFont *xfont = (PangoXFont *)font;
  PangoXSubfontInfo *info;
  
  info = g_new (PangoXSubfontInfo, 1);
  
  info->xlfd = g_strdup (xlfd);
  info->font_struct = NULL;
  info->n_ligs = 0;
  info->ligs = 0;
  info->ligature_sets = 0;

  xfont->n_subfonts++;
  
  if (xfont->n_subfonts > xfont->max_subfonts)
    {
      xfont->max_subfonts *= 2;
      xfont->subfonts = g_renew (PangoXSubfontInfo *, xfont->subfonts, xfont->max_subfonts);
    }
  
  xfont->subfonts[xfont->n_subfonts - 1] = info;
  
  return xfont->n_subfonts;
}

/**
 * pango_x_list_subfonts:
 * @font: a #PangoFont.
 * @charsets: the charsets to list subfonts for.
 * @n_charsets: the number of charsets in @charsets.
 * @subfont_ids: location to store a pointer to an array of subfont IDs for each found subfont;
 *               the result must be freed using g_free().
 * @subfont_charsets: location to store a pointer to an array of subfont IDs for each found subfont;
 *               the result must be freed using g_free().
 * 
 * Lists the subfonts of a given font.
 *
 * Return value: length of the arrays stored in @subfont_ids and 
 * @subfont_charsets.
 **/
int
pango_x_list_subfonts (PangoFont        *font,
		       char            **charsets,
		       int               n_charsets,
		       PangoXSubfont   **subfont_ids,
		       int             **subfont_charsets)
{
  PangoXFont *xfont = (PangoXFont *)font;
  PangoXSubfont **subfont_lists;
  PangoFontMap *fontmap;
  int i, j;
  int n_subfonts = 0;

  g_return_val_if_fail (font != NULL, 0);
  g_return_val_if_fail (n_charsets == 0 || charsets != NULL, 0);

  fontmap = pango_x_font_map_for_display (xfont->display);
  
  subfont_lists = g_new (PangoXSubfont *, n_charsets);

  for (j=0; j<n_charsets; j++)
    {
      subfont_lists[j] = g_hash_table_lookup (xfont->subfonts_by_charset, charsets[j]);
      if (!subfont_lists[j])
	{
	  subfont_lists[j] = g_new (PangoXSubfont, xfont->n_fonts);
	  
	  for (i = 0; i < xfont->n_fonts; i++)
	    {
	      PangoXSubfont subfont = 0;
	      char *xlfd;

	      if (xfont->size == -1)
		{
		  xlfd = name_for_charset (xfont->fonts[i], charsets[j]);
	      
		  if (xlfd)
		    {
		      int count;
		      char **names = XListFonts (xfont->display, xlfd, 1, &count);
		      if (count > 0)
			subfont = pango_x_insert_subfont (font, names[0]);
		      
		      XFreeFontNames (names);
		      g_free (xlfd);
		    }
		}
	      else
		{
		  xlfd = pango_x_make_matching_xlfd (fontmap, xfont->fonts[i], charsets[j], xfont->size);
		  if (xlfd)
		    {
		      subfont = pango_x_insert_subfont (font, xlfd);
		      g_free (xlfd);
		    }
		}
		  
	      subfont_lists[j][i] = subfont;
	    }

	  g_hash_table_insert (xfont->subfonts_by_charset, g_strdup (charsets[j]), subfont_lists[j]);
	}

      for (i = 0; i < xfont->n_fonts; i++)
	if (subfont_lists[j][i])
	  n_subfonts++;
    }

  *subfont_ids = g_new (PangoXSubfont, n_subfonts);
  *subfont_charsets = g_new (int, n_subfonts);

  n_subfonts = 0;

  for (i=0; i<xfont->n_fonts; i++)
    for (j=0; j<n_charsets; j++)
      if (subfont_lists[j][i])
	{
	  (*subfont_ids)[n_subfonts] = subfont_lists[j][i];
	  (*subfont_charsets)[n_subfonts] = j;
	  n_subfonts++;
	}

  g_free (subfont_lists);

  return n_subfonts;
}

/**
 * pango_x_has_glyph:
 * @font: a #PangoFont which must be from the X backend.
 * @glyph: the index of a glyph in the font. (Formed
 *         using the #PANGO_X_MAKE_GLYPH macro)
 * 
 * Checks if the given glyph is present in a X font.
 * 
 * Return value: %TRUE if the glyph is present.
 **/
gboolean
pango_x_has_glyph (PangoFont  *font,
		   PangoGlyph  glyph)
{
  PangoXSubfontInfo *subfont;
  XCharStruct *cs;

  guint16 char_index = PANGO_X_GLYPH_INDEX (glyph);
  guint16 subfont_index = PANGO_X_GLYPH_SUBFONT (glyph);

  subfont = pango_x_find_subfont (font, subfont_index);
  if (!subfont)
    return FALSE;
  
  cs = pango_x_get_per_char (font, subfont, char_index);

  if (cs && (cs->lbearing != cs->rbearing || cs->width != 0))
    return TRUE;
  else
    return FALSE;
}

/**
 * pango_x_font_subfont_xlfd:
 * @font: a #PangoFont which must be from the X backend.
 * @subfont_id: the id of a subfont within the font.
 * 
 * Determines the X Logical Font Description for the specified
 * subfont.
 * 
 * Return value: A newly-allocated string containing the XLFD for the
 * subfont. This string must be freed with g_free().
 **/
char *
pango_x_font_subfont_xlfd (PangoFont     *font,
			   PangoXSubfont  subfont_id)
{
  PangoXSubfontInfo *subfont;

  g_return_val_if_fail (font != NULL, NULL);
  g_return_val_if_fail (PANGO_X_IS_FONT (font), NULL);

  subfont = pango_x_find_subfont (font, subfont_id);
  if (!subfont)
    {
      g_warning ("pango_x_font_subfont_xlfd: Invalid subfont_id specified");
      return NULL;
    }

  return g_strdup (subfont->xlfd);
}

static void
pango_x_font_dispose (GObject *object)
{
  PangoXFont *xfont = PANGO_X_FONT (object);

  /* If the font is not already in the freed-fonts cache, add it,
   * if it is already there, do nothing and the font will be
   * freed.
   */
  if (!xfont->in_cache && xfont->fontmap)
    pango_x_fontmap_cache_add (xfont->fontmap, xfont);

  G_OBJECT_CLASS (parent_class)->dispose (object);
}


static void
subfonts_foreach (gpointer key, gpointer value, gpointer data)
{
  g_free (key);
  g_free (value);
}

static void
free_sets_foreach (gpointer key, gpointer value, gpointer data)
{
  g_free (key);
  pango_int_set_destroy (value);
}

static void
free_metrics_info (PangoXMetricsInfo *info)
{
  pango_font_metrics_unref (info->metrics);
  g_free (info);
}

static void
pango_x_font_finalize (GObject *object)
{
  PangoXFont *xfont = (PangoXFont *)object;
  PangoXFontCache *cache = pango_x_font_map_get_font_cache (xfont->fontmap);

  int i, j;

  for (i=0; i<xfont->n_subfonts; i++)
    {
      PangoXSubfontInfo *info = xfont->subfonts[i];

      g_free (info->xlfd);

      if (info->font_struct)
	pango_x_font_cache_unload (cache, info->font_struct);

      if (info->ligs) 
	{
	  
	  for (j=0; j<info->n_ligs;j++) 
	    {
	      g_free (info->ligs[j].source);
	    }
	  
	  g_free (info->ligs);
	  
	  g_hash_table_foreach (info->ligature_sets, free_sets_foreach, NULL);
	  g_hash_table_destroy (info->ligature_sets);
	}

      g_free (info);
    }

  g_free (xfont->subfonts);

  g_hash_table_foreach (xfont->subfonts_by_charset, subfonts_foreach, NULL);
  g_hash_table_destroy (xfont->subfonts_by_charset);

  g_slist_foreach (xfont->metrics_by_lang, (GFunc)free_metrics_info, NULL);
  g_slist_free (xfont->metrics_by_lang);
  
  if (xfont->xface)
    pango_x_face_remove (xfont->xface, (PangoFont *)xfont);

  g_object_unref (G_OBJECT (xfont->fontmap));

  g_strfreev (xfont->fonts);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static PangoFontDescription *
pango_x_font_describe (PangoFont *font)
{
  /* FIXME: this doesn't work for fonts from pango_x_font_load()
   */
  PangoXFont *xfont = (PangoXFont *)font;

  if (xfont->xface)
    {
      PangoFontDescription *desc = pango_font_face_describe (PANGO_FONT_FACE (xfont->xface));
      pango_font_description_set_size (desc, xfont->size);

      return desc;
    }
  else
    return NULL;
}

PangoMap *
pango_x_get_shaper_map (PangoLanguage *language)
{
  static guint engine_type_id = 0;
  static guint render_type_id = 0;
  
  if (engine_type_id == 0)
    {
      engine_type_id = g_quark_from_static_string (PANGO_ENGINE_TYPE_SHAPE);
      render_type_id = g_quark_from_static_string (PANGO_RENDER_TYPE_X);
    }
  
  return pango_find_map (language, engine_type_id, render_type_id);
}

static PangoCoverage *
pango_x_font_get_coverage (PangoFont     *font,
			   PangoLanguage *language)
{
  PangoXFont *xfont = (PangoXFont *)font;

  return pango_x_face_get_coverage (xfont->xface, font, language);
}

static PangoEngineShape *
pango_x_font_find_shaper (PangoFont     *font,
			  PangoLanguage *language,
			  guint32        ch)
{
  PangoMap *shape_map = NULL;

  shape_map = pango_x_get_shaper_map (language);
  return (PangoEngineShape *)pango_map_get_engine (shape_map, ch);
}

/* Utility functions */

static XCharStruct *
pango_x_get_per_char (PangoFont         *font,
		      PangoXSubfontInfo *subfont,
		      guint16            char_index)
{
  XFontStruct *fs;

  int index;
  int byte1;
  int byte2;

  fs = pango_x_get_font_struct (font, subfont);
  if (!fs)
    return NULL;

  if (subfont->is_1byte)
    {
      index = (int)char_index - fs->min_char_or_byte2;
      if (index < 0 || index >= subfont->range_byte2)
	return NULL;
    }
  else
    {
      byte1 = (int)(char_index / 256) - fs->min_byte1;
      if (byte1 < 0 || byte1 >= subfont->range_byte1)
	return NULL;
	  
      byte2 = (int)(char_index % 256) - fs->min_char_or_byte2;
      if (byte2 < 0 || byte2 >= subfont->range_byte2)
	return NULL;

      index = byte1 * subfont->range_byte2 + byte2;
    }
  
  if (fs->per_char)
    return &fs->per_char[index];
  else
    return &fs->min_bounds;
}

static gboolean
pango_x_find_glyph (PangoFont *font,
		    PangoGlyph glyph,
		    PangoXSubfontInfo **subfont_return,
		    XCharStruct **charstruct_return)
{
  PangoXSubfontInfo *subfont;
  XCharStruct *cs;

  guint16 char_index = PANGO_X_GLYPH_INDEX (glyph);
  guint16 subfont_index = PANGO_X_GLYPH_SUBFONT (glyph);

  subfont = pango_x_find_subfont (font, subfont_index);
  if (!subfont)
    return FALSE;
  
  cs = pango_x_get_per_char (font, subfont, char_index);

  if (cs && (cs->lbearing != cs->rbearing || cs->width != 0))
    {
      if (subfont_return)
	*subfont_return = subfont;

      if (charstruct_return)
	*charstruct_return = cs;
      
      return TRUE;
    }
  else
    return FALSE;
}

/**
 * pango_x_get_unknown_glyph:
 * @font: a #PangoFont.
 * 
 * Returns the index of a glyph suitable for drawing unknown characters.
 * 
 * Return value: a glyph index into @font.
 **/
PangoGlyph
pango_x_get_unknown_glyph (PangoFont *font)
{
  PangoXFont *xfont = (PangoXFont *)font;
  
  /* The strategy here is to find _a_ X font, any X font in the fontset, and
   * then get the unknown glyph for that font.
   */

  g_return_val_if_fail (font != 0, 0);
  g_return_val_if_fail (xfont->n_fonts != 0, 0);

  if (xfont->n_subfonts == 0)
    {
      int count;
      char **names = XListFonts (xfont->display, xfont->fonts[0], 1, &count);

      if (count > 0)
	pango_x_insert_subfont (font, names[0]);

      XFreeFontNames (names);
    }

  if (xfont->n_subfonts > 0)
    {
      XFontStruct *font_struct = pango_x_get_font_struct (font, xfont->subfonts[0]);

      if (font_struct)
	return PANGO_X_MAKE_GLYPH (1,font_struct->default_char);
    }

  return 0;
}

/**
 * pango_x_render_layout_line:
 * @display:   the X display.
 * @drawable:  the drawable on which to draw.
 * @gc:        GC to use for uncolored drawing.
 * @line:      a #PangoLayoutLine.
 * @x:         the x position of start of string (in pixels).
 * @y:         the y position of baseline (in pixels).
 *
 * Renders a #PangoLayoutLine onto an X drawable.
 */
void 
pango_x_render_layout_line (Display          *display,
			    Drawable          drawable,
			    GC                gc,
			    PangoLayoutLine  *line,
			    int               x, 
			    int               y)
{
  GSList *tmp_list = line->runs;
  PangoRectangle overall_rect;
  PangoRectangle logical_rect;
  PangoRectangle ink_rect;
  PangoContext *context = pango_layout_get_context (line->layout);
  PangoXContextInfo *info =
    g_object_get_qdata (G_OBJECT (context),
                        g_quark_from_static_string ("pango-x-info"));
  
  int x_off = 0;

  pango_layout_line_get_extents (line,NULL, &overall_rect);
  
  while (tmp_list)
    {
      PangoUnderline uline = PANGO_UNDERLINE_NONE;
      PangoLayoutRun *run = tmp_list->data;
      PangoAttrColor fg_color, bg_color;
      gboolean fg_set, bg_set;
      GC fg_gc;
      
      tmp_list = tmp_list->next;

      pango_x_get_item_properties (run->item, &uline, &fg_color, &fg_set, &bg_color, &bg_set);

      if (fg_set && info->get_gc_func)
	fg_gc = info->get_gc_func (context, &fg_color.color, gc);
      else
	fg_gc = gc;

      if (uline == PANGO_UNDERLINE_NONE)
	pango_glyph_string_extents (run->glyphs, run->item->analysis.font,
				    NULL, &logical_rect);
      else
	pango_glyph_string_extents (run->glyphs, run->item->analysis.font,
				    &ink_rect, &logical_rect);

      if (bg_set && info->get_gc_func)
	{
	  GC bg_gc = info->get_gc_func (context, &bg_color.color, gc);

	  XFillRectangle (display, drawable, bg_gc,
			  x + (x_off + logical_rect.x) / PANGO_SCALE,
			  y + overall_rect.y / PANGO_SCALE,
			  logical_rect.width / PANGO_SCALE,
			  overall_rect.height / PANGO_SCALE);

	  if (info->free_gc_func)
	    info->free_gc_func (context, bg_gc);
	}

      pango_x_render (display, drawable, fg_gc, run->item->analysis.font, run->glyphs,
		      x + x_off / PANGO_SCALE, y);

      switch (uline)
	{
	case PANGO_UNDERLINE_NONE:
	  break;
	case PANGO_UNDERLINE_DOUBLE:
	  XDrawLine (display, drawable, fg_gc,
		     x + (x_off + ink_rect.x) / PANGO_SCALE - 1, y + 4,
		     x + (x_off + ink_rect.x + ink_rect.width) / PANGO_SCALE, y + 4);
	  /* Fall through */
	case PANGO_UNDERLINE_SINGLE:
	  XDrawLine (display, drawable, fg_gc,
		     x + (x_off + ink_rect.x) / PANGO_SCALE - 1, y + 2,
		     x + (x_off + ink_rect.x + ink_rect.width) / PANGO_SCALE, y + 2);
	  break;
	case PANGO_UNDERLINE_LOW:
	  XDrawLine (display, drawable, fg_gc,
		     x + (x_off + ink_rect.x) / PANGO_SCALE - 1, y + (ink_rect.y + ink_rect.height) / PANGO_SCALE + 2,
		     x + (x_off + ink_rect.x + ink_rect.width) / PANGO_SCALE, y + (ink_rect.y + ink_rect.height) / PANGO_SCALE + 2);
	  break;
	}

      if (fg_set && info->get_gc_func && info->free_gc_func)
	info->free_gc_func (context, fg_gc);
      
      x_off += logical_rect.width;
    }
}

/**
 * pango_x_render_layout:
 * @display:   the X display.
 * @drawable:  the drawable on which to draw.
 * @gc:        GC to use for uncolored drawing.
 * @layout:    a #PangoLayout.
 * @x:         the x position of the left of the layout (in pixels).
 * @y:         the y position of the top of the layout (in pixels).
 *
 * Renders a #PangoLayoutLine onto an X drawable.
 */
void 
pango_x_render_layout (Display         *display,
		       Drawable         drawable,
		       GC               gc,
		       PangoLayout     *layout,
		       int              x, 
		       int              y)
{
  PangoRectangle logical_rect;
  GSList *tmp_list;
  PangoAlignment align;
  int indent;
  int width;
  int y_offset = 0;

  gboolean first = TRUE;
  
  g_return_if_fail (display != NULL);
  g_return_if_fail (layout != NULL);

  indent = pango_layout_get_indent (layout);
  width = pango_layout_get_width (layout);
  align = pango_layout_get_alignment (layout);

  if (width == -1 && align != PANGO_ALIGN_LEFT)
    {
      pango_layout_get_extents (layout, NULL, &logical_rect);
      width = logical_rect.width;
    }
  
  tmp_list = pango_layout_get_lines (layout);
  while (tmp_list)
    {
      PangoLayoutLine *line = tmp_list->data;
      int x_offset;
      
      pango_layout_line_get_extents (line, NULL, &logical_rect);

      if (width != 1 && align == PANGO_ALIGN_RIGHT)
	x_offset = width - logical_rect.width;
      else if (width != 1 && align == PANGO_ALIGN_CENTER)
	x_offset = (width - logical_rect.width) / 2;
      else
	x_offset = 0;

      if (first)
	{
	  if (indent > 0)
	    {
	      if (align == PANGO_ALIGN_LEFT)
		x_offset += indent;
	      else
		x_offset -= indent;
	    }

	  first = FALSE;
	}
      else
	{
	  if (indent < 0)
	    {
	      if (align == PANGO_ALIGN_LEFT)
		x_offset -= indent;
	      else
		x_offset += indent;
	    }
	}
	  
      pango_x_render_layout_line (display, drawable, gc,
				  line, x + x_offset / PANGO_SCALE, y + (y_offset - logical_rect.y) / PANGO_SCALE);

      y_offset += logical_rect.height;
      tmp_list = tmp_list->next;
    }
}

/* This utility function is duplicated here and in pango-layout.c; should it be
 * public? Trouble is - what is the appropriate set of properties?
 */
static void
pango_x_get_item_properties (PangoItem      *item,
			     PangoUnderline *uline,
			     PangoAttrColor *fg_color,
			     gboolean       *fg_set,
			     PangoAttrColor *bg_color,
			     gboolean       *bg_set)
{
  GSList *tmp_list = item->analysis.extra_attrs;

  if (fg_set)
    *fg_set = FALSE;
  
  if (bg_set)
    *bg_set = FALSE;
  
  while (tmp_list)
    {
      PangoAttribute *attr = tmp_list->data;

      switch (attr->klass->type)
	{
	case PANGO_ATTR_UNDERLINE:
	  if (uline)
	    *uline = ((PangoAttrInt *)attr)->value;
	  break;
	  
	case PANGO_ATTR_FOREGROUND:
	  if (fg_color)
	    *fg_color = *((PangoAttrColor *)attr);
	  if (fg_set)
	    *fg_set = TRUE;
	  
	  break;
	  
	case PANGO_ATTR_BACKGROUND:
	  if (bg_color)
	    *bg_color = *((PangoAttrColor *)attr);
	  if (bg_set)
	    *bg_set = TRUE;
	  
	  break;
	  
	default:
	  break;
	}
      tmp_list = tmp_list->next;
    }
}

static void 
font_struct_get_ligatures (PangoFontMap *fontmap,
                           Display *display, 
                           XFontStruct *fs,
                           PangoXSubfontInfo *info)
{
  int i;
   
  PangoXLigatureInfo *linfo = 0;
  int n_linfo = 0;

  GList *list = g_list_append (NULL, g_strdup ("PANGO_LIGATURE_HACK"));
  GList *list_start = list;

  info->ligature_sets = g_hash_table_new (g_str_hash, g_str_equal);
   
  while (list) 
    {
      Atom this_atom = pango_x_fontmap_atom_from_name (fontmap, (char *)list->data);
      for (i = 0; i < fs->n_properties; i++)
        {
          if (fs->properties[i].name == this_atom) 
            {
              char *val = g_strdup (pango_x_fontmap_name_from_atom (fontmap, fs->properties[i].card32));
              char *p;
              char *a = my_strtok_r (val, " ", &p);
              while (a)
                {
                  char *r;
                  char *m;
                  char *q;
                  PangoXLigatureSource *source = NULL;
                  gunichar *dest = NULL;
                  int n_source = 0;
                  int n_dest = 0;
                  PangoXLigatureInfo *xli;
                  
                  switch (*a) 
                    {
                      
                    case '$': 
                      /* class being defined */
                      {
                        char *name = a + 1;
                        char *data = strchr (a, '=');
                        PangoIntSet *set;
                        if (!data) 
                          {
#ifdef PANGO_LIGATURE_HACK_DEBUG
                            g_warning ("Error parsing ligature info: Isolated $.\n");
#endif 
                            break;
                          }
                        
                        *data = 0;
                        data++;
                        set = parse_gintset_spec (data);
                        if (!set) 
                          {
#ifdef PANGO_LIGATURE_HACK_DEBUG
                            g_warning ("Error parsing ligature info: Invalid glyphset.\n");
#endif
                            break;
                          }
                        g_hash_table_insert (info->ligature_sets, 
                                             g_strdup (name), set);
                        break;
                      }
                      
                    case ':': 
                      /* a pointer */
                      {
                        char *lang = a+1;
                        char *name = strchr (lang, ':');
                        if (name) 
                          {
                            name++;
                            list = g_list_append (list, g_strdup (name));
                          }
                        else 
			  {
#ifdef PANGO_LIGATURE_HACK_DEBUG
			    g_warning ("Error parsing ligature info: Bad pointer.\n");
#endif
			  }
                        break;
                      }
                      
                    default:
                      /* a literal */
                      {
                        n_linfo++;
                        linfo = g_realloc (linfo, sizeof (PangoXLigatureInfo) * 
                                           n_linfo);
                        r = strchr (a, '=');
                        if (!r) 
                          {
#ifdef PANGO_LIGATURE_HACK_DEBUG
                            g_warning ("Error parsing ligature info: No equals.\n");
#endif
                            n_linfo--;
                            break;
                          }
                        *r = 0;
                        r++;
                        q = a;
                        q = my_strtok_r (q, "+", &m);
                        while (q) 
                          {
                            n_source ++;
                            source = g_realloc (source, n_source * 
                                                sizeof (PangoXLigatureSource));
                            if (q[0] == '%') 
                              {
                                source[n_source-1].is_set = 1;
                                source[n_source-1].data.set = 
                                  g_hash_table_lookup (info->ligature_sets, 
                                                       q+1);
                                if (!source[n_source-1].data.set) 
				  {
#ifdef PANGO_LIGATURE_HACK_DEBUG
				    g_warning ("Error parsing ligature info: Unable to locate glyphset : %s\n", q+1);
#endif
				    source [n_source-1].is_set = 0;
				    source [n_source-1].data.glyph = 0;
				  }
                              } 
                            else 
                              {
                                int i = hex_to_integer (q);
                                if (i == -1) 
				  {
#ifdef PANGO_LIGATURE_HACK_DEBUG
				    g_warning ("Error parsing ligature info: Bad character value : %s. Assuming 0\n", q);
#endif
				    i = 0;
				  }
                                source [n_source-1].is_set = 0;
                                source [n_source-1].data.glyph = i;
                              }
                            q = my_strtok_r (NULL, "+", &m);
                          }
                        q = r;
                        q = my_strtok_r (q, "+", &m);
                        while (q) 
                          {
                            n_dest++;
                            dest = g_realloc (dest, n_dest * sizeof (gunichar));
                            
                            if (q[0] == '%') 
			      {
				char *er;
				dest[n_dest-1] = -strtol (q+1, &er, 10);
				if (*er) 
				  {
#ifdef PANGO_LIGATURE_HACK_DEBUG
				    g_warning ("Error parsing ligature info: Bad %% reference. Assuming 1");
#endif
				    dest[n_dest-1] = -1;
				  }
			      }
                            else 
			      {
				int i = hex_to_integer (q);
				if (i != -1) 
				  {
				    dest[n_dest-1] = i;
				  } 
				else 
				  {
				    dest[n_dest-1] = 0;
				  }
			      }
                            
                            q = my_strtok_r (NULL, "+", &m);
                          }
                        
                        xli = linfo + n_linfo - 1;
                        
                        xli->source = source;
                        xli->n_source = n_source;
                        xli->dest = dest;
                        xli->n_dest = n_dest;
                        
                        if (xli->n_dest > xli->n_source)
                          {
                            g_warning ("Error parsing ligature info: Warning : truncating substitute string.");
                            xli->n_dest = n_source;
                          }
                      }
                    }
                  
                  /* end switch */
                  a = my_strtok_r (NULL, " ", &p);
                }
              g_free (val);
            }
        }
      list = g_list_next (list);
    }
  
  list = list_start;
  
  while (list) 
    {
      g_free (list->data);
      list = g_list_next (list);
    }

  g_list_free (list_start);
  
  info->n_ligs = n_linfo;
  info->ligs = linfo;
}

/**
 * pango_x_apply_ligatures:
 * @font: a #PangoFont.
 * @subfont: a #PangoXSubFont.
 * @glyphs: a pointer to a pointer to an array of
 *          glyph indices. This holds the input glyphs
 *          on entry, and ligation will be performed
 *          on this array in-place. If the number
 *          of glyphs is increased, Pango will
 *          call g_realloc() on @glyphs, so @chars
 *          must be allocated with g_malloc().
 * @n_glyphs: a pointer to the number of glyphs
 *            *@n_glyphs is the number of original glyphs
 *            on entry and the number of resulting glyphs
 *            upon return.
 * @clusters: a pointer to the cluster information.
 *
 * Does subfont-specific ligation.  This involves replacing
 * groups of glyphs in @chars with alternate groups of glyphs
 * based on information provided in the X font.
 *
 * Return value: %TRUE if any ligations were performed.
 */
gboolean
pango_x_apply_ligatures (PangoFont     *font, 
                         PangoXSubfont  subfont_id,
                         gunichar     **glyphs, 
                         int           *n_glyphs,
                         int           **clusters) 
{
  int hits = 0;
  int i, j, k;
  PangoXSubfontInfo *subfont;
  PangoXLigatureInfo *linfo;
  int n_linfo = 0;
  XFontStruct *fs;
  
  g_return_val_if_fail (font != NULL, 0);

  subfont = pango_x_find_subfont (font, subfont_id);
  if (!subfont)
    return 0;

  fs = pango_x_get_font_struct (font, subfont);
  if (!fs)
    return 0;

  linfo = subfont->ligs;
  n_linfo = subfont->n_ligs;
  
  for (i = 0; i < *n_glyphs; i++) 
    for (j= 0; j < n_linfo; j++) 
      {
        PangoXLigatureInfo *li = &linfo[j];
        gunichar *temp;
        
        if (i + li->n_source > *n_glyphs) 
          continue;
        
        for (k = 0; k < li->n_source; k++) 
          {
            if ((li->source[k].is_set && 
                 !pango_int_set_contains (li->source[k].data.set,
                                          (*glyphs)[i + k]))
                || (!li->source[k].is_set && 
                    (*glyphs)[i + k] != li->source[k].data.glyph))
              goto next_pattern;
          }
        

        {
          gunichar buffer[16];
          if (li->n_source < G_N_ELEMENTS (buffer))
            {
              memcpy (buffer, &(*glyphs)[i], li->n_source * sizeof (gunichar));
              temp = buffer;
            }
          else
            { 
              temp = g_memdup (&(*glyphs)[i], li->n_source * sizeof (gunichar));
            }
          
          for (k = 0; k < li->n_dest; k++) 
            {
              int f = li->dest[k];
              if (f < 0) 
                f = temp[i - (1+f)];
              
              (*glyphs) [i + k - (li->n_dest - li->n_source)] = f;
            }
          
          for (k = 0; k < li->n_source-li->n_dest; k++)
            (*glyphs) [i+k] = 0;
          
          hits++;
          i += li->n_source - 1;

          if (temp != buffer) 
            g_free (temp);
        }

      next_pattern: ;
      }
  
  return hits >= 1;
}
  
/**
 * pango_x_find_first_subfont:
 * @font: A #PangoFont.
 * @rfont: A pointer to a #PangoXSubfont.
 * @charsets: An array of charsets.
 * @n_charsets: The number of charsets in @charsets.
 * 
 * Looks for subfonts with the @charset charset,
 * in @font, and puts the first one in *@rfont.
 *
 * Return value: %TRUE if *@rfont now contains a font.
 */
gboolean
pango_x_find_first_subfont (PangoFont      *font, 
                            char          **charsets,
			    int             n_charsets,
                            PangoXSubfont  *rfont)
{
  int n_subfonts;
  gboolean result = FALSE;
  PangoXSubfont *subfonts;
  int *subfont_charsets;

  g_return_val_if_fail (font, 0);
  g_return_val_if_fail (charsets, 0);
  g_return_val_if_fail (rfont, 0);

  n_subfonts = pango_x_list_subfonts (font, charsets, n_charsets,
                                      &subfonts, &subfont_charsets);

  if (n_subfonts > 0)
    {
      *rfont = subfonts[0];
      result = TRUE;
    }

  g_free (subfonts);
  g_free (subfont_charsets);
  return result;
}

/**
 * pango_x_fallback_shape:
 * @font: A #PangoFont.
 * @glyphs: A pointer to a #PangoGlyphString.
 * @text: UTF-8 string.
 * @n_chars: Number of UTF-8 seqs in @text.
 * 
 * This is a simple fallback shaper, that can be used
 * if no subfont that supports a given script is found. 
 * For every character in @text, it puts the Unknown glyph.
 */
void 
pango_x_fallback_shape (PangoFont        *font, 
                        PangoGlyphString *glyphs, 
                        const char       *text, 
                        int               n_chars) 
{
  PangoGlyph unknown_glyph = pango_x_get_unknown_glyph (font);
  PangoRectangle logical_rect;
  const char *p;
  int i;
  
  g_return_if_fail (font);
  g_return_if_fail (glyphs);
  g_return_if_fail (text);
  g_return_if_fail (n_chars >= 0);

  pango_font_get_glyph_extents (font, unknown_glyph, NULL, &logical_rect);
  pango_glyph_string_set_size (glyphs, n_chars);
  p = text;
  for (i = 0; i < n_chars; i++)
    {
      glyphs->glyphs[i].glyph = unknown_glyph;
      glyphs->glyphs[i].geometry.x_offset = 0;
      glyphs->glyphs[i].geometry.y_offset = 0;
      glyphs->glyphs[i].geometry.width = logical_rect.width;
      glyphs->log_clusters[i] = 0;
      
      p = g_utf8_next_char (p);
    }
}

/**
 * pango_x_font_get_unknown_glyph:
 * @font: a #PangoFont.
 * @wc: the Unicode character for which a glyph is needed.
 *
 * Returns the index of a glyph suitable for drawing @wc as an
 * unknown character.
 *
 * Return value: a glyph index into @font.
 */
PangoGlyph
pango_x_font_get_unknown_glyph (PangoFont *font,
                                gunichar   wc)
{
  g_return_val_if_fail (PANGO_IS_FONT (font), 0);

  switch (wc)
    {
    case '\n':
    case '\r':
    case 0x2028: /* Line separator */
    case 0x2029: /* Paragraph separator */
      return PANGO_X_UNKNOWN_FLAG | wc;
      break;
    default:
      return 0;
      break;
    }
}