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