* lisp/vc/vc-filewise.el: Comment fixes.
[emacs.git] / src / nsimage.m
blob580d8f327c2980042177a9c8d9b86e6983c67a61
1 /* Image support for the NeXT/Open/GNUstep and MacOSX window system.
2    Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2014 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
10 (at 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 MacOSX/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"
37 extern Lisp_Object QCfile, QCdata;
39 /* call tracing */
40 #if 0
41 int image_trace_num = 0;
42 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
43                                 __FILE__, __LINE__, ++image_trace_num)
44 #else
45 #define NSTRACE(x)
46 #endif
49 /* ==========================================================================
51    C interface.  This allows easy calling from C files.  We could just
52    compile everything as Objective-C, but that might mean slower
53    compilation and possible difficulties on some platforms..
55    ========================================================================== */
57 void *
58 ns_image_from_XBM (unsigned char *bits, int width, int height)
60   NSTRACE (ns_image_from_XBM);
61   return [[EmacsImage alloc] initFromXBM: bits
62                                    width: width height: height
63                                     flip: YES];
66 void *
67 ns_image_for_XPM (int width, int height, int depth)
69   NSTRACE (ns_image_for_XPM);
70   return [[EmacsImage alloc] initForXPMWithDepth: depth
71                                            width: width height: height];
74 void *
75 ns_image_from_file (Lisp_Object file)
77   NSTRACE (ns_image_from_bitmap_file);
78   return [EmacsImage allocInitFromFile: file];
81 bool
82 ns_load_image (struct frame *f, struct image *img,
83                Lisp_Object spec_file, Lisp_Object spec_data)
85   EmacsImage *eImg = nil;
86   NSSize size;
88   NSTRACE (ns_load_image);
90   if (STRINGP (spec_file))
91     {
92       eImg = [EmacsImage allocInitFromFile: spec_file];
93     }
94   else if (STRINGP (spec_data))
95     {
96       NSData *data;
98       data = [NSData dataWithBytes: SSDATA (spec_data)
99                             length: SBYTES (spec_data)];
100       eImg = [[EmacsImage alloc] initWithData: data];
101       [eImg setPixmapData];
102     }
104   if (eImg == nil)
105     {
106       add_to_log ("Unable to load image %s", img->spec, Qnil);
107       return 0;
108     }
110   size = [eImg size];
111   img->width = size.width;
112   img->height = size.height;
114   /* 4) set img->pixmap = emacsimage */
115   img->pixmap = eImg;
116   return 1;
121 ns_image_width (void *img)
123   return [(id)img size].width;
127 ns_image_height (void *img)
129   return [(id)img size].height;
132 unsigned long
133 ns_get_pixel (void *img, int x, int y)
135   return [(EmacsImage *)img getPixelAtX: x Y: y];
138 void
139 ns_put_pixel (void *img, int x, int y, unsigned long argb)
141   unsigned char alpha = (argb >> 24) & 0xFF;
142   if (alpha == 0)
143     alpha = 0xFF;
144   [(EmacsImage *)img setPixelAtX: x Y: y toRed: (argb >> 16) & 0xFF
145    green: (argb >> 8) & 0xFF blue: (argb & 0xFF) alpha: alpha];
148 void
149 ns_set_alpha (void *img, int x, int y, unsigned char a)
151   [(EmacsImage *)img setAlphaAtX: x Y: y to: a];
155 /* ==========================================================================
157    Class supporting bitmaps and images of various sorts.
159    ========================================================================== */
161 @implementation EmacsImage
163 + allocInitFromFile: (Lisp_Object)file
165   NSImageRep *imgRep;
166   Lisp_Object found;
167   EmacsImage *image;
169   /* Search bitmap-file-path for the file, if appropriate.  */
170   found = x_find_image_file (file);
171   if (!STRINGP (found))
172     return nil;
174   image = [[EmacsImage alloc] initByReferencingFile:
175                      [NSString stringWithUTF8String: SSDATA (found)]];
177   image->bmRep = nil;
178 #ifdef NS_IMPL_COCOA
179   imgRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
180 #else
181   imgRep = [image bestRepresentationForDevice: nil];
182 #endif
183   if (imgRep == nil)
184     {
185       [image release];
186       return nil;
187     }
189   /* The next two lines cause the DPI of the image to be ignored.
190      This seems to be the behavior users expect. */
191   [image setScalesWhenResized: YES];
192   [image setSize: NSMakeSize([imgRep pixelsWide], [imgRep pixelsHigh])];
194   [image setName: [NSString stringWithUTF8String: SSDATA (file)]];
196   return image;
200 - (void)dealloc
202   [stippleMask release];
203   [bmRep release];
204   [super dealloc];
208 - initFromXBM: (unsigned char *)bits width: (int)w height: (int)h
209          flip: (BOOL)flip
211   return [self initFromSkipXBM: bits width: w height: h flip: flip length: 0];
215 - initFromSkipXBM: (unsigned char *)bits width: (int)w height: (int)h
216              flip: (BOOL)flip length: (int)length;
218   int bpr = (w + 7) / 8;
219   unsigned char *planes[5];
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];
231   {
232     /* pull bits out to set the (bytewise) alpha mask */
233     int i, j, k;
234     unsigned char *s = bits;
235     unsigned char *alpha = planes[3];
236     unsigned char swt[16] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13,
237                              3, 11, 7, 15};
238     unsigned char c, bitPat;
240     for (j = 0; j < h; j++)
241       for (i = 0; i < bpr; i++)
242         {
243           if (length)
244             {
245               unsigned char s1, s2;
246               while (*s++ != 'x' && s < bits + length);
247               if (s >= bits + length)
248                 {
249                   [bmRep release];
250                   return nil;
251                 }
252 #define hexchar(x) ('0' <= (x) && (x) <= '9' ? (x) - '0' : (x) - 'a' + 10)
253               s1 = *s++;
254               s2 = *s++;
255               c = hexchar (s1) * 0x10 + hexchar (s2);
256             }
257           else
258             c = *s++;
260           bitPat = flip ? swt[c >> 4] | (swt[c & 0xf] << 4) : c ^ 255;
261           for (k =0; k<8; k++)
262             {
263               *alpha++ = (bitPat & 0x80) ? 0xff : 0;
264               bitPat <<= 1;
265             }
266         }
267   }
269   [self addRepresentation: bmRep];
271   memset (planes[0], 0, w*h);
272   memset (planes[1], 0, w*h);
273   memset (planes[2], 0, w*h);
274   [self setXBMColor: [NSColor blackColor]];
275   return self;
279 /* Set color for a bitmap image (see initFromSkipXBM).  Note that the alpha
280    is used as a mask, so we just memset the entire array. */
281 - setXBMColor: (NSColor *)color
283   NSSize s = [self size];
284   unsigned char *planes[5];
285   EmacsCGFloat r, g, b, a;
286   NSColor *rgbColor;
288   if (bmRep == nil || color == nil)
289     return self;
291   if ([color colorSpaceName] != NSCalibratedRGBColorSpace)
292     rgbColor = [color colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
293   else
294     rgbColor = color;
296   [rgbColor getRed: &r green: &g blue: &b alpha: &a];
298   [bmRep getBitmapDataPlanes: planes];
300   /* we used to just do this, but Cocoa seems to have a bug when rendering
301      an alpha-masked image onto a dark background where it bloats the mask */
302    /* memset (planes[0..2], r, g, b*0xff, len); */
303   {
304     int i, len = s.width*s.height;
305     int rr = r * 0xff, gg = g * 0xff, bb = b * 0xff;
306     for (i =0; i<len; i++)
307       if (planes[3][i] != 0)
308         {
309           planes[0][i] = rr;
310           planes[1][i] = gg;
311           planes[2][i] = bb;
312         }
313   }
315   return self;
319 - initForXPMWithDepth: (int)depth width: (int)width height: (int)height
321   NSSize s = {width, height};
322   int i;
324   [self initWithSize: s];
326   bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
327                                   pixelsWide: width pixelsHigh: height
328                                   /* keep things simple for now */
329                                   bitsPerSample: 8 samplesPerPixel: 4 /*RGB+A*/
330                                   hasAlpha: YES isPlanar: YES
331                                   colorSpaceName: NSCalibratedRGBColorSpace
332                                   bytesPerRow: width bitsPerPixel: 0];
334   [bmRep getBitmapDataPlanes: pixmapData];
335   for (i =0; i<4; i++)
336     memset (pixmapData[i], 0, width*height);
337   [self addRepresentation: bmRep];
338   return self;
342 /* attempt to pull out pixmap data from a BitmapImageRep; returns NO if fails */
343 - (void) setPixmapData
345   NSEnumerator *reps;
346   NSImageRep *rep;
348   reps = [[self representations] objectEnumerator];
349   while ((rep = (NSImageRep *) [reps nextObject]))
350     {
351       if ([rep respondsToSelector: @selector (getBitmapDataPlanes:)])
352         {
353           bmRep = (NSBitmapImageRep *) rep;
355           if ([bmRep numberOfPlanes] >= 3)
356               [bmRep getBitmapDataPlanes: pixmapData];
358           /* The next two lines cause the DPI of the image to be ignored.
359              This seems to be the behavior users expect. */
360           [self setScalesWhenResized: YES];
361           [self setSize: NSMakeSize([bmRep pixelsWide], [bmRep pixelsHigh])];
363           break;
364         }
365     }
369 /* note; this and next work only for image created with initForXPMWithDepth,
370          initFromSkipXBM, or where setPixmapData was called successfully */
371 /* return ARGB */
372 - (unsigned long) getPixelAtX: (int)x Y: (int)y
374   if (bmRep == nil)
375     return 0;
377   /* this method is faster but won't work for bitmaps */
378   if (pixmapData[0] != NULL)
379     {
380       int loc = x + y * [self size].width;
381       return (pixmapData[3][loc] << 24) /* alpha */
382        | (pixmapData[0][loc] << 16) | (pixmapData[1][loc] << 8)
383        | (pixmapData[2][loc]);
384     }
385   else
386     {
387       NSColor *color = [bmRep colorAtX: x y: y];
388       EmacsCGFloat r, g, b, a;
389       [color getRed: &r green: &g blue: &b alpha: &a];
390       return ((int)(a * 255.0) << 24)
391         | ((int)(r * 255.0) << 16) | ((int)(g * 255.0) << 8)
392         | ((int)(b * 255.0));
394     }
397 - (void) setPixelAtX: (int)x Y: (int)y toRed: (unsigned char)r
398                green: (unsigned char)g blue: (unsigned char)b
399                alpha:(unsigned char)a;
401   if (bmRep == nil)
402     return;
404   if (pixmapData[0] != NULL)
405     {
406       int loc = x + y * [self size].width;
407       pixmapData[0][loc] = r;
408       pixmapData[1][loc] = g;
409       pixmapData[2][loc] = b;
410       pixmapData[3][loc] = a;
411     }
412   else
413     {
414       [bmRep setColor:
415                [NSColor colorWithCalibratedRed: (r/255.0) green: (g/255.0)
416                                           blue: (b/255.0) alpha: (a/255.0)]
417                   atX: x y: y];
418     }
421 - (void) setAlphaAtX: (int) x Y: (int) y to: (unsigned char) a
423   if (bmRep == nil)
424     return;
426   if (pixmapData[0] != NULL)
427     {
428       int loc = x + y * [self size].width;
430       pixmapData[3][loc] = a;
431     }
432   else
433     {
434       NSColor *color = [bmRep colorAtX: x y: y];
435       color = [color colorWithAlphaComponent: (a / 255.0)];
436       [bmRep setColor: color atX: x y: y];
437     }
440 /* returns a pattern color, which is cached here */
441 - (NSColor *)stippleMask
443   if (stippleMask == nil)
444       stippleMask = [[NSColor colorWithPatternImage: self] retain];
445   return stippleMask;
448 @end