summaryrefslogtreecommitdiff
path: root/src/vtepangocairo.c
blob: 5d213ddeed1db18110e56dd3c6fc59483d3305ff (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
/*
 * Copyright (C) 2003,2008 Red Hat, Inc.
 *
 * This 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 program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */


#include <config.h>

#include <sys/param.h>
#include <string.h>
#include <gtk/gtk.h>
#include <glib.h>
#include "debug.h"
#include "vtebg.h"
#include "vtedraw.h"
#include "vtepangocairo.h"
#include "vte-private.h"

#include <pango/pangocairo.h>


/* Overview:
 *
 *
 * This file implements vte rendering using pangocairo.  Note that this does
 * NOT implement any kind of complex text rendering.  That's not currently a
 * goal.
 *
 * The aim is to be super-fast and avoid unneeded work as much as possible.
 * Here is an overview of how that is accomplished:
 *
 *   - We attach a font_info to draw as our private data.  A font_info has
 *     all the information to quickly draw text.
 *
 *   - A font_info keeps uses unichar_font_info structs that represent all
 *     information needed to quickly draw a single gunichar.  The font_info
 *     creates those unichar_font_info structs on demand and caches them
 *     indefinitely.  It uses a direct array for the ASCII range and a hash
 *     table for the rest.
 *
 *
 * Fast rendering of unichars:
 *
 * A unichar_font_info (uinfo) calls Pango to set text for the unichar upon
 * initialization and then caches information needed to draw the results
 * later.  It uses three different internal representations and respectively
 * three drawing paths:
 *
 *   - COVERAGE_USE_CAIRO_GLYPH:
 *     Keeping a single glyph index and a cairo scaled-font.  This is the
 *     fastest way to draw text as it bypasses Pango completely and allows
 *     for stuffing multiple glyphs into a single cairo_show_glyphs() request
 *     (if scaled-fonts match).  This method is used if the glyphs used for
 *     the gunichar as determined by Pango consists of a single regular glyph
 *     positioned at 0,0 using a regular font.  This method is used for more
 *     than 99% of the cases.  Only exceptional cases fall through to the
 *     other two methods.
 *
 *   - COVERAGE_USE_PANGO_GLYPH_STRING:
 *     Keeping a pango glyphstring and a pango font.  This is slightly slower
 *     than the previous case as drawing each glyph goes through pango
 *     separately and causes a separate cairo_show_glyphs() call.  This method
 *     is used when the previous method cannot be used by the glyphs for the
 *     character all use a single font.  This is the method used for hexboxes
 *     and "empty" characters like U+200C ZERO WIDTH NON-JOINER for example.
 *
 *   - COVERAGE_USE_PANGO_LAYOUT_LINE:
 *     Keeping a pango layout line.  This method is used only in the very
 *     weird and exception case that a single gunichar uses more than one font
 *     to be drawn.  This is not expected to happen, but exists for
 *     completeness, to make sure we can deal with any junk pango decides to
 *     throw at us.
 *
 *
 * Caching of font infos:
 *
 * To avoid recreating font info structs for the same font again and again we
 * do the following:
 *
 *   - Use a global cache to share font info structs across different widgets.
 *     We use cairo font options, resolution, and font description as the key
 *     for our hash table.
 *
 *   - When a font info struct is no longer used by any widget, we delay
 *     destroying it for a while (FONT_CACHE_TIMEOUT seconds).  This is
 *     supposed to serve two purposes:
 *
 *       * Destroying a terminal widget and creating it again right after will
 *         reuse the font info struct from the previous widget.
 *
 *       * Zooming in and out a terminal reuses the font info structs.
 *
 *     Since we use gdk timeout to schedule the delayed destruction, we also
 *     add a gtk quit handler which is run when the innermost main loop exits
 *     to cleanup any pending delayed destructions.
 *
 *
 * Pre-caching ASCII letters:
 *
 * When initializing a font info struct we measure a string consisting of all
 * ASCII letters and some other ASCII characters.  Since we have a shaped pango
 * layout at hand, we walk over it and cache unichar font info for the ASCII
 * letters if we can do that easily using COVERAGE_USE_CAIRO_GLYPH.  This
 * means that we precache all ASCII letters without any extra pango shaping
 * involved.
 */



#define FONT_CACHE_TIMEOUT (30) /* seconds */


/* All shared data structures are implicitly protected by GDK mutex, because
 * that's how vte.c works and we only get called from there. */


/* cairo_show_glyphs accepts runs up to 102 glyphs before it allocates a
 * temporary array.
 *
 * Setting this to a large value can cause dramatic slow-downs for some
 * xservers (notably fglrx), see bug #410534.
 *
 * Moreover, setting it larger than VTE_DRAW_MAX_LENGTH is nonsensical,
 * as the higher layers will not submit runs longer than that value.
 */
#define MAX_RUN_LENGTH 100


enum unichar_coverage {
	/* in increasing order of speed */
	COVERAGE_UNKNOWN = 0,		/* we don't know about the character yet */
	COVERAGE_USE_PANGO_LAYOUT_LINE,	/* use a PangoLayoutLine for the character */
	COVERAGE_USE_PANGO_GLYPH_STRING,	/* use a PangoGlyphString for the character */
	COVERAGE_USE_CAIRO_GLYPH	/* use a cairo_glyph_t for the character */
};

union unichar_font_info {
	/* COVERAGE_USE_PANGO_LAYOUT_LINE */
	struct {
		PangoLayoutLine *line;
	} using_pango_layout_line;
	/* COVERAGE_USE_PANGO_GLYPH_STRING */
	struct {
		PangoFont *font;
		PangoGlyphString *glyph_string;
	} using_pango_glyph_string;
	/* COVERAGE_USE_CAIRO_GLYPH */
	struct {
		cairo_scaled_font_t *scaled_font;
		unsigned int glyph_index;
	} using_cairo_glyph;
};

struct unichar_info {
	guchar coverage;
	guchar has_unknown_chars;
	guint16 width;
	union unichar_font_info ufi;
};

static struct unichar_info *
unichar_info_create (void)
{
	return g_slice_new0 (struct unichar_info);
}

static void
unichar_info_finish (struct unichar_info *uinfo)
{
	union unichar_font_info *ufi = &uinfo->ufi;

	switch (uinfo->coverage) {
	default:
	case COVERAGE_UNKNOWN:
		g_assert_not_reached ();
		break;
	case COVERAGE_USE_PANGO_LAYOUT_LINE:
		/* we hold a manual reference on layout */
		g_object_unref (ufi->using_pango_layout_line.line->layout);
		ufi->using_pango_layout_line.line->layout = NULL;
		pango_layout_line_unref (ufi->using_pango_layout_line.line);
		ufi->using_pango_layout_line.line = NULL;
		break;
	case COVERAGE_USE_PANGO_GLYPH_STRING:
		if (ufi->using_pango_glyph_string.font)
			g_object_unref (ufi->using_pango_glyph_string.font);
		ufi->using_pango_glyph_string.font = NULL;
		pango_glyph_string_free (ufi->using_pango_glyph_string.glyph_string);
		ufi->using_pango_glyph_string.glyph_string = NULL;
		break;
	case COVERAGE_USE_CAIRO_GLYPH:
		cairo_scaled_font_destroy (ufi->using_cairo_glyph.scaled_font);
		ufi->using_cairo_glyph.scaled_font = NULL;
		break;
	}
}

static void
unichar_info_destroy (struct unichar_info *uinfo)
{
	unichar_info_finish (uinfo);
	g_slice_free (struct unichar_info, uinfo);
}

struct font_info {
	/* lifecycle */
	int ref_count;
	guint destroy_timeout; /* only used when ref_count == 0 */

	/* reusable layout set with font and everything */
	PangoLayout *layout;

	/* cache of character info */
	struct unichar_info ascii_unichar_info[128];
	GHashTable *other_unichar_info;

	/* cell metrics */
	gint width, height, ascent;

#ifdef VTE_DEBUG
	/* profiling info */
	int coverage_count[4];
#endif
};


static struct unichar_info *
font_info_find_unichar_info (struct font_info    *info,
			     gunichar             c)
{
	struct unichar_info *uinfo;

	if (G_LIKELY (c < G_N_ELEMENTS (info->ascii_unichar_info)))
		return &info->ascii_unichar_info[c];

	if (G_UNLIKELY (info->other_unichar_info == NULL))
		info->other_unichar_info = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) unichar_info_destroy);

	uinfo = g_hash_table_lookup (info->other_unichar_info, GINT_TO_POINTER (c));
	if (G_LIKELY (uinfo))
		return uinfo;

	uinfo = unichar_info_create ();
	g_hash_table_insert (info->other_unichar_info, GINT_TO_POINTER (c), uinfo);
	return uinfo;
}


static void
font_info_cache_ascii (struct font_info *info)
{
	PangoLayoutLine *line;
	PangoGlyphItemIter iter;
	PangoGlyphItem *glyph_item;
	PangoGlyphString *glyph_string;
	PangoFont *pango_font;
	cairo_scaled_font_t *scaled_font;
	const char *text;
	gboolean more;
	
	/* We have info->layout holding most ASCII characters.  We want to
	 * cache as much info as we can about the ASCII letters so we don't
	 * have to look them up again later */

	/* Don't cache if unknown glyphs found in layout */
	if (pango_layout_get_unknown_glyphs_count (info->layout) != 0)
		return;

	text = pango_layout_get_text (info->layout);

	line = pango_layout_get_line_readonly (info->layout, 0);

	/* Don't cache if more than one font used for the line */
	if (G_UNLIKELY (!line || !line->runs || line->runs->next))
		return;

	glyph_item = line->runs->data;
	glyph_string = glyph_item->glyphs;
	pango_font = glyph_item->item->analysis.font;
	if (!pango_font)
		return;
	scaled_font = pango_cairo_font_get_scaled_font ((PangoCairoFont *) pango_font);
	if (!scaled_font)
		return;

	for (more = pango_glyph_item_iter_init_start (&iter, glyph_item, text);
	     more;
	     more = pango_glyph_item_iter_next_cluster (&iter))
	{
		struct unichar_info *uinfo;
		union unichar_font_info *ufi;
	 	PangoGlyphGeometry *geometry;
		PangoGlyph glyph;
		gunichar c;

		/* Only cache simple clusters */
		if (iter.start_char +1 != iter.end_char  ||
		    iter.start_index+1 != iter.end_index ||
		    iter.start_glyph+1 != iter.end_glyph)
			continue;

		c = text[iter.start_index];
		glyph = glyph_string->glyphs[iter.start_glyph].glyph;
		geometry = &glyph_string->glyphs[iter.start_glyph].geometry;

		/* Only cache non-common characters as common characters get
		 * their font from their neighbors */
		if (pango_script_for_unichar (c) <= PANGO_SCRIPT_INHERITED)
			continue;

		/* Only cache simple glyphs */
		if (!(glyph <= 0xFFFF) || (geometry->x_offset | geometry->y_offset) != 0)
			continue;

		uinfo = font_info_find_unichar_info (info, c);
		if (G_UNLIKELY (uinfo->coverage != COVERAGE_UNKNOWN))
			continue;

		ufi = &uinfo->ufi;

		uinfo->width = PANGO_PIXELS_CEIL (geometry->width);
		uinfo->has_unknown_chars = FALSE;

		uinfo->coverage = COVERAGE_USE_CAIRO_GLYPH;

		ufi->using_cairo_glyph.scaled_font = cairo_scaled_font_reference (scaled_font);
		ufi->using_cairo_glyph.glyph_index = glyph;

#ifdef VTE_DEBUG
		info->coverage_count[0]++;
		info->coverage_count[uinfo->coverage]++;
#endif
	}

#ifdef VTE_DEBUG
	_vte_debug_print (VTE_DEBUG_PANGOCAIRO,
			  "vtepangocairo: %p cached %d ASCII letters\n",
			  info, info->coverage_count[0]);
#endif
}

static void
font_info_measure_font (struct font_info *info)
{
	PangoRectangle logical;
	gunichar full_codepoints[] = {VTE_DRAW_DOUBLE_WIDE_IDEOGRAPHS};
	GString *full_string;
	gint single_width, full_width;
	guint i;

	/* Estimate for ASCII characters. */
	pango_layout_set_text (info->layout, VTE_DRAW_SINGLE_WIDE_CHARACTERS, -1);
	pango_layout_get_extents (info->layout, NULL, &logical);
	single_width = howmany (logical.width, strlen(VTE_DRAW_SINGLE_WIDE_CHARACTERS));
	info->height = PANGO_PIXELS_CEIL (logical.height);
	info->ascent = PANGO_PIXELS_CEIL (pango_layout_get_baseline (info->layout));

	/* Now that we shaped the entire ASCII character string, cache glyph
	 * info for them */
	font_info_cache_ascii (info);

	/* Estimate for CJK characters. */
	full_width = single_width * 2;
	full_string = g_string_new(NULL);
	for (i = 0; i < G_N_ELEMENTS (full_codepoints); i++) {
		g_string_append_unichar (full_string, full_codepoints[i]);
	}
	pango_layout_set_text (info->layout, full_string->str, -1);
	g_string_free (full_string, TRUE);
	pango_layout_get_extents (info->layout, NULL, &logical);
	full_width = howmany (logical.width, G_N_ELEMENTS(full_codepoints));

	/* If they're the same, then we have a screwy font. */
	if (full_width == single_width) {
		single_width = (full_width + 1) / 2;
	}

	/* We don't do CEIL for width since we are averaging; rounding is
	 * more accurate */
	info->width = PANGO_PIXELS (single_width);

	if (info->height == 0) {
		info->height = PANGO_PIXELS_CEIL (logical.height);
	}
	if (info->ascent == 0) {
		info->ascent = PANGO_PIXELS_CEIL (pango_layout_get_baseline (info->layout));
	}

	_vte_debug_print (VTE_DEBUG_MISC,
			  "vtepangocairo: %p font metrics = %dx%d (%d)\n",
			  info, info->width, info->height, info->ascent);
}


static struct font_info *
font_info_allocate (PangoContext *context)
{
	struct font_info *info;

	info = g_slice_new0 (struct font_info);

	_vte_debug_print (VTE_DEBUG_PANGOCAIRO,
			  "vtepangocairo: %p allocating font_info\n",
			  info);

	info->layout = pango_layout_new (context);

	font_info_measure_font (info);

	return info;
}

static void
font_info_free (struct font_info *info)
{
	gunichar i;

#ifdef VTE_DEBUG
	_vte_debug_print (VTE_DEBUG_PANGOCAIRO,
			  "vtepangocairo: %p freeing font_info.  coverages %d = %d + %d + %d\n",
			  info,
			  info->coverage_count[0],
			  info->coverage_count[1],
			  info->coverage_count[2],
			  info->coverage_count[3]);
#endif

	g_object_unref (info->layout);

	for (i = 0; i < G_N_ELEMENTS (info->ascii_unichar_info); i++)
		unichar_info_finish (&info->ascii_unichar_info[i]);
		
	if (info->other_unichar_info) {
		g_hash_table_destroy (info->other_unichar_info);
	}

	g_slice_free (struct font_info, info);
}


static GHashTable *font_info_for_context;
static guint quit_id;

static gboolean
cleanup_delayed_font_info_destroys_predicate (PangoContext *context,
					      struct font_info *info)
{
	if (info->destroy_timeout) {
		g_source_remove (info->destroy_timeout);
		info->destroy_timeout = 0;

		font_info_free (info);
		return TRUE;
	}

	return FALSE;
}

static gboolean
cleanup_delayed_font_info_destroys (void)
{
	g_hash_table_foreach_remove (font_info_for_context,
				     (GHRFunc) cleanup_delayed_font_info_destroys_predicate,
				     NULL);

	quit_id = 0;
	return 0;
}

static void
ensure_quit_handler (void)
{
	if (G_UNLIKELY (quit_id == 0))
		quit_id = gtk_quit_add (1,
					(GtkFunction) cleanup_delayed_font_info_destroys,
					NULL);
}

static struct font_info *
font_info_register (struct font_info *info)
{
	g_hash_table_insert (font_info_for_context,
			     pango_layout_get_context (info->layout),
			     info);

	return info;
}

static void
font_info_unregister (struct font_info *info)
{
	g_hash_table_remove (font_info_for_context,
			     pango_layout_get_context (info->layout));
}


static struct font_info *
font_info_reference (struct font_info *info)
{
	if (!info)
		return info;

	g_return_val_if_fail (info->ref_count >= 0, info);

	if (info->destroy_timeout) {
		g_source_remove (info->destroy_timeout);
		info->destroy_timeout = 0;
	}

	info->ref_count++;

	return info;
}

static gboolean
font_info_destroy_delayed (struct font_info *info)
{
	info->destroy_timeout = 0;

	font_info_unregister (info);
	font_info_free (info);

	return FALSE;
}

static void
font_info_destroy (struct font_info *info)
{
	if (!info)
		return;

	g_return_if_fail (info->ref_count > 0);

	info->ref_count--;
	if (info->ref_count)
		return;

#if !GTK_CHECK_VERSION (2, 14, 0)
#define gdk_threads_add_timeout_seconds(sec, func, data) gdk_threads_add_timeout ((sec) * 1000, (func), (data))
#endif

	/* Delay destruction by a few seconds, in case we need it again */
	ensure_quit_handler ();
	info->destroy_timeout = gdk_threads_add_timeout_seconds (FONT_CACHE_TIMEOUT,
								 (GSourceFunc) font_info_destroy_delayed,
								 info);
}

static guint
context_hash (PangoContext *context)
{
	return pango_units_from_double (pango_cairo_context_get_resolution (context))
	     ^ pango_font_description_hash (pango_context_get_font_description (context))
	     ^ cairo_font_options_hash (pango_cairo_context_get_font_options (context));
}

static gboolean
context_equal (PangoContext *a,
	       PangoContext *b)
{
	return pango_cairo_context_get_resolution (a) == pango_cairo_context_get_resolution (b)
	    && pango_font_description_equal (pango_context_get_font_description (a), pango_context_get_font_description (b))
	    && cairo_font_options_equal (pango_cairo_context_get_font_options (a), pango_cairo_context_get_font_options (b));
}

static struct font_info *
font_info_find_for_context (PangoContext *context)
{
	struct font_info *info;

	if (G_UNLIKELY (font_info_for_context == NULL))
		font_info_for_context = g_hash_table_new ((GHashFunc) context_hash, (GEqualFunc) context_equal);

	info = g_hash_table_lookup (font_info_for_context, context);
	if (G_LIKELY (info)) {
		_vte_debug_print (VTE_DEBUG_PANGOCAIRO,
				  "vtepangocairo: %p found font_info in cache\n",
				  info);
		return font_info_reference (info);
	}

	info = font_info_allocate (context);
	info->ref_count = 1;
	font_info_register (info);

	g_object_unref (context);

	return info;
}

/* assumes ownership/reference of context */
static struct font_info *
font_info_create_for_context (PangoContext               *context,
			      const PangoFontDescription *desc,
			      VteTerminalAntiAlias        antialias)
{
	if (!PANGO_IS_CAIRO_FONT_MAP (pango_context_get_font_map (context))) {
		/* Ouch, Gtk+ switched over to some drawing system?
		 * Lets just create one from the default font map.
		 */
		g_object_unref (context);
		context = pango_font_map_create_context (pango_cairo_font_map_get_default ());
	}

	pango_context_set_base_dir (context, PANGO_DIRECTION_LTR);
	if (desc)
		pango_context_set_font_description (context, desc);

	switch (antialias) {
		cairo_font_options_t *font_options;
		cairo_antialias_t cr_aa;

	case VTE_ANTI_ALIAS_FORCE_ENABLE:
	case VTE_ANTI_ALIAS_FORCE_DISABLE:

		if (antialias == VTE_ANTI_ALIAS_FORCE_ENABLE)
			cr_aa = CAIRO_ANTIALIAS_DEFAULT; /* let surface decide between gray and subpixel */
		else
			cr_aa = CAIRO_ANTIALIAS_NONE;

		font_options = cairo_font_options_copy (pango_cairo_context_get_font_options (context));
		cairo_font_options_set_antialias (font_options, cr_aa);
		pango_cairo_context_set_font_options (context, font_options);
		cairo_font_options_destroy (font_options);

		break;

	default:
	case VTE_ANTI_ALIAS_USE_DEFAULT:
		/* Make sure our contexts have a font_options set.  We use
		 * this invariant in our context hash and equal functions.
		 */
		if (!pango_cairo_context_get_font_options (context)) {
			font_options = cairo_font_options_create ();
			pango_cairo_context_set_font_options (context, font_options);
			cairo_font_options_destroy (font_options);
		}
		break;
	}

	return font_info_find_for_context (context);
}

static struct font_info *
font_info_create_for_screen (GdkScreen                  *screen,
			     const PangoFontDescription *desc,
			     VteTerminalAntiAlias        antialias)
{
	return font_info_create_for_context (gdk_pango_context_get_for_screen (screen),
					     desc, antialias);
}

static struct font_info *
font_info_create_for_widget (GtkWidget                  *widget,
			     const PangoFontDescription *desc,
			     VteTerminalAntiAlias        antialias)
{
	GdkScreen *screen = gtk_widget_get_screen (widget);

	return font_info_create_for_screen (screen, desc, antialias);
}

static struct unichar_info *
font_info_get_unichar_info (struct font_info *info,
			    gunichar c)
{
	struct unichar_info *uinfo;
	union unichar_font_info *ufi;
	char buf[VTE_UTF8_BPC+1];
	PangoRectangle logical;
	PangoLayoutLine *line;

	uinfo = font_info_find_unichar_info (info, c);
	if (G_LIKELY (uinfo->coverage != COVERAGE_UNKNOWN))
		return uinfo;

	ufi = &uinfo->ufi;

	buf[g_unichar_to_utf8 (c, buf)] = '\0';
	pango_layout_set_text (info->layout, buf, -1);
	pango_layout_get_extents (info->layout, NULL, &logical);

	uinfo->width = PANGO_PIXELS_CEIL (logical.width);

	line = pango_layout_get_line_readonly (info->layout, 0);

	uinfo->has_unknown_chars = pango_layout_get_unknown_glyphs_count (info->layout) != 0;
	/* we use PangoLayoutRun rendering unless there is exactly one run in the line. */
	if (G_UNLIKELY (!line || !line->runs || line->runs->next))
	{
		uinfo->coverage = COVERAGE_USE_PANGO_LAYOUT_LINE;

		ufi->using_pango_layout_line.line = pango_layout_line_ref (line);
		/* we hold a manual reference on layout.  pango currently
		 * doesn't work if line->layout is NULL.  ugh! */
		pango_layout_set_text (info->layout, "", -1); /* make layout disassociate from the line */
		ufi->using_pango_layout_line.line->layout = g_object_ref (info->layout);

	} else {
		PangoGlyphItem *glyph_item = line->runs->data;
		PangoFont *pango_font = glyph_item->item->analysis.font;
		PangoGlyphString *glyph_string = glyph_item->glyphs;

		/* we use fast cairo path if glyph string has only one real
		 * glyph and at origin */
		if (!uinfo->has_unknown_chars &&
		    glyph_string->num_glyphs == 1 && glyph_string->glyphs[0].glyph <= 0xFFFF &&
		    (glyph_string->glyphs[0].geometry.x_offset |
		     glyph_string->glyphs[0].geometry.y_offset) == 0)
		{
			cairo_scaled_font_t *scaled_font = pango_cairo_font_get_scaled_font ((PangoCairoFont *) pango_font);

			if (scaled_font) {
				uinfo->coverage = COVERAGE_USE_CAIRO_GLYPH;

				ufi->using_cairo_glyph.scaled_font = cairo_scaled_font_reference (scaled_font);
				ufi->using_cairo_glyph.glyph_index = glyph_string->glyphs[0].glyph;
			}
		}

		/* use pango fast path otherwise */
		if (G_UNLIKELY (uinfo->coverage == COVERAGE_UNKNOWN)) {
			uinfo->coverage = COVERAGE_USE_PANGO_GLYPH_STRING;

			ufi->using_pango_glyph_string.font = pango_font ? g_object_ref (pango_font) : NULL;
			ufi->using_pango_glyph_string.glyph_string = pango_glyph_string_copy (glyph_string);
		}
	}

	/* release internal layout resources */
	pango_layout_set_text (info->layout, "", -1);

#ifdef VTE_DEBUG
	info->coverage_count[0]++;
	info->coverage_count[uinfo->coverage]++;
#endif

	return uinfo;
}


struct _vte_pangocairo_data {
	struct font_info *font;

	cairo_t *cr;

	GdkPixmap *pixmap;
	gint pixmapw, pixmaph;
};

static void
set_source_color_alpha (cairo_t        *cr,
			const GdkColor *color,
			guchar alpha)
{
	cairo_set_source_rgba (cr,
			      color->red / 65535.,
			      color->green / 65535.,
			      color->blue / 65535.,
			      alpha / 255.);
}


static void
_vte_pangocairo_create (struct _vte_draw *draw, GtkWidget *widget)
{
	struct _vte_pangocairo_data *data;

	data = g_slice_new0 (struct _vte_pangocairo_data);
	draw->impl_data = data;
}

static void
_vte_pangocairo_destroy (struct _vte_draw *draw)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	if (data->pixmap != NULL) {
		g_object_unref (data->pixmap);
		data->pixmap = NULL;
	}

	if (data->font != NULL) {
		font_info_destroy (data->font);
		data->font = NULL;
	}

	g_slice_free (struct _vte_pangocairo_data, draw->impl_data);
}

static void
_vte_pangocairo_start (struct _vte_draw *draw)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	data->cr = gdk_cairo_create (draw->widget->window);
}

static void
_vte_pangocairo_end (struct _vte_draw *draw)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	if (data->cr != NULL) {
		cairo_destroy (data->cr);
		data->cr = NULL;
	}
}

static void
_vte_pangocairo_set_background_image (struct _vte_draw *draw,
				      enum VteBgSourceType type,
				      GdkPixbuf *pixbuf,
				      const char *file,
				      const GdkColor *color,
				      double saturation)
{
	struct _vte_pangocairo_data *data = draw->impl_data;
	GdkPixmap *pixmap;
	GdkScreen *screen;

	if (data->pixmap != NULL) {
		g_object_unref(data->pixmap);
	}

	screen = gtk_widget_get_screen(draw->widget);
	pixmap = vte_bg_get_pixmap(vte_bg_get_for_screen(screen),
				   type, pixbuf, file,
				   color, saturation,
				   _vte_draw_get_colormap(draw, TRUE));

	data->pixmap = NULL;
	data->pixmapw = data->pixmaph = 0;
	if (pixmap) {
		gdk_drawable_get_size(pixmap, &data->pixmapw, &data->pixmaph);
		data->pixmap = pixmap;
	}
}

static void
_vte_pangocairo_clip (struct _vte_draw *draw,
		      GdkRegion *region)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	gdk_cairo_region(data->cr, region);
	cairo_clip (data->cr);
}

static void
_vte_pangocairo_clear (struct _vte_draw *draw,
		       gint x, gint y, gint width, gint height)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	cairo_rectangle (data->cr, x, y, width, height);
	cairo_set_operator (data->cr, CAIRO_OPERATOR_SOURCE);

	if (data->pixmap == NULL) {
		set_source_color_alpha (data->cr, &draw->bg_color, draw->bg_opacity >> 8);
	} else {
		gdk_cairo_set_source_pixmap (data->cr, data->pixmap,
					     draw->scrollx, draw->scrolly);
		cairo_pattern_set_extend (cairo_get_source (data->cr), CAIRO_EXTEND_REPEAT);
	}

	cairo_fill (data->cr);
}

static void
_vte_pangocairo_set_text_font (struct _vte_draw *draw,
			       const PangoFontDescription *fontdesc,
			       VteTerminalAntiAlias antialias)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	font_info_destroy (data->font);
	data->font = font_info_create_for_widget (draw->widget, fontdesc, antialias);
}

static void
_vte_pangocairo_get_text_metrics(struct _vte_draw *draw,
				 gint *width, gint *height, gint *ascent)
{
	struct _vte_pangocairo_data *data = draw->impl_data;
	
	g_return_if_fail (data->font != NULL);

	*width  = data->font->width;
	*height = data->font->height;
	*ascent = data->font->ascent;
}


static int
_vte_pangocairo_get_char_width (struct _vte_draw *draw, gunichar c, int columns)
{
	struct _vte_pangocairo_data *data = draw->impl_data;
	struct unichar_info *uinfo;

	g_return_val_if_fail (data->font != NULL, 0);

	uinfo = font_info_get_unichar_info (data->font, c);
	return uinfo->width;
}

static void
_vte_pangocairo_draw_text (struct _vte_draw *draw,
			   struct _vte_draw_text_request *requests, gsize n_requests,
			   GdkColor *color, guchar alpha)
{
	struct _vte_pangocairo_data *data = draw->impl_data;
	gsize i;
	cairo_scaled_font_t *last_scaled_font = NULL;
	int n_cr_glyphs = 0;
	cairo_glyph_t cr_glyphs[MAX_RUN_LENGTH];

	g_return_if_fail (data->font != NULL);

	set_source_color_alpha (data->cr, color, alpha);
	cairo_set_operator (data->cr, CAIRO_OPERATOR_OVER);

	for (i = 0; i < n_requests; i++) {
		gunichar c = requests[i].c;
		int x = requests[i].x;
		int y = requests[i].y + data->font->ascent;
		struct unichar_info *uinfo = font_info_get_unichar_info (data->font, c);
		union unichar_font_info *ufi = &uinfo->ufi;

		switch (uinfo->coverage) {
		default:
		case COVERAGE_UNKNOWN:
			g_assert_not_reached ();
			break;
		case COVERAGE_USE_PANGO_LAYOUT_LINE:
			cairo_move_to (data->cr, x, y);
			pango_cairo_show_layout_line (data->cr,
						      ufi->using_pango_layout_line.line);
			break;
		case COVERAGE_USE_PANGO_GLYPH_STRING:
			cairo_move_to (data->cr, x, y);
			pango_cairo_show_glyph_string (data->cr,
						       ufi->using_pango_glyph_string.font,
						       ufi->using_pango_glyph_string.glyph_string);
			break;
		case COVERAGE_USE_CAIRO_GLYPH:
			if (last_scaled_font != ufi->using_cairo_glyph.scaled_font || n_cr_glyphs == MAX_RUN_LENGTH) {
				if (n_cr_glyphs) {
					cairo_set_scaled_font (data->cr, last_scaled_font);
					cairo_show_glyphs (data->cr,
							   cr_glyphs,
							   n_cr_glyphs);
					n_cr_glyphs = 0;
				}
				last_scaled_font = ufi->using_cairo_glyph.scaled_font;
			}
			cr_glyphs[n_cr_glyphs].index = ufi->using_cairo_glyph.glyph_index;
			cr_glyphs[n_cr_glyphs].x = x;
			cr_glyphs[n_cr_glyphs].y = y;
			n_cr_glyphs++;
			break;
		}
	}
	if (n_cr_glyphs) {
		cairo_set_scaled_font (data->cr, last_scaled_font);
		cairo_show_glyphs (data->cr,
				   cr_glyphs,
				   n_cr_glyphs);
		n_cr_glyphs = 0;
	}
}

static gboolean
_vte_pangocairo_draw_has_char (struct _vte_draw *draw, gunichar c)
{
	struct _vte_pangocairo_data *data = draw->impl_data;
	struct unichar_info *uinfo;

	g_return_val_if_fail (data->font != NULL, FALSE);

	uinfo = font_info_get_unichar_info (data->font, c);
	return !uinfo->has_unknown_chars;
}

static void
_vte_pangocairo_draw_rectangle (struct _vte_draw *draw,
				gint x, gint y, gint width, gint height,
				GdkColor *color, guchar alpha)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	cairo_set_operator (data->cr, CAIRO_OPERATOR_OVER);
	cairo_rectangle (data->cr, x+.5, y+.5, width-1, height-1);
	set_source_color_alpha (data->cr, color, alpha);
	cairo_set_line_width (data->cr, 1);
	cairo_stroke (data->cr);
}

static void
_vte_pangocairo_fill_rectangle (struct _vte_draw *draw,
				gint x, gint y, gint width, gint height,
				GdkColor *color, guchar alpha)
{
	struct _vte_pangocairo_data *data = draw->impl_data;

	cairo_set_operator (data->cr, CAIRO_OPERATOR_OVER);
	cairo_rectangle (data->cr, x, y, width, height);
	set_source_color_alpha (data->cr, color, alpha);
	cairo_fill (data->cr);
}

const struct _vte_draw_impl _vte_draw_pangocairo = {
	"pangocairo",
	NULL, /* check */
	_vte_pangocairo_create,
	_vte_pangocairo_destroy,
	NULL, /* get_visual */
	NULL, /* get_colormap */
	_vte_pangocairo_start,
	_vte_pangocairo_end,
	_vte_pangocairo_set_background_image,
	_vte_pangocairo_clip,
	FALSE, /* always_requires_clear */
	_vte_pangocairo_clear,
	_vte_pangocairo_set_text_font,
	_vte_pangocairo_get_text_metrics,
	_vte_pangocairo_get_char_width,
	_vte_pangocairo_draw_text,
	_vte_pangocairo_draw_has_char,
	_vte_pangocairo_draw_rectangle,
	_vte_pangocairo_fill_rectangle
};