* admin/gitmerge.el (gitmerge-missing):
[emacs.git] / src / nsimage.m
blob52e3bae05f18a01878cc3a047c89977747832a80
1 /* Image support for the NeXT/Open/GNUstep and macOS window system.
2    Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2017 Free Software
3    Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 macOS/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29    interpretation of even the system includes. */
30 #include <config.h>
32 #include "lisp.h"
33 #include "dispextern.h"
34 #include "nsterm.h"
35 #include "frame.h"
36 #include "coding.h"
40 /* ==========================================================================
42    C interface.  This allows easy calling from C files.  We could just
43    compile everything as Objective-C, but that might mean slower
44    compilation and possible difficulties on some platforms..
46    ========================================================================== */
48 void *
49 ns_image_from_XBM (char *bits, int width, int height,
50                    unsigned long fg, unsigned long bg)
52   NSTRACE ("ns_image_from_XBM");
53   return [[EmacsImage alloc] initFromXBM: (unsigned char *) bits
54                                    width: width height: height
55                                       fg: fg bg: bg];
58 void *
59 ns_image_for_XPM (int width, int height, int depth)
61   NSTRACE ("ns_image_for_XPM");
62   return [[EmacsImage alloc] initForXPMWithDepth: depth
63                                            width: width height: height];
66 void *
67 ns_image_from_file (Lisp_Object file)
69   NSTRACE ("ns_image_from_file");
70   return [EmacsImage allocInitFromFile: file];
73 bool
74 ns_load_image (struct frame *f, struct image *img,
75                Lisp_Object spec_file, Lisp_Object spec_data)
77   EmacsImage *eImg = nil;
78   NSSize size;
79   Lisp_Object lisp_index, lisp_rotation;
80   unsigned int index;
81   double rotation;
83   NSTRACE ("ns_load_image");
85   eassert (valid_image_p (img->spec));
87   lisp_index = Fplist_get (XCDR (img->spec), QCindex);
88   index = INTEGERP (lisp_index) ? XFASTINT (lisp_index) : 0;
90   lisp_rotation = Fplist_get (XCDR (img->spec), QCrotation);
91   rotation = NUMBERP (lisp_rotation) ? XFLOATINT (lisp_rotation) : 0;
93   if (STRINGP (spec_file))
94     {
95       eImg = [EmacsImage allocInitFromFile: spec_file];
96     }
97   else if (STRINGP (spec_data))
98     {
99       NSData *data;
101       data = [NSData dataWithBytes: SSDATA (spec_data)
102                             length: SBYTES (spec_data)];
103       eImg = [[EmacsImage alloc] initWithData: data];
104       [eImg setPixmapData];
105     }
107   if (eImg == nil)
108     {
109       add_to_log ("Unable to load image %s", img->spec);
110       return 0;
111     }
113   if (![eImg setFrame: index])
114     {
115       add_to_log ("Unable to set index %d for image %s",
116                   make_number (index), img->spec);
117       return 0;
118     }
120   img->lisp_data = [eImg getMetadata];
122   if (rotation != 0)
123     {
124       EmacsImage *temp = [eImg rotate:rotation];
125       [eImg release];
126       eImg = temp;
127     }
129   [eImg setSizeFromSpec:XCDR (img->spec)];
131   size = [eImg size];
132   img->width = size.width;
133   img->height = size.height;
135   /* 4) set img->pixmap = emacsimage */
136   img->pixmap = eImg;
138   return 1;
143 ns_image_width (void *img)
145   return [(id)img size].width;
149 ns_image_height (void *img)
151   return [(id)img size].height;
154 unsigned long
155 ns_get_pixel (void *img, int x, int y)
157   return [(EmacsImage *)img getPixelAtX: x Y: y];
160 void
161 ns_put_pixel (void *img, int x, int y, unsigned long argb)
163   unsigned char alpha = (argb >> 24) & 0xFF;
164   if (alpha == 0)
165     alpha = 0xFF;
166   [(EmacsImage *)img setPixelAtX: x Y: y toRed: (argb >> 16) & 0xFF
167    green: (argb >> 8) & 0xFF blue: (argb & 0xFF) alpha: alpha];
170 void
171 ns_set_alpha (void *img, int x, int y, unsigned char a)
173   [(EmacsImage *)img setAlphaAtX: x Y: y to: a];
177 /* ==========================================================================
179    Class supporting bitmaps and images of various sorts.
181    ========================================================================== */
183 @implementation EmacsImage
185 + (instancetype)allocInitFromFile: (Lisp_Object)file
187   NSImageRep *imgRep;
188   Lisp_Object found;
189   EmacsImage *image;
191   /* Search bitmap-file-path for the file, if appropriate.  */
192   found = x_find_image_file (file);
193   if (!STRINGP (found))
194     return nil;
195   found = ENCODE_FILE (found);
197   image = [[EmacsImage alloc] initByReferencingFile:
198                      [NSString stringWithUTF8String: SSDATA (found)]];
200   image->bmRep = nil;
201 #ifdef NS_IMPL_COCOA
202   imgRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
203 #else
204   imgRep = [image bestRepresentationForDevice: nil];
205 #endif
206   if (imgRep == nil)
207     {
208       [image release];
209       return nil;
210     }
212   [image setSize: NSMakeSize([imgRep pixelsWide], [imgRep pixelsHigh])];
214   [image setName: [NSString stringWithUTF8String: SSDATA (file)]];
216   return image;
220 - (void)dealloc
222   [stippleMask release];
223   [bmRep release];
224   [super dealloc];
228 /* Create image from monochrome bitmap. If both FG and BG are 0
229    (black), set the background to white and make it transparent. */
230 - (instancetype)initFromXBM: (unsigned char *)bits width: (int)w height: (int)h
231            fg: (unsigned long)fg bg: (unsigned long)bg
233   unsigned char *planes[5];
234   unsigned char bg_alpha = 0xff;
236   [self initWithSize: NSMakeSize (w, h)];
238   bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
239                                     pixelsWide: w pixelsHigh: h
240                                     bitsPerSample: 8 samplesPerPixel: 4
241                                     hasAlpha: YES isPlanar: YES
242                                     colorSpaceName: NSCalibratedRGBColorSpace
243                                     bytesPerRow: w bitsPerPixel: 0];
245   [bmRep getBitmapDataPlanes: planes];
247   if (fg == 0 && bg == 0)
248     {
249       bg = 0xffffff;
250       bg_alpha = 0;
251     }
253   {
254     /* pull bits out to set the (bytewise) alpha mask */
255     int i, j, k;
256     unsigned char *s = bits;
257     unsigned char *rr = planes[0];
258     unsigned char *gg = planes[1];
259     unsigned char *bb = planes[2];
260     unsigned char *alpha = planes[3];
261     unsigned char fgr = (fg >> 16) & 0xff;
262     unsigned char fgg = (fg >> 8) & 0xff;
263     unsigned char fgb = fg & 0xff;
264     unsigned char bgr = (bg >> 16) & 0xff;
265     unsigned char bgg = (bg >> 8) & 0xff;
266     unsigned char bgb = bg & 0xff;
267     unsigned char c;
269     int idx = 0;
270     for (j = 0; j < h; ++j)
271       for (i = 0; i < w; )
272         {
273           c = *s++;
274           for (k = 0; i < w && k < 8; ++k, ++i)
275             {
276               if (c & 0x80)
277                 {
278                   *rr++ = fgr;
279                   *gg++ = fgg;
280                   *bb++ = fgb;
281                   *alpha++ = 0xff;
282                 }
283               else
284                 {
285                   *rr++ = bgr;
286                   *gg++ = bgg;
287                   *bb++ = bgb;
288                   *alpha++ = bg_alpha;
289                 }
290               idx++;
291               c <<= 1;
292             }
293         }
294   }
296   xbm_fg = fg;
297   [self addRepresentation: bmRep];
298   return self;
301 /* Set color for a bitmap image.  */
302 - (instancetype)setXBMColor: (NSColor *)color
304   NSSize s = [self size];
305   unsigned char *planes[5];
306   EmacsCGFloat r, g, b, a;
307   NSColor *rgbColor;
309   if (bmRep == nil || color == nil)
310     return self;
312   if ([color colorSpaceName] != NSCalibratedRGBColorSpace)
313     rgbColor = [color colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
314   else
315     rgbColor = color;
317   [rgbColor getRed: &r green: &g blue: &b alpha: &a];
319   [bmRep getBitmapDataPlanes: planes];
321   {
322     int i, len = s.width*s.height;
323     int rr = r * 0xff, gg = g * 0xff, bb = b * 0xff;
324     unsigned char fgr = (xbm_fg >> 16) & 0xff;
325     unsigned char fgg = (xbm_fg >> 8) & 0xff;
326     unsigned char fgb = xbm_fg & 0xff;
328     for (i = 0; i < len; ++i)
329       if (planes[0][i] == fgr && planes[1][i] == fgg && planes[2][i] == fgb)
330         {
331           planes[0][i] = rr;
332           planes[1][i] = gg;
333           planes[2][i] = bb;
334         }
335     xbm_fg = ((rr << 16) & 0xff0000) + ((gg << 8) & 0xff00) + (bb & 0xff);
336   }
338   return self;
342 - (instancetype)initForXPMWithDepth: (int)depth width: (int)width height: (int)height
344   NSSize s = {width, height};
345   int i;
347   [self initWithSize: s];
349   bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
350                                   pixelsWide: width pixelsHigh: height
351                                   /* keep things simple for now */
352                                   bitsPerSample: 8 samplesPerPixel: 4 /*RGB+A*/
353                                   hasAlpha: YES isPlanar: YES
354                                   colorSpaceName: NSCalibratedRGBColorSpace
355                                   bytesPerRow: width bitsPerPixel: 0];
357   [bmRep getBitmapDataPlanes: pixmapData];
358   for (i =0; i<4; i++)
359     memset (pixmapData[i], 0, width*height);
360   [self addRepresentation: bmRep];
361   return self;
365 /* attempt to pull out pixmap data from a BitmapImageRep; returns NO if fails */
366 - (void) setPixmapData
368   NSEnumerator *reps;
369   NSImageRep *rep;
371   reps = [[self representations] objectEnumerator];
372   while ((rep = (NSImageRep *) [reps nextObject]))
373     {
374       if ([rep respondsToSelector: @selector (getBitmapDataPlanes:)])
375         {
376           NSBitmapImageRep *bmr = (NSBitmapImageRep *) rep;
378           if ([bmr numberOfPlanes] >= 3)
379               [bmr getBitmapDataPlanes: pixmapData];
381           [self setSize: NSMakeSize([bmr pixelsWide], [bmr pixelsHigh])];
383           break;
384         }
385     }
389 /* note; this and next work only for image created with initForXPMWithDepth,
390          initFromSkipXBM, or where setPixmapData was called successfully */
391 /* return ARGB */
392 - (unsigned long) getPixelAtX: (int)x Y: (int)y
394   if (bmRep == nil)
395     return 0;
397   /* this method is faster but won't work for bitmaps */
398   if (pixmapData[0] != NULL)
399     {
400       int loc = x + y * [self size].width;
401       return (pixmapData[3][loc] << 24) /* alpha */
402        | (pixmapData[0][loc] << 16) | (pixmapData[1][loc] << 8)
403        | (pixmapData[2][loc]);
404     }
405   else
406     {
407       NSColor *color = [bmRep colorAtX: x y: y];
408       EmacsCGFloat r, g, b, a;
409       [color getRed: &r green: &g blue: &b alpha: &a];
410       return ((int)(a * 255.0) << 24)
411         | ((int)(r * 255.0) << 16) | ((int)(g * 255.0) << 8)
412         | ((int)(b * 255.0));
414     }
417 - (void) setPixelAtX: (int)x Y: (int)y toRed: (unsigned char)r
418                green: (unsigned char)g blue: (unsigned char)b
419                alpha:(unsigned char)a
421   if (bmRep == nil)
422     return;
424   if (pixmapData[0] != NULL)
425     {
426       int loc = x + y * [self size].width;
427       pixmapData[0][loc] = r;
428       pixmapData[1][loc] = g;
429       pixmapData[2][loc] = b;
430       pixmapData[3][loc] = a;
431     }
432   else
433     {
434       [bmRep setColor:
435                [NSColor colorWithCalibratedRed: (r/255.0) green: (g/255.0)
436                                           blue: (b/255.0) alpha: (a/255.0)]
437                   atX: x y: y];
438     }
441 - (void) setAlphaAtX: (int) x Y: (int) y to: (unsigned char) a
443   if (bmRep == nil)
444     return;
446   if (pixmapData[0] != NULL)
447     {
448       int loc = x + y * [self size].width;
450       pixmapData[3][loc] = a;
451     }
452   else
453     {
454       NSColor *color = [bmRep colorAtX: x y: y];
455       color = [color colorWithAlphaComponent: (a / 255.0)];
456       [bmRep setColor: color atX: x y: y];
457     }
460 /* returns a pattern color, which is cached here */
461 - (NSColor *)stippleMask
463   if (stippleMask == nil)
464       stippleMask = [[NSColor colorWithPatternImage: self] retain];
465   return stippleMask;
468 /* Find the first NSBitmapImageRep which has multiple frames. */
469 - (NSBitmapImageRep *)getAnimatedBitmapImageRep
471   for (NSImageRep * r in [self representations])
472     {
473       if ([r isKindOfClass:[NSBitmapImageRep class]])
474         {
475           NSBitmapImageRep * bm = (NSBitmapImageRep *)r;
476           if ([[bm valueForProperty:NSImageFrameCount] intValue] > 0)
477             return bm;
478         }
479     }
480   return nil;
483 /* If the image has multiple frames, get a count of them and the
484    animation delay, if available. */
485 - (Lisp_Object)getMetadata
487   Lisp_Object metadata = Qnil;
489   NSBitmapImageRep * bm = [self getAnimatedBitmapImageRep];
491   if (bm != nil)
492     {
493       int frames = [[bm valueForProperty:NSImageFrameCount] intValue];
494       float delay = [[bm valueForProperty:NSImageCurrentFrameDuration]
495                       floatValue];
497       if (frames > 1)
498         metadata = Fcons (Qcount, Fcons (make_number (frames), metadata));
499       if (delay > 0)
500         metadata = Fcons (Qdelay, Fcons (make_float (delay), metadata));
501     }
502   return metadata;
505 /* Attempt to set the animation frame to be displayed. */
506 - (BOOL)setFrame: (unsigned int) index
508   NSBitmapImageRep * bm = [self getAnimatedBitmapImageRep];
510   if (bm != nil)
511     {
512       int frames = [[bm valueForProperty:NSImageFrameCount] intValue];
514       /* If index is invalid, give up. */
515       if (index < 0 || index > frames)
516         return NO;
518       [bm setProperty: NSImageCurrentFrame
519             withValue: [NSNumber numberWithUnsignedInt:index]];
520     }
522   /* Setting the frame has succeeded, or the image doesn't have
523      multiple frames. */
524   return YES;
527 - (void)setSizeFromSpec: (Lisp_Object) spec
529   NSSize size = [self size];
530   Lisp_Object value;
531   double scale = 1, aspect = size.width / size.height;
532   double width = -1, height = -1, max_width = -1, max_height = -1;
534   value = Fplist_get (spec, QCscale);
535   if (NUMBERP (value))
536     scale = XFLOATINT (value) ;
538   value = Fplist_get (spec, QCmax_width);
539   if (NUMBERP (value))
540     max_width = XFLOATINT (value);
542   value = Fplist_get (spec, QCmax_height);
543   if (NUMBERP (value))
544     max_height = XFLOATINT (value);
546   value = Fplist_get (spec, QCwidth);
547   if (NUMBERP (value))
548     {
549       width = XFLOATINT (value) * scale;
550       /* :width overrides :max-width. */
551       max_width = -1;
552     }
554   value = Fplist_get (spec, QCheight);
555   if (NUMBERP (value))
556     {
557       height = XFLOATINT (value) * scale;
558       /* :height overrides :max-height. */
559       max_height = -1;
560     }
562   if (width <= 0 && height <= 0)
563     {
564       width = size.width * scale;
565       height = size.height * scale;
566     }
567   else if (width > 0 && height <= 0)
568       height = width / aspect;
569   else if (height > 0 && width <= 0)
570       width = height * aspect;
572   if (max_width > 0 && width > max_width)
573     {
574       width = max_width;
575       height = max_width / aspect;
576     }
578   if (max_height > 0 && height > max_height)
579     {
580       height = max_height;
581       width = max_height * aspect;
582     }
584   [self setSize:NSMakeSize(width, height)];
587 - (instancetype)rotate: (double)rotation
589   EmacsImage *new_image;
590   NSPoint new_origin;
591   NSSize new_size, size = [self size];
592   NSRect rect = { NSZeroPoint, [self size] };
594   /* Create a bezier path of the outline of the image and do the
595    * rotation on it.  */
596   NSBezierPath *bounds_path = [NSBezierPath bezierPathWithRect:rect];
597   NSAffineTransform *transform = [NSAffineTransform transform];
598   [transform rotateByDegrees: rotation * -1];
599   [bounds_path transformUsingAffineTransform:transform];
601   /* Now we can find out how large the rotated image needs to be.  */
602   new_size = [bounds_path bounds].size;
603   new_image = [[EmacsImage alloc] initWithSize:new_size];
605   new_origin = NSMakePoint((new_size.width - size.width)/2,
606                            (new_size.height - size.height)/2);
608   [new_image lockFocus];
610   /* Create the final transform.  */
611   transform = [NSAffineTransform transform];
612   [transform translateXBy:new_size.width/2 yBy:new_size.height/2];
613   [transform rotateByDegrees: rotation * -1];
614   [transform translateXBy:-new_size.width/2 yBy:-new_size.height/2];
616   [transform concat];
617   [self drawAtPoint:new_origin fromRect:NSZeroRect
618           operation:NSCompositingOperationCopy fraction:1];
620   [new_image unlockFocus];
622   return new_image;
625 @end