summaryrefslogtreecommitdiff
path: root/pango/pangowin32.c
blob: e3af31c7718239107598ba46e0d57b4ebe445340 (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
/* Pango
 * pangowin32.c: Routines for handling Windows fonts
 *
 * Copyright (C) 1999 Red Hat Software
 * Copyright (C) 2000 Tor Lillqvist
 * Copyright (C) 2001 Alexander Larsson
 *
 * 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 <config.h>

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

#include "pango-utils.h"
#include "pangowin32.h"
#include "pangowin32-private.h"

#define CH_IS_UNIHAN_BMP(ch) ((ch) >= 0x3400 && (ch) <= 0x9FFF)
#define CH_IS_UNIHAN(ch) (CH_IS_UNIHAN_BMP (ch) || \
			  ((ch) >= 0x20000 && (ch) <= 0x2A6DF) ||	\
			  ((ch) >= 0x2F800 && (ch) <= 0x2FA1F))

HDC pango_win32_hdc;
OSVERSIONINFO pango_win32_os_version_info;
gboolean pango_win32_debug = FALSE;

static void pango_win32_font_dispose    (GObject             *object);
static void pango_win32_font_finalize   (GObject             *object);

static gboolean pango_win32_font_real_select_font        (PangoFont *font,
							  HDC        hdc);
static void     pango_win32_font_real_done_font          (PangoFont *font);
static double   pango_win32_font_real_get_metrics_factor (PangoFont *font);

static PangoFontDescription *pango_win32_font_describe          (PangoFont        *font);
static PangoCoverage        *pango_win32_font_get_coverage      (PangoFont        *font,
								 PangoLanguage    *lang);
static void                  pango_win32_font_calc_coverage     (PangoFont        *font,
								 PangoCoverage    *coverage,
								 PangoLanguage    *lang);
static PangoEngineShape     *pango_win32_font_find_shaper       (PangoFont        *font,
								 PangoLanguage    *lang,
								 guint32           ch);
static void                  pango_win32_font_get_glyph_extents (PangoFont        *font,
								 PangoGlyph        glyph,
								 PangoRectangle   *ink_rect,
								 PangoRectangle   *logical_rect);
static PangoFontMetrics *    pango_win32_font_get_metrics       (PangoFont        *font,
								 PangoLanguage    *lang);
static PangoFontMap *        pango_win32_font_get_font_map      (PangoFont        *font);

static gboolean pango_win32_font_real_select_font      (PangoFont *font,
							HDC        hdc);
static void     pango_win32_font_real_done_font        (PangoFont *font);
static double   pango_win32_font_real_get_metrics_factor (PangoFont *font);

static HFONT                 pango_win32_get_hfont              (PangoFont        *font);
static void                  pango_win32_get_item_properties    (PangoItem        *item,
								 PangoUnderline   *uline,
								 PangoAttrColor   *fg_color,
								 gboolean         *fg_set,
								 PangoAttrColor   *bg_color,
								 gboolean         *bg_set);

static HFONT
pango_win32_get_hfont (PangoFont *font)
{
  PangoWin32Font *win32font = (PangoWin32Font *)font;
  PangoWin32FontCache *cache;
  TEXTMETRIC tm;

  if (!win32font->hfont)
    {
      cache = pango_win32_font_map_get_font_cache (win32font->fontmap);
      
      win32font->hfont = pango_win32_font_cache_load (cache, &win32font->logfont);
      if (!win32font->hfont)
	{
	  gchar *face_utf8 = g_locale_to_utf8 (win32font->logfont.lfFaceName,
					       -1, NULL, NULL, NULL);
	  g_warning ("Cannot load font '%s\n", face_utf8);
	  g_free (face_utf8);
	  return NULL;
	}

      SelectObject (pango_win32_hdc, win32font->hfont);
      GetTextMetrics (pango_win32_hdc, &tm);

      win32font->tm_overhang = tm.tmOverhang;
      win32font->tm_descent = tm.tmDescent;
      win32font->tm_ascent = tm.tmAscent;
    }
  
  return win32font->hfont;
}

/**
 * pango_win32_get_context:
 * 
 * Retrieves a #PangoContext appropriate for rendering with Windows fonts.
  * 
 * Return value: the new #PangoContext
 **/
PangoContext *
pango_win32_get_context (void)
{
  PangoContext *result;

  result = pango_context_new ();
  pango_context_set_font_map (result, pango_win32_font_map_for_display ());

  return result;
}

G_DEFINE_TYPE (PangoWin32Font, pango_win32_font, PANGO_TYPE_FONT)

static void 
pango_win32_font_init (PangoWin32Font *win32font)
{
  win32font->size = -1;

  win32font->metrics_by_lang = NULL;

  win32font->glyph_info = g_hash_table_new_full (NULL, NULL, NULL, g_free);
}

/**
 * pango_win32_get_dc:
 * 
 * Obtains a handle to the Windows device context that is used by Pango.
 * 
 * Return value: A handle to the Windows device context that is used by Pango.
 **/
HDC
pango_win32_get_dc (void)
{
  if (pango_win32_hdc == NULL)
    {
      pango_win32_hdc = CreateDC ("DISPLAY", NULL, NULL, NULL);
      memset (&pango_win32_os_version_info, 0,
	      sizeof (pango_win32_os_version_info));
      pango_win32_os_version_info.dwOSVersionInfoSize =
	sizeof (OSVERSIONINFO);
      GetVersionEx (&pango_win32_os_version_info);

      /* Also do some generic pangowin32 initialisations... this function
       * is a suitable place for those as it is called from a couple
       * of class_init functions.
       */
#ifdef PANGO_WIN32_DEBUGGING
      if (getenv ("PANGO_WIN32_DEBUG") != NULL)
	pango_win32_debug = TRUE;
#endif      
    }

  return pango_win32_hdc;
}  

/**
 * pango_win32_get_debug_flag:
 *
 * Returns wether debugging is turned on.
 * 
 * Return value: %TRUE if debugging is turned on.
 * 
 * Since: 1.2
 */
gboolean
pango_win32_get_debug_flag (void)
{
  return pango_win32_debug;
}

static void
pango_win32_font_class_init (PangoWin32FontClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);
  PangoFontClass *font_class = PANGO_FONT_CLASS (class);

  object_class->finalize = pango_win32_font_finalize;
  object_class->dispose = pango_win32_font_dispose;
  
  font_class->describe = pango_win32_font_describe;
  font_class->get_coverage = pango_win32_font_get_coverage;
  font_class->find_shaper = pango_win32_font_find_shaper;
  font_class->get_glyph_extents = pango_win32_font_get_glyph_extents;
  font_class->get_metrics = pango_win32_font_get_metrics;
  font_class->get_font_map = pango_win32_font_get_font_map;

  class->select_font = pango_win32_font_real_select_font;
  class->done_font = pango_win32_font_real_done_font;
  class->get_metrics_factor = pango_win32_font_real_get_metrics_factor;

  pango_win32_get_dc ();
}

PangoWin32Font *
pango_win32_font_new (PangoFontMap  *fontmap,
		      const LOGFONT *lfp,
		      int	     size)
{
  PangoWin32Font *result;

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

  result = (PangoWin32Font *)g_object_new (PANGO_TYPE_WIN32_FONT, NULL);
  
  result->fontmap = fontmap;
  g_object_ref (fontmap);

  result->size = size;
  pango_win32_make_matching_logfont (fontmap, lfp, size,
				     &result->logfont);

  return result;
}

/**
 * pango_win32_render:
 * @hdc:     the device 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)
 *
 * Render a PangoGlyphString onto a Windows DC
 */
void 
pango_win32_render (HDC               hdc,
		    PangoFont        *font,
		    PangoGlyphString *glyphs,
		    int               x, 
		    int               y)
{
  HFONT hfont, old_hfont = NULL;
  int i, j, num_valid_glyphs;
  guint16 *glyph_indexes;
  gint *dX;
  gint this_x;
  PangoGlyphUnit start_x_offset, x_offset, next_x_offset, cur_y_offset;

  g_return_if_fail (glyphs != NULL);

#ifdef PANGO_WIN32_DEBUGGING
  if (pango_win32_debug)
    {
      PING (("num_glyphs:%d", glyphs->num_glyphs));
      for (i = 0; i < glyphs->num_glyphs; i++)
	{
	  printf (" %d:%d", glyphs->glyphs[i].glyph, glyphs->glyphs[i].geometry.width);
	  if (glyphs->glyphs[i].geometry.x_offset != 0 || 
	      glyphs->glyphs[i].geometry.y_offset != 0)
	    printf (":%d,%d", glyphs->glyphs[i].geometry.x_offset,
		    glyphs->glyphs[i].geometry.y_offset);
	}
      printf ("\n");
    }
#endif

  if (glyphs->num_glyphs == 0)
    return;

  hfont = pango_win32_get_hfont (font);
  if (!hfont)
    return;

  old_hfont = SelectObject (hdc, hfont);
		
  glyph_indexes = g_new (guint16, glyphs->num_glyphs);
  dX = g_new (INT, glyphs->num_glyphs);

  /* Render glyphs using one ExtTextOutW() call for each run of glyphs
   * that have the same y offset. The big majoroty of glyphs will have
   * y offset of zero, so in general, the whole glyph string will be
   * rendered by one call to ExtTextOutW().
   *
   * In order to minimize buildup of rounding errors, we keep track of
   * where the glyphs should be rendered in PangoGlyphUnits, and round
   * to pixels separately for each glyph,
   */

  i = 0;

  /* Outer loop through all glyphs in string */
  while (i < glyphs->num_glyphs)
    {
      cur_y_offset = glyphs->glyphs[i].geometry.y_offset;
      num_valid_glyphs = 0;
      x_offset = 0;
      start_x_offset = glyphs->glyphs[i].geometry.x_offset;
      this_x = PANGO_PIXELS (start_x_offset);

      /* Inner loop through glyphs with the same y offset, or code
       * point zero (just spacing).
       */
      while (i < glyphs->num_glyphs &&
	     (glyphs->glyphs[i].glyph == PANGO_GLYPH_EMPTY ||
	      cur_y_offset == glyphs->glyphs[i].geometry.y_offset))
	{
	  if (glyphs->glyphs[i].glyph == PANGO_GLYPH_EMPTY)
	    {
	      /* PANGO_GLYPH_EMPTY glyphs should not be rendered, but their
	       * indicated width (set up by PangoLayout) should be taken
	       * into account.
	       */

	      /* If the string starts with spacing, must shift the
	       * starting point for the glyphs actually rendered.  For
	       * spacing in the middle of the glyph string, add to the dX
	       * of the previous glyph to be rendered.
	       */
	      if (num_valid_glyphs == 0)
		start_x_offset += glyphs->glyphs[i].geometry.width;
	      else
		{
		  x_offset += glyphs->glyphs[i].geometry.width;
		  dX[num_valid_glyphs-1] = PANGO_PIXELS (x_offset) - this_x;
		}
	    }
	  else
	    {
	      if (glyphs->glyphs[i].glyph & PANGO_GLYPH_UNKNOWN_FLAG)
		{
		  /* Glyph index is actually the char value that doesn't
		   * have any glyph (ORed with the flag). We should really
		   * do the same that pango_xft_real_render() does: render
		   * a box with the char value in hex inside it in a tiny
		   * font. Later. For now, use the TrueType invalid glyph
		   * at 0.
		   */
		  glyph_indexes[num_valid_glyphs] = 0;
		}
	      else
		glyph_indexes[num_valid_glyphs] = glyphs->glyphs[i].glyph;

	      x_offset += glyphs->glyphs[i].geometry.width;

	      /* If the next glyph has an X offset, take that into consideration now */
	      if (i < glyphs->num_glyphs - 1)
		next_x_offset = glyphs->glyphs[i+1].geometry.x_offset;
	      else
		next_x_offset = 0;

	      dX[num_valid_glyphs] = PANGO_PIXELS (x_offset + next_x_offset) - this_x;

	      /* Prepare for next glyph */
	      this_x += dX[num_valid_glyphs];
	      num_valid_glyphs++;
	    }
	  i++;
	}
#ifdef PANGO_WIN32_DEBUGGING
      if (pango_win32_debug)
	{
	  printf ("ExtTextOutW at %d,%d deltas:",
		  x + PANGO_PIXELS (start_x_offset),
		  y + PANGO_PIXELS (cur_y_offset));
	  for (j = 0; j < num_valid_glyphs; j++)
	    printf (" %d", dX[j]);
	  printf ("\n");
	}
#endif

      ExtTextOutW (hdc,
		   x + PANGO_PIXELS (start_x_offset),
		   y + PANGO_PIXELS (cur_y_offset),
		   ETO_GLYPH_INDEX,
		   NULL,
		   glyph_indexes, num_valid_glyphs,
		   dX);
      x += this_x;
    }


  SelectObject (hdc, old_hfont); /* restore */
  g_free (glyph_indexes);
  g_free (dX);
}

/**
 * pango_win32_render_transformed:
 * @hdc:     a windows device context
 * @matrix:  a #PangoMatrix, or %NULL to use an identity transformation
 * @font:    the font in which to draw the string
 * @glyphs:  the glyph string to draw
 * @x:       the x position of the start of the string (in Pango
 *           units in user space coordinates)
 * @y:       the y position of the baseline (in Pango units
 *           in user space coordinates)
 *
 * Renders a #PangoGlyphString onto a windows DC, possibly
 * transforming the layed-out coordinates through a transformation
 * matrix. Note that the transformation matrix for @font is not
 * changed, so to produce correct rendering results, the @font
 * must have been loaded using a #PangoContext with an identical
 * transformation matrix to that passed in to this function.
 **/
void 
pango_win32_render_transformed (HDC                hdc,
				const PangoMatrix *matrix,
				PangoFont         *font,
				PangoGlyphString  *glyphs,
				int                x, 
				int                y)
{
  XFORM xForm;
  XFORM xFormPrev = {1.0, 0.0, 0.0, 1.0, 0.0, 0.0};
  int   mode = GetGraphicsMode (hdc);

  if (!SetGraphicsMode (hdc, GM_ADVANCED))
    g_warning ("SetGraphicsMode() failed");
  else if (!GetWorldTransform (hdc, &xFormPrev))
    g_warning ("GetWorldTransform() failed");
  else if (matrix)
    {
      xForm.eM11 = matrix->xx;
      xForm.eM12 = matrix->yx;
      xForm.eM21 = matrix->xy;
      xForm.eM22 = matrix->yy;
      xForm.eDx = matrix->x0;
      xForm.eDy = matrix->y0;
      if (!SetWorldTransform (hdc, &xForm))
        g_warning ("GetWorldTransform() failed");
    }

  pango_win32_render (hdc, font, glyphs, x/PANGO_SCALE, y/PANGO_SCALE);

  /* restore */
  SetWorldTransform (hdc, &xFormPrev);
  SetGraphicsMode (hdc, mode);
}

static void
pango_win32_font_get_glyph_extents (PangoFont      *font,
				    PangoGlyph      glyph,
				    PangoRectangle *ink_rect,
				    PangoRectangle *logical_rect)
{
  PangoWin32Font *win32font = (PangoWin32Font *)font;
  guint16 glyph_index = glyph;
  GLYPHMETRICS gm;
  guint32 res;
  HFONT hfont;
  MAT2 m = {{0,1}, {0,0}, {0,0}, {0,1}};
  PangoWin32GlyphInfo *info;

  if (glyph == PANGO_GLYPH_EMPTY)
    {
      if (ink_rect)
	ink_rect->x = ink_rect->width = ink_rect->y = ink_rect->height = 0;
      if (logical_rect)
	logical_rect->x = logical_rect->width = logical_rect->y = logical_rect->height = 0;
      return;
    }

  if (glyph & PANGO_GLYPH_UNKNOWN_FLAG)
    glyph_index = glyph = 0;

  info = g_hash_table_lookup (win32font->glyph_info, GUINT_TO_POINTER (glyph));
  
  if (!info)
    {
      info = g_new0 (PangoWin32GlyphInfo, 1);

      memset (&gm, 0, sizeof (gm));

      hfont = pango_win32_get_hfont (font);
      SelectObject (pango_win32_hdc, hfont);
      /* FIXME: (Alex) This constant reuse of pango_win32_hdc is
	 not thread-safe */
      res = GetGlyphOutlineA (pango_win32_hdc, 
			      glyph_index,
			      GGO_METRICS | GGO_GLYPH_INDEX,
			      &gm, 
			      0, NULL,
			      &m);
  
      if (res == GDI_ERROR)
	{
	  gchar *error = g_win32_error_message (GetLastError ());
	  g_warning ("GetGlyphOutline(%04X) failed: %s\n",
		     glyph_index, error);
	  g_free (error);

	  /* Don't just return now, use the still zeroed out gm */
	}

      info->ink_rect.x = PANGO_SCALE * gm.gmptGlyphOrigin.x;
      info->ink_rect.width = PANGO_SCALE * gm.gmBlackBoxX;
      info->ink_rect.y = - PANGO_SCALE * gm.gmptGlyphOrigin.y;
      info->ink_rect.height = PANGO_SCALE * gm.gmBlackBoxY;

      info->logical_rect.x = 0;
      info->logical_rect.width = PANGO_SCALE * gm.gmCellIncX;
      info->logical_rect.y = - PANGO_SCALE * win32font->tm_ascent;
      info->logical_rect.height = PANGO_SCALE * (win32font->tm_ascent + win32font->tm_descent);

      g_hash_table_insert (win32font->glyph_info, GUINT_TO_POINTER(glyph), info);
    }

  if (ink_rect)
    *ink_rect = info->ink_rect;

  if (logical_rect)
    *logical_rect = info->logical_rect;
}

static int
max_glyph_width (PangoLayout *layout)
{
  int max_width = 0;
  GSList *l, *r;

  for (l = pango_layout_get_lines (layout); l; l = l->next)
    {
      PangoLayoutLine *line = l->data;

      for (r = line->runs; r; r = r->next)
        {
          PangoGlyphString *glyphs = ((PangoGlyphItem *)r->data)->glyphs;
          int i;

          for (i = 0; i < glyphs->num_glyphs; i++)
            if (glyphs->glyphs[i].geometry.width > max_width)
              max_width = glyphs->glyphs[i].geometry.width;
        }
    }

  return max_width;
}

static PangoFontMetrics *
pango_win32_font_get_metrics (PangoFont     *font,
			      PangoLanguage *language)
{
  PangoWin32MetricsInfo *info = NULL; /* Quiet gcc */
  PangoWin32Font *win32font = (PangoWin32Font *)font;
  GSList *tmp_list;
      
  const char *sample_str = pango_language_get_sample_string (language);
  
  tmp_list = win32font->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)
    {
      HFONT hfont;
      PangoFontMetrics *metrics;
      
      info = g_new (PangoWin32MetricsInfo, 1);
      win32font->metrics_by_lang = g_slist_prepend (win32font->metrics_by_lang, info);

      info->sample_str = sample_str;
      info->metrics = metrics = pango_font_metrics_new ();

      hfont = pango_win32_get_hfont (font);
      if (hfont != NULL)
	{
	  PangoCoverage *coverage;
	  TEXTMETRIC tm;
	    
	  SelectObject (pango_win32_hdc, hfont);
	  GetTextMetrics (pango_win32_hdc, &tm);

	  metrics->ascent = tm.tmAscent * PANGO_SCALE;
	  metrics->descent = tm.tmDescent * PANGO_SCALE;
	  metrics->approximate_char_width = tm.tmAveCharWidth * PANGO_SCALE;

	  coverage = pango_win32_font_get_coverage (font, language);
	  if (pango_coverage_get (coverage, '0') != PANGO_COVERAGE_NONE &&
	      pango_coverage_get (coverage, '9') != PANGO_COVERAGE_NONE)
	    {
	      PangoContext *context;
	      PangoFontDescription *font_desc;
	      PangoLayout *layout;
	      
	      /*  Get the average width of the chars in "0123456789" */
	      context = pango_win32_get_context ();
	      pango_context_set_language (context, language);
	      font_desc = pango_font_describe (font);
	      pango_context_set_font_description (context, font_desc);
	      layout = pango_layout_new (context);
	      pango_layout_set_text (layout, "0123456789", -1);

	      metrics->approximate_digit_width = max_glyph_width (layout);

	      pango_font_description_free (font_desc);
	      g_object_unref (layout);
	      g_object_unref (context);
	    }
	  else
	    metrics->approximate_digit_width = metrics->approximate_char_width;

	  pango_coverage_unref (coverage);

	  /* FIXME: Should get the real values from the TrueType font file */
	  metrics->underline_position = -2 * PANGO_SCALE;
	  metrics->underline_thickness = 1 * PANGO_SCALE;
	  metrics->strikethrough_thickness = metrics->underline_thickness;
	  /* Really really wild guess */
	  metrics->strikethrough_position = metrics->ascent / 3;
	}
    }
      
  return pango_font_metrics_ref (info->metrics);
}

static PangoFontMap *
pango_win32_font_get_font_map (PangoFont *font)
{
  PangoWin32Font *win32font = (PangoWin32Font *)font;

  return win32font->fontmap;
}

static gboolean
pango_win32_font_real_select_font (PangoFont *font,
				   HDC        hdc)
{
  HFONT hfont = pango_win32_get_hfont (font);

  if (!hfont)
    return FALSE;
  
  if (!SelectObject (hdc, hfont))
    {
      g_warning ("pango_win32_font_real_select_font: Cannot select font\n");
      return FALSE;
    }
  
  return TRUE;
}

static void
pango_win32_font_real_done_font (PangoFont *font)
{
}

static double
pango_win32_font_real_get_metrics_factor (PangoFont *font)
{
  return PANGO_SCALE;
}

/**
 * pango_win32_font_logfont:
 * @font: a #PangoFont which must be from the Win32 backend
 * 
 * Determine the LOGFONT struct for the specified bfont.
 * 
 * Return value: A newly allocated LOGFONT struct. It must be
 * freed with g_free().
 **/
LOGFONT *
pango_win32_font_logfont (PangoFont *font)
{
  PangoWin32Font *win32font = (PangoWin32Font *)font;
  LOGFONT *lfp;

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

  lfp = g_new (LOGFONT, 1);
  *lfp = win32font->logfont;

  return lfp;
}

/**
 * pango_win32_font_select_font:
 * @font: a #PangoFont from the Win32 backend
 * @hdc: a windows device context
 * 
 * Selects the font into the specified DC and changes the mapping mode
 * and world transformation of the DC appropriately for the font.
 * You may want to surround the use of this function with calls
 * to SaveDC and RestoreDC. Call pango_win32_font_done_font() when
 * you are done using the DC to release allocated resources.
 *
 * See pango_win32_font_get_metrics_factor() for information about
 * converting from the coordinate space used by this function
 * into Pango units.
 * 
 * Return value: %TRUE if the operation succeeded.
 **/
gboolean
pango_win32_font_select_font (PangoFont *font,
			      HDC        hdc)
{
  g_return_val_if_fail (PANGO_WIN32_IS_FONT (font), FALSE);
  
  return PANGO_WIN32_FONT_GET_CLASS (font)->select_font (font, hdc);
}

/**
 * pango_win32_font_done_font:
 * @font: a #PangoFont from the win32 backend
 *
 * Releases any resources allocated by pango_win32_font_done_font()
 **/
void
pango_win32_font_done_font (PangoFont *font)
{
  g_return_if_fail (PANGO_WIN32_IS_FONT (font));
  
  PANGO_WIN32_FONT_GET_CLASS (font)->done_font (font);
}

/**
 * pango_win32_font_get_metrics_factor:
 * @font: a #PangoFont from the win32 backend
 * 
 * Returns the scale factor from logical units in the coordinate
 * space used by pango_win32_font_select_font() to Pango units
 * in user space.
 * 
 * Return value: factor to multiply logical units by to get Pango
 *               units.
 **/
double
pango_win32_font_get_metrics_factor (PangoFont *font)
{
  g_return_val_if_fail (PANGO_WIN32_IS_FONT (font), 1.);
  
  return PANGO_WIN32_FONT_GET_CLASS (font)->get_metrics_factor (font);
}

static void
pango_win32_font_dispose (GObject *object)
{
  PangoWin32Font *win32font = PANGO_WIN32_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 (!win32font->in_cache && win32font->fontmap)
    pango_win32_fontmap_cache_add (win32font->fontmap, win32font);

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

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

static void
pango_win32_font_finalize (GObject *object)
{
  PangoWin32Font *win32font = (PangoWin32Font *)object;
  PangoWin32FontCache *cache = pango_win32_font_map_get_font_cache (win32font->fontmap);

  if (win32font->hfont != NULL)
    pango_win32_font_cache_unload (cache, win32font->hfont);

  g_slist_foreach (win32font->metrics_by_lang, (GFunc)free_metrics_info, NULL);
  g_slist_free (win32font->metrics_by_lang);
  
  if (win32font->win32face)
    pango_win32_font_entry_remove (win32font->win32face, PANGO_FONT (win32font));
 
  g_hash_table_destroy (win32font->glyph_info);
 
  g_object_unref (win32font->fontmap);

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

static PangoFontDescription *
pango_win32_font_describe (PangoFont *font)
{
  PangoFontDescription *desc;
  PangoWin32Font *win32font = PANGO_WIN32_FONT (font);

  desc = pango_font_description_copy (win32font->win32face->description);
  pango_font_description_set_size (desc, win32font->size);
  
  return desc;
}

PangoMap *
pango_win32_get_shaper_map (PangoLanguage *lang)
{
  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_WIN32);
    }
  
  return pango_find_map (lang, engine_type_id, render_type_id);
}

static PangoCoverage *
pango_win32_font_get_coverage (PangoFont     *font,
			       PangoLanguage *lang)
{
  PangoCoverage *coverage;
  PangoWin32Font *win32font = (PangoWin32Font *)font;

  coverage = pango_win32_font_entry_get_coverage (win32font->win32face, lang);
  if (!coverage)
    {
      coverage = pango_coverage_new ();
      pango_win32_font_calc_coverage (font, coverage, lang);
      
      pango_win32_font_entry_set_coverage (win32font->win32face, coverage, lang);
    }

  return coverage;
}

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

  shape_map = pango_win32_get_shaper_map (lang);
  return (PangoEngineShape *)pango_map_get_engine (shape_map, ch);
}

/* Utility functions */

/**
 * pango_win32_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_win32_get_unknown_glyph (PangoFont *font,
			       gunichar   wc)
{
  return wc | PANGO_GLYPH_UNKNOWN_FLAG;
}

/**
 * pango_win32_render_layout_line:
 * @hdc:       DC 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)
 *
 * Render a #PangoLayoutLine onto a device context. For underlining to
 * work property the text alignment of the DC should have TA_BASELINE
 * and TA_LEFT.
 */
void 
pango_win32_render_layout_line (HDC              hdc,
				PangoLayoutLine *line,
				int              x, 
				int              y)
{
  GSList *tmp_list = line->runs;
  PangoRectangle overall_rect;
  PangoRectangle logical_rect;
  PangoRectangle ink_rect;
  
  int x_off = 0;

  pango_layout_line_get_extents (line,NULL, &overall_rect);
  
  while (tmp_list)
    {
      HBRUSH oldfg = NULL;
      HBRUSH brush = NULL;
      POINT points[2];
      PangoUnderline uline = PANGO_UNDERLINE_NONE;
      PangoLayoutRun *run = tmp_list->data;
      PangoAttrColor fg_color, bg_color;
      gboolean fg_set, bg_set;
      
      tmp_list = tmp_list->next;

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

      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)
	{
	  HBRUSH oldbrush;

	  brush = CreateSolidBrush (RGB ((bg_color.color.red + 128) >> 8,
					 (bg_color.color.green + 128) >> 8,
					 (bg_color.color.blue + 128) >> 8));
	  oldbrush = SelectObject (hdc, brush);
	  Rectangle (hdc, x + PANGO_PIXELS (x_off + logical_rect.x),
			  y + PANGO_PIXELS (overall_rect.y),
			  PANGO_PIXELS (logical_rect.width),
			  PANGO_PIXELS (overall_rect.height));
	  SelectObject (hdc, oldbrush);
	  DeleteObject (brush);
	}

      if (fg_set)
	{
	  brush = CreateSolidBrush (RGB ((fg_color.color.red + 128) >> 8,
					 (fg_color.color.green + 128) >> 8,
					 (fg_color.color.blue + 128) >> 8));
	  oldfg = SelectObject (hdc, brush);
	}

      pango_win32_render (hdc, run->item->analysis.font, run->glyphs,
			  x + PANGO_PIXELS (x_off), y);

      switch (uline)
	{
	case PANGO_UNDERLINE_NONE:
	  break;
	case PANGO_UNDERLINE_DOUBLE:
	  points[0].x = x + PANGO_PIXELS (x_off + ink_rect.x) - 1;
	  points[0].y = points[1].y = y + 4;
	  points[1].x = x + PANGO_PIXELS (x_off + ink_rect.x + ink_rect.width);
	  Polyline (hdc, points, 2);
	  points[0].y = points[1].y = y + 2;
	  Polyline (hdc, points, 2);
	  break;
	case PANGO_UNDERLINE_SINGLE:
	  points[0].x = x + PANGO_PIXELS (x_off + ink_rect.x) - 1;
	  points[0].y = points[1].y = y + 2;
	  points[1].x = x + PANGO_PIXELS (x_off + ink_rect.x + ink_rect.width);
	  Polyline (hdc, points, 2);
	  break;
	case PANGO_UNDERLINE_ERROR:
          {
            int point_x;
            int counter = 0;
	    int end_x = x + PANGO_PIXELS (x_off + ink_rect.x + ink_rect.width);

            for (point_x = x + PANGO_PIXELS (x_off + ink_rect.x) - 1;
                 point_x <= end_x;
                 point_x += 2)
            {
	      points[0].x = point_x;
	      points[1].x = MAX (point_x + 1, end_x);

              if (counter)
	        points[0].y = points[1].y = y + 2;
              else
	        points[0].y = points[1].y = y + 3;

	      Polyline (hdc, points, 2);
              counter = (counter + 1) % 2;
            }
          }
	  break;
	case PANGO_UNDERLINE_LOW:
	  points[0].x = x + PANGO_PIXELS (x_off + ink_rect.x) - 1;
	  points[0].y = points[1].y = y + PANGO_PIXELS (ink_rect.y + ink_rect.height) + 2;
	  points[1].x = x + PANGO_PIXELS (x_off + ink_rect.x + ink_rect.width);
	  Polyline (hdc, points, 2);
	  break;
	}

      if (fg_set)
	{
	  SelectObject (hdc, oldfg);
	  DeleteObject (brush);
	}
      
      x_off += logical_rect.width;
    }
}

/**
 * pango_win32_render_layout:
 * @hdc:       HDC 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)
 *
 * Render a #PangoLayoutLine onto an X drawable
 */
void 
pango_win32_render_layout (HDC          hdc,
			   PangoLayout *layout,
			   int          x, 
			   int          y)
{
  PangoLayoutIter *iter;

  g_return_if_fail (hdc != NULL);
  g_return_if_fail (PANGO_IS_LAYOUT (layout));

  iter = pango_layout_get_iter (layout);

  do
    {
      PangoRectangle   logical_rect;
      PangoLayoutLine *line;
      int              baseline;
      
      line = pango_layout_iter_get_line (iter);
      
      pango_layout_iter_get_line_extents (iter, NULL, &logical_rect);
      baseline = pango_layout_iter_get_baseline (iter);
      
      pango_win32_render_layout_line (hdc,
                                      line,
                                      x + PANGO_PIXELS (logical_rect.x),
                                      y + PANGO_PIXELS (baseline));
    }
  while (pango_layout_iter_next_line (iter));

  pango_layout_iter_free (iter);  
}

/* 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_win32_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 guint 
get_cmap_offset (HDC     hdc,
		 guint16 encoding_id)
{
  guint16 n_tables;
  struct cmap_encoding_subtable *table;
  gint32 res;
  int i;
  guint32 offset;

  /* Get The number of encoding tables, at offset 2 */
  res = GetFontData (hdc, CMAP, 2, &n_tables, 2);
  if (res != 2)
    return 0;

  n_tables = GUINT16_FROM_BE (n_tables);
  
  table = g_malloc (ENCODING_TABLE_SIZE*n_tables);
  
  res = GetFontData (hdc, CMAP, CMAP_HEADER_SIZE, table, ENCODING_TABLE_SIZE*n_tables);
  if (res != ENCODING_TABLE_SIZE*n_tables)
    return 0;

  for (i = 0; i < n_tables; i++)
    {
      if (table[i].platform_id == GUINT16_TO_BE (MICROSOFT_PLATFORM_ID) &&
	  table[i].encoding_id == GUINT16_TO_BE (encoding_id))
	{
	  offset = GUINT32_FROM_BE (table[i].offset);
	  g_free (table);
	  return offset;
	}
    }
  g_free (table);
  return 0;
}

static gpointer
get_format_4_cmap (HDC hdc)
{
  guint32 offset;
  guint32 res;
  guint16 length;
  guint16 *tbl, *tbl_end;
  struct format_4_cmap *table;

  /* FIXME: Could look here at the CRC for the font in the DC 
            and return a cached copy if the same */

  offset = get_cmap_offset (hdc, UNICODE_ENCODING_ID);
  if (offset == 0)
    return NULL;

  res = GetFontData (hdc, CMAP, offset + 2, &length, 2);
  if (res != 2)
    return NULL;
  length = GUINT16_FROM_BE (length);

  table = g_malloc (length);

  res = GetFontData (hdc, CMAP, offset, table, length);
  if (res != length ||
      GUINT16_FROM_BE (table->format) != 4 ||
      (GUINT16_FROM_BE (table->length) % 2) != 0)
    {
      g_free (table);
      return NULL;
    }
  
  table->format = GUINT16_FROM_BE (table->format);
  table->length = GUINT16_FROM_BE (table->length);
  table->language = GUINT16_FROM_BE (table->language);
  table->seg_count_x_2 = GUINT16_FROM_BE (table->seg_count_x_2);
  table->search_range = GUINT16_FROM_BE (table->search_range);
  table->entry_selector = GUINT16_FROM_BE (table->entry_selector);
  table->range_shift = GUINT16_FROM_BE (table->range_shift);

  tbl_end = (guint16 *)((char *)table + length);
  tbl = &table->reserved;

  while (tbl < tbl_end)
    {
      *tbl = GUINT16_FROM_BE (*tbl);
      tbl++;
    }

  return table;
}

static guint16 *
get_id_range_offset (struct format_4_cmap *table)
{
  gint32 seg_count = table->seg_count_x_2/2;
  return &table->arrays[seg_count*3];
}

static guint16 *
get_id_delta (struct format_4_cmap *table)
{
  gint32 seg_count = table->seg_count_x_2/2;
  return &table->arrays[seg_count*2];
}

static guint16 *
get_start_count (struct format_4_cmap *table)
{
  gint32 seg_count = table->seg_count_x_2/2;
  return &table->arrays[seg_count*1];
}

static guint16 *
get_end_count (struct format_4_cmap *table)
{
  gint32 seg_count = table->seg_count_x_2/2;
  /* Apparently the reseved spot is not reserved for 
     the end_count array!? */
  return (&table->arrays[seg_count*0])-1;
}

static gboolean
find_segment (struct format_4_cmap *table, 
	      guint16               wc,
	      guint16              *segment)
{
  guint16 start, end, i;
  guint16 seg_count = table->seg_count_x_2/2;
  guint16 *end_count = get_end_count (table);
  guint16 *start_count = get_start_count (table);
  static guint last = 0; /* Cache of one */
  
  if (last < seg_count &&
      wc >= start_count[last] &&
      wc <= end_count[last])
    {
      *segment = last;
      return TRUE;
    }
      

  /* Binary search for the segment */
  start = 0; /* inclusive */
  end = seg_count; /* not inclusive */
  while (start < end) 
    {
      /* Look at middle pos */
      i = (start + end)/2;

      if (i == start)
	{
	  /* We made no progress. Look if this is the one. */
	  
	  if (wc >= start_count[i] &&
	      wc <= end_count[i])
	    {
	      *segment = i;
	      last = i;
	      return TRUE;
	    }
	  else
	    return FALSE;
	}
      else if (wc < start_count[i])
	{
	  end = i;
	}
      else if (wc > end_count[i])
	{
	  start = i;
	}
      else
	{
	  /* Found it! */
	  *segment = i;
	  last = i;
	  return TRUE;
	}
    }
  return FALSE;
}

static gpointer
get_format_12_cmap (HDC hdc)
{
  guint32 offset;
  guint32 res;
  guint32 length;
  guint32 *tbl, *tbl_end;
  struct format_12_cmap *table;
  
  offset = get_cmap_offset (hdc, UCS4_ENCODING_ID);
  if (offset == 0)
    return NULL;

  res = GetFontData (hdc, CMAP, offset + 4, &length, 4);
  if (res != 4)
    return NULL;
  length = GUINT32_FROM_BE (length);

  table = g_malloc (length);

  res = GetFontData (hdc, CMAP, offset, table, length);
  if (res != length)
    {
      g_free (table);
      return NULL;
    }

  table->format = GUINT16_FROM_BE (table->format);
  table->length = GUINT32_FROM_BE (table->length);
  table->language = GUINT32_FROM_BE (table->language);
  table->count = GUINT32_FROM_BE (table->count);

  if (table->format != 12 ||
      (table->length % 4) != 0 ||
      table->length > length ||
      table->length < 16 + table->count * 12)
    {
      g_free (table);
      return NULL;
    }
  
  tbl_end = (guint32 *) ((char *) table + length);
  tbl = table->groups;

  while (tbl < tbl_end)
    {
      *tbl = GUINT32_FROM_BE (*tbl);
      tbl++;
    }

  return table;
}
  
static gpointer
font_get_cmap (PangoFont *font)
{
  PangoWin32Font *win32font = (PangoWin32Font *)font;
  gpointer cmap;

  if (win32font->win32face->cmap)
    return win32font->win32face->cmap;

  pango_win32_font_select_font (font, pango_win32_hdc);

  /* Prefer the format 12 cmap */
  if ((cmap = get_format_12_cmap (pango_win32_hdc)) != NULL)
    {
      win32font->win32face->cmap_format = 12;
      win32font->win32face->cmap = cmap;
    }
  else if ((cmap = get_format_4_cmap (pango_win32_hdc)) != NULL)
    {
      win32font->win32face->cmap_format = 4;
      win32font->win32face->cmap = cmap;
    }

  pango_win32_font_done_font (font);

  return cmap;
}

/**
 * pango_win32_font_get_glyph_index:
 * @font: a #PangoFont.
 * @wc: a Unicode character.
 *
 * Obtains the index of the glyph for @wc in @font, or 0, if not
 * covered.
 *
 * Return value: the glyph index for @wc.
 **/
gint
pango_win32_font_get_glyph_index (PangoFont *font,
				  gunichar   wc)
{
  PangoWin32Font *win32font = (PangoWin32Font *)font;
  gpointer cmap;
  guint16 glyph;

  /* Do GetFontData magic on font->hfont here. */
  cmap = font_get_cmap (font);

  if (cmap == NULL)
    return 0;

  if (win32font->win32face->cmap_format == 4)
    {
      struct format_4_cmap *cmap4 = cmap;
      guint16 *id_range_offset;
      guint16 *id_delta;
      guint16 *start_count;
      guint16 segment;
      guint16 id;
      guint16 ch = wc;
  
      if (wc > 0xFFFF)
	return 0;

      if (!find_segment (cmap4, ch, &segment))
	return 0;

      id_range_offset = get_id_range_offset (cmap4);
      id_delta = get_id_delta (cmap4);
      start_count = get_start_count (cmap4);

      if (id_range_offset[segment] == 0)
	glyph = (id_delta[segment] + ch) % 65536;
      else
	{
	  id = *(id_range_offset[segment]/2 +
		 (ch - start_count[segment]) +
		 &id_range_offset[segment]);
	  if (id)
	    glyph = (id_delta[segment] + id) %65536;
	  else
	    glyph = 0;
	}
    }
  else if (win32font->win32face->cmap_format == 12)
    {
      struct format_12_cmap *cmap12 = cmap;
      guint32 i;

      glyph = 0;
      for (i = 0; i < cmap12->count; i++)
	{
	  if (cmap12->groups[i*3+0] <= wc && wc <= cmap12->groups[i*3+1])
	    {
	      glyph = cmap12->groups[i*3+2] + (wc - cmap12->groups[i*3+0]);
	      break;
	    }
	}
    }
  else
    g_assert_not_reached ();

  return glyph;
}

gboolean
pango_win32_get_name_header (HDC                 hdc,
			     struct name_header *header)
{
  if (GetFontData (hdc, NAME, 0, header, sizeof (*header)) != sizeof (*header))
    return FALSE;

  header->num_records = GUINT16_FROM_BE (header->num_records);
  header->string_storage_offset = GUINT16_FROM_BE (header->string_storage_offset);

  return TRUE;
}
  
gboolean
pango_win32_get_name_record (HDC                 hdc,
			     gint                i,
			     struct name_record *record)
{
  if (GetFontData (hdc, NAME, 6 + i * sizeof (*record),
		   record, sizeof (*record)) != sizeof (*record))
    return FALSE;
  
  record->platform_id = GUINT16_FROM_BE (record->platform_id);
  record->encoding_id = GUINT16_FROM_BE (record->encoding_id);
  record->language_id = GUINT16_FROM_BE (record->language_id);
  record->name_id = GUINT16_FROM_BE (record->name_id);
  record->string_length = GUINT16_FROM_BE (record->string_length);
  record->string_offset = GUINT16_FROM_BE (record->string_offset);

  return TRUE;
}

static gboolean
font_has_name_in (PangoFont                       *font,
		  PangoWin32CoverageLanguageClass  cjkv)
{
  HFONT hfont, oldhfont;
  struct name_header header;
  struct name_record record;
  gint i;
  gboolean retval = FALSE;

  if (cjkv == PANGO_WIN32_COVERAGE_UNSPEC)
    return TRUE;

  hfont = pango_win32_get_hfont (font);
  oldhfont = SelectObject (pango_win32_hdc, hfont);

  if (!pango_win32_get_name_header (pango_win32_hdc, &header))
    {
      SelectObject (pango_win32_hdc, oldhfont);
      return FALSE;
    }

  for (i = 0; i < header.num_records; i++)
    {
      if (!pango_win32_get_name_record (pango_win32_hdc, i, &record))
	{
	  SelectObject (pango_win32_hdc, oldhfont);
	  return FALSE;
	}

      if ((record.name_id != 1 && record.name_id != 16) || record.string_length <= 0)
	continue;

      PING(("platform:%d encoding:%d language:%04x name_id:%d",
	    record.platform_id, record.encoding_id, record.language_id, record.name_id));

      if (record.platform_id == MICROSOFT_PLATFORM_ID)
	if ((cjkv == PANGO_WIN32_COVERAGE_ZH_TW &&
	     record.language_id == MAKELANGID (LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL))
	    ||
	    (cjkv == PANGO_WIN32_COVERAGE_ZH_CN &&
	     record.language_id == MAKELANGID (LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED))
	    ||
	    (cjkv == PANGO_WIN32_COVERAGE_JA &&
	     PRIMARYLANGID (record.language_id) == LANG_JAPANESE)
	    ||
	    (cjkv == PANGO_WIN32_COVERAGE_KO &&
	     PRIMARYLANGID (record.language_id) == LANG_KOREAN)
	    ||
	    (cjkv == PANGO_WIN32_COVERAGE_VI &&
	     PRIMARYLANGID (record.language_id) == LANG_VIETNAMESE))
	  {
	    PING (("yep:%d:%04x", cjkv, record.language_id));
	    retval = TRUE;
	    break;
	  }
    }

  SelectObject (pango_win32_hdc, oldhfont);
  return retval;
}

static void
pango_win32_font_calc_coverage (PangoFont     *font,
				PangoCoverage *coverage,
				PangoLanguage *lang)
{
  PangoWin32Font *win32font = (PangoWin32Font *)font;
  gpointer cmap;
  guint32 ch;
  guint32 i;
  PangoWin32CoverageLanguageClass cjkv;
  gboolean hide_unihan = FALSE;
  
  PING(("font:%s lang:%s",
	pango_font_description_to_string (pango_font_describe (font)),
	pango_language_to_string (lang)));

  cjkv = pango_win32_coverage_language_classify (lang);

  if (cjkv != PANGO_WIN32_COVERAGE_UNSPEC && !font_has_name_in (font, cjkv))
    {
      PING(("hiding UniHan chars"));
      hide_unihan = TRUE;
    }

  /* Do GetFontData magic on font->hfont here. */
  cmap = font_get_cmap (font);
  if (cmap == NULL)
    {
      PING(("no table"));
      return;
    }
  
  PING (("coverage:"));
  if (win32font->win32face->cmap_format == 4)
    {
      struct format_4_cmap *cmap4 = cmap;
      guint16 *id_range_offset;
      guint16 *start_count;
      guint16 *end_count;
      guint16 seg_count;
      guint16 id;

      seg_count = cmap4->seg_count_x_2/2;
      end_count = get_end_count (cmap4);
      start_count = get_start_count (cmap4);
      id_range_offset = get_id_range_offset (cmap4);

      for (i = 0; i < seg_count; i++)
	{
	  if (id_range_offset[i] == 0)
	    {
#ifdef PANGO_WIN32_DEBUGGING
	      if (pango_win32_debug)
		{
		  if (end_count[i] == start_count[i])
		    printf ("%04x ", start_count[i]);
		  else
		    printf ("%04x:%04x ", start_count[i], end_count[i]);
		}
#endif	  
	      for (ch = start_count[i]; ch <= end_count[i]; ch++)
		if (hide_unihan && CH_IS_UNIHAN_BMP (ch))
		  pango_coverage_set (coverage, ch, PANGO_COVERAGE_APPROXIMATE);
		else
		  pango_coverage_set (coverage, ch, PANGO_COVERAGE_EXACT);
	    }
	  else
	    {
#ifdef PANGO_WIN32_DEBUGGING
	      guint32 ch0 = G_MAXUINT;
#endif
	      for (ch = start_count[i]; ch <= end_count[i]; ch++)
		{
		  if (ch == 0xFFFF)
		    break;
		  
		  id = *(id_range_offset[i]/2 +
			 (ch - start_count[i]) +
			 &id_range_offset[i]);
		  if (id)
		    {
#ifdef PANGO_WIN32_DEBUGGING
		      if (ch0 == G_MAXUINT)
			ch0 = ch;
#endif
		      if (hide_unihan && CH_IS_UNIHAN_BMP (ch))
			pango_coverage_set (coverage, ch, PANGO_COVERAGE_APPROXIMATE);
		      else
			pango_coverage_set (coverage, ch, PANGO_COVERAGE_EXACT);
		    }
#ifdef PANGO_WIN32_DEBUGGING
		  else if (ch0 < G_MAXUINT)
		    {
		      if (pango_win32_debug)
			{
			  if (ch > ch0 + 2)
			    printf ("%04x:%04x ", ch0, ch - 1);
			  else
			    printf ("%04x ", ch0);
			}
		      ch0 = G_MAXUINT;
		    }
#endif
		}
#ifdef PANGO_WIN32_DEBUGGING
	      if (ch0 < G_MAXUINT)
		{
		  if (pango_win32_debug)
		    {
		      if (ch > ch0 + 2)
			printf ("%04x:%04x ", ch0, ch - 1);
		      else
			printf ("%04x ", ch0);
		    }
		}
#endif
	    }
	}
    }
  else if (win32font->win32face->cmap_format == 12)
    {
      struct format_12_cmap *cmap12 = cmap;

      for (i = 0; i < cmap12->count; i++)
	{
#ifdef PANGO_WIN32_DEBUGGING
	  if (pango_win32_debug)
	    {
	      if (cmap12->groups[i*3+0] == cmap12->groups[i*3+1])
		printf ("%04x ", cmap12->groups[i*3+0]);
	      else
		printf ("%04x:%04x ", cmap12->groups[i*3+0], cmap12->groups[i*3+1]);
	    }
#endif
	  for (ch = cmap12->groups[i*3+0]; ch <= cmap12->groups[i*3+1]; ch++)
	    {
	      if (hide_unihan && CH_IS_UNIHAN (ch))
		pango_coverage_set (coverage, ch, PANGO_COVERAGE_APPROXIMATE);
	      else
		pango_coverage_set (coverage, ch, PANGO_COVERAGE_EXACT);
	    }
	}
    }
  else
    g_assert_not_reached ();
#ifdef PANGO_WIN32_DEBUGGING
  if (pango_win32_debug)
    printf ("\n");
#endif
}