1 /* Image support for the NeXT/Open/GNUstep and macOS window system.
2 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2018 Free Software
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. */
33 #include "dispextern.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 ========================================================================== */
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
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];
67 ns_image_from_file (Lisp_Object file)
69 NSTRACE ("ns_image_from_file");
70 return [EmacsImage allocInitFromFile: file];
74 ns_load_image (struct frame *f, struct image *img,
75 Lisp_Object spec_file, Lisp_Object spec_data)
77 EmacsImage *eImg = nil;
79 Lisp_Object lisp_index, lisp_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))
95 eImg = [EmacsImage allocInitFromFile: spec_file];
97 else if (STRINGP (spec_data))
101 data = [NSData dataWithBytes: SSDATA (spec_data)
102 length: SBYTES (spec_data)];
103 eImg = [[EmacsImage alloc] initWithData: data];
104 [eImg setPixmapData];
109 add_to_log ("Unable to load image %s", img->spec);
113 if (![eImg setFrame: index])
115 add_to_log ("Unable to set index %d for image %s",
116 make_number (index), img->spec);
120 img->lisp_data = [eImg getMetadata];
124 EmacsImage *temp = [eImg rotate:rotation];
129 [eImg setSizeFromSpec:XCDR (img->spec)];
132 img->width = size.width;
133 img->height = size.height;
135 /* 4) set img->pixmap = emacsimage */
143 ns_image_width (void *img)
145 return [(id)img size].width;
149 ns_image_height (void *img)
151 return [(id)img size].height;
155 ns_get_pixel (void *img, int x, int y)
157 return [(EmacsImage *)img getPixelAtX: x Y: y];
161 ns_put_pixel (void *img, int x, int y, unsigned long argb)
163 unsigned char alpha = (argb >> 24) & 0xFF;
166 [(EmacsImage *)img setPixelAtX: x Y: y toRed: (argb >> 16) & 0xFF
167 green: (argb >> 8) & 0xFF blue: (argb & 0xFF) alpha: alpha];
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
191 /* Search bitmap-file-path for the file, if appropriate. */
192 found = x_find_image_file (file);
193 if (!STRINGP (found))
195 found = ENCODE_FILE (found);
197 image = [[EmacsImage alloc] initByReferencingFile:
198 [NSString stringWithUTF8String: SSDATA (found)]];
202 imgRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
204 imgRep = [image bestRepresentationForDevice: nil];
212 [image setSize: NSMakeSize([imgRep pixelsWide], [imgRep pixelsHigh])];
214 [image setName: [NSString stringWithUTF8String: SSDATA (file)]];
222 [stippleMask release];
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)
254 /* pull bits out to set the (bytewise) alpha mask */
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;
270 for (j = 0; j < h; ++j)
274 for (k = 0; i < w && k < 8; ++k, ++i)
297 [self addRepresentation: bmRep];
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;
309 if (bmRep == nil || color == nil)
312 if ([color colorSpaceName] != NSCalibratedRGBColorSpace)
313 rgbColor = [color colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
317 [rgbColor getRed: &r green: &g blue: &b alpha: &a];
319 [bmRep getBitmapDataPlanes: planes];
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)
335 xbm_fg = ((rr << 16) & 0xff0000) + ((gg << 8) & 0xff00) + (bb & 0xff);
342 - (instancetype)initForXPMWithDepth: (int)depth width: (int)width height: (int)height
344 NSSize s = {width, height};
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];
359 memset (pixmapData[i], 0, width*height);
360 [self addRepresentation: bmRep];
365 /* attempt to pull out pixmap data from a BitmapImageRep; returns NO if fails */
366 - (void) setPixmapData
371 reps = [[self representations] objectEnumerator];
372 while ((rep = (NSImageRep *) [reps nextObject]))
374 if ([rep respondsToSelector: @selector (getBitmapDataPlanes:)])
376 NSBitmapImageRep *bmr = (NSBitmapImageRep *) rep;
378 if ([bmr numberOfPlanes] >= 3)
379 [bmr getBitmapDataPlanes: pixmapData];
381 [self setSize: NSMakeSize([bmr pixelsWide], [bmr pixelsHigh])];
389 /* note; this and next work only for image created with initForXPMWithDepth,
390 initFromSkipXBM, or where setPixmapData was called successfully */
392 - (unsigned long) getPixelAtX: (int)x Y: (int)y
397 /* this method is faster but won't work for bitmaps */
398 if (pixmapData[0] != NULL)
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]);
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));
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
424 if (pixmapData[0] != NULL)
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;
435 [NSColor colorWithCalibratedRed: (r/255.0) green: (g/255.0)
436 blue: (b/255.0) alpha: (a/255.0)]
441 - (void) setAlphaAtX: (int) x Y: (int) y to: (unsigned char) a
446 if (pixmapData[0] != NULL)
448 int loc = x + y * [self size].width;
450 pixmapData[3][loc] = a;
454 NSColor *color = [bmRep colorAtX: x y: y];
455 color = [color colorWithAlphaComponent: (a / 255.0)];
456 [bmRep setColor: color atX: x y: y];
460 /* returns a pattern color, which is cached here */
461 - (NSColor *)stippleMask
463 if (stippleMask == nil)
464 stippleMask = [[NSColor colorWithPatternImage: self] retain];
468 /* Find the first NSBitmapImageRep which has multiple frames. */
469 - (NSBitmapImageRep *)getAnimatedBitmapImageRep
471 for (NSImageRep * r in [self representations])
473 if ([r isKindOfClass:[NSBitmapImageRep class]])
475 NSBitmapImageRep * bm = (NSBitmapImageRep *)r;
476 if ([[bm valueForProperty:NSImageFrameCount] intValue] > 0)
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];
493 int frames = [[bm valueForProperty:NSImageFrameCount] intValue];
494 float delay = [[bm valueForProperty:NSImageCurrentFrameDuration]
498 metadata = Fcons (Qcount, Fcons (make_number (frames), metadata));
500 metadata = Fcons (Qdelay, Fcons (make_float (delay), metadata));
505 /* Attempt to set the animation frame to be displayed. */
506 - (BOOL)setFrame: (unsigned int) index
508 NSBitmapImageRep * bm = [self getAnimatedBitmapImageRep];
512 int frames = [[bm valueForProperty:NSImageFrameCount] intValue];
514 /* If index is invalid, give up. */
515 if (index < 0 || index > frames)
518 [bm setProperty: NSImageCurrentFrame
519 withValue: [NSNumber numberWithUnsignedInt:index]];
522 /* Setting the frame has succeeded, or the image doesn't have
527 - (void)setSizeFromSpec: (Lisp_Object) spec
529 NSSize size = [self size];
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);
536 scale = XFLOATINT (value) ;
538 value = Fplist_get (spec, QCmax_width);
540 max_width = XFLOATINT (value);
542 value = Fplist_get (spec, QCmax_height);
544 max_height = XFLOATINT (value);
546 value = Fplist_get (spec, QCwidth);
549 width = XFLOATINT (value) * scale;
550 /* :width overrides :max-width. */
554 value = Fplist_get (spec, QCheight);
557 height = XFLOATINT (value) * scale;
558 /* :height overrides :max-height. */
562 if (width <= 0 && height <= 0)
564 width = size.width * scale;
565 height = size.height * scale;
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)
575 height = max_width / aspect;
578 if (max_height > 0 && height > max_height)
581 width = max_height * aspect;
584 [self setSize:NSMakeSize(width, height)];
587 - (instancetype)rotate: (double)rotation
589 EmacsImage *new_image;
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
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];
617 [self drawAtPoint:new_origin fromRect:NSZeroRect
618 operation:NSCompositingOperationCopy fraction:1];
620 [new_image unlockFocus];