]> granicus.if.org Git - imagemagick/blob - MagickCore/annotate.c
(no commit message)
[imagemagick] / MagickCore / annotate.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %           AAA   N   N  N   N   OOO   TTTTT   AAA   TTTTT  EEEEE             %
7 %          A   A  NN  N  NN  N  O   O    T    A   A    T    E                 %
8 %          AAAAA  N N N  N N N  O   O    T    AAAAA    T    EEE               %
9 %          A   A  N  NN  N  NN  O   O    T    A   A    T    E                 %
10 %          A   A  N   N  N   N   OOO     T    A   A    T    EEEEE             %
11 %                                                                             %
12 %                                                                             %
13 %                   MagickCore Image Annotation Methods                       %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 % Digital Applications (www.digapp.com) contributed the stroked text algorithm.
37 % It was written by Leonard Rosenthol.
38 %
39 %
40 */
41 \f
42 /*
43   Include declarations.
44 */
45 #include "MagickCore/studio.h"
46 #include "MagickCore/annotate.h"
47 #include "MagickCore/attribute.h"
48 #include "MagickCore/cache-view.h"
49 #include "MagickCore/client.h"
50 #include "MagickCore/color.h"
51 #include "MagickCore/color-private.h"
52 #include "MagickCore/composite.h"
53 #include "MagickCore/composite-private.h"
54 #include "MagickCore/constitute.h"
55 #include "MagickCore/draw.h"
56 #include "MagickCore/draw-private.h"
57 #include "MagickCore/exception.h"
58 #include "MagickCore/exception-private.h"
59 #include "MagickCore/gem.h"
60 #include "MagickCore/geometry.h"
61 #include "MagickCore/image-private.h"
62 #include "MagickCore/log.h"
63 #include "MagickCore/quantum.h"
64 #include "MagickCore/quantum-private.h"
65 #include "MagickCore/pixel-accessor.h"
66 #include "MagickCore/property.h"
67 #include "MagickCore/resource_.h"
68 #include "MagickCore/semaphore.h"
69 #include "MagickCore/statistic.h"
70 #include "MagickCore/string_.h"
71 #include "MagickCore/token-private.h"
72 #include "MagickCore/transform.h"
73 #include "MagickCore/type.h"
74 #include "MagickCore/utility.h"
75 #include "MagickCore/xwindow-private.h"
76 #if defined(MAGICKCORE_FREETYPE_DELEGATE)
77 #if defined(__MINGW32__)
78 #  undef interface
79 #endif
80 #if defined(MAGICKCORE_HAVE_FT2BUILD_H)
81 #  include <ft2build.h>
82 #endif
83 #if defined(FT_FREETYPE_H)
84 #  include FT_FREETYPE_H
85 #else
86 #  include <freetype/freetype.h>
87 #endif
88 #if defined(FT_GLYPH_H)
89 #  include FT_GLYPH_H
90 #else
91 #  include <freetype/ftglyph.h>
92 #endif
93 #if defined(FT_OUTLINE_H)
94 #  include FT_OUTLINE_H
95 #else
96 #  include <freetype/ftoutln.h>
97 #endif
98 #if defined(FT_BBOX_H)
99 #  include FT_BBOX_H
100 #else
101 #  include <freetype/ftbbox.h>
102 #endif /* defined(FT_BBOX_H) */
103 #endif
104 \f
105 /*
106   Annotate semaphores.
107 */
108 static SemaphoreInfo
109   *annotate_semaphore = (SemaphoreInfo *) NULL;
110 \f
111 /*
112   Forward declarations.
113 */
114 static MagickBooleanType
115   RenderType(Image *,const DrawInfo *,const PointInfo *,TypeMetric *),
116   RenderPostscript(Image *,const DrawInfo *,const PointInfo *,TypeMetric *),
117   RenderFreetype(Image *,const DrawInfo *,const char *,const PointInfo *,
118     TypeMetric *),
119   RenderX11(Image *,const DrawInfo *,const PointInfo *,TypeMetric *);
120 \f
121 /*
122 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
123 %                                                                             %
124 %                                                                             %
125 %                                                                             %
126 +   A n n o t a t e C o m p o n e n t G e n e s i s                           %
127 %                                                                             %
128 %                                                                             %
129 %                                                                             %
130 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
131 %
132 %  AnnotateComponentGenesis() instantiates the annotate component.
133 %
134 %  The format of the AnnotateComponentGenesis method is:
135 %
136 %      MagickBooleanType AnnotateComponentGenesis(void)
137 %
138 */
139 MagickExport MagickBooleanType AnnotateComponentGenesis(void)
140 {
141   AcquireSemaphoreInfo(&annotate_semaphore);
142   return(MagickTrue);
143 }
144 \f
145 /*
146 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
147 %                                                                             %
148 %                                                                             %
149 %                                                                             %
150 +   A n n o t a t e C o m p o n e n t T e r m i n u s                         %
151 %                                                                             %
152 %                                                                             %
153 %                                                                             %
154 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
155 %
156 %  AnnotateComponentTerminus() destroys the annotate component.
157 %
158 %  The format of the AnnotateComponentTerminus method is:
159 %
160 %      AnnotateComponentTerminus(void)
161 %
162 */
163 MagickExport void AnnotateComponentTerminus(void)
164 {
165   if (annotate_semaphore == (SemaphoreInfo *) NULL)
166     AcquireSemaphoreInfo(&annotate_semaphore);
167   DestroySemaphoreInfo(&annotate_semaphore);
168 }
169 \f
170 /*
171 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
172 %                                                                             %
173 %                                                                             %
174 %                                                                             %
175 %   A n n o t a t e I m a g e                                                 %
176 %                                                                             %
177 %                                                                             %
178 %                                                                             %
179 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
180 %
181 %  AnnotateImage() annotates an image with text.  Optionally you can include
182 %  any of the following bits of information about the image by embedding
183 %  the appropriate special characters:
184 %
185 %    %b   file size in bytes.
186 %    %c   comment.
187 %    %d   directory in which the image resides.
188 %    %e   extension of the image file.
189 %    %f   original filename of the image.
190 %    %h   height of image.
191 %    %i   filename of the image.
192 %    %k   number of unique colors.
193 %    %l   image label.
194 %    %m   image file format.
195 %    %n   number of images in a image sequence.
196 %    %o   output image filename.
197 %    %p   page number of the image.
198 %    %q   image depth (8 or 16).
199 %    %q   image depth (8 or 16).
200 %    %s   image scene number.
201 %    %t   image filename without any extension.
202 %    %u   a unique temporary filename.
203 %    %w   image width.
204 %    %x   x resolution of the image.
205 %    %y   y resolution of the image.
206 %
207 %  The format of the AnnotateImage method is:
208 %
209 %      MagickBooleanType AnnotateImage(Image *image,DrawInfo *draw_info)
210 %
211 %  A description of each parameter follows:
212 %
213 %    o image: the image.
214 %
215 %    o draw_info: the draw info.
216 %
217 */
218 MagickExport MagickBooleanType AnnotateImage(Image *image,
219   const DrawInfo *draw_info)
220 {
221   char
222     primitive[MaxTextExtent],
223     **textlist;
224
225   DrawInfo
226     *annotate,
227     *annotate_info;
228
229   GeometryInfo
230     geometry_info;
231
232   MagickBooleanType
233     status;
234
235   PointInfo
236     offset;
237
238   RectangleInfo
239     geometry;
240
241   register ssize_t
242     i;
243
244   size_t
245     length;
246
247   TypeMetric
248     metrics;
249
250   size_t
251     height,
252     number_lines;
253
254   assert(image != (Image *) NULL);
255   assert(image->signature == MagickSignature);
256   if (image->debug != MagickFalse)
257     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
258   assert(draw_info != (DrawInfo *) NULL);
259   assert(draw_info->signature == MagickSignature);
260   if (draw_info->text == (char *) NULL)
261     return(MagickFalse);
262   if (*draw_info->text == '\0')
263     return(MagickTrue);
264   textlist=StringToList(draw_info->text);
265   if (textlist == (char **) NULL)
266     return(MagickFalse);
267   length=strlen(textlist[0]);
268   for (i=1; textlist[i] != (char *) NULL; i++)
269     if (strlen(textlist[i]) > length)
270       length=strlen(textlist[i]);
271   number_lines=(size_t) i;
272   annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
273   annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
274   SetGeometry(image,&geometry);
275   SetGeometryInfo(&geometry_info);
276   if (annotate_info->geometry != (char *) NULL)
277     {
278       (void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
279         &image->exception);
280       (void) ParseGeometry(annotate_info->geometry,&geometry_info);
281     }
282   if (SetImageStorageClass(image,DirectClass,&image->exception) == MagickFalse)
283     return(MagickFalse);
284   status=MagickTrue;
285   for (i=0; textlist[i] != (char *) NULL; i++)
286   {
287     /*
288       Position text relative to image.
289     */
290     annotate_info->affine.tx=geometry_info.xi-image->page.x;
291     annotate_info->affine.ty=geometry_info.psi-image->page.y;
292     (void) CloneString(&annotate->text,textlist[i]);
293     (void) GetTypeMetrics(image,annotate,&metrics);
294     height=(ssize_t) (metrics.ascent-metrics.descent+
295       draw_info->interline_spacing+0.5);
296     switch (annotate->gravity)
297     {
298       case UndefinedGravity:
299       default:
300       {
301         offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
302         offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
303         break;
304       }
305       case NorthWestGravity:
306       {
307         offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
308           annotate_info->affine.ry*height+annotate_info->affine.ry*
309           (metrics.ascent+metrics.descent);
310         offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
311           annotate_info->affine.sy*height+annotate_info->affine.sy*
312           metrics.ascent;
313         break;
314       }
315       case NorthGravity:
316       {
317         offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
318           geometry.width/2.0+i*annotate_info->affine.ry*height-
319           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1)/2.0+
320           annotate_info->affine.ry*(metrics.ascent+metrics.descent);
321         offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
322           annotate_info->affine.sy*height+annotate_info->affine.sy*
323           metrics.ascent-annotate_info->affine.rx*(metrics.width-
324           metrics.bounds.x1)/2.0;
325         break;
326       }
327       case NorthEastGravity:
328       {
329         offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
330           geometry.width+i*annotate_info->affine.ry*height-
331           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1)+
332           annotate_info->affine.ry*(metrics.ascent+metrics.descent)-1.0;
333         offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
334           annotate_info->affine.sy*height+annotate_info->affine.sy*
335           metrics.ascent-annotate_info->affine.rx*(metrics.width-
336           metrics.bounds.x1);
337         break;
338       }
339       case WestGravity:
340       {
341         offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
342           annotate_info->affine.ry*height+annotate_info->affine.ry*
343           (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
344         offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
345           geometry.height/2.0+i*annotate_info->affine.sy*height+
346           annotate_info->affine.sy*(metrics.ascent+metrics.descent-
347           (number_lines-1.0)*height)/2.0;
348         break;
349       }
350       case StaticGravity:
351       case CenterGravity:
352       {
353         offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
354           geometry.width/2.0+i*annotate_info->affine.ry*height-
355           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1)/2.0+
356           annotate_info->affine.ry*(metrics.ascent+metrics.descent-
357           (number_lines-1)*height)/2.0;
358         offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
359           geometry.height/2.0+i*annotate_info->affine.sy*height-
360           annotate_info->affine.rx*(metrics.width+metrics.bounds.x1)/2.0+
361           annotate_info->affine.sy*(metrics.ascent+metrics.descent-
362           (number_lines-1.0)*height)/2.0;
363         break;
364       }
365       case EastGravity:
366       {
367         offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
368           geometry.width+i*annotate_info->affine.ry*height-
369           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1)+
370           annotate_info->affine.ry*(metrics.ascent+metrics.descent-
371           (number_lines-1.0)*height)/2.0-1.0;
372         offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
373           geometry.height/2.0+i*annotate_info->affine.sy*height-
374           annotate_info->affine.rx*(metrics.width+metrics.bounds.x1)+
375           annotate_info->affine.sy*(metrics.ascent+metrics.descent-
376           (number_lines-1.0)*height)/2.0;
377         break;
378       }
379       case SouthWestGravity:
380       {
381         offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
382           annotate_info->affine.ry*height-annotate_info->affine.ry*
383           (number_lines-1.0)*height;
384         offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
385           geometry.height+i*annotate_info->affine.sy*height-
386           annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
387         break;
388       }
389       case SouthGravity:
390       {
391         offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
392           geometry.width/2.0+i*annotate_info->affine.ry*height-
393           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1)/2.0-
394           annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
395         offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
396           geometry.height+i*annotate_info->affine.sy*height-
397           annotate_info->affine.rx*(metrics.width+metrics.bounds.x1)/2.0-
398           annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
399         break;
400       }
401       case SouthEastGravity:
402       {
403         offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
404           geometry.width+i*annotate_info->affine.ry*height-
405           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1)-
406           annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
407         offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
408           geometry.height+i*annotate_info->affine.sy*height-
409           annotate_info->affine.rx*(metrics.width+metrics.bounds.x1)-
410           annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
411         break;
412       }
413     }
414     switch (annotate->align)
415     {
416       case LeftAlign:
417       {
418         offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
419         offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
420         break;
421       }
422       case CenterAlign:
423       {
424         offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
425           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1)/2.0;
426         offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
427           annotate_info->affine.rx*(metrics.width+metrics.bounds.x1)/2.0;
428         break;
429       }
430       case RightAlign:
431       {
432         offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
433           annotate_info->affine.sx*(metrics.width+metrics.bounds.x1);
434         offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
435           annotate_info->affine.rx*(metrics.width+metrics.bounds.x1);
436         break;
437       }
438       default:
439         break;
440     }
441     if (draw_info->undercolor.alpha != TransparentAlpha)
442       {
443         DrawInfo
444           *undercolor_info;
445
446         /*
447           Text box.
448         */
449         undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
450         undercolor_info->fill=draw_info->undercolor;
451         undercolor_info->affine=draw_info->affine;
452         undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
453         undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
454         (void) FormatLocaleString(primitive,MaxTextExtent,
455           "rectangle 0,0 %g,%.20g",metrics.origin.x,(double) height);
456         (void) CloneString(&undercolor_info->primitive,primitive);
457         (void) DrawImage(image,undercolor_info);
458         (void) DestroyDrawInfo(undercolor_info);
459       }
460     annotate_info->affine.tx=offset.x;
461     annotate_info->affine.ty=offset.y;
462     (void) FormatLocaleString(primitive,MaxTextExtent,"stroke-width %g "
463       "line 0,0 %g,0",metrics.underline_thickness,metrics.width);
464     if (annotate->decorate == OverlineDecoration)
465       {
466         annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
467           metrics.descent-metrics.underline_position));
468         (void) CloneString(&annotate_info->primitive,primitive);
469         (void) DrawImage(image,annotate_info);
470       }
471     else
472       if (annotate->decorate == UnderlineDecoration)
473         {
474           annotate_info->affine.ty-=(draw_info->affine.sy*
475             metrics.underline_position);
476           (void) CloneString(&annotate_info->primitive,primitive);
477           (void) DrawImage(image,annotate_info);
478         }
479     /*
480       Annotate image with text.
481     */
482     status=RenderType(image,annotate,&offset,&metrics);
483     if (status == MagickFalse)
484       break;
485     if (annotate->decorate == LineThroughDecoration)
486       {
487         annotate_info->affine.ty-=(draw_info->affine.sy*(height+
488           metrics.underline_position+metrics.descent)/2.0);
489         (void) CloneString(&annotate_info->primitive,primitive);
490         (void) DrawImage(image,annotate_info);
491       }
492   }
493   /*
494     Relinquish resources.
495   */
496   annotate_info=DestroyDrawInfo(annotate_info);
497   annotate=DestroyDrawInfo(annotate);
498   for (i=0; textlist[i] != (char *) NULL; i++)
499     textlist[i]=DestroyString(textlist[i]);
500   textlist=(char **) RelinquishMagickMemory(textlist);
501   return(status);
502 }
503 \f
504 /*
505 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
506 %                                                                             %
507 %                                                                             %
508 %                                                                             %
509 %  F o r m a t M a g i c k C a p t i o n                                      %
510 %                                                                             %
511 %                                                                             %
512 %                                                                             %
513 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
514 %
515 %  FormatMagickCaption() formats a caption so that it fits within the image
516 %  width.  It returns the number of lines in the formatted caption.
517 %
518 %  The format of the FormatMagickCaption method is:
519 %
520 %      ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
521 %        const MagickBooleanType split,TypeMetric *metrics,char **caption)
522 %
523 %  A description of each parameter follows.
524 %
525 %    o image:  The image.
526 %
527 %    o draw_info: the draw info.
528 %
529 %    o split: when no convenient line breaks-- insert newline.
530 %
531 %    o metrics: Return the font metrics in this structure.
532 %
533 %    o caption: the caption.
534 %
535 */
536 MagickExport ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
537   const MagickBooleanType split,TypeMetric *metrics,char **caption)
538 {
539   MagickBooleanType
540     status;
541
542   register char
543     *p,
544     *q,
545     *s;
546
547   register ssize_t
548     i;
549
550   size_t
551     width;
552
553   q=draw_info->text;
554   s=(char *) NULL;
555   for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
556   {
557     if (IsUTFSpace(GetUTFCode(p)) != MagickFalse)
558       s=p;
559     for (i=0; i < (ssize_t) GetUTFOctets(p); i++)
560       *q++=(*(p+i));
561     *q='\0';
562     status=GetTypeMetrics(image,draw_info,metrics);
563     if (status == MagickFalse)
564       break;
565     width=(size_t) floor(metrics->width+0.5);
566     if (GetUTFCode(p) != '\n')
567       if (width <= image->columns)
568         continue;
569     if (s == (char *) NULL)
570       {
571         s=p;
572         while ((IsUTFSpace(GetUTFCode(s)) == MagickFalse) &&
573                (GetUTFCode(s) != 0))
574           s+=GetUTFOctets(s);
575       }
576     if (GetUTFCode(s) != 0)
577       {
578         *s='\n';
579         p=s;
580       }
581     else
582       if (split != MagickFalse)
583         {
584           char
585             *target;
586
587           ssize_t
588             n;
589
590           /*
591             No convenient line breaks-- insert newline.
592           */
593           target=AcquireString(*caption);
594           n=p-(*caption);
595           CopyMagickString(target,*caption,n+1);
596           ConcatenateMagickString(target,"\n",strlen(*caption)+1);
597           ConcatenateMagickString(target,p,strlen(*caption)+2);
598           (void) DestroyString(*caption);
599           *caption=target;
600           p=(*caption)+n;
601         }
602     s=(char *) NULL;
603     q=draw_info->text;
604   }
605   i=0;
606   for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
607     if (GetUTFCode(p) == '\n')
608       i++;
609   return(i);
610 }
611 \f
612 /*
613 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
614 %                                                                             %
615 %                                                                             %
616 %                                                                             %
617 %   G e t M u l t i l i n e T y p e M e t r i c s                             %
618 %                                                                             %
619 %                                                                             %
620 %                                                                             %
621 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
622 %
623 %  GetMultilineTypeMetrics() returns the following information for the
624 %  specified font and text:
625 %
626 %    character width
627 %    character height
628 %    ascender
629 %    descender
630 %    text width
631 %    text height
632 %    maximum horizontal advance
633 %    bounds: x1
634 %    bounds: y1
635 %    bounds: x2
636 %    bounds: y2
637 %    origin: x
638 %    origin: y
639 %    underline position
640 %    underline thickness
641 %
642 %  This method is like GetTypeMetrics() but it returns the maximum text width
643 %  and height for multiple lines of text.
644 %
645 %  The format of the GetMultilineTypeMetrics method is:
646 %
647 %      MagickBooleanType GetMultilineTypeMetrics(Image *image,
648 %        const DrawInfo *draw_info,TypeMetric *metrics)
649 %
650 %  A description of each parameter follows:
651 %
652 %    o image: the image.
653 %
654 %    o draw_info: the draw info.
655 %
656 %    o metrics: Return the font metrics in this structure.
657 %
658 */
659 MagickExport MagickBooleanType GetMultilineTypeMetrics(Image *image,
660   const DrawInfo *draw_info,TypeMetric *metrics)
661 {
662   char
663     **textlist;
664
665   DrawInfo
666     *annotate_info;
667
668   MagickBooleanType
669     status;
670
671   register ssize_t
672     i;
673
674   TypeMetric
675     extent;
676
677   assert(image != (Image *) NULL);
678   assert(image->signature == MagickSignature);
679   if (image->debug != MagickFalse)
680     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
681   assert(draw_info != (DrawInfo *) NULL);
682   assert(draw_info->text != (char *) NULL);
683   assert(draw_info->signature == MagickSignature);
684   if (*draw_info->text == '\0')
685     return(MagickFalse);
686   annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
687   annotate_info->text=DestroyString(annotate_info->text);
688   /*
689     Convert newlines to multiple lines of text.
690   */
691   textlist=StringToList(draw_info->text);
692   if (textlist == (char **) NULL)
693     return(MagickFalse);
694   annotate_info->render=MagickFalse;
695   annotate_info->direction=UndefinedDirection;
696   (void) ResetMagickMemory(metrics,0,sizeof(*metrics));
697   (void) ResetMagickMemory(&extent,0,sizeof(extent));
698   /*
699     Find the widest of the text lines.
700   */
701   annotate_info->text=textlist[0];
702   status=GetTypeMetrics(image,annotate_info,&extent);
703   *metrics=extent;
704   for (i=1; textlist[i] != (char *) NULL; i++)
705   {
706     annotate_info->text=textlist[i];
707     status=GetTypeMetrics(image,annotate_info,&extent);
708     if (extent.width > metrics->width)
709       *metrics=extent;
710   }
711   metrics->height=(double) (i*(size_t) (metrics->ascent-
712     metrics->descent+0.5)+(i-1)*draw_info->interline_spacing);
713   /*
714     Relinquish resources.
715   */
716   annotate_info->text=(char *) NULL;
717   annotate_info=DestroyDrawInfo(annotate_info);
718   for (i=0; textlist[i] != (char *) NULL; i++)
719     textlist[i]=DestroyString(textlist[i]);
720   textlist=(char **) RelinquishMagickMemory(textlist);
721   return(status);
722 }
723 \f
724 /*
725 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
726 %                                                                             %
727 %                                                                             %
728 %                                                                             %
729 %   G e t T y p e M e t r i c s                                               %
730 %                                                                             %
731 %                                                                             %
732 %                                                                             %
733 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
734 %
735 %  GetTypeMetrics() returns the following information for the specified font
736 %  and text:
737 %
738 %    character width
739 %    character height
740 %    ascender
741 %    descender
742 %    text width
743 %    text height
744 %    maximum horizontal advance
745 %    bounds: x1
746 %    bounds: y1
747 %    bounds: x2
748 %    bounds: y2
749 %    origin: x
750 %    origin: y
751 %    underline position
752 %    underline thickness
753 %
754 %  The format of the GetTypeMetrics method is:
755 %
756 %      MagickBooleanType GetTypeMetrics(Image *image,const DrawInfo *draw_info,
757 %        TypeMetric *metrics)
758 %
759 %  A description of each parameter follows:
760 %
761 %    o image: the image.
762 %
763 %    o draw_info: the draw info.
764 %
765 %    o metrics: Return the font metrics in this structure.
766 %
767 */
768 MagickExport MagickBooleanType GetTypeMetrics(Image *image,
769   const DrawInfo *draw_info,TypeMetric *metrics)
770 {
771   DrawInfo
772     *annotate_info;
773
774   MagickBooleanType
775     status;
776
777   PointInfo
778     offset;
779
780   assert(image != (Image *) NULL);
781   assert(image->signature == MagickSignature);
782   if (image->debug != MagickFalse)
783     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
784   assert(draw_info != (DrawInfo *) NULL);
785   assert(draw_info->text != (char *) NULL);
786   assert(draw_info->signature == MagickSignature);
787   annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
788   annotate_info->render=MagickFalse;
789   annotate_info->direction=UndefinedDirection;
790   (void) ResetMagickMemory(metrics,0,sizeof(*metrics));
791   offset.x=0.0;
792   offset.y=0.0;
793   status=RenderType(image,annotate_info,&offset,metrics);
794   if (image->debug != MagickFalse)
795     (void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Metrics: text: %s; "
796       "width: %g; height: %g; ascent: %g; descent: %g; max advance: %g; "
797       "bounds: %g,%g  %g,%g; origin: %g,%g; pixels per em: %g,%g; "
798       "underline position: %g; underline thickness: %g",annotate_info->text,
799       metrics->width,metrics->height,metrics->ascent,metrics->descent,
800       metrics->max_advance,metrics->bounds.x1,metrics->bounds.y1,
801       metrics->bounds.x2,metrics->bounds.y2,metrics->origin.x,metrics->origin.y,
802       metrics->pixels_per_em.x,metrics->pixels_per_em.y,
803       metrics->underline_position,metrics->underline_thickness);
804   annotate_info=DestroyDrawInfo(annotate_info);
805   return(status);
806 }
807 \f
808 /*
809 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
810 %                                                                             %
811 %                                                                             %
812 %                                                                             %
813 +   R e n d e r T y p e                                                       %
814 %                                                                             %
815 %                                                                             %
816 %                                                                             %
817 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
818 %
819 %  RenderType() renders text on the image.  It also returns the bounding box of
820 %  the text relative to the image.
821 %
822 %  The format of the RenderType method is:
823 %
824 %      MagickBooleanType RenderType(Image *image,DrawInfo *draw_info,
825 %        const PointInfo *offset,TypeMetric *metrics)
826 %
827 %  A description of each parameter follows:
828 %
829 %    o image: the image.
830 %
831 %    o draw_info: the draw info.
832 %
833 %    o offset: (x,y) location of text relative to image.
834 %
835 %    o metrics: bounding box of text.
836 %
837 */
838 static MagickBooleanType RenderType(Image *image,const DrawInfo *draw_info,
839   const PointInfo *offset,TypeMetric *metrics)
840 {
841   const TypeInfo
842     *type_info;
843
844   DrawInfo
845     *annotate_info;
846
847   MagickBooleanType
848     status;
849
850   type_info=(const TypeInfo *) NULL;
851   if (draw_info->font != (char *) NULL)
852     {
853       if (*draw_info->font == '@')
854         {
855           status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
856             metrics);
857           return(status);
858         }
859       if (*draw_info->font == '-')
860         return(RenderX11(image,draw_info,offset,metrics));
861       if (IsPathAccessible(draw_info->font) != MagickFalse)
862         {
863           status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
864             metrics);
865           return(status);
866         }
867       type_info=GetTypeInfo(draw_info->font,&image->exception);
868       if (type_info == (const TypeInfo *) NULL)
869         (void) ThrowMagickException(&image->exception,GetMagickModule(),
870           TypeWarning,"UnableToReadFont","`%s'",draw_info->font);
871     }
872   if ((type_info == (const TypeInfo *) NULL) &&
873       (draw_info->family != (const char *) NULL))
874     {
875       type_info=GetTypeInfoByFamily(draw_info->family,draw_info->style,
876         draw_info->stretch,draw_info->weight,&image->exception);
877       if (type_info == (const TypeInfo *) NULL)
878         (void) ThrowMagickException(&image->exception,GetMagickModule(),
879           TypeWarning,"UnableToReadFont","`%s'",draw_info->family);
880     }
881   if (type_info == (const TypeInfo *) NULL)
882     type_info=GetTypeInfoByFamily("Arial",draw_info->style,
883       draw_info->stretch,draw_info->weight,&image->exception);
884   if (type_info == (const TypeInfo *) NULL)
885     type_info=GetTypeInfoByFamily("Helvetica",draw_info->style,
886       draw_info->stretch,draw_info->weight,&image->exception);
887   if (type_info == (const TypeInfo *) NULL)
888     type_info=GetTypeInfoByFamily("Century Schoolbook",draw_info->style,
889       draw_info->stretch,draw_info->weight,&image->exception);
890   if (type_info == (const TypeInfo *) NULL)
891     type_info=GetTypeInfoByFamily((const char *) NULL,draw_info->style,
892       draw_info->stretch,draw_info->weight,&image->exception);
893   if (type_info == (const TypeInfo *) NULL)
894     type_info=GetTypeInfo("*",&image->exception);
895   if (type_info == (const TypeInfo *) NULL)
896     {
897       status=RenderFreetype(image,draw_info,draw_info->encoding,offset,metrics);
898       return(status);
899     }
900   annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
901   annotate_info->face=type_info->face;
902   if (type_info->metrics != (char *) NULL)
903     (void) CloneString(&annotate_info->metrics,type_info->metrics);
904   if (type_info->glyphs != (char *) NULL)
905     (void) CloneString(&annotate_info->font,type_info->glyphs);
906   status=RenderFreetype(image,annotate_info,type_info->encoding,offset,metrics);
907   annotate_info=DestroyDrawInfo(annotate_info);
908   return(status);
909 }
910 \f
911 /*
912 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
913 %                                                                             %
914 %                                                                             %
915 %                                                                             %
916 +   R e n d e r F r e e t y p e                                               %
917 %                                                                             %
918 %                                                                             %
919 %                                                                             %
920 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
921 %
922 %  RenderFreetype() renders text on the image with a Truetype font.  It also
923 %  returns the bounding box of the text relative to the image.
924 %
925 %  The format of the RenderFreetype method is:
926 %
927 %      MagickBooleanType RenderFreetype(Image *image,DrawInfo *draw_info,
928 %        const char *encoding,const PointInfo *offset,TypeMetric *metrics)
929 %
930 %  A description of each parameter follows:
931 %
932 %    o image: the image.
933 %
934 %    o draw_info: the draw info.
935 %
936 %    o encoding: the font encoding.
937 %
938 %    o offset: (x,y) location of text relative to image.
939 %
940 %    o metrics: bounding box of text.
941 %
942 */
943
944 #if defined(MAGICKCORE_FREETYPE_DELEGATE)
945
946 static int TraceCubicBezier(FT_Vector *p,FT_Vector *q,FT_Vector *to,
947   DrawInfo *draw_info)
948 {
949   AffineMatrix
950     affine;
951
952   char
953     path[MaxTextExtent];
954
955   affine=draw_info->affine;
956   (void) FormatLocaleString(path,MaxTextExtent,
957     "C%g,%g %g,%g %g,%g",affine.tx+p->x/64.0,affine.ty-
958     p->y/64.0,affine.tx+q->x/64.0,affine.ty-q->y/64.0,affine.tx+to->x/64.0,
959     affine.ty-to->y/64.0);
960   (void) ConcatenateString(&draw_info->primitive,path);
961   return(0);
962 }
963
964 static int TraceLineTo(FT_Vector *to,DrawInfo *draw_info)
965 {
966   AffineMatrix
967     affine;
968
969   char
970     path[MaxTextExtent];
971
972   affine=draw_info->affine;
973   (void) FormatLocaleString(path,MaxTextExtent,"L%g,%g",affine.tx+
974     to->x/64.0,affine.ty-to->y/64.0);
975   (void) ConcatenateString(&draw_info->primitive,path);
976   return(0);
977 }
978
979 static int TraceMoveTo(FT_Vector *to,DrawInfo *draw_info)
980 {
981   AffineMatrix
982     affine;
983
984   char
985     path[MaxTextExtent];
986
987   affine=draw_info->affine;
988   (void) FormatLocaleString(path,MaxTextExtent,"M%g,%g",affine.tx+
989     to->x/64.0,affine.ty-to->y/64.0);
990   (void) ConcatenateString(&draw_info->primitive,path);
991   return(0);
992 }
993
994 static int TraceQuadraticBezier(FT_Vector *control,FT_Vector *to,
995   DrawInfo *draw_info)
996 {
997   AffineMatrix
998     affine;
999
1000   char
1001     path[MaxTextExtent];
1002
1003   affine=draw_info->affine;
1004   (void) FormatLocaleString(path,MaxTextExtent,"Q%g,%g %g,%g",
1005     affine.tx+control->x/64.0,affine.ty-control->y/64.0,affine.tx+to->x/64.0,
1006     affine.ty-to->y/64.0);
1007   (void) ConcatenateString(&draw_info->primitive,path);
1008   return(0);
1009 }
1010
1011 static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info,
1012   const char *encoding,const PointInfo *offset,TypeMetric *metrics)
1013 {
1014 #if !defined(FT_OPEN_PATHNAME)
1015 #define FT_OPEN_PATHNAME  ft_open_pathname
1016 #endif
1017
1018   typedef struct _GlyphInfo
1019   {
1020     FT_UInt
1021       id;
1022
1023     FT_Vector
1024       origin;
1025
1026     FT_Glyph
1027       image;
1028   } GlyphInfo;
1029
1030   const char
1031     *value;
1032
1033   double
1034     direction;
1035
1036   DrawInfo
1037     *annotate_info;
1038
1039   FT_BBox
1040     bounds;
1041
1042   FT_BitmapGlyph
1043     bitmap;
1044
1045   FT_Encoding
1046     encoding_type;
1047
1048   FT_Error
1049     status;
1050
1051   FT_Face
1052     face;
1053
1054   FT_Int32
1055     flags;
1056
1057   FT_Library
1058     library;
1059
1060   FT_Matrix
1061     affine;
1062
1063   FT_Open_Args
1064     args;
1065
1066   FT_Vector
1067     origin;
1068
1069   GlyphInfo
1070     glyph,
1071     last_glyph;
1072
1073   PointInfo
1074     point,
1075     resolution;
1076
1077   register char
1078     *p;
1079
1080   ssize_t
1081     code,
1082     y;
1083
1084   static FT_Outline_Funcs
1085     OutlineMethods =
1086     {
1087       (FT_Outline_MoveTo_Func) TraceMoveTo,
1088       (FT_Outline_LineTo_Func) TraceLineTo,
1089       (FT_Outline_ConicTo_Func) TraceQuadraticBezier,
1090       (FT_Outline_CubicTo_Func) TraceCubicBezier,
1091       0, 0
1092     };
1093
1094   unsigned char
1095     *utf8;
1096
1097   /*
1098     Initialize Truetype library.
1099   */
1100   status=FT_Init_FreeType(&library);
1101   if (status != 0)
1102     ThrowBinaryException(TypeError,"UnableToInitializeFreetypeLibrary",
1103       image->filename);
1104   args.flags=FT_OPEN_PATHNAME;
1105   if (draw_info->font == (char *) NULL)
1106     args.pathname=ConstantString("helvetica");
1107   else
1108     if (*draw_info->font != '@')
1109       args.pathname=ConstantString(draw_info->font);
1110     else
1111       args.pathname=ConstantString(draw_info->font+1);
1112   face=(FT_Face) NULL;
1113   status=FT_Open_Face(library,&args,(long) draw_info->face,&face);
1114   args.pathname=DestroyString(args.pathname);
1115   if (status != 0)
1116     {
1117       (void) FT_Done_FreeType(library);
1118       (void) ThrowMagickException(&image->exception,GetMagickModule(),
1119         TypeError,"UnableToReadFont","`%s'",draw_info->font);
1120       return(RenderPostscript(image,draw_info,offset,metrics));
1121     }
1122   if ((draw_info->metrics != (char *) NULL) &&
1123       (IsPathAccessible(draw_info->metrics) != MagickFalse))
1124     (void) FT_Attach_File(face,draw_info->metrics);
1125   encoding_type=ft_encoding_unicode;
1126   status=FT_Select_Charmap(face,encoding_type);
1127   if ((status != 0) && (face->num_charmaps != 0))
1128     status=FT_Set_Charmap(face,face->charmaps[0]);
1129   if (encoding != (const char *) NULL)
1130     {
1131       if (LocaleCompare(encoding,"AdobeCustom") == 0)
1132         encoding_type=ft_encoding_adobe_custom;
1133       if (LocaleCompare(encoding,"AdobeExpert") == 0)
1134         encoding_type=ft_encoding_adobe_expert;
1135       if (LocaleCompare(encoding,"AdobeStandard") == 0)
1136         encoding_type=ft_encoding_adobe_standard;
1137       if (LocaleCompare(encoding,"AppleRoman") == 0)
1138         encoding_type=ft_encoding_apple_roman;
1139       if (LocaleCompare(encoding,"BIG5") == 0)
1140         encoding_type=ft_encoding_big5;
1141       if (LocaleCompare(encoding,"GB2312") == 0)
1142         encoding_type=ft_encoding_gb2312;
1143       if (LocaleCompare(encoding,"Johab") == 0)
1144         encoding_type=ft_encoding_johab;
1145 #if defined(ft_encoding_latin_1)
1146       if (LocaleCompare(encoding,"Latin-1") == 0)
1147         encoding_type=ft_encoding_latin_1;
1148 #endif
1149       if (LocaleCompare(encoding,"Latin-2") == 0)
1150         encoding_type=ft_encoding_latin_2;
1151       if (LocaleCompare(encoding,"None") == 0)
1152         encoding_type=ft_encoding_none;
1153       if (LocaleCompare(encoding,"SJIScode") == 0)
1154         encoding_type=ft_encoding_sjis;
1155       if (LocaleCompare(encoding,"Symbol") == 0)
1156         encoding_type=ft_encoding_symbol;
1157       if (LocaleCompare(encoding,"Unicode") == 0)
1158         encoding_type=ft_encoding_unicode;
1159       if (LocaleCompare(encoding,"Wansung") == 0)
1160         encoding_type=ft_encoding_wansung;
1161       status=FT_Select_Charmap(face,encoding_type);
1162       if (status != 0)
1163         ThrowBinaryException(TypeError,"UnrecognizedFontEncoding",encoding);
1164     }
1165   /*
1166     Set text size.
1167   */
1168   resolution.x=DefaultResolution;
1169   resolution.y=DefaultResolution;
1170   if (draw_info->density != (char *) NULL)
1171     {
1172       GeometryInfo
1173         geometry_info;
1174
1175       MagickStatusType
1176         flags;
1177
1178       flags=ParseGeometry(draw_info->density,&geometry_info);
1179       resolution.x=geometry_info.rho;
1180       resolution.y=geometry_info.sigma;
1181       if ((flags & SigmaValue) == 0)
1182         resolution.y=resolution.x;
1183     }
1184   status=FT_Set_Char_Size(face,(FT_F26Dot6) (64.0*draw_info->pointsize),
1185     (FT_F26Dot6) (64.0*draw_info->pointsize),(FT_UInt) resolution.x,
1186     (FT_UInt) resolution.y);
1187   metrics->pixels_per_em.x=face->size->metrics.x_ppem;
1188   metrics->pixels_per_em.y=face->size->metrics.y_ppem;
1189   metrics->ascent=(double) face->size->metrics.ascender/64.0;
1190   metrics->descent=(double) face->size->metrics.descender/64.0;
1191   metrics->width=0;
1192   metrics->origin.x=0;
1193   metrics->origin.y=0;
1194   metrics->height=(double) face->size->metrics.height/64.0;
1195   metrics->max_advance=0.0;
1196   if (face->size->metrics.max_advance > MagickEpsilon)
1197     metrics->max_advance=(double) face->size->metrics.max_advance/64.0;
1198   metrics->bounds.x1=0.0;
1199   metrics->bounds.y1=metrics->descent;
1200   metrics->bounds.x2=metrics->ascent+metrics->descent;
1201   metrics->bounds.y2=metrics->ascent+metrics->descent;
1202   metrics->underline_position=face->underline_position/64.0;
1203   metrics->underline_thickness=face->underline_thickness/64.0;
1204   if (*draw_info->text == '\0')
1205     {
1206       (void) FT_Done_Face(face);
1207       (void) FT_Done_FreeType(library);
1208       return(MagickTrue);
1209     }
1210   /*
1211     Compute bounding box.
1212   */
1213   if (image->debug != MagickFalse)
1214     (void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Font %s; "
1215       "font-encoding %s; text-encoding %s; pointsize %g",
1216       draw_info->font != (char *) NULL ? draw_info->font : "none",
1217       encoding != (char *) NULL ? encoding : "none",
1218       draw_info->encoding != (char *) NULL ? draw_info->encoding : "none",
1219       draw_info->pointsize);
1220   flags=FT_LOAD_NO_BITMAP;
1221   value=GetImageProperty(image,"type:hinting");
1222   if ((value != (const char *) NULL) && (LocaleCompare(value,"off") == 0))
1223     flags|=FT_LOAD_NO_HINTING;
1224   glyph.id=0;
1225   glyph.image=NULL;
1226   last_glyph.id=0;
1227   last_glyph.image=NULL;
1228   origin.x=0;
1229   origin.y=0;
1230   affine.xx=65536L;
1231   affine.yx=0L;
1232   affine.xy=0L;
1233   affine.yy=65536L;
1234   if (draw_info->render != MagickFalse)
1235     {
1236       affine.xx=(FT_Fixed) (65536L*draw_info->affine.sx+0.5);
1237       affine.yx=(FT_Fixed) (-65536L*draw_info->affine.rx+0.5);
1238       affine.xy=(FT_Fixed) (-65536L*draw_info->affine.ry+0.5);
1239       affine.yy=(FT_Fixed) (65536L*draw_info->affine.sy+0.5);
1240     }
1241   annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
1242   (void) CloneString(&annotate_info->primitive,"path '");
1243   if (draw_info->render != MagickFalse)
1244     {
1245       if (image->storage_class != DirectClass)
1246         (void) SetImageStorageClass(image,DirectClass,&image->exception);
1247       if (image->matte == MagickFalse)
1248         (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,&image->exception);
1249     }
1250   direction=1.0;
1251   if (draw_info->direction == RightToLeftDirection)
1252     direction=(-1.0);
1253   point.x=0.0;
1254   point.y=0.0;
1255   for (p=draw_info->text; GetUTFCode(p) != 0; p+=GetUTFOctets(p))
1256     if (GetUTFCode(p) < 0)
1257       break;
1258   utf8=(unsigned char *) NULL;
1259   if (GetUTFCode(p) == 0)
1260     p=draw_info->text;
1261   else
1262     {
1263       utf8=ConvertLatin1ToUTF8((unsigned char *) draw_info->text);
1264       if (utf8 != (unsigned char *) NULL)
1265         p=(char *) utf8;
1266     }
1267   for (code=0; GetUTFCode(p) != 0; p+=GetUTFOctets(p))
1268   {
1269     /*
1270       Render UTF-8 sequence.
1271     */
1272     glyph.id=FT_Get_Char_Index(face,GetUTFCode(p));
1273     if (glyph.id == 0)
1274       glyph.id=FT_Get_Char_Index(face,'?');
1275     if ((glyph.id != 0) && (last_glyph.id != 0))
1276       {
1277         if (draw_info->kerning != 0.0)
1278           origin.x+=64.0*direction*draw_info->kerning;
1279         else
1280           if (FT_HAS_KERNING(face))
1281             {
1282               FT_Vector
1283                 kerning;
1284
1285               status=FT_Get_Kerning(face,last_glyph.id,glyph.id,
1286                 ft_kerning_default,&kerning);
1287               if (status == 0)
1288                 origin.x+=direction*kerning.x;
1289             }
1290         }
1291     glyph.origin=origin;
1292     status=FT_Load_Glyph(face,glyph.id,flags);
1293     if (status != 0)
1294       continue;
1295     status=FT_Get_Glyph(face->glyph,&glyph.image);
1296     if (status != 0)
1297       continue;
1298     status=FT_Outline_Get_BBox(&((FT_OutlineGlyph) glyph.image)->outline,
1299       &bounds);
1300     if (status != 0)
1301       continue;
1302     if ((p == draw_info->text) || (bounds.xMin < metrics->bounds.x1))
1303       metrics->bounds.x1=bounds.xMin;
1304     if ((p == draw_info->text) || (bounds.yMin < metrics->bounds.y1))
1305       metrics->bounds.y1=bounds.yMin;
1306     if ((p == draw_info->text) || (bounds.xMax > metrics->bounds.x2))
1307       metrics->bounds.x2=bounds.xMax;
1308     if ((p == draw_info->text) || (bounds.yMax > metrics->bounds.y2))
1309       metrics->bounds.y2=bounds.yMax;
1310     if (draw_info->render != MagickFalse)
1311       if ((draw_info->stroke.alpha != TransparentAlpha) ||
1312           (draw_info->stroke_pattern != (Image *) NULL))
1313         {
1314           /*
1315             Trace the glyph.
1316           */
1317           annotate_info->affine.tx=glyph.origin.x/64.0;
1318           annotate_info->affine.ty=glyph.origin.y/64.0;
1319           (void) FT_Outline_Decompose(&((FT_OutlineGlyph) glyph.image)->
1320             outline,&OutlineMethods,annotate_info);
1321         }
1322     FT_Vector_Transform(&glyph.origin,&affine);
1323     (void) FT_Glyph_Transform(glyph.image,&affine,&glyph.origin);
1324     status=FT_Glyph_To_Bitmap(&glyph.image,ft_render_mode_normal,
1325       (FT_Vector *) NULL,MagickTrue);
1326     if (status != 0)
1327       continue;
1328     bitmap=(FT_BitmapGlyph) glyph.image;
1329     point.x=offset->x+bitmap->left;
1330     point.y=offset->y-bitmap->top;
1331     if (draw_info->render != MagickFalse)
1332       {
1333         CacheView
1334           *image_view;
1335
1336         ExceptionInfo
1337           *exception;
1338
1339         MagickBooleanType
1340           status;
1341
1342         /*
1343           Rasterize the glyph.
1344         */
1345         status=MagickTrue;
1346         exception=(&image->exception);
1347         image_view=AcquireCacheView(image);
1348         for (y=0; y < (ssize_t) bitmap->bitmap.rows; y++)
1349         {
1350           MagickBooleanType
1351             active,
1352             sync;
1353
1354           MagickRealType
1355             fill_opacity;
1356
1357           PixelPacket
1358             fill_color;
1359
1360           register Quantum
1361             *restrict q;
1362
1363           register ssize_t
1364             x;
1365
1366           register unsigned char
1367             *p;
1368
1369           ssize_t
1370             x_offset,
1371             y_offset;
1372
1373           if (status == MagickFalse)
1374             continue;
1375           x_offset=(ssize_t) ceil(point.x-0.5);
1376           y_offset=(ssize_t) ceil(point.y+y-0.5);
1377           if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows))
1378             continue;
1379           q=(Quantum *) NULL;
1380           if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
1381             active=MagickFalse;
1382           else
1383             {
1384               q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset,
1385                 bitmap->bitmap.width,1,exception);
1386               active=q != (Quantum *) NULL ? MagickTrue : MagickFalse;
1387             }
1388           p=bitmap->bitmap.buffer+y*bitmap->bitmap.width;
1389           for (x=0; x < (ssize_t) bitmap->bitmap.width; x++)
1390           {
1391             x_offset++;
1392             if ((*p == 0) || (x_offset < 0) ||
1393                 (x_offset >= (ssize_t) image->columns))
1394               {
1395                 p++;
1396                 q+=GetPixelChannels(image);
1397                 continue;
1398               }
1399             fill_opacity=(MagickRealType) (*p)/(bitmap->bitmap.num_grays-1);
1400             if (draw_info->text_antialias == MagickFalse)
1401               fill_opacity=fill_opacity >= 0.5 ? 1.0 : 0.0;
1402             if (active == MagickFalse)
1403               q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset,1,1,
1404                 exception);
1405             if (q == (const Quantum *) NULL)
1406               {
1407                 p++;
1408                 q+=GetPixelChannels(image);
1409                 continue;
1410               }
1411             (void) GetFillColor(draw_info,x_offset,y_offset,&fill_color);
1412             fill_opacity=fill_opacity*fill_color.alpha;
1413             CompositePixelOver(image,&fill_color,fill_opacity,q,
1414               GetPixelAlpha(image,q),q);
1415             if (active == MagickFalse)
1416               {
1417                 sync=SyncCacheViewAuthenticPixels(image_view,exception);
1418                 if (sync == MagickFalse)
1419                   status=MagickFalse;
1420               }
1421             p++;
1422             q+=GetPixelChannels(image);
1423           }
1424           sync=SyncCacheViewAuthenticPixels(image_view,exception);
1425           if (sync == MagickFalse)
1426             status=MagickFalse;
1427         }
1428         image_view=DestroyCacheView(image_view);
1429       }
1430     if ((bitmap->left+bitmap->bitmap.width) > metrics->width)
1431       metrics->width=bitmap->left+bitmap->bitmap.width;
1432     if ((draw_info->interword_spacing != 0.0) &&
1433         (IsUTFSpace(GetUTFCode(p)) != MagickFalse) &&
1434         (IsUTFSpace(code) == MagickFalse))
1435       origin.x+=64.0*direction*draw_info->interword_spacing;
1436     else
1437       origin.x+=direction*face->glyph->advance.x;
1438     metrics->origin.x=origin.x;
1439     metrics->origin.y=origin.y;
1440     if (last_glyph.id != 0)
1441       FT_Done_Glyph(last_glyph.image);
1442     last_glyph=glyph;
1443     code=GetUTFCode(p);
1444   }
1445   if (utf8 != (unsigned char *) NULL)
1446     utf8=(unsigned char *) RelinquishMagickMemory(utf8);
1447   if (last_glyph.id != 0)
1448     FT_Done_Glyph(last_glyph.image);
1449   if ((draw_info->stroke.alpha != TransparentAlpha) ||
1450       (draw_info->stroke_pattern != (Image *) NULL))
1451     {
1452       if (draw_info->render != MagickFalse)
1453         {
1454           /*
1455             Draw text stroke.
1456           */
1457           annotate_info->linejoin=RoundJoin;
1458           annotate_info->affine.tx=offset->x;
1459           annotate_info->affine.ty=offset->y;
1460           (void) ConcatenateString(&annotate_info->primitive,"'");
1461           (void) DrawImage(image,annotate_info);
1462         }
1463       }
1464   /*
1465     Determine font metrics.
1466   */
1467   glyph.id=FT_Get_Char_Index(face,'_');
1468   glyph.origin=origin;
1469   status=FT_Load_Glyph(face,glyph.id,flags);
1470   if (status == 0)
1471     {
1472       status=FT_Get_Glyph(face->glyph,&glyph.image);
1473       if (status == 0)
1474         {
1475           status=FT_Outline_Get_BBox(&((FT_OutlineGlyph) glyph.image)->
1476             outline,&bounds);
1477           if (status == 0)
1478             {
1479               FT_Vector_Transform(&glyph.origin,&affine);
1480               (void) FT_Glyph_Transform(glyph.image,&affine,&glyph.origin);
1481               status=FT_Glyph_To_Bitmap(&glyph.image,ft_render_mode_normal,
1482                 (FT_Vector *) NULL,MagickTrue);
1483               bitmap=(FT_BitmapGlyph) glyph.image;
1484               if (bitmap->left > metrics->width)
1485                 metrics->width=bitmap->left;
1486             }
1487         }
1488       if (glyph.id != 0)
1489         FT_Done_Glyph(glyph.image);
1490     }
1491   metrics->width-=metrics->bounds.x1/64.0;
1492   metrics->bounds.x1/=64.0;
1493   metrics->bounds.y1/=64.0;
1494   metrics->bounds.x2/=64.0;
1495   metrics->bounds.y2/=64.0;
1496   metrics->origin.x/=64.0;
1497   metrics->origin.y/=64.0;
1498   /*
1499     Relinquish resources.
1500   */
1501   annotate_info=DestroyDrawInfo(annotate_info);
1502   (void) FT_Done_Face(face);
1503   (void) FT_Done_FreeType(library);
1504   return(MagickTrue);
1505 }
1506 #else
1507 static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info,
1508   const char *magick_unused(encoding),const PointInfo *offset,
1509   TypeMetric *metrics)
1510 {
1511   (void) ThrowMagickException(&image->exception,GetMagickModule(),
1512     MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (Freetype)",
1513     draw_info->font != (char *) NULL ? draw_info->font : "none");
1514   return(RenderPostscript(image,draw_info,offset,metrics));
1515 }
1516 #endif
1517 \f
1518 /*
1519 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1520 %                                                                             %
1521 %                                                                             %
1522 %                                                                             %
1523 +   R e n d e r P o s t s c r i p t                                           %
1524 %                                                                             %
1525 %                                                                             %
1526 %                                                                             %
1527 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1528 %
1529 %  RenderPostscript() renders text on the image with a Postscript font.  It
1530 %  also returns the bounding box of the text relative to the image.
1531 %
1532 %  The format of the RenderPostscript method is:
1533 %
1534 %      MagickBooleanType RenderPostscript(Image *image,DrawInfo *draw_info,
1535 %        const PointInfo *offset,TypeMetric *metrics)
1536 %
1537 %  A description of each parameter follows:
1538 %
1539 %    o image: the image.
1540 %
1541 %    o draw_info: the draw info.
1542 %
1543 %    o offset: (x,y) location of text relative to image.
1544 %
1545 %    o metrics: bounding box of text.
1546 %
1547 */
1548
1549 static inline size_t MagickMin(const size_t x,const size_t y)
1550 {
1551   if (x < y)
1552     return(x);
1553   return(y);
1554 }
1555
1556 static char *EscapeParenthesis(const char *text)
1557 {
1558   char
1559     *buffer;
1560
1561   register char
1562     *p;
1563
1564   register ssize_t
1565     i;
1566
1567   size_t
1568     escapes;
1569
1570   escapes=0;
1571   buffer=AcquireString(text);
1572   p=buffer;
1573   for (i=0; i < (ssize_t) MagickMin(strlen(text),MaxTextExtent-escapes-1); i++)
1574   {
1575     if ((text[i] == '(') || (text[i] == ')'))
1576       {
1577         *p++='\\';
1578         escapes++;
1579       }
1580     *p++=text[i];
1581   }
1582   *p='\0';
1583   return(buffer);
1584 }
1585
1586 static MagickBooleanType RenderPostscript(Image *image,
1587   const DrawInfo *draw_info,const PointInfo *offset,TypeMetric *metrics)
1588 {
1589   char
1590     filename[MaxTextExtent],
1591     geometry[MaxTextExtent],
1592     *text;
1593
1594   FILE
1595     *file;
1596
1597   Image
1598     *annotate_image;
1599
1600   ImageInfo
1601     *annotate_info;
1602
1603   int
1604     unique_file;
1605
1606   MagickBooleanType
1607     identity;
1608
1609   PointInfo
1610     extent,
1611     point,
1612     resolution;
1613
1614   register ssize_t
1615     i;
1616
1617   ssize_t
1618     y;
1619
1620   /*
1621     Render label with a Postscript font.
1622   */
1623   if (image->debug != MagickFalse)
1624     (void) LogMagickEvent(AnnotateEvent,GetMagickModule(),
1625       "Font %s; pointsize %g",draw_info->font != (char *) NULL ?
1626       draw_info->font : "none",draw_info->pointsize);
1627   file=(FILE *) NULL;
1628   unique_file=AcquireUniqueFileResource(filename);
1629   if (unique_file != -1)
1630     file=fdopen(unique_file,"wb");
1631   if ((unique_file == -1) || (file == (FILE *) NULL))
1632     {
1633       ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
1634         filename);
1635       return(MagickFalse);
1636     }
1637   (void) FormatLocaleFile(file,"%%!PS-Adobe-3.0\n");
1638   (void) FormatLocaleFile(file,"/ReencodeType\n");
1639   (void) FormatLocaleFile(file,"{\n");
1640   (void) FormatLocaleFile(file,"  findfont dup length\n");
1641   (void) FormatLocaleFile(file,
1642     "  dict begin { 1 index /FID ne {def} {pop pop} ifelse } forall\n");
1643   (void) FormatLocaleFile(file,
1644     "  /Encoding ISOLatin1Encoding def currentdict end definefont pop\n");
1645   (void) FormatLocaleFile(file,"} bind def\n");
1646   /*
1647     Sample to compute bounding box.
1648   */
1649   identity=(draw_info->affine.sx == draw_info->affine.sy) &&
1650     (draw_info->affine.rx == 0.0) && (draw_info->affine.ry == 0.0) ?
1651     MagickTrue : MagickFalse;
1652   extent.x=0.0;
1653   extent.y=0.0;
1654   for (i=0; i <= (ssize_t) (strlen(draw_info->text)+2); i++)
1655   {
1656     point.x=fabs(draw_info->affine.sx*i*draw_info->pointsize+
1657       draw_info->affine.ry*2.0*draw_info->pointsize);
1658     point.y=fabs(draw_info->affine.rx*i*draw_info->pointsize+
1659       draw_info->affine.sy*2.0*draw_info->pointsize);
1660     if (point.x > extent.x)
1661       extent.x=point.x;
1662     if (point.y > extent.y)
1663       extent.y=point.y;
1664   }
1665   (void) FormatLocaleFile(file,"%g %g moveto\n",identity  != MagickFalse ? 0.0 :
1666     extent.x/2.0,extent.y/2.0);
1667   (void) FormatLocaleFile(file,"%g %g scale\n",draw_info->pointsize,
1668     draw_info->pointsize);
1669   if ((draw_info->font == (char *) NULL) || (*draw_info->font == '\0') ||
1670       (strchr(draw_info->font,'/') != (char *) NULL))
1671     (void) FormatLocaleFile(file,
1672       "/Times-Roman-ISO dup /Times-Roman ReencodeType findfont setfont\n");
1673   else
1674     (void) FormatLocaleFile(file,
1675       "/%s-ISO dup /%s ReencodeType findfont setfont\n",draw_info->font,
1676       draw_info->font);
1677   (void) FormatLocaleFile(file,"[%g %g %g %g 0 0] concat\n",
1678     draw_info->affine.sx,-draw_info->affine.rx,-draw_info->affine.ry,
1679     draw_info->affine.sy);
1680   text=EscapeParenthesis(draw_info->text);
1681   if (identity == MagickFalse)
1682     (void) FormatLocaleFile(file,"(%s) stringwidth pop -0.5 mul -0.5 rmoveto\n",
1683       text);
1684   (void) FormatLocaleFile(file,"(%s) show\n",text);
1685   text=DestroyString(text);
1686   (void) FormatLocaleFile(file,"showpage\n");
1687   (void) fclose(file);
1688   (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g+0+0!",
1689     floor(extent.x+0.5),floor(extent.y+0.5));
1690   annotate_info=AcquireImageInfo();
1691   (void) FormatLocaleString(annotate_info->filename,MaxTextExtent,"ps:%s",
1692     filename);
1693   (void) CloneString(&annotate_info->page,geometry);
1694   if (draw_info->density != (char *) NULL)
1695     (void) CloneString(&annotate_info->density,draw_info->density);
1696   annotate_info->antialias=draw_info->text_antialias;
1697   annotate_image=ReadImage(annotate_info,&image->exception);
1698   CatchException(&image->exception);
1699   annotate_info=DestroyImageInfo(annotate_info);
1700   (void) RelinquishUniqueFileResource(filename);
1701   if (annotate_image == (Image *) NULL)
1702     return(MagickFalse);
1703   resolution.x=DefaultResolution;
1704   resolution.y=DefaultResolution;
1705   if (draw_info->density != (char *) NULL)
1706     {
1707       GeometryInfo
1708         geometry_info;
1709
1710       MagickStatusType
1711         flags;
1712
1713       flags=ParseGeometry(draw_info->density,&geometry_info);
1714       resolution.x=geometry_info.rho;
1715       resolution.y=geometry_info.sigma;
1716       if ((flags & SigmaValue) == 0)
1717         resolution.y=resolution.x;
1718     }
1719   if (identity == MagickFalse)
1720     (void) TransformImage(&annotate_image,"0x0",(char *) NULL);
1721   else
1722     {
1723       RectangleInfo
1724         crop_info;
1725
1726       crop_info=GetImageBoundingBox(annotate_image,&annotate_image->exception);
1727       crop_info.height=(size_t) ((resolution.y/DefaultResolution)*
1728         ExpandAffine(&draw_info->affine)*draw_info->pointsize+0.5);
1729       crop_info.y=(ssize_t) ceil((resolution.y/DefaultResolution)*extent.y/8.0-
1730         0.5);
1731       (void) FormatLocaleString(geometry,MaxTextExtent,
1732         "%.20gx%.20g%+.20g%+.20g",(double) crop_info.width,(double)
1733         crop_info.height,(double) crop_info.x,(double) crop_info.y);
1734       (void) TransformImage(&annotate_image,geometry,(char *) NULL);
1735     }
1736   metrics->pixels_per_em.x=(resolution.y/DefaultResolution)*
1737     ExpandAffine(&draw_info->affine)*draw_info->pointsize;
1738   metrics->pixels_per_em.y=metrics->pixels_per_em.x;
1739   metrics->ascent=metrics->pixels_per_em.x;
1740   metrics->descent=metrics->pixels_per_em.y/-5.0;
1741   metrics->width=(double) annotate_image->columns/
1742     ExpandAffine(&draw_info->affine);
1743   metrics->height=1.152*metrics->pixels_per_em.x;
1744   metrics->max_advance=metrics->pixels_per_em.x;
1745   metrics->bounds.x1=0.0;
1746   metrics->bounds.y1=metrics->descent;
1747   metrics->bounds.x2=metrics->ascent+metrics->descent;
1748   metrics->bounds.y2=metrics->ascent+metrics->descent;
1749   metrics->underline_position=(-2.0);
1750   metrics->underline_thickness=1.0;
1751   if (draw_info->render == MagickFalse)
1752     {
1753       annotate_image=DestroyImage(annotate_image);
1754       return(MagickTrue);
1755     }
1756   if (draw_info->fill.alpha != TransparentAlpha)
1757     {
1758       ExceptionInfo
1759         *exception;
1760
1761       MagickBooleanType
1762         sync;
1763
1764       PixelPacket
1765         fill_color;
1766
1767       CacheView
1768         *annotate_view;
1769
1770       /*
1771         Render fill color.
1772       */
1773       exception=(&image->exception);
1774       if (image->matte == MagickFalse)
1775         (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
1776       if (annotate_image->matte == MagickFalse)
1777         (void) SetImageAlphaChannel(annotate_image,OpaqueAlphaChannel,
1778           exception);
1779       fill_color=draw_info->fill;
1780       annotate_view=AcquireCacheView(annotate_image);
1781       for (y=0; y < (ssize_t) annotate_image->rows; y++)
1782       {
1783         register ssize_t
1784           x;
1785
1786         register Quantum
1787           *restrict q;
1788
1789         q=GetCacheViewAuthenticPixels(annotate_view,0,y,annotate_image->columns,
1790           1,exception);
1791         if (q == (const Quantum *) NULL)
1792           break;
1793         for (x=0; x < (ssize_t) annotate_image->columns; x++)
1794         {
1795           (void) GetFillColor(draw_info,x,y,&fill_color);
1796           SetPixelAlpha(annotate_image,ClampToQuantum((((MagickRealType)
1797             GetPixelIntensity(annotate_image,q)*fill_color.alpha)/
1798             QuantumRange)),q);
1799           SetPixelRed(annotate_image,fill_color.red,q);
1800           SetPixelGreen(annotate_image,fill_color.green,q);
1801           SetPixelBlue(annotate_image,fill_color.blue,q);
1802           q+=GetPixelChannels(annotate_image);
1803         }
1804         sync=SyncCacheViewAuthenticPixels(annotate_view,exception);
1805         if (sync == MagickFalse)
1806           break;
1807       }
1808       annotate_view=DestroyCacheView(annotate_view);
1809       (void) CompositeImage(image,OverCompositeOp,annotate_image,
1810         (ssize_t) ceil(offset->x-0.5),(ssize_t) ceil(offset->y-(metrics->ascent+
1811         metrics->descent)-0.5));
1812     }
1813   annotate_image=DestroyImage(annotate_image);
1814   return(MagickTrue);
1815 }
1816 \f
1817 /*
1818 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1819 %                                                                             %
1820 %                                                                             %
1821 %                                                                             %
1822 +   R e n d e r X 1 1                                                         %
1823 %                                                                             %
1824 %                                                                             %
1825 %                                                                             %
1826 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1827 %
1828 %  RenderX11() renders text on the image with an X11 font.  It also returns the
1829 %  bounding box of the text relative to the image.
1830 %
1831 %  The format of the RenderX11 method is:
1832 %
1833 %      MagickBooleanType RenderX11(Image *image,DrawInfo *draw_info,
1834 %        const PointInfo *offset,TypeMetric *metrics)
1835 %
1836 %  A description of each parameter follows:
1837 %
1838 %    o image: the image.
1839 %
1840 %    o draw_info: the draw info.
1841 %
1842 %    o offset: (x,y) location of text relative to image.
1843 %
1844 %    o metrics: bounding box of text.
1845 %
1846 */
1847 #if defined(MAGICKCORE_X11_DELEGATE)
1848 static MagickBooleanType RenderX11(Image *image,const DrawInfo *draw_info,
1849   const PointInfo *offset,TypeMetric *metrics)
1850 {
1851   MagickBooleanType
1852     status;
1853
1854   static DrawInfo
1855     cache_info;
1856
1857   static Display
1858     *display = (Display *) NULL;
1859
1860   static XAnnotateInfo
1861     annotate_info;
1862
1863   static XFontStruct
1864     *font_info;
1865
1866   static XPixelInfo
1867     pixel;
1868
1869   static XResourceInfo
1870     resource_info;
1871
1872   static XrmDatabase
1873     resource_database;
1874
1875   static XStandardColormap
1876     *map_info;
1877
1878   static XVisualInfo
1879     *visual_info;
1880
1881   size_t
1882     height,
1883     width;
1884
1885   if (annotate_semaphore == (SemaphoreInfo *) NULL)
1886     AcquireSemaphoreInfo(&annotate_semaphore);
1887   LockSemaphoreInfo(annotate_semaphore);
1888   if (display == (Display *) NULL)
1889     {
1890       const char
1891         *client_name;
1892
1893       ImageInfo
1894         *image_info;
1895
1896       /*
1897         Open X server connection.
1898       */
1899       display=XOpenDisplay(draw_info->server_name);
1900       if (display == (Display *) NULL)
1901         {
1902           ThrowXWindowException(XServerError,"UnableToOpenXServer",
1903             draw_info->server_name);
1904           return(MagickFalse);
1905         }
1906       /*
1907         Get user defaults from X resource database.
1908       */
1909       (void) XSetErrorHandler(XError);
1910       image_info=AcquireImageInfo();
1911       client_name=GetClientName();
1912       resource_database=XGetResourceDatabase(display,client_name);
1913       XGetResourceInfo(image_info,resource_database,client_name,&resource_info);
1914       resource_info.close_server=MagickFalse;
1915       resource_info.colormap=PrivateColormap;
1916       resource_info.font=AcquireString(draw_info->font);
1917       resource_info.background_color=AcquireString("#ffffffffffff");
1918       resource_info.foreground_color=AcquireString("#000000000000");
1919       map_info=XAllocStandardColormap();
1920       if (map_info == (XStandardColormap *) NULL)
1921         {
1922           ThrowXWindowException(ResourceLimitError,"MemoryAllocationFailed",
1923             image->filename);
1924           return(MagickFalse);
1925         }
1926       /*
1927         Initialize visual info.
1928       */
1929       visual_info=XBestVisualInfo(display,map_info,&resource_info);
1930       if (visual_info == (XVisualInfo *) NULL)
1931         {
1932           ThrowXWindowException(XServerError,"UnableToGetVisual",
1933             image->filename);
1934           return(MagickFalse);
1935         }
1936       map_info->colormap=(Colormap) NULL;
1937       pixel.pixels=(unsigned long *) NULL;
1938       /*
1939         Initialize Standard Colormap info.
1940       */
1941       XGetMapInfo(visual_info,XDefaultColormap(display,visual_info->screen),
1942         map_info);
1943       XGetPixelInfo(display,visual_info,map_info,&resource_info,(Image *) NULL,
1944         &pixel);
1945       pixel.annotate_context=XDefaultGC(display,visual_info->screen);
1946       /*
1947         Initialize font info.
1948       */
1949       font_info=XBestFont(display,&resource_info,MagickFalse);
1950       if (font_info == (XFontStruct *) NULL)
1951         {
1952           ThrowXWindowException(XServerError,"UnableToLoadFont",
1953             draw_info->font);
1954           return(MagickFalse);
1955         }
1956       if ((map_info == (XStandardColormap *) NULL) ||
1957           (visual_info == (XVisualInfo *) NULL) ||
1958           (font_info == (XFontStruct *) NULL))
1959         {
1960           XFreeResources(display,visual_info,map_info,&pixel,font_info,
1961             &resource_info,(XWindowInfo *) NULL);
1962           ThrowXWindowException(XServerError,"UnableToLoadFont",
1963             image->filename);
1964           return(MagickFalse);
1965         }
1966       cache_info=(*draw_info);
1967     }
1968   UnlockSemaphoreInfo(annotate_semaphore);
1969   /*
1970     Initialize annotate info.
1971   */
1972   XGetAnnotateInfo(&annotate_info);
1973   annotate_info.stencil=ForegroundStencil;
1974   if (cache_info.font != draw_info->font)
1975     {
1976       /*
1977         Type name has changed.
1978       */
1979       (void) XFreeFont(display,font_info);
1980       (void) CloneString(&resource_info.font,draw_info->font);
1981       font_info=XBestFont(display,&resource_info,MagickFalse);
1982       if (font_info == (XFontStruct *) NULL)
1983         {
1984           ThrowXWindowException(XServerError,"UnableToLoadFont",
1985             draw_info->font);
1986           return(MagickFalse);
1987         }
1988     }
1989   if (image->debug != MagickFalse)
1990     (void) LogMagickEvent(AnnotateEvent,GetMagickModule(),
1991       "Font %s; pointsize %g",draw_info->font != (char *) NULL ?
1992       draw_info->font : "none",draw_info->pointsize);
1993   cache_info=(*draw_info);
1994   annotate_info.font_info=font_info;
1995   annotate_info.text=(char *) draw_info->text;
1996   annotate_info.width=(unsigned int) XTextWidth(font_info,draw_info->text,
1997     (int) strlen(draw_info->text));
1998   annotate_info.height=(unsigned int) font_info->ascent+font_info->descent;
1999   metrics->pixels_per_em.x=(double) font_info->max_bounds.width;
2000   metrics->pixels_per_em.y=(double) font_info->ascent+font_info->descent;
2001   metrics->ascent=(double) font_info->ascent+4;
2002   metrics->descent=(double) (-font_info->descent);
2003   metrics->width=annotate_info.width/ExpandAffine(&draw_info->affine);
2004   metrics->height=font_info->ascent+font_info->descent;
2005   metrics->max_advance=(double) font_info->max_bounds.width;
2006   metrics->bounds.x1=0.0;
2007   metrics->bounds.y1=metrics->descent;
2008   metrics->bounds.x2=metrics->ascent+metrics->descent;
2009   metrics->bounds.y2=metrics->ascent+metrics->descent;
2010   metrics->underline_position=(-2.0);
2011   metrics->underline_thickness=1.0;
2012   if (draw_info->render == MagickFalse)
2013     return(MagickTrue);
2014   if (draw_info->fill.alpha == TransparentAlpha)
2015     return(MagickTrue);
2016   /*
2017     Render fill color.
2018   */
2019   width=annotate_info.width;
2020   height=annotate_info.height;
2021   if ((draw_info->affine.rx != 0.0) || (draw_info->affine.ry != 0.0))
2022     {
2023       if (((draw_info->affine.sx-draw_info->affine.sy) == 0.0) &&
2024           ((draw_info->affine.rx+draw_info->affine.ry) == 0.0))
2025         annotate_info.degrees=(180.0/MagickPI)*
2026           atan2(draw_info->affine.rx,draw_info->affine.sx);
2027     }
2028   (void) FormatLocaleString(annotate_info.geometry,MaxTextExtent,
2029     "%.20gx%.20g%+.20g%+.20g",(double) width,(double) height,
2030     ceil(offset->x-0.5),ceil(offset->y-metrics->ascent-metrics->descent+
2031     draw_info->interline_spacing-0.5));
2032   pixel.pen_color.red=ScaleQuantumToShort(draw_info->fill.red);
2033   pixel.pen_color.green=ScaleQuantumToShort(draw_info->fill.green);
2034   pixel.pen_color.blue=ScaleQuantumToShort(draw_info->fill.blue);
2035   status=XAnnotateImage(display,&pixel,&annotate_info,image);
2036   if (status == 0)
2037     {
2038       ThrowXWindowException(ResourceLimitError,"MemoryAllocationFailed",
2039         image->filename);
2040       return(MagickFalse);
2041     }
2042   return(MagickTrue);
2043 }
2044 #else
2045 static MagickBooleanType RenderX11(Image *image,const DrawInfo *draw_info,
2046   const PointInfo *offset,TypeMetric *metrics)
2047 {
2048   (void) draw_info;
2049   (void) offset;
2050   (void) metrics;
2051   (void) ThrowMagickException(&image->exception,GetMagickModule(),
2052     MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (X11)",
2053     image->filename);
2054   return(MagickFalse);
2055 }
2056 #endif