]> granicus.if.org Git - imagemagick/blob - coders/caption.c
(no commit message)
[imagemagick] / coders / caption.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %               CCCC   AAA   PPPP   TTTTT  IIIII   OOO   N   N                %
7 %              C      A   A  P   P    T      I    O   O  NN  N                %
8 %              C      AAAAA  PPPP     T      I    O   O  N N N                %
9 %              C      A   A  P        T      I    O   O  N  NN                %
10 %               CCCC  A   A  P        T    IIIII   OOO   N   N                %
11 %                                                                             %
12 %                                                                             %
13 %                             Read Text Caption.                              %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                               February 2002                                 %
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 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/annotate.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/composite-private.h"
47 #include "MagickCore/draw.h"
48 #include "MagickCore/draw-private.h"
49 #include "MagickCore/exception.h"
50 #include "MagickCore/exception-private.h"
51 #include "MagickCore/image.h"
52 #include "MagickCore/image-private.h"
53 #include "MagickCore/list.h"
54 #include "MagickCore/magick.h"
55 #include "MagickCore/memory_.h"
56 #include "MagickCore/module.h"
57 #include "MagickCore/option.h"
58 #include "MagickCore/property.h"
59 #include "MagickCore/quantum-private.h"
60 #include "MagickCore/static.h"
61 #include "MagickCore/string_.h"
62 #include "MagickCore/string-private.h"
63 #include "MagickCore/utility.h"
64 #if defined(MAGICKCORE_PANGOFT2_DELEGATE)
65 #include <pango/pango.h>
66 #include <pango/pangoft2.h>
67 #include <pango/pango-features.h>
68 #endif
69 \f
70 /*
71 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
72 %                                                                             %
73 %                                                                             %
74 %                                                                             %
75 %   R e a d C A P T I O N I m a g e                                           %
76 %                                                                             %
77 %                                                                             %
78 %                                                                             %
79 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
80 %
81 %  ReadCAPTIONImage() reads a CAPTION image file and returns it.  It
82 %  allocates the memory necessary for the new Image structure and returns a
83 %  pointer to the new image.
84 %
85 %  The format of the ReadCAPTIONImage method is:
86 %
87 %      Image *ReadCAPTIONImage(const ImageInfo *image_info,
88 %        ExceptionInfo *exception)
89 %
90 %  A description of each parameter follows:
91 %
92 %    o image_info: the image info.
93 %
94 %    o exception: return any errors or warnings in this structure.
95 %
96 */
97 #if defined(MAGICKCORE_PANGOFT2_DELEGATE)
98 static void PangoSubstitute(FcPattern *pattern,void *context)
99 {
100   const char
101     *option;
102
103   option=(const char *) context;
104   if (option == (const char *) NULL)
105     return;
106   FcPatternDel(pattern,FC_HINTING);
107   FcPatternAddBool(pattern, FC_HINTING,LocaleCompare(option,"none") != 0);
108   FcPatternDel(pattern,FC_AUTOHINT);
109   FcPatternAddBool(pattern,FC_AUTOHINT,LocaleCompare(option,"auto") == 0);
110 }
111
112 static Image *ReadCAPTIONImage(const ImageInfo *image_info,
113   ExceptionInfo *exception)
114 {
115   char
116     *caption,
117     *property;
118
119   const char
120     *option;
121
122   DrawInfo
123     *draw_info;
124
125   FT_Bitmap
126     *canvas;
127
128   Image
129     *image;
130
131   PangoAlignment
132     align;
133
134   PangoContext
135     *context;
136
137   PangoFontDescription
138     *description;
139
140   PangoFontMap
141     *fontmap;
142
143   PangoGravity
144     gravity;
145
146   PangoLayout
147     *layout;
148
149   PangoRectangle
150     extent;
151
152   PixelInfo
153     fill_color;
154
155   RectangleInfo
156     page;
157
158   register Quantum
159     *q;
160
161   register unsigned char
162     *p;
163
164   ssize_t
165     y;
166
167   /*
168     Initialize Image structure.
169   */
170   assert(image_info != (const ImageInfo *) NULL);
171   assert(image_info->signature == MagickSignature);
172   if (image_info->debug != MagickFalse)
173     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
174       image_info->filename);
175   assert(exception != (ExceptionInfo *) NULL);
176   assert(exception->signature == MagickSignature);
177   image=AcquireImage(image_info,exception);
178   (void) ResetImagePage(image,"0x0+0+0");
179   /*
180     Get context.
181   */
182   fontmap=(PangoFontMap *) pango_ft2_font_map_new();
183   pango_ft2_font_map_set_resolution((PangoFT2FontMap *) fontmap,
184     image->resolution.x,image->resolution.y);
185   option=GetImageOption(image_info,"caption:hinting");
186   pango_ft2_font_map_set_default_substitute((PangoFT2FontMap *) fontmap,
187     PangoSubstitute,(char *) option,NULL);
188   context=pango_font_map_create_context(fontmap);
189   option=GetImageOption(image_info,"caption:language");
190   if (option != (const char *) NULL)
191     pango_context_set_language(context,pango_language_from_string(option));
192   draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
193   pango_context_set_base_dir(context,draw_info->direction ==
194     RightToLeftDirection ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR);
195   switch (draw_info->gravity)
196   {
197     case NorthGravity: gravity=PANGO_GRAVITY_NORTH; break;
198     case WestGravity: gravity=PANGO_GRAVITY_WEST; break;
199     case EastGravity: gravity=PANGO_GRAVITY_EAST; break;
200     case SouthGravity: gravity=PANGO_GRAVITY_SOUTH; break;
201     default: gravity=PANGO_GRAVITY_AUTO; break;
202   }
203   pango_context_set_base_gravity(context,gravity);
204   option=GetImageOption(image_info,"caption:gravity-hint");
205   if (option != (const char *) NULL)
206     {
207       if (LocaleCompare(option,"line") == 0)
208         pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_LINE);
209       if (LocaleCompare(option,"natural") == 0)
210         pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_NATURAL);
211       if (LocaleCompare(option,"strong") == 0)
212         pango_context_set_gravity_hint(context,PANGO_GRAVITY_HINT_STRONG);
213     }
214   /*
215     Configure layout.
216   */
217   layout=pango_layout_new(context);
218   option=GetImageOption(image_info,"caption:auto-dir");
219   if (option != (const char *) NULL)
220     pango_layout_set_auto_dir(layout,1);
221   option=GetImageOption(image_info,"caption:ellipsize");
222   if (option != (const char *) NULL)
223     {
224       if (LocaleCompare(option,"end") == 0)
225         pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_END);
226       if (LocaleCompare(option,"middle") == 0)
227         pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_MIDDLE);
228       if (LocaleCompare(option,"none") == 0)
229         pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_NONE);
230       if (LocaleCompare(option,"start") == 0)
231         pango_layout_set_ellipsize(layout,PANGO_ELLIPSIZE_START);
232     }
233   option=GetImageOption(image_info,"caption:justify");
234   if ((option != (const char *) NULL) && (IsMagickTrue(option) != MagickFalse))
235     pango_layout_set_justify(layout,1);
236   option=GetImageOption(image_info,"caption:single-paragraph");
237   if ((option != (const char *) NULL) && (IsMagickTrue(option) != MagickFalse))
238     pango_layout_set_single_paragraph_mode(layout,1);
239   option=GetImageOption(image_info,"caption:wrap");
240   if (option != (const char *) NULL)
241     {
242       if (LocaleCompare(option,"char") == 0)
243         pango_layout_set_wrap(layout,PANGO_WRAP_CHAR);
244       if (LocaleCompare(option,"word") == 0)
245         pango_layout_set_wrap(layout,PANGO_WRAP_WORD);
246       if (LocaleCompare(option,"word-char") == 0)
247         pango_layout_set_wrap(layout,PANGO_WRAP_WORD_CHAR);
248     }
249   option=GetImageOption(image_info,"caption:indent");
250   if (option != (const char *) NULL)
251     pango_layout_set_indent(layout,(StringToLong(option)*image->resolution.x*
252       PANGO_SCALE+36)/72);
253   switch (draw_info->align)
254   {
255     case CenterAlign: align=PANGO_ALIGN_CENTER; break;
256     case RightAlign: align=PANGO_ALIGN_RIGHT; break;
257     case LeftAlign:
258     default: align=PANGO_ALIGN_LEFT; break;
259   }
260   if ((align != PANGO_ALIGN_CENTER) &&
261       (draw_info->direction == RightToLeftDirection))
262     align=PANGO_ALIGN_LEFT+PANGO_ALIGN_RIGHT-align;
263   pango_layout_set_alignment(layout,align);
264   description=pango_font_description_from_string(draw_info->font ==
265     (char *) NULL ? "helvetica" : draw_info->font);
266   pango_font_description_set_size(description,PANGO_SCALE*draw_info->pointsize);
267   pango_layout_set_font_description(layout,description);
268   pango_font_description_free(description);
269   property=InterpretImageProperties(image_info,image,image_info->filename,
270     exception);
271   (void) SetImageProperty(image,"caption",property,exception);
272   property=DestroyString(property);
273   caption=ConstantString(GetImageProperty(image,"caption",exception));
274   /*
275     Render caption.
276   */
277   option=GetImageOption(image_info,"caption:markup");
278   if ((option != (const char *) NULL) && (IsMagickTrue(option) != MagickFalse))
279     pango_layout_set_markup(layout,caption,-1);
280   else
281     pango_layout_set_text(layout,caption,-1);
282   pango_layout_context_changed(layout);
283   page.x=0;
284   page.y=0;
285   if (image_info->page != (char *) NULL)
286     (void) ParseAbsoluteGeometry(image_info->page,&page);
287   if (image->columns == 0)
288     {
289       pango_layout_get_pixel_extents(layout,NULL,&extent);
290       image->columns=extent.x+extent.width;
291     }
292   else
293     {
294       image->columns-=2*page.x;
295       pango_layout_set_width(layout,(PANGO_SCALE*image->columns*
296         image->resolution.x+36.0)/72.0);
297     }
298   if (image->rows == 0)
299     {
300       pango_layout_get_pixel_extents(layout,NULL,&extent);
301       image->rows=extent.y+extent.height;
302     }
303   else
304     {
305       image->rows-=2*page.y;
306       pango_layout_set_height(layout,(PANGO_SCALE*image->rows*
307         image->resolution.y+36.0)/72.0);
308     }
309   /*
310     Create canvas.
311   */
312   canvas=(FT_Bitmap *) AcquireMagickMemory(sizeof(*canvas));
313   if (canvas == (FT_Bitmap *) NULL)
314     {
315       draw_info=DestroyDrawInfo(draw_info);
316       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
317     }
318   canvas->width=image->columns;
319   canvas->pitch=(canvas->width+3) & ~3;
320   canvas->rows=image->rows;
321   canvas->buffer=(unsigned char *) AcquireQuantumMemory(canvas->pitch,
322     canvas->rows*sizeof(*canvas->buffer));
323   if (canvas->buffer == (unsigned char *) NULL)
324     {
325       draw_info=DestroyDrawInfo(draw_info);
326       canvas=(FT_Bitmap *) RelinquishMagickMemory(canvas);
327       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
328     }
329   canvas->num_grays=256;
330   canvas->pixel_mode=ft_pixel_mode_grays;
331   ResetMagickMemory(canvas->buffer,0x00,canvas->pitch*canvas->rows);
332   pango_ft2_render_layout(canvas,layout,0,0);
333   /*
334     Convert caption to image.
335   */
336   image->columns+=2*page.x;
337   image->rows+=2*page.y;
338   if (SetImageBackgroundColor(image,exception) == MagickFalse)
339     {
340       draw_info=DestroyDrawInfo(draw_info);
341       canvas->buffer=(unsigned char *) RelinquishMagickMemory(canvas->buffer);
342       canvas=(FT_Bitmap *) RelinquishMagickMemory(canvas);
343       caption=DestroyString(caption);
344       image=DestroyImageList(image);
345       return((Image *) NULL);
346     }
347   GetPixelInfo(image,&fill_color);
348   p=canvas->buffer;
349   for (y=page.y; y < (ssize_t) (image->rows-page.y); y++)
350   {
351     register ssize_t
352       x;
353
354     q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
355     if (q == (Quantum *) NULL)
356       break;
357     q+=page.x*GetPixelChannels(image);
358     for (x=page.x; x < (ssize_t) (image->columns-page.x); x++)
359     {
360       MagickRealType
361         fill_opacity;
362
363       (void) GetFillColor(draw_info,x,y,&fill_color,exception);
364       fill_opacity=(*p)*fill_color.alpha/canvas->num_grays;
365       if (draw_info->text_antialias == MagickFalse)
366         fill_opacity=fill_opacity >= 0.5 ? 1.0 : 0.0;
367       CompositePixelOver(image,&fill_color,fill_opacity,q,
368         GetPixelAlpha(image,q),q);
369       p++;
370       q+=GetPixelChannels(image);
371     }
372     for ( ; x < (ssize_t) ((canvas->width+3) & ~3); x++)
373       p++;
374   }
375   /*
376     Relinquish resources.
377   */
378   draw_info=DestroyDrawInfo(draw_info);
379   canvas->buffer=(unsigned char *) RelinquishMagickMemory(canvas->buffer);
380   canvas=(FT_Bitmap *) RelinquishMagickMemory(canvas);
381   caption=DestroyString(caption);
382   return(GetFirstImageInList(image));
383 }
384 #else
385 static Image *ReadCAPTIONImage(const ImageInfo *image_info,
386   ExceptionInfo *exception)
387 {
388   char
389     *caption,
390     geometry[MaxTextExtent],
391     *property;
392
393   const char
394     *gravity;
395
396   DrawInfo
397     *draw_info;
398
399   Image
400     *image;
401
402   MagickBooleanType
403     status;
404
405   register ssize_t
406     i;
407
408   size_t
409     height,
410     width;
411
412   TypeMetric
413     metrics;
414
415   /*
416     Initialize Image structure.
417   */
418   assert(image_info != (const ImageInfo *) NULL);
419   assert(image_info->signature == MagickSignature);
420   if (image_info->debug != MagickFalse)
421     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
422       image_info->filename);
423   assert(exception != (ExceptionInfo *) NULL);
424   assert(exception->signature == MagickSignature);
425   image=AcquireImage(image_info,exception);
426   if (image->columns == 0)
427     ThrowReaderException(OptionError,"MustSpecifyImageSize");
428   (void) ResetImagePage(image,"0x0+0+0");
429   /*
430     Format caption.
431   */
432   property=InterpretImageProperties(image_info,image,image_info->filename,
433     exception);
434   (void) SetImageProperty(image,"caption",property,exception);
435   property=DestroyString(property);
436   caption=ConstantString(GetImageProperty(image,"caption",exception));
437   draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
438   (void) CloneString(&draw_info->text,caption);
439   gravity=GetImageOption(image_info,"gravity");
440   if (gravity != (char *) NULL)
441     draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
442       MagickFalse,gravity);
443   if ((*caption != '\0') && (image->rows != 0) &&
444       (image_info->pointsize == 0.0))
445     {
446       char
447         *text;
448
449       /*
450         Scale text to fit bounding box.
451       */
452       for ( ; ; )
453       {
454         text=AcquireString(caption);
455         i=FormatMagickCaption(image,draw_info,MagickFalse,&metrics,&text,
456           exception);
457         (void) CloneString(&draw_info->text,text);
458         text=DestroyString(text);
459         (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
460           -metrics.bounds.x1,metrics.ascent);
461         if (draw_info->gravity == UndefinedGravity)
462           (void) CloneString(&draw_info->geometry,geometry);
463         status=GetMultilineTypeMetrics(image,draw_info,&metrics,exception);
464         (void) status;
465         width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
466         height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
467         if ((width > (image->columns+1)) || (height > (image->rows+1)))
468           break;
469         draw_info->pointsize*=2.0;
470       }
471       draw_info->pointsize/=2.0;
472       for ( ; ; )
473       {
474         text=AcquireString(caption);
475         i=FormatMagickCaption(image,draw_info,MagickFalse,&metrics,&text,
476           exception);
477         (void) CloneString(&draw_info->text,text);
478         text=DestroyString(text);
479         (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
480           -metrics.bounds.x1,metrics.ascent);
481         if (draw_info->gravity == UndefinedGravity)
482           (void) CloneString(&draw_info->geometry,geometry);
483         status=GetMultilineTypeMetrics(image,draw_info,&metrics,exception);
484         width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
485         height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
486         if ((width > (image->columns+1)) || (height > (image->rows+1)))
487           break;
488         draw_info->pointsize++;
489       }
490       draw_info->pointsize--;
491     }
492   i=FormatMagickCaption(image,draw_info,MagickTrue,&metrics,&caption,exception);
493   if (image->rows == 0)
494     image->rows=(size_t) ((i+1)*(metrics.ascent-metrics.descent+
495       draw_info->interline_spacing+draw_info->stroke_width)+0.5);
496   if (image->rows == 0)
497     image->rows=(size_t) ((i+1)*draw_info->pointsize+
498       draw_info->interline_spacing+draw_info->stroke_width+0.5);
499   if (SetImageBackgroundColor(image,exception) == MagickFalse)
500     {
501       image=DestroyImageList(image);
502       return((Image *) NULL);
503     }
504   /*
505     Draw caption.
506   */
507   (void) CloneString(&draw_info->text,caption);
508   status=GetMultilineTypeMetrics(image,draw_info,&metrics,exception);
509   if ((draw_info->gravity != UndefinedGravity) &&
510       (draw_info->direction != RightToLeftDirection))
511     image->page.x=(ssize_t) (metrics.bounds.x1-draw_info->stroke_width/2.0);
512   else
513     {
514       (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
515         -metrics.bounds.x1+draw_info->stroke_width/2.0,metrics.ascent+
516         draw_info->stroke_width/2.0);
517       if (draw_info->direction == RightToLeftDirection)
518         (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
519           image->columns-(metrics.bounds.x2+draw_info->stroke_width/2.0),
520           metrics.ascent+draw_info->stroke_width/2.0);
521       draw_info->geometry=AcquireString(geometry);
522     }
523   (void) AnnotateImage(image,draw_info,exception);
524   draw_info=DestroyDrawInfo(draw_info);
525   caption=DestroyString(caption);
526   return(GetFirstImageInList(image));
527 }
528 #endif
529 \f
530 /*
531 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
532 %                                                                             %
533 %                                                                             %
534 %                                                                             %
535 %   R e g i s t e r C A P T I O N I m a g e                                   %
536 %                                                                             %
537 %                                                                             %
538 %                                                                             %
539 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
540 %
541 %  RegisterCAPTIONImage() adds attributes for the CAPTION image format to
542 %  the list of supported formats.  The attributes include the image format
543 %  tag, a method to read and/or write the format, whether the format
544 %  supports the saving of more than one frame to the same file or blob,
545 %  whether the format supports native in-memory I/O, and a brief
546 %  description of the format.
547 %
548 %  The format of the RegisterCAPTIONImage method is:
549 %
550 %      size_t RegisterCAPTIONImage(void)
551 %
552 */
553 ModuleExport size_t RegisterCAPTIONImage(void)
554 {
555   char
556     version[MaxTextExtent];
557
558   MagickInfo
559     *entry;
560
561   *version='\0';
562 #if defined(PANGO_VERSION_STRING)
563   (void) FormatLocaleString(version,MaxTextExtent,"(Pangoft2 %s)",
564     PANGO_VERSION_STRING);
565 #endif
566   entry=SetMagickInfo("CAPTION");
567   entry->decoder=(DecodeImageHandler *) ReadCAPTIONImage;
568   entry->description=ConstantString("Caption");
569   if (*version != '\0')
570     entry->version=ConstantString(version);
571   entry->adjoin=MagickFalse;
572   entry->module=ConstantString("CAPTION");
573   (void) RegisterMagickInfo(entry);
574   return(MagickImageCoderSignature);
575 }
576 \f
577 /*
578 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
579 %                                                                             %
580 %                                                                             %
581 %                                                                             %
582 %   U n r e g i s t e r C A P T I O N I m a g e                               %
583 %                                                                             %
584 %                                                                             %
585 %                                                                             %
586 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
587 %
588 %  UnregisterCAPTIONImage() removes format registrations made by the
589 %  CAPTION module from the list of supported formats.
590 %
591 %  The format of the UnregisterCAPTIONImage method is:
592 %
593 %      UnregisterCAPTIONImage(void)
594 %
595 */
596 ModuleExport void UnregisterCAPTIONImage(void)
597 {
598   (void) UnregisterMagickInfo("CAPTION");
599 }