summaryrefslogtreecommitdiff
path: root/decorate-render.c
blob: b30f25aa200e20a24c97faf642b8e409b5a04672 (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
/*
 * decorate-render.c
 *
 * Part of gwm, the Gratuitous Window Manager,
 *     by Gary Wong, <gtw@gnu.org>.
 *
 * Copyright (C) 2009  Gary Wong
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of version 3 of the GNU General Public License as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $Id$
 */

#include <config.h>

#include <assert.h>
#include <fontconfig/fontconfig.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_BITMAP_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xcb/render.h>
#include <xcb/xcb.h>

#include "gwm.h"

#include "button.h"
#include "decorate-render.h"

enum style_id {
    STYLE_TITLE, STYLE_MENU, NUM_STYLES
};

#define TITLE_FONT_SIZE 12
#define MENU_FONT_SIZE 10

#define STRING2(x) #x
#define STRING(x) STRING2(x)
#define TITLE_FONT_SIZE_STRING STRING( TITLE_FONT_SIZE )
#define MENU_FONT_SIZE_STRING STRING( MENU_FONT_SIZE )

static const FcChar8 *const style_names[ NUM_STYLES ] = {
    /* FIXME make this configurable */
    (FcChar8 *) "sans:pixelsize=" TITLE_FONT_SIZE_STRING ":bold",
    (FcChar8 *) "sans:pixelsize=" MENU_FONT_SIZE_STRING
};

static struct font {
    FcPattern *pattern;
    FcCharSet *charset;
    FT_Face face;
    FT_Int32 load_flags;
} *fonts;
static int num_fonts;

static struct style {
    int *fonts; /* indices into font table above */
    int num_fonts;    
    FcCharSet *charset;
} styles[ NUM_STYLES ];

static FT_Library ftl;

static const uint16_t decoration_cols[ NUM_COLS ][ 3 ] = {
    { 0x2222, 0x3333, 0xEEEE }, /* COL_FRAME_ACTIVE */
    { 0xAAAA, 0xAAAA, 0xAAAA }, /* COL_FRAME_INACTIVE */
    { 0x0000, 0x0000, 0x0000 }, /* COL_BORDER */
    { 0xFFFF, 0x0000, 0x0000 }, /* COL_BUTTON_ACTIVE */
    { 0xCCCC, 0xCCCC, 0xCCCC }, /* COL_BUTTON_INACTIVE */
    { 0xFFFF, 0xFFFF, 0xFFFF }, /* COL_TITLE_ACTIVE */
    { 0x3333, 0x3333, 0x3333 }, /* COL_TITLE_INACTIVE */
    { 0xFFFF, 0xFFFF, 0xFFFF }, /* COL_FEEDBACK_BACK */
    { 0x0000, 0x0000, 0x0000 }  /* COL_FEEDBACK_FORE */
};

#define METRIC_CACHE_SIZE_BITS 14
#define METRIC_CACHE_SIZE ( 1 << METRIC_CACHE_SIZE_BITS )
#define METRIC_CACHE_ASSOC_BITS 2
#define METRIC_CACHE_ASSOC ( 1 << METRIC_CACHE_ASSOC_BITS )

#define GLYPH_CACHE_SIZE_BITS 11
#define GLYPH_CACHE_SIZE ( 1 << GLYPH_CACHE_SIZE_BITS )
#define GLYPH_CACHE_ASSOC_BITS 3
#define GLYPH_CACHE_ASSOC ( 1 << GLYPH_CACHE_ASSOC_BITS )

#if GLYPH_CACHE_SIZE_BITS + GLYPH_CACHE_ASSOC_BITS > 16
#error "Glyph cache is too big for 16-bit indices."
#endif

static struct metric_cache_line {
    enum style_id style;
    uint32_t c; /* character code */
    unsigned int time;
    int x_off, y_off;
} metric_cache[ METRIC_CACHE_SIZE ][ METRIC_CACHE_ASSOC ];

static struct glyph_cache_line {
    enum style_id style;
    uint32_t c; /* character code */
    unsigned int time;
} glyph_cache[ GLYPH_CACHE_SIZE ][ GLYPH_CACHE_ASSOC ];

static unsigned int current_time;

static struct font *lookup_font( enum style_id style, uint32_t c ) {

    int i;
    
    if( !FcCharSetHasChar( styles[ style ].charset, c ) )
	return NULL;

    for( i = 0; i < styles[ style ].num_fonts; i++ ) {
	struct font *font = fonts + styles[ style ].fonts[ i ];
	
	if( FcCharSetHasChar( font->charset, c ) ) {
	    if( !font->face ) {
		FcChar8 *filename;
		FcMatrix *matrix = NULL;
		FT_Matrix ft_matrix;
		int index = 0, hintstyle = FC_HINT_MEDIUM;
		double size;
		FcBool hinting = TRUE, autohint = FALSE, globaladvance = TRUE,
		    embeddedbitmap = TRUE;
		
		if( FcPatternGetString( font->pattern, FC_FILE, 0,
					&filename ) ||
		    FcPatternGetDouble( font->pattern, FC_PIXEL_SIZE, 0,
					&size ) )
		    continue;
		
		FcPatternGetInteger( font->pattern, FC_INDEX, 0, &index );
		FcPatternGetMatrix( font->pattern, FC_MATRIX, 0, &matrix );
		
		if( FT_New_Face( ftl, (char *) filename, index, &font->face ) )
		    continue;

		FT_Set_Pixel_Sizes( font->face, 0, (int) ( size + 0.5 ) );

		if( matrix ) {
		    ft_matrix.xx = matrix->xx * 64.0;
		    ft_matrix.xy = matrix->xy * 64.0;
		    ft_matrix.yx = matrix->yx * 64.0;
		    ft_matrix.yy = matrix->yy * 64.0;
		    FT_Set_Transform( font->face, &ft_matrix, NULL );
		}
		
		FT_Select_Charmap( font->face, FT_ENCODING_UNICODE );

		FcPatternGetBool( font->pattern, FC_HINTING, 0, &hinting );
		FcPatternGetInteger( font->pattern, FC_HINT_STYLE, 0,
				     &hintstyle );
		FcPatternGetBool( font->pattern, FC_AUTOHINT, 0, &autohint );
		FcPatternGetBool( font->pattern, FC_GLOBAL_ADVANCE, 0,
				  &globaladvance );
		FcPatternGetBool( font->pattern, FC_EMBEDDED_BITMAP, 0,
				  &embeddedbitmap );

		font->load_flags = FT_LOAD_DEFAULT;
		
		if( !hinting )
		    font->load_flags |= FT_LOAD_NO_HINTING;
		
		switch( hintstyle ) {
		case FC_HINT_NONE:
		    font->load_flags |= FT_LOAD_NO_HINTING;
		    break;
		    
		case FC_HINT_SLIGHT:
		    font->load_flags |= FT_LOAD_TARGET_LIGHT;
		    break;
		    
		case FC_HINT_MEDIUM:
		default:
		    font->load_flags |= FT_LOAD_TARGET_NORMAL;
		    break;
		    
		case FC_HINT_FULL:
		    font->load_flags |= FT_LOAD_TARGET_MONO;
		    break;
		}
		
		if( autohint )
		    font->load_flags |= FT_LOAD_FORCE_AUTOHINT;

		if( !globaladvance )
		    font->load_flags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;

		if( !embeddedbitmap )
		    font->load_flags |= FT_LOAD_NO_BITMAP;
	    }

	    return font;
	}
    }

    return NULL;
}

static void query_metrics( enum style_id style, uint32_t c,
			   int *x_off, int *y_off ) {

    int row = c & ( METRIC_CACHE_SIZE - 1 );
    int i, max;
    struct font *font;
    
    for( i = 0; i < METRIC_CACHE_ASSOC; i++ )
	if( metric_cache[ row ][ i ].style == style &&
	    metric_cache[ row ][ i ].c == c ) {
	    /* Cache hit. */
	    metric_cache[ row ][ i ].time = current_time;
	    *x_off = metric_cache[ row ][ i ].x_off;
	    *y_off = metric_cache[ row ][ i ].y_off;
	    return;
	}

    font = lookup_font( style, c );
    
    /* Cache miss. */
    if( FT_Load_Char( font->face, c, font->load_flags ) ) {
	/* Couldn't load metrics.  Don't bother evicting anything. */
	*x_off = *y_off = 0;
	return;
    }

    /* Search for a line to evict. */
    for( i = 1, max = 0; i < METRIC_CACHE_ASSOC; i++ )
	if( current_time - metric_cache[ row ][ i ].time >
	    current_time - metric_cache[ row ][ max ].time )
	    max = i;

    metric_cache[ row ][ max ].style = style;
    metric_cache[ row ][ max ].c = c;
    metric_cache[ row ][ max ].time = current_time;
    *x_off = metric_cache[ row ][ max ].x_off =
	( font->face->glyph->advance.x + 0x20 ) >> 6;
    *y_off = metric_cache[ row ][ max ].y_off =
	( font->face->glyph->advance.y + 0x20 ) >> 6;
}

static int query_glyph( enum style_id style, uint32_t c ) {
    
    int row = c & ( GLYPH_CACHE_SIZE - 1 );
    int i;

    for( i = 0; i < GLYPH_CACHE_ASSOC; i++ )
	if( glyph_cache[ row ][ i ].style == style &&
	    glyph_cache[ row ][ i ].c == c ) {
	    /* Cache hit. */
	    glyph_cache[ row ][ i ].time = current_time;
	    return ( row << GLYPH_CACHE_ASSOC_BITS ) | i;
	}

    return -1;
}

static int replace_glyph( enum style_id style, uint32_t c ) {

    int row = c & ( GLYPH_CACHE_SIZE - 1 );
    int i, max;

    /* Search for a line to evict. */
    for( i = 1, max = 0; i < METRIC_CACHE_ASSOC; i++ ) {
	assert( glyph_cache[ row ][ i ].style != style ||
		glyph_cache[ row ][ i ].c != c);
	if( current_time - glyph_cache[ row ][ i ].time >
	    current_time - glyph_cache[ row ][ max ].time )
	    max = i;
    }

    if( glyph_cache[ row ][ max ].time == current_time )
	/* Cache line set is full, and nothing is old enough to evict. */
	return -1;
    
    glyph_cache[ row ][ max ].style = style;
    glyph_cache[ row ][ max ].c = c;
    glyph_cache[ row ][ max ].time = current_time;

    return ( row << GLYPH_CACHE_ASSOC_BITS ) | max;
}

static xcb_render_glyphset_t glyphset;   
static struct picture {
    xcb_render_picture_t pic;
    enum decoration_col col;
} *pictures; /* indexed by screen */

static xcb_void_cookie_t render_text( xcb_drawable_t drawable, int screen, 
				      int col, int x, int y,
				      const char *text, enum style_id style,
				      const xcb_rectangle_t *clip ) {

    xcb_render_picture_t src, dest;
    xcb_rectangle_t rect;
    xcb_render_color_t rc;
    int i, len;
    const unsigned char *p;
    uint32_t *buf;
    
    if( !text || !*text ) {
	xcb_void_cookie_t r = { 0 };

	return r;
    }

    len = 0;
    p = (const unsigned char *) text;
    for(;;)
	if( !p[ 0 ] )
	    /* End of string. */
	    break;
	else if( !( p[ 0 ] & 0x80 ) ) {
	    /* Legal single byte character. */
	    len++;
	    p++;
	} else if( *p >= 0xC2 && *p <= 0xDF &&
		   p[ 1 ] >= 0x80 && p[ 1 ] <= 0xBF ) {
	    /* Legal two byte character. */
	    len++;
	    p += 2;
	} else if( *p >= 0xE0 && *p <= 0xEF &&
		   p[ 1 ] >= 0x80 && p[ 1 ] <= 0xBF &&
		   p[ 2 ] >= 0x80 && p[ 2 ] <= 0xBF &&
		   ( *p > 0xE0 || p[ 1 ] > 0x80 ) ) {
	    /* Legal three byte character. */
	    len++;
	    p += 3;
	} else if( *p >= 0xF0 && *p <= 0xF4 &&
		   p[ 1 ] >= 0x80 && p[ 1 ] <= 0xBF &&
		   p[ 2 ] >= 0x80 && p[ 2 ] <= 0xBF &&
		   p[ 3 ] >= 0x80 && p[ 3 ] <= 0xBF &&
		   ( *p > 0xF0 || p[ 1 ] > 0x80 ) ) {
	    /* Legal four byte character. */
	    len++;
	    p += 4;
	} else
	    /* Illegal character: ignore this byte and continue. */
	    p++;

    if( !len ) {
	xcb_void_cookie_t r = { 0 };

	return r;
    }
    
    buf = alloca( len * sizeof *buf );

    for( p = (const unsigned char *) text, i = 0; i < len; i++ ) {
    retry:
	assert( *p );

	if( !( p[ 0 ] & 0x80 ) )
	    /* One byte character. */
	    buf[ i ] = *p++;
	else if( *p >= 0xC2 && *p <= 0xDF &&
		   p[ 1 ] >= 0x80 && p[ 1 ] <= 0xBF ) {
	    /* Two byte character. */
	    buf[ i ] = ( ( p[ 0 ] & 0x1F ) << 6 ) | ( p[ 1 ] & 0x3F );
	    p += 2;
	} else if( *p >= 0xE0 && *p <= 0xEF &&
		   p[ 1 ] >= 0x80 && p[ 1 ] <= 0xBF &&
		   p[ 2 ] >= 0x80 && p[ 2 ] <= 0xBF &&
		   ( *p > 0xE0 || p[ 1 ] > 0x80 ) ) {
	    /* Three byte character. */
	    buf[ i ] = ( ( p[ 0 ] & 0x0F ) << 12 ) |
		( ( p[ 1 ] & 0x3F ) << 6 ) | ( p[ 2 ] & 0x3F );
	    p += 3;
	} else if( *p >= 0xF0 && *p <= 0xF4 &&
		   p[ 1 ] >= 0x80 && p[ 1 ] <= 0xBF &&
		   p[ 2 ] >= 0x80 && p[ 2 ] <= 0xBF &&
		   p[ 3 ] >= 0x80 && p[ 3 ] <= 0xBF &&
		   ( *p > 0xF0 || p[ 1 ] > 0x80 ) ) {
	    /* Four byte character. */
	    buf[ i ] = ( ( p[ 0 ] & 0x07 ) << 18 ) |
		( ( p[ 1 ] & 0x3F ) << 12 ) | ( ( p[ 2 ] & 0x3F ) << 6 ) |
		( p[ 3 ] & 0x3F );
	    p += 4;
	} else {
	    p++;
	    goto retry;
	}
    }

    src = pictures[ screen ].pic;
    
    dest = xcb_generate_id( c );
    xcb_render_create_picture( c, dest, drawable,
			       gwm_screens[ screen ].root_pictformat, 0, NULL );

    if( clip )
	xcb_render_set_picture_clip_rectangles( c, dest, 0, 0, 1, clip );

    if( pictures[ screen ].col != col ) {
	rc.red = decoration_cols[ col ][ 0 ];
	rc.green = decoration_cols[ col ][ 1 ];
	rc.blue = decoration_cols[ col ][ 2 ];
	rc.alpha = 0xFFFF;
	rect.x = 0;
	rect.y = 0;
	rect.width = 1;
	rect.height = 1;
	xcb_render_fill_rectangles( c, XCB_RENDER_PICT_OP_SRC, src, rc, 1,
				    &rect );

	pictures[ screen ].col = col;
    }
    
    i = 0;
    while( i < len ) {
	uint32_t glyphids[ 0x80 ];
	xcb_render_glyphinfo_t glyphs[ 0x80 ];
	int num_glyphs; /* number of glyphs in AddGlyphs request */
	/* Buffer for "data" parameter of AddGlyphs request.  We want
	   this to be big enough to hold at least one glyph, but no
	   bigger than the biggest request the server will accept (once
	   the other parameters are included).  All servers must
	   accept requests of 16,384 bytes or smaller (see X Window
	   System Protocol, section 8), so this is safe. */
	uint8_t data[ 0x2000 ], *p;
	/* Buffer for "glyphcmds" parameter of CompositeGlyphs16
	   request.  We always send exactly one command, which has an
	   8-byte header and at most a 254 glyph string. */
	uint8_t param[ 8 + ( 0xFE << 1 ) ], *out;
	int num_chars; /* number of characters for CompositeGlyphs16 */
	
	current_time++;

	p = data;
	num_glyphs = 0;

	memset( param, 0, 4 );
	*( (uint16_t *) ( param + 4 ) ) = x;
	*( (uint16_t *) ( param + 6 ) ) = y;	
	out = param + 8;
	num_chars = 0;
	
	while( i < len && num_chars < 0xFF ) {
	    int dx, dy, index;
	    
	    if( ( index = query_glyph( style, buf[ i ] ) ) < 0 ) {
		/* Cache miss. */
		int bitmap_size;
		struct font *font;
		FT_GlyphSlot slot;
		
		if( ( index = replace_glyph( style, buf[ i ] ) ) < 0 )
		    /* Cache set full: spill the partial string to make
		       room for later glyphs. */
		    break;

		if( !( font = lookup_font( style, buf[ i ] ) ) ||
		    FT_Load_Char( font->face, buf[ i ], font->load_flags |
				  FT_LOAD_RENDER ) ||
		    ( bitmap_size = ( ( font->face->glyph->bitmap.width +
					3 ) & ~3 ) *
		      font->face->glyph->bitmap.rows ) > sizeof data ) {
		    /* We couldn't load the character, or it was so
		       huge that it won't fit in an empty AddGlyph
		       data buffer.  We'll have to send the server
		       an empty glyph and carry on. */
		    slot = NULL;
		    bitmap_size = 0;
		} else
		    slot = font->face->glyph;
		
		if( ( p - data ) + bitmap_size > sizeof data ||
		    num_glyphs == sizeof glyphids / sizeof *glyphids ) {
		    /* Can't fit this glyph into the existing request:
		       transmit what we have... */
		    xcb_render_add_glyphs( c, glyphset, num_glyphs, glyphids,
					   glyphs, p - data, data );

		    /* ...and start building another AddGlyph request. */
		    p = data;
		    num_glyphs = 0;
		}

		glyphids[ num_glyphs ] = index;

		if( slot ) {
		    FT_Bitmap bitmap;

		    FT_Bitmap_New( &bitmap );
		    FT_Bitmap_Convert( ftl, &slot->bitmap, &bitmap, 4 );

		    glyphs[ num_glyphs ].width = bitmap.width;
		    glyphs[ num_glyphs ].height = bitmap.rows;
		    glyphs[ num_glyphs ].x = -slot->bitmap_left;
		    glyphs[ num_glyphs ].y = slot->bitmap_top;
		    glyphs[ num_glyphs ].x_off =
			( slot->advance.x + 0x20 ) >> 6;
		    glyphs[ num_glyphs ].y_off =
			( slot->advance.y + 0x20 ) >> 6;

		    memcpy( p, bitmap.buffer, bitmap.pitch * bitmap.rows );
		    
		    if( bitmap.num_grays != 0x100 ) {
			unsigned char *c,
			    *end = p + bitmap.pitch * bitmap.rows;

			for( c = p; c < end; c++ )
			    *c = ( (unsigned int) *c * 0xFF /
				   ( bitmap.num_grays - 1 ) );
		    }
		    
		    p += bitmap.pitch * bitmap.rows;

		    FT_Bitmap_Done( ftl, &bitmap );
		} else {
		    glyphs[ num_glyphs ].width = 0;
		    glyphs[ num_glyphs ].height = 0;
		    glyphs[ num_glyphs ].x = 0;
		    glyphs[ num_glyphs ].y = 0;
		    glyphs[ num_glyphs ].x_off = 0;
		    glyphs[ num_glyphs ].y_off = 0;
		}

		num_glyphs++;
	    }

	    *( (uint16_t *) out ) = index;
	    out += 2;

	    query_metrics( style, buf[ i ], &dx, &dy );
	    x += dx;
	    y += dy;

	    num_chars++;
	    i++;
	}

	if( num_glyphs ) {
	    xcb_render_add_glyphs( c, glyphset, num_glyphs, glyphids, glyphs,
				   p - data, data );

	    p = data;
	    num_glyphs = 0;
	}
	
	param[ 0 ] = num_chars;

	xcb_render_composite_glyphs_16( c, XCB_RENDER_PICT_OP_OVER, src, dest,
					XCB_NONE, glyphset, 0, 0, out - param,
					param );
    }

    return xcb_render_free_picture( c, dest );
}

extern void render_update_window( struct gwm_window *window ) {

    if( !window->cleared )
	xcb_clear_area( c, FALSE, window->w, window->update.x, window->update.y,
			window->update.width, window->update.height );

    if( window->type == WINDOW_FRAME ) {
	char *name = window->u.frame.child->u.managed.name;

	render_text( window->w, window->screen, window == focus_frame ?
		     COL_TITLE_ACTIVE : COL_TITLE_INACTIVE,
		     button_size( window->u.frame.button, TRUE ) + 4,
		     TITLE_FONT_SIZE, name ? name : "(Untitled)",
		     STYLE_TITLE, &window->update );
    } else if( window->type == WINDOW_FEEDBACK ) {
	char *p, text[ 32 ];
	int width;
	
	sprintf( text, "%dx%d", window->u.feedback.fb_width,
		 window->u.feedback.fb_height );

	for( width = 0, p = text; *p; p++ ) {
	    int dx, dy;

	    query_metrics( STYLE_TITLE, *p, &dx, &dy );
	    width += dx;
	}

	render_text( window->w, window->screen, COL_FEEDBACK_FORE,
		     ( FEEDBACK_WIDTH - width ) >> 1, 16, text,
		     STYLE_TITLE, &window->update );
    }
}

static uint16_t luma( int col ) {

    return ( decoration_cols[ col ][ 0 ] * 0x4C8BU +
	     decoration_cols[ col ][ 1 ] * 0x9646U +
	     decoration_cols[ col ][ 2 ] * 0x1D2FU ) >> 16;
}

static void handle_alloc_color( unsigned int sequence, void *reply,
				xcb_generic_error_t *error,
				union callback_param p ) {
    
    xcb_alloc_color_reply_t *r = reply;
    int screen = p.l >> 16, col = p.l & 0xFFFF;
    
    if( error ) {
	if( error->error_code != XCB_ALLOC )
	    show_error( error );
	
	/* No standard RGB map available, and we couldn't allocate a shared
	   colour.  Fall back to black or white. */
	gwm_screens[ screen ].pixels[ col ] = luma( col ) >= 0x8000 ?
	    screens[ screen ]->white_pixel : screens[ screen ]->black_pixel;

	free( error );
    }

    if( reply ) {
	gwm_screens[ screen ].pixels[ col ] = r->pixel;

	free( reply );
    }
}

static void handle_get_default_map( unsigned int sequence, void *reply,
				    xcb_generic_error_t *error,
				    union callback_param p ) {

    int col, got_cols = FALSE;
    
    if( error ) {
	show_error( error );

	free( error );
    }

    if( reply ) {
	xcb_get_property_reply_t *prop = reply;    
	struct std_cmap {
	    /* RGB_COLOR_MAP property -- see ICCCM 2.0, section 6.4. */
	    xcb_colormap_t colormap;
	    uint32_t red_max, red_mult, green_max, green_mult, blue_max,
		blue_mult, base_pixel;
	    xcb_visualid_t visual_id;
	    uint32_t kill_id;
	} *std_cmaps = xcb_get_property_value( prop );
	int num_cmaps = ( xcb_get_property_value_length( prop ) << 2 ) /
	    sizeof *std_cmaps;
	int i;

	if( prop->format == 32 )
	    for( i = 0; i < num_cmaps; i++ )
		if( std_cmaps[ i ].visual_id ==
		    gwm_screens[ p.l ].root_visual->visual_id ) {
		    
		    for( col = 0; col < NUM_COLS; col++ ) {
			int r0, g0, b0, r, g, b;

			if( gwm_screens[ p.l ].root_visual->_class ==
			    XCB_VISUAL_CLASS_STATIC_GRAY ||
			    gwm_screens[ p.l ].root_visual->_class ==
			    XCB_VISUAL_CLASS_GRAY_SCALE ) {
			    r0 = luma( col );
			    g0 = b0 = 0;
			} else {
			    r0 = decoration_cols[ col ][ 0 ];
			    g0 = decoration_cols[ col ][ 1 ];
			    b0 = decoration_cols[ col ][ 2 ];
			}

			r = ( r0 * std_cmaps[ i ].red_max + 0x8000 ) >> 16;
			g = ( g0 * std_cmaps[ i ].green_max + 0x8000 ) >> 16;
			b = ( b0 * std_cmaps[ i ].blue_max + 0x8000 ) >> 16;

			gwm_screens[ p.l ].pixels[ col ] =
			    std_cmaps[ i ].base_pixel +
			    r * std_cmaps[ i ].red_mult +
			    g * std_cmaps[ i ].green_mult +
			    b * std_cmaps[ i ].blue_mult;
		    }

		    got_cols = TRUE;
		    break;
		}

	free( reply );
    }

    if( !got_cols )
	/* No useful default maps found; try allocating directly. */
	for( col = 0; col < NUM_COLS; col++ ) {
	    int r, g, b;
	    union callback_param cp;
	    
	    if( gwm_screens[ p.l ].root_visual->_class ==
		XCB_VISUAL_CLASS_STATIC_GRAY ||
		gwm_screens[ p.l ].root_visual->_class ==
		XCB_VISUAL_CLASS_GRAY_SCALE )
		r = g = b = luma( col );
	    else {
		r = decoration_cols[ col ][ 0 ];
		g = decoration_cols[ col ][ 1 ];
		b = decoration_cols[ col ][ 2 ];
	    }
	    
	    cp.l = ( p.l << 16 ) | col;
	    /* Ideally, we would like a guarantee that this operation will
	       complete before the pixel values are ever looked up.  In
	       practice, it will, and it is too messy to insert a
	       sync_with_callback() before every single pixel reference. */
	    handle_async_reply( xcb_alloc_color(
				    c, screens[ p.l ]->default_colormap,
				    r, g, b ).sequence, handle_alloc_color,
				cp );
	}
}

static void decorate_compat_init( void ) {

    int i;
    const char *cursor_font_name = "cursor";
    xcb_font_t cursor_font;
    static const int cursor_glyphs[ NUM_CURSORS ] = {
	68, /* CURSOR_ARROW */
	88, /* CURSOR_DESTROY */
	134, /* CURSOR_TL */
	138, /* CURSOR_T */
	136, /* CURSOR_TR */
	70, /* CURSOR_L */
	52, /* CURSOR_C */
	96, /* CURSOR_R */
	12, /* CURSOR_BL */
	16, /* CURSOR_B */
	14 /* CURSOR_BR */
    };
    
    cursor_font = xcb_generate_id( c );
    xcb_open_font( c, cursor_font, strlen( cursor_font_name ),
		   cursor_font_name );
    for( i = 0; i < NUM_CURSORS; i++ ) {
	cursors[ i ] = xcb_generate_id( c );
	xcb_create_glyph_cursor( c, cursors[ i ], cursor_font, cursor_font,
				 cursor_glyphs[ i ], cursor_glyphs[ i ] | 1,
				 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF );
    }
    xcb_close_font( c, cursor_font );

    /* Retrieve any RGB_DEFAULT_MAP properties on the roots. */
    for( i = 0; i < num_screens; i++ ) {
	union callback_param cp;

	cp.l = i;
	handle_async_reply( xcb_get_property( c, FALSE, screens[ i ]->root,
					      RGB_DEFAULT_MAP, RGB_COLOR_MAP,
					      0, 0x10000 ).sequence,
			    handle_get_default_map, cp );
    }
}

extern void decorate_render_init( void ) {

    FT_Error err;
    FcFontSet *sets[ NUM_STYLES ];
    FcPattern *style_pats[ NUM_STYLES ];
    FcChar32 *hashes;
    FcResult r;
    int i, total;
    xcb_pixmap_t pixmap;
    uint32_t n;
    
    if( !FcInit() )
	fatal( "font configuration error" );

    if( ( err = FT_Init_FreeType( &ftl ) ) )
	fatal( "typeface initialisation error %d", err );    
    
    for( i = 0, total = 0; i < NUM_STYLES; i++ ) {
	if( !( style_pats[ i ] = FcNameParse( style_names[ i ] ) ) )
	    fatal( "could not parse font \"%s\"\n", style_names[ i ] );

	FcConfigSubstitute( NULL, style_pats[ i ], FcMatchPattern );
	FcDefaultSubstitute( style_pats[ i ] );

	sets[ i ] = FcFontSort( NULL, style_pats[ i ], TRUE,
				&styles[ i ].charset, &r );

	total += sets[ i ]->nfont;
    }

    fonts = xmalloc( total * sizeof *fonts );
    hashes = alloca( total * sizeof *hashes );
	
    for( i = 0; i < NUM_STYLES; i++ ) {
	int j;

	styles[ i ].fonts = xmalloc( sets[ i ]->nfont *
				     sizeof (struct font *) );
	
	for( j = 0; j < sets[ i ]->nfont; j++ ) {
	    FcPattern *pat;

	    if( ( pat = FcFontRenderPrepare( NULL, style_pats[ i ],
					     sets[ i ]->fonts[ j ] ) ) ) {
		FcChar32 hash = FcPatternHash( pat );
		int search;
		
		for( search = 0; search < num_fonts; search++ )
		    if( hashes[ search ] == hash &&
			FcPatternEqual( fonts[ search ].pattern, pat ) ) {
			FcPatternDestroy( pat );
			break;
		    }

		if( search == num_fonts ) {
		    hashes[ num_fonts ] = hash;
		    fonts[ num_fonts ].pattern = pat;
		    FcPatternGetCharSet( pat, FC_CHARSET, 0,
					 &fonts[ num_fonts ].charset );
		    fonts[ num_fonts ].face = NULL;
		    num_fonts++;
		}

		styles[ i ].fonts[ styles[ i ].num_fonts ] = search;
		styles[ i ].num_fonts++;
	    }	    
	}

	styles[ i ].fonts = xrealloc( styles[ i ].fonts,
				      styles[ i ].num_fonts *
				      sizeof (struct font *) );

	FcFontSetDestroy( sets[ i ] );
	FcPatternDestroy( style_pats[ i ] );
    }

    fonts = xrealloc( fonts, num_fonts * sizeof *fonts );

    glyphset = xcb_generate_id( c );
    xcb_render_create_glyph_set( c, glyphset, fmt_a8 );
	
    pixmap = xcb_generate_id( c );
    
    pictures = xmalloc( num_screens * sizeof *pictures );

    n = XCB_RENDER_REPEAT_NORMAL;
    for( i = 0; i < num_screens; i++ ) {
	xcb_create_pixmap( c, screens[ i ]->root_depth, pixmap,
			   screens[ i ]->root, 1, 1 );
			   
	pictures[ i ].pic = xcb_generate_id( c );
	xcb_render_create_picture( c, pictures[ i ].pic, pixmap,
				   gwm_screens[ i ].root_pictformat,
				   XCB_RENDER_CP_REPEAT, &n );
	pictures[ i ].col = -1;
	
	xcb_free_pixmap( c, pixmap );
    }

    decorate_compat_init(); /* FIXME this is for pixel values (backgrounds)
			       and cursors */
}

extern void decorate_render_done( void ) {

#if DEBUG
    int i;

    for( i = 0; i < NUM_STYLES; i++ ) {
	FcCharSetDestroy( styles[ i ].charset );
	free( styles[ i ].fonts );
    }
    
    for( i = 0; i < num_fonts; i++ ) {
	FcPatternDestroy( fonts[ i ].pattern );
	FT_Done_Face( fonts[ i ].face );
    }

    free( fonts );

    FcFini();
    
    FT_Done_FreeType( ftl );
    
    free( pictures );
#endif
}