; Typo fixes, mostly repeated words
[emacs.git] / src / nsimage.m
blob9d45b063af1ddd4542b6263c14b4f09486cf8c0f
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;
80   unsigned int index;
82   NSTRACE ("ns_load_image");
84   eassert (valid_image_p (img->spec));
86   lisp_index = Fplist_get (XCDR (img->spec), QCindex);
87   index = INTEGERP (lisp_index) ? XFASTINT (lisp_index) : 0;
89   if (STRINGP (spec_file))
90     {
91       eImg = [EmacsImage allocInitFromFile: spec_file];
92     }
93   else if (STRINGP (spec_data))
94     {
95       NSData *data;
97       data = [NSData dataWithBytes: SSDATA (spec_data)
98                             length: SBYTES (spec_data)];
99       eImg = [[EmacsImage alloc] initWithData: data];
100       [eImg setPixmapData];
101     }
103   if (eImg == nil)
104     {
105       add_to_log ("Unable to load image %s", img->spec);
106       return 0;
107     }
109   if (![eImg setFrame: index])
110     {
111       add_to_log ("Unable to set index %d for image %s",
112                   make_number (index), img->spec);
113       return 0;
114     }
116   size = [eImg size];
117   img->width = size.width;
118   img->height = size.height;
120   /* 4) set img->pixmap = emacsimage */
121   img->pixmap = eImg;
123   img->lisp_data = [eImg getMetadata];
124   return 1;
129 ns_image_width (void *img)
131   return [(id)img size].width;
135 ns_image_height (void *img)
137   return [(id)img size].height;
140 unsigned long
141 ns_get_pixel (void *img, int x, int y)
143   return [(EmacsImage *)img getPixelAtX: x Y: y];
146 void
147 ns_put_pixel (void *img, int x, int y, unsigned long argb)
149   unsigned char alpha = (argb >> 24) & 0xFF;
150   if (alpha == 0)
151     alpha = 0xFF;
152   [(EmacsImage *)img setPixelAtX: x Y: y toRed: (argb >> 16) & 0xFF
153    green: (argb >> 8) & 0xFF blue: (argb & 0xFF) alpha: alpha];
156 void
157 ns_set_alpha (void *img, int x, int y, unsigned char a)
159   [(EmacsImage *)img setAlphaAtX: x Y: y to: a];
163 /* ==========================================================================
165    Class supporting bitmaps and images of various sorts.
167    ========================================================================== */
169 @implementation EmacsImage
171 + (instancetype)allocInitFromFile: (Lisp_Object)file
173   NSImageRep *imgRep;
174   Lisp_Object found;
175   EmacsImage *image;
177   /* Search bitmap-file-path for the file, if appropriate.  */
178   found = x_find_image_file (file);
179   if (!STRINGP (found))
180     return nil;
181   found = ENCODE_FILE (found);
183   image = [[EmacsImage alloc] initByReferencingFile:
184                      [NSString stringWithUTF8String: SSDATA (found)]];
186   image->bmRep = nil;
187 #ifdef NS_IMPL_COCOA
188   imgRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
189 #else
190   imgRep = [image bestRepresentationForDevice: nil];
191 #endif
192   if (imgRep == nil)
193     {
194       [image release];
195       return nil;
196     }
198   [image setSize: NSMakeSize([imgRep pixelsWide], [imgRep pixelsHigh])];
200   [image setName: [NSString stringWithUTF8String: SSDATA (file)]];
202   return image;
206 - (void)dealloc
208   [stippleMask release];
209   [bmRep release];
210   [super dealloc];
214 /* Create image from monochrome bitmap. If both FG and BG are 0
215    (black), set the background to white and make it transparent. */
216 - (instancetype)initFromXBM: (unsigned char *)bits width: (int)w height: (int)h
217            fg: (unsigned long)fg bg: (unsigned long)bg
219   unsigned char *planes[5];
220   unsigned char bg_alpha = 0xff;
222   [self initWithSize: NSMakeSize (w, h)];
224   bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
225                                     pixelsWide: w pixelsHigh: h
226                                     bitsPerSample: 8 samplesPerPixel: 4
227                                     hasAlpha: YES isPlanar: YES
228                                     colorSpaceName: NSCalibratedRGBColorSpace
229                                     bytesPerRow: w bitsPerPixel: 0];
231   [bmRep getBitmapDataPlanes: planes];
233   if (fg == 0 && bg == 0)
234     {
235       bg = 0xffffff;
236       bg_alpha = 0;
237     }
239   {
240     /* pull bits out to set the (bytewise) alpha mask */
241     int i, j, k;
242     unsigned char *s = bits;
243     unsigned char *rr = planes[0];
244     unsigned char *gg = planes[1];
245     unsigned char *bb = planes[2];
246     unsigned char *alpha = planes[3];
247     unsigned char fgr = (fg >> 16) & 0xff;
248     unsigned char fgg = (fg >> 8) & 0xff;
249     unsigned char fgb = fg & 0xff;
250     unsigned char bgr = (bg >> 16) & 0xff;
251     unsigned char bgg = (bg >> 8) & 0xff;
252     unsigned char bgb = bg & 0xff;
253     unsigned char c;
255     int idx = 0;
256     for (j = 0; j < h; ++j)
257       for (i = 0; i < w; )
258         {
259           c = *s++;
260           for (k = 0; i < w && k < 8; ++k, ++i)
261             {
262               if (c & 0x80)
263                 {
264                   *rr++ = fgr;
265                   *gg++ = fgg;
266                   *bb++ = fgb;
267                   *alpha++ = 0xff;
268                 }
269               else
270                 {
271                   *rr++ = bgr;
272                   *gg++ = bgg;
273                   *bb++ = bgb;
274                   *alpha++ = bg_alpha;
275                 }
276               idx++;
277               c <<= 1;
278             }
279         }
280   }
282   xbm_fg = fg;
283   [self addRepresentation: bmRep];
284   return self;
287 /* Set color for a bitmap image.  */
288 - (instancetype)setXBMColor: (NSColor *)color
290   NSSize s = [self size];
291   unsigned char *planes[5];
292   EmacsCGFloat r, g, b, a;
293   NSColor *rgbColor;
295   if (bmRep == nil || color == nil)
296     return self;
298   if ([color colorSpaceName] != NSCalibratedRGBColorSpace)
299     rgbColor = [color colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
300   else
301     rgbColor = color;
303   [rgbColor getRed: &r green: &g blue: &b alpha: &a];
305   [bmRep getBitmapDataPlanes: planes];
307   {
308     int i, len = s.width*s.height;
309     int rr = r * 0xff, gg = g * 0xff, bb = b * 0xff;
310     unsigned char fgr = (xbm_fg >> 16) & 0xff;
311     unsigned char fgg = (xbm_fg >> 8) & 0xff;
312     unsigned char fgb = xbm_fg & 0xff;
314     for (i = 0; i < len; ++i)
315       if (planes[0][i] == fgr && planes[1][i] == fgg && planes[2][i] == fgb)
316         {
317           planes[0][i] = rr;
318           planes[1][i] = gg;
319           planes[2][i] = bb;
320         }
321     xbm_fg = ((rr << 16) & 0xff0000) + ((gg << 8) & 0xff00) + (bb & 0xff);
322   }
324   return self;
328 - (instancetype)initForXPMWithDepth: (int)depth width: (int)width height: (int)height
330   NSSize s = {width, height};
331   int i;
333   [self initWithSize: s];
335   bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
336                                   pixelsWide: width pixelsHigh: height
337                                   /* keep things simple for now */
338                                   bitsPerSample: 8 samplesPerPixel: 4 /*RGB+A*/
339                                   hasAlpha: YES isPlanar: YES
340                                   colorSpaceName: NSCalibratedRGBColorSpace
341                                   bytesPerRow: width bitsPerPixel: 0];
343   [bmRep getBitmapDataPlanes: pixmapData];
344   for (i =0; i<4; i++)
345     memset (pixmapData[i], 0, width*height);
346   [self addRepresentation: bmRep];
347   return self;
351 /* attempt to pull out pixmap data from a BitmapImageRep; returns NO if fails */
352 - (void) setPixmapData
354   NSEnumerator *reps;
355   NSImageRep *rep;
357   reps = [[self representations] objectEnumerator];
358   while ((rep = (NSImageRep *) [reps nextObject]))
359     {
360       if ([rep respondsToSelector: @selector (getBitmapDataPlanes:)])
361         {
362           NSBitmapImageRep *bmr = (NSBitmapImageRep *) rep;
364           if ([bmr numberOfPlanes] >= 3)
365               [bmr getBitmapDataPlanes: pixmapData];
367           [self setSize: NSMakeSize([bmr pixelsWide], [bmr pixelsHigh])];
369           break;
370         }
371     }
375 /* note; this and next work only for image created with initForXPMWithDepth,
376          initFromSkipXBM, or where setPixmapData was called successfully */
377 /* return ARGB */
378 - (unsigned long) getPixelAtX: (int)x Y: (int)y
380   if (bmRep == nil)
381     return 0;
383   /* this method is faster but won't work for bitmaps */
384   if (pixmapData[0] != NULL)
385     {
386       int loc = x + y * [self size].width;
387       return (pixmapData[3][loc] << 24) /* alpha */
388        | (pixmapData[0][loc] << 16) | (pixmapData[1][loc] << 8)
389        | (pixmapData[2][loc]);
390     }
391   else
392     {
393       NSColor *color = [bmRep colorAtX: x y: y];
394       EmacsCGFloat r, g, b, a;
395       [color getRed: &r green: &g blue: &b alpha: &a];
396       return ((int)(a * 255.0) << 24)
397         | ((int)(r * 255.0) << 16) | ((int)(g * 255.0) << 8)
398         | ((int)(b * 255.0));
400     }
403 - (void) setPixelAtX: (int)x Y: (int)y toRed: (unsigned char)r
404                green: (unsigned char)g blue: (unsigned char)b
405                alpha:(unsigned char)a
407   if (bmRep == nil)
408     return;
410   if (pixmapData[0] != NULL)
411     {
412       int loc = x + y * [self size].width;
413       pixmapData[0][loc] = r;
414       pixmapData[1][loc] = g;
415       pixmapData[2][loc] = b;
416       pixmapData[3][loc] = a;
417     }
418   else
419     {
420       [bmRep setColor:
421                [NSColor colorWithCalibratedRed: (r/255.0) green: (g/255.0)
422                                           blue: (b/255.0) alpha: (a/255.0)]
423                   atX: x y: y];
424     }
427 - (void) setAlphaAtX: (int) x Y: (int) y to: (unsigned char) a
429   if (bmRep == nil)
430     return;
432   if (pixmapData[0] != NULL)
433     {
434       int loc = x + y * [self size].width;
436       pixmapData[3][loc] = a;
437     }
438   else
439     {
440       NSColor *color = [bmRep colorAtX: x y: y];
441       color = [color colorWithAlphaComponent: (a / 255.0)];
442       [bmRep setColor: color atX: x y: y];
443     }
446 /* returns a pattern color, which is cached here */
447 - (NSColor *)stippleMask
449   if (stippleMask == nil)
450       stippleMask = [[NSColor colorWithPatternImage: self] retain];
451   return stippleMask;
454 /* Find the first NSBitmapImageRep which has multiple frames. */
455 - (NSBitmapImageRep *)getAnimatedBitmapImageRep
457   for (NSImageRep * r in [self representations])
458     {
459       if ([r isKindOfClass:[NSBitmapImageRep class]])
460         {
461           NSBitmapImageRep * bm = (NSBitmapImageRep *)r;
462           if ([[bm valueForProperty:NSImageFrameCount] intValue] > 0)
463             return bm;
464         }
465     }
466   return nil;
469 /* If the image has multiple frames, get a count of them and the
470    animation delay, if available. */
471 - (Lisp_Object)getMetadata
473   Lisp_Object metadata = Qnil;
475   NSBitmapImageRep * bm = [self getAnimatedBitmapImageRep];
477   if (bm != nil)
478     {
479       int frames = [[bm valueForProperty:NSImageFrameCount] intValue];
480       float delay = [[bm valueForProperty:NSImageCurrentFrameDuration]
481                       floatValue];
483       if (frames > 1)
484         metadata = Fcons (Qcount, Fcons (make_number (frames), metadata));
485       if (delay > 0)
486         metadata = Fcons (Qdelay, Fcons (make_float (delay), metadata));
487     }
488   return metadata;
491 /* Attempt to set the animation frame to be displayed. */
492 - (BOOL)setFrame: (unsigned int) index
494   NSBitmapImageRep * bm = [self getAnimatedBitmapImageRep];
496   if (bm != nil)
497     {
498       int frames = [[bm valueForProperty:NSImageFrameCount] intValue];
500       /* If index is invalid, give up. */
501       if (index < 0 || index > frames)
502         return NO;
504       [bm setProperty: NSImageCurrentFrame
505             withValue: [NSNumber numberWithUnsignedInt:index]];
506     }
508   /* Setting the frame has succeeded, or the image doesn't have
509      multiple frames. */
510   return YES;
513 @end