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