Implement HiDPI support for underwave on MS-Windows
[emacs.git] / src / nsimage.m
blob94b24a3912c3bef521d869cbdaa9229bdc9d8ab3
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 <http://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 (index < 0 || ![eImg setFrame: index])
110     {
111       add_to_log ("Unable to set index %d for image %s", index, img->spec);
112       return 0;
113     }
115   size = [eImg size];
116   img->width = size.width;
117   img->height = size.height;
119   /* 4) set img->pixmap = emacsimage */
120   img->pixmap = eImg;
122   img->lisp_data = [eImg getMetadata];
123   return 1;
128 ns_image_width (void *img)
130   return [(id)img size].width;
134 ns_image_height (void *img)
136   return [(id)img size].height;
139 unsigned long
140 ns_get_pixel (void *img, int x, int y)
142   return [(EmacsImage *)img getPixelAtX: x Y: y];
145 void
146 ns_put_pixel (void *img, int x, int y, unsigned long argb)
148   unsigned char alpha = (argb >> 24) & 0xFF;
149   if (alpha == 0)
150     alpha = 0xFF;
151   [(EmacsImage *)img setPixelAtX: x Y: y toRed: (argb >> 16) & 0xFF
152    green: (argb >> 8) & 0xFF blue: (argb & 0xFF) alpha: alpha];
155 void
156 ns_set_alpha (void *img, int x, int y, unsigned char a)
158   [(EmacsImage *)img setAlphaAtX: x Y: y to: a];
162 /* ==========================================================================
164    Class supporting bitmaps and images of various sorts.
166    ========================================================================== */
168 @implementation EmacsImage
170 + (instancetype)allocInitFromFile: (Lisp_Object)file
172   NSImageRep *imgRep;
173   Lisp_Object found;
174   EmacsImage *image;
176   /* Search bitmap-file-path for the file, if appropriate.  */
177   found = x_find_image_file (file);
178   if (!STRINGP (found))
179     return nil;
180   found = ENCODE_FILE (found);
182   image = [[EmacsImage alloc] initByReferencingFile:
183                      [NSString stringWithUTF8String: SSDATA (found)]];
185   image->bmRep = nil;
186 #ifdef NS_IMPL_COCOA
187   imgRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
188 #else
189   imgRep = [image bestRepresentationForDevice: nil];
190 #endif
191   if (imgRep == nil)
192     {
193       [image release];
194       return nil;
195     }
197   [image setSize: NSMakeSize([imgRep pixelsWide], [imgRep pixelsHigh])];
199   [image setName: [NSString stringWithUTF8String: SSDATA (file)]];
201   return image;
205 - (void)dealloc
207   [stippleMask release];
208   [bmRep release];
209   [super dealloc];
213 /* Create image from monochrome bitmap. If both FG and BG are 0
214    (black), set the background to white and make it transparent. */
215 - (instancetype)initFromXBM: (unsigned char *)bits width: (int)w height: (int)h
216            fg: (unsigned long)fg bg: (unsigned long)bg
218   unsigned char *planes[5];
219   unsigned char bg_alpha = 0xff;
221   [self initWithSize: NSMakeSize (w, h)];
223   bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
224                                     pixelsWide: w pixelsHigh: h
225                                     bitsPerSample: 8 samplesPerPixel: 4
226                                     hasAlpha: YES isPlanar: YES
227                                     colorSpaceName: NSCalibratedRGBColorSpace
228                                     bytesPerRow: w bitsPerPixel: 0];
230   [bmRep getBitmapDataPlanes: planes];
232   if (fg == 0 && bg == 0)
233     {
234       bg = 0xffffff;
235       bg_alpha = 0;
236     }
238   {
239     /* pull bits out to set the (bytewise) alpha mask */
240     int i, j, k;
241     unsigned char *s = bits;
242     unsigned char *rr = planes[0];
243     unsigned char *gg = planes[1];
244     unsigned char *bb = planes[2];
245     unsigned char *alpha = planes[3];
246     unsigned char fgr = (fg >> 16) & 0xff;
247     unsigned char fgg = (fg >> 8) & 0xff;
248     unsigned char fgb = fg & 0xff;
249     unsigned char bgr = (bg >> 16) & 0xff;
250     unsigned char bgg = (bg >> 8) & 0xff;
251     unsigned char bgb = bg & 0xff;
252     unsigned char c;
254     int idx = 0;
255     for (j = 0; j < h; ++j)
256       for (i = 0; i < w; )
257         {
258           c = *s++;
259           for (k = 0; i < w && k < 8; ++k, ++i)
260             {
261               if (c & 0x80)
262                 {
263                   *rr++ = fgr;
264                   *gg++ = fgg;
265                   *bb++ = fgb;
266                   *alpha++ = 0xff;
267                 }
268               else
269                 {
270                   *rr++ = bgr;
271                   *gg++ = bgg;
272                   *bb++ = bgb;
273                   *alpha++ = bg_alpha;
274                 }
275               idx++;
276               c <<= 1;
277             }
278         }
279   }
281   xbm_fg = fg;
282   [self addRepresentation: bmRep];
283   return self;
286 /* Set color for a bitmap image.  */
287 - (instancetype)setXBMColor: (NSColor *)color
289   NSSize s = [self size];
290   unsigned char *planes[5];
291   EmacsCGFloat r, g, b, a;
292   NSColor *rgbColor;
294   if (bmRep == nil || color == nil)
295     return self;
297   if ([color colorSpaceName] != NSCalibratedRGBColorSpace)
298     rgbColor = [color colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
299   else
300     rgbColor = color;
302   [rgbColor getRed: &r green: &g blue: &b alpha: &a];
304   [bmRep getBitmapDataPlanes: planes];
306   {
307     int i, len = s.width*s.height;
308     int rr = r * 0xff, gg = g * 0xff, bb = b * 0xff;
309     unsigned char fgr = (xbm_fg >> 16) & 0xff;
310     unsigned char fgg = (xbm_fg >> 8) & 0xff;
311     unsigned char fgb = xbm_fg & 0xff;
313     for (i = 0; i < len; ++i)
314       if (planes[0][i] == fgr && planes[1][i] == fgg && planes[2][i] == fgb)
315         {
316           planes[0][i] = rr;
317           planes[1][i] = gg;
318           planes[2][i] = bb;
319         }
320     xbm_fg = ((rr << 16) & 0xff0000) + ((gg << 8) & 0xff00) + (bb & 0xff);
321   }
323   return self;
327 - (instancetype)initForXPMWithDepth: (int)depth width: (int)width height: (int)height
329   NSSize s = {width, height};
330   int i;
332   [self initWithSize: s];
334   bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
335                                   pixelsWide: width pixelsHigh: height
336                                   /* keep things simple for now */
337                                   bitsPerSample: 8 samplesPerPixel: 4 /*RGB+A*/
338                                   hasAlpha: YES isPlanar: YES
339                                   colorSpaceName: NSCalibratedRGBColorSpace
340                                   bytesPerRow: width bitsPerPixel: 0];
342   [bmRep getBitmapDataPlanes: pixmapData];
343   for (i =0; i<4; i++)
344     memset (pixmapData[i], 0, width*height);
345   [self addRepresentation: bmRep];
346   return self;
350 /* attempt to pull out pixmap data from a BitmapImageRep; returns NO if fails */
351 - (void) setPixmapData
353   NSEnumerator *reps;
354   NSImageRep *rep;
356   reps = [[self representations] objectEnumerator];
357   while ((rep = (NSImageRep *) [reps nextObject]))
358     {
359       if ([rep respondsToSelector: @selector (getBitmapDataPlanes:)])
360         {
361           NSBitmapImageRep *bmr = (NSBitmapImageRep *) rep;
363           if ([bmr numberOfPlanes] >= 3)
364               [bmr getBitmapDataPlanes: pixmapData];
366           [self setSize: NSMakeSize([bmr pixelsWide], [bmr pixelsHigh])];
368           break;
369         }
370     }
374 /* note; this and next work only for image created with initForXPMWithDepth,
375          initFromSkipXBM, or where setPixmapData was called successfully */
376 /* return ARGB */
377 - (unsigned long) getPixelAtX: (int)x Y: (int)y
379   if (bmRep == nil)
380     return 0;
382   /* this method is faster but won't work for bitmaps */
383   if (pixmapData[0] != NULL)
384     {
385       int loc = x + y * [self size].width;
386       return (pixmapData[3][loc] << 24) /* alpha */
387        | (pixmapData[0][loc] << 16) | (pixmapData[1][loc] << 8)
388        | (pixmapData[2][loc]);
389     }
390   else
391     {
392       NSColor *color = [bmRep colorAtX: x y: y];
393       EmacsCGFloat r, g, b, a;
394       [color getRed: &r green: &g blue: &b alpha: &a];
395       return ((int)(a * 255.0) << 24)
396         | ((int)(r * 255.0) << 16) | ((int)(g * 255.0) << 8)
397         | ((int)(b * 255.0));
399     }
402 - (void) setPixelAtX: (int)x Y: (int)y toRed: (unsigned char)r
403                green: (unsigned char)g blue: (unsigned char)b
404                alpha:(unsigned char)a
406   if (bmRep == nil)
407     return;
409   if (pixmapData[0] != NULL)
410     {
411       int loc = x + y * [self size].width;
412       pixmapData[0][loc] = r;
413       pixmapData[1][loc] = g;
414       pixmapData[2][loc] = b;
415       pixmapData[3][loc] = a;
416     }
417   else
418     {
419       [bmRep setColor:
420                [NSColor colorWithCalibratedRed: (r/255.0) green: (g/255.0)
421                                           blue: (b/255.0) alpha: (a/255.0)]
422                   atX: x y: y];
423     }
426 - (void) setAlphaAtX: (int) x Y: (int) y to: (unsigned char) a
428   if (bmRep == nil)
429     return;
431   if (pixmapData[0] != NULL)
432     {
433       int loc = x + y * [self size].width;
435       pixmapData[3][loc] = a;
436     }
437   else
438     {
439       NSColor *color = [bmRep colorAtX: x y: y];
440       color = [color colorWithAlphaComponent: (a / 255.0)];
441       [bmRep setColor: color atX: x y: y];
442     }
445 /* returns a pattern color, which is cached here */
446 - (NSColor *)stippleMask
448   if (stippleMask == nil)
449       stippleMask = [[NSColor colorWithPatternImage: self] retain];
450   return stippleMask;
453 /* If the image has multiple frames, get a count of them and the
454    animation delay, if available. */
455 - (Lisp_Object)getMetadata
457   Lisp_Object metadata = Qnil;
459   for (NSImageRep * r in [self representations])
460     {
461       if ([r isKindOfClass:[NSBitmapImageRep class]])
462         {
463           NSBitmapImageRep * bm = (NSBitmapImageRep *)r;
464           int frames = [[bm valueForProperty: NSImageFrameCount] intValue];
465           float delay = [[bm valueForProperty: NSImageCurrentFrameDuration]
466                           floatValue];
468           if (frames > 1)
469             metadata = Fcons (Qcount, Fcons (make_number (frames), metadata));
470           if (delay > 0)
471             metadata = Fcons (Qdelay, Fcons (make_float (delay), metadata));
472           break;
473         }
474     }
475   return metadata;
478 /* Attempt to set the animation frame to be displayed. */
479 - (BOOL)setFrame: (unsigned int) index
481   for (NSImageRep * r in [self representations])
482     {
483       if ([r isKindOfClass:[NSBitmapImageRep class]])
484         {
485           NSBitmapImageRep * bm = (NSBitmapImageRep *)r;
486           if ([[bm valueForProperty: NSImageFrameCount] intValue] <= index)
487             continue;
489           [bm setProperty: NSImageCurrentFrame
490                 withValue: [NSNumber numberWithUnsignedInt: index]];
491           return YES;
492         }
493     }
495   return NO;
498 @end