Implement CopyFromIcon
[wxWidgets.git] / src / cocoa / bitmap.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/cocoa/bitmap.cpp
3 // Purpose:     wxBitmap
4 // Author:      David Elliott
5 // Modified by:
6 // Created:     2003/07/19
7 // RCS-ID:      $Id$
8 // Copyright:   (c) 2003 David Elliott
9 // Licence:     wxWidgets licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13 #ifndef WX_PRECOMP
14     #include "wx/log.h"
15     #include "wx/utils.h"
16     #include "wx/palette.h"
17     #include "wx/icon.h"
18     #include "wx/colour.h"
19 #endif //WX_PRECOMP
20 #include "wx/bitmap.h"
21 #include "wx/image.h"
22 #include "wx/xpmdecod.h"
23 #include "wx/rawbmp.h"
24
25 #include "wx/cocoa/autorelease.h"
26 #include "wx/cocoa/string.h"
27
28 #import <AppKit/NSBitmapImageRep.h>
29 #import <AppKit/NSGraphics.h>
30 #import <AppKit/NSImage.h>
31
32 // ========================================================================
33 // wxBitmapRefData
34 // ========================================================================
35 class wxBitmapRefData: public wxGDIRefData
36 {
37     friend class wxBitmap;
38 public:
39     wxBitmapRefData();
40     wxBitmapRefData( const wxBitmapRefData& data );
41     virtual ~wxBitmapRefData();
42
43 protected:
44     int                 m_width;
45     int                 m_height;
46     int                 m_depth;
47     bool                m_ok;
48     int                 m_numColors;
49     wxPalette           m_bitmapPalette;
50     int                 m_quality;
51     WX_NSBitmapImageRep m_cocoaNSBitmapImageRep;
52     wxMask             *m_bitmapMask; // Optional mask
53 };
54
55 #define M_BITMAPDATA ((wxBitmapRefData *)m_refData)
56
57 wxBitmapRefData::wxBitmapRefData()
58 {
59     m_ok = FALSE;
60     m_width = 0;
61     m_height = 0;
62     m_depth = 0;
63     m_quality = 0;
64     m_numColors = 0;
65     m_cocoaNSBitmapImageRep = nil;
66     m_bitmapMask = NULL;
67 }
68
69 wxBitmapRefData::wxBitmapRefData( const wxBitmapRefData& data)
70 {
71     m_width = data.m_width;
72     m_height = data.m_height;
73     m_depth = data.m_depth;
74     m_ok = data.m_ok;
75     m_numColors = data.m_numColors;
76     m_bitmapPalette = data.m_bitmapPalette;
77     m_quality = data.m_quality;
78     m_cocoaNSBitmapImageRep = [data.m_cocoaNSBitmapImageRep copyWithZone:nil];
79     m_bitmapMask = data.m_bitmapMask?new wxMask(*data.m_bitmapMask):NULL;
80 }
81
82 wxBitmapRefData::~wxBitmapRefData()
83 {
84     [m_cocoaNSBitmapImageRep release];
85     m_cocoaNSBitmapImageRep = NULL;
86
87     delete m_bitmapMask;
88     m_bitmapMask = NULL;
89 }
90
91 // ========================================================================
92 // wxBitmap
93 // ========================================================================
94 IMPLEMENT_DYNAMIC_CLASS(wxBitmap, wxGDIObject)
95
96 wxBitmap::wxBitmap()
97 {
98     m_refData = NULL;
99 }
100
101 wxBitmap::~wxBitmap()
102 {
103 }
104
105 wxBitmap::wxBitmap(const char bits[], int the_width, int the_height, int no_bits)
106 {
107     m_refData = new wxBitmapRefData;
108
109     M_BITMAPDATA->m_width = the_width ;
110     M_BITMAPDATA->m_height = the_height ;
111     M_BITMAPDATA->m_depth = no_bits ;
112     M_BITMAPDATA->m_numColors = 0;
113
114     /* TODO: create the bitmap from data */
115 }
116
117 wxBitmap::wxBitmap(int w, int h, int d)
118 {
119     (void)Create(w, h, d);
120 }
121
122 wxBitmap::wxBitmap(void *data, wxBitmapType type, int width, int height, int depth)
123 {
124     (void) Create(data, type, width, height, depth);
125 }
126
127 wxBitmap::wxBitmap(const wxString& filename, wxBitmapType type)
128 {
129     LoadFile(filename, type);
130 }
131
132 wxObjectRefData *wxBitmap::CreateRefData() const
133 {
134     return new wxBitmapRefData;
135 }
136
137 wxObjectRefData *wxBitmap::CloneRefData(const wxObjectRefData *data) const
138 {
139     return new wxBitmapRefData(*(wxBitmapRefData*)data);
140 }
141
142 WX_NSBitmapImageRep wxBitmap::GetNSBitmapImageRep()
143 {
144     if(!M_BITMAPDATA)
145         return NULL;
146     return M_BITMAPDATA->m_cocoaNSBitmapImageRep;
147 }
148
149 WX_NSImage wxBitmap::GetNSImage(bool useMask) const
150 {
151     if(!Ok())
152         return nil;
153     NSImage *nsimage = [[[NSImage alloc]
154             initWithSize:NSMakeSize(GetWidth(), GetHeight())] autorelease];
155     if(!nsimage)
156         return nil;
157     [nsimage addRepresentation: M_BITMAPDATA->m_cocoaNSBitmapImageRep];
158     if(useMask && GetMask())
159     {
160         // Show before/after to prove that the bitmap itself is not changed
161         // even though we just composited onto the NSImage
162         wxLogTrace(wxTRACE_COCOA,wxT("Before: bpp=%d"),[M_BITMAPDATA->m_cocoaNSBitmapImageRep bitsPerPixel]);
163         NSImage *maskImage = [[NSImage alloc]
164                 initWithSize:NSMakeSize(GetWidth(), GetHeight())];
165         [maskImage addRepresentation: GetMask()->GetNSBitmapImageRep()];
166         [nsimage lockFocus];
167         [maskImage compositeToPoint:NSZeroPoint operation:NSCompositeDestinationIn];
168         [nsimage unlockFocus];
169         [maskImage release];
170         wxLogTrace(wxTRACE_COCOA,wxT("After: bpp=%d"),[M_BITMAPDATA->m_cocoaNSBitmapImageRep bitsPerPixel]);
171     }
172     return nsimage;
173 }
174
175 void wxBitmap::SetNSBitmapImageRep(WX_NSBitmapImageRep bitmapImageRep)
176 {
177     if(!M_BITMAPDATA)
178         return;
179     // NOTE: No checking is done to make sure width/height agree
180     [bitmapImageRep retain];
181     [M_BITMAPDATA->m_cocoaNSBitmapImageRep release];
182     M_BITMAPDATA->m_cocoaNSBitmapImageRep = bitmapImageRep;
183 }
184
185 void wxBitmap::SetWidth(int w)
186 {
187     if (!M_BITMAPDATA)
188         m_refData = new wxBitmapRefData;
189
190     M_BITMAPDATA->m_width = w;
191 }
192
193 void wxBitmap::SetHeight(int h)
194 {
195     if (!M_BITMAPDATA)
196         m_refData = new wxBitmapRefData;
197
198     M_BITMAPDATA->m_height = h;
199 }
200
201 void wxBitmap::SetDepth(int d)
202 {
203     if (!M_BITMAPDATA)
204         m_refData = new wxBitmapRefData;
205
206     M_BITMAPDATA->m_depth = d;
207 }
208
209 void wxBitmap::SetQuality(int q)
210 {
211     if (!M_BITMAPDATA)
212         m_refData = new wxBitmapRefData;
213
214     M_BITMAPDATA->m_quality = q;
215 }
216
217 void wxBitmap::SetOk(bool isOk)
218 {
219     if (!M_BITMAPDATA)
220         m_refData = new wxBitmapRefData;
221
222     M_BITMAPDATA->m_ok = isOk;
223 }
224
225 void wxBitmap::SetPalette(const wxPalette& palette)
226 {
227     if (!M_BITMAPDATA)
228         m_refData = new wxBitmapRefData;
229
230     M_BITMAPDATA->m_bitmapPalette = palette ;
231 }
232
233 void wxBitmap::SetMask(wxMask *mask)
234 {
235     if (!M_BITMAPDATA)
236         m_refData = new wxBitmapRefData;
237
238     M_BITMAPDATA->m_bitmapMask = mask ;
239 }
240
241 bool wxBitmap::Ok() const
242 {
243     return m_refData && M_BITMAPDATA->m_ok;
244 }
245
246 wxPalette* wxBitmap::GetPalette() const
247 {
248     if(!m_refData)
249         return NULL;
250     return &M_BITMAPDATA->m_bitmapPalette;
251 }
252
253 wxMask* wxBitmap::GetMask() const
254 {
255     if(!m_refData)
256         return NULL;
257     return M_BITMAPDATA->m_bitmapMask;
258 }
259
260 int wxBitmap::GetDepth() const
261 {
262     if(!m_refData)
263         return 0;
264     return M_BITMAPDATA->m_depth;
265 }
266
267 int wxBitmap::GetWidth() const
268 {
269     if(!m_refData)
270         return 0;
271     return M_BITMAPDATA->m_width;
272 }
273
274 int wxBitmap::GetHeight() const
275 {
276     if(!m_refData)
277         return 0;
278     return M_BITMAPDATA->m_height;
279 }
280
281 bool wxBitmap::Create(int w, int h, int d)
282 {
283     UnRef();
284
285     m_refData = new wxBitmapRefData;
286
287     M_BITMAPDATA->m_width = w;
288     M_BITMAPDATA->m_height = h;
289     M_BITMAPDATA->m_depth = d;
290
291     /* TODO: create new bitmap */
292     M_BITMAPDATA->m_cocoaNSBitmapImageRep = [[NSBitmapImageRep alloc]
293             initWithBitmapDataPlanes: NULL
294             pixelsWide: w
295             pixelsHigh: h
296             bitsPerSample: 8
297             samplesPerPixel: 3
298             hasAlpha: NO
299             isPlanar: NO
300             colorSpaceName: NSCalibratedRGBColorSpace
301             bytesPerRow: 0
302             bitsPerPixel: 0];
303
304     wxLogTrace(wxTRACE_COCOA,wxT("M_BITMAPDATA=%p NSBitmapImageRep bitmapData=%p"), M_BITMAPDATA, [M_BITMAPDATA->m_cocoaNSBitmapImageRep bitmapData]);
305     M_BITMAPDATA->m_ok = true;
306     M_BITMAPDATA->m_numColors = 0;
307     M_BITMAPDATA->m_quality = 0;
308     M_BITMAPDATA->m_bitmapMask = NULL;
309
310     return M_BITMAPDATA->m_ok;
311 }
312
313 bool wxBitmap::LoadFile(const wxString& filename, wxBitmapType type)
314 {
315     wxAutoNSAutoreleasePool pool;
316     UnRef();
317
318     m_refData = new wxBitmapRefData;
319
320     NSBitmapImageRep *imageRep = [NSBitmapImageRep
321         imageRepWithContentsOfFile:wxNSStringWithWxString(filename)];
322
323     if(imageRep)
324     {
325         M_BITMAPDATA->m_width = [imageRep pixelsWide];
326         M_BITMAPDATA->m_height = [imageRep pixelsHigh];
327         M_BITMAPDATA->m_depth = 24; // FIXME
328         M_BITMAPDATA->m_ok = true;
329         M_BITMAPDATA->m_numColors = 0;
330         M_BITMAPDATA->m_quality = 0;
331         M_BITMAPDATA->m_cocoaNSBitmapImageRep = [imageRep retain];
332         M_BITMAPDATA->m_bitmapMask = NULL;
333         return true;
334     }
335     wxImage image;
336     if(!image.LoadFile(filename,type))
337         return false;
338     if(!image.Ok())
339         return false;
340     *this = wxBitmap(image);
341     return true;
342 }
343
344 bool wxBitmap::Create(void *data, wxBitmapType type, int width, int height, int depth)
345 {
346     UnRef();
347
348     m_refData = new wxBitmapRefData;
349
350     return false;
351 }
352
353 bool wxBitmap::SaveFile(const wxString& filename, wxBitmapType type, const wxPalette *palette) const
354 {
355     return false;
356 }
357
358 bool wxBitmap::CopyFromIcon(const wxIcon& icon)
359 {
360     UnRef();
361     if(!icon.GetNSImage());
362     [icon.GetNSImage() lockFocus];
363     NSRect imageRect;
364     imageRect.origin.x = imageRect.origin.y = 0.0;
365     imageRect.size = [icon.GetNSImage() size];
366     NSBitmapImageRep *newBitmapRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:imageRect];
367     [icon.GetNSImage() unlockFocus];
368     if(!newBitmapRep)
369         return false;
370     m_refData = new wxBitmapRefData;
371     M_BITMAPDATA->m_cocoaNSBitmapImageRep = newBitmapRep;
372     M_BITMAPDATA->m_width = [newBitmapRep pixelsWide];
373     M_BITMAPDATA->m_height = [newBitmapRep pixelsHigh];
374     M_BITMAPDATA->m_depth = [newBitmapRep bitsPerSample];
375     M_BITMAPDATA->m_ok = true;
376     M_BITMAPDATA->m_numColors = 0;
377     M_BITMAPDATA->m_quality = 0;
378     M_BITMAPDATA->m_bitmapMask = NULL;
379     return true;
380 }
381
382 wxBitmap wxBitmap::GetSubBitmap(wxRect const&) const
383 {
384     return wxNullBitmap;
385 }
386
387 wxImage wxBitmap::ConvertToImage() const
388 {
389     if(!Ok())
390         return /*wxImage(5,5)*/wxNullImage;
391     return wxImage(M_BITMAPDATA->m_width,M_BITMAPDATA->m_height);
392 }
393
394 bool wxBitmap::CreateFromXpm(const char **xpm)
395 {
396 #if wxUSE_IMAGE && wxUSE_XPM
397     UnRef();
398
399     wxCHECK_MSG( xpm, false, wxT("invalid XPM data") )
400
401     wxXPMDecoder decoder;
402     wxImage img = decoder.ReadData(xpm);
403     wxCHECK_MSG( img.Ok(), false, wxT("invalid XPM data") )
404
405     *this = wxBitmap(img);
406     return true;
407 #else
408     return false;
409 #endif
410 }
411
412 bool wxBitmap::CreateFromImage(const wxImage& image, int depth)
413 {
414     UnRef();
415
416     wxCHECK_MSG(image.Ok(), false, wxT("invalid image"));
417     wxCHECK_MSG(depth == -1 || depth == 1, false, wxT("invalid bitmap depth"));
418
419     m_refData = new wxBitmapRefData();
420
421     M_BITMAPDATA->m_width = image.GetWidth();
422     M_BITMAPDATA->m_height = image.GetHeight();
423     NSBitmapImageRep *bitmapImage = [[NSBitmapImageRep alloc]
424             initWithBitmapDataPlanes: NULL
425             pixelsWide: image.GetWidth()
426             pixelsHigh: image.GetHeight()
427             bitsPerSample: 8
428             samplesPerPixel: 3
429             hasAlpha: NO
430             isPlanar: NO
431             colorSpaceName: NSCalibratedRGBColorSpace
432             bytesPerRow: 0
433             bitsPerPixel: 0];
434
435     const int numBytes = image.GetWidth()*image.GetHeight()*3;
436     memcpy([bitmapImage bitmapData], image.GetData(), numBytes);
437     // TODO: Alpha and convert to desired depth
438     M_BITMAPDATA->m_depth = 24;
439     M_BITMAPDATA->m_ok = true;
440     M_BITMAPDATA->m_numColors = 0;
441     M_BITMAPDATA->m_quality = 0;
442     M_BITMAPDATA->m_cocoaNSBitmapImageRep = bitmapImage;
443     M_BITMAPDATA->m_bitmapMask = new wxMask(*this,wxColour(image.GetMaskRed(),image.GetMaskGreen(),image.GetMaskBlue()));
444     return true;
445 }
446
447 void *wxBitmap::GetRawData(wxPixelDataBase& data, int bpp)
448 {
449     if(!Ok())
450         return NULL;
451
452     NSBitmapImageRep *bitmapRep = M_BITMAPDATA->m_cocoaNSBitmapImageRep;
453     if(!bitmapRep)
454         return NULL;
455
456     if([bitmapRep bitsPerPixel]!=bpp)
457     {
458         wxFAIL_MSG( _T("incorrect bitmap type in wxBitmap::GetRawData()") );
459         return NULL;
460     }
461     data.m_width = [bitmapRep pixelsWide];
462     data.m_height = [bitmapRep pixelsHigh];
463     data.m_stride = [bitmapRep bytesPerRow];
464     return [bitmapRep bitmapData];
465
466     // NOTE: It is up to the user to make sure they used the proper
467     // pixel format class that details what is actually inside the pixels
468     // We can only check to make sure that the total number of bits per
469     // pixel are being iterated over properly
470     // NSBitmapImageRep can contain grayscale or CMYK data and
471     // wxPixelDataBase doesn't really define the color format
472 }
473
474 void wxBitmap::UngetRawData(wxPixelDataBase& data)
475 {   // TODO
476 }
477
478 void wxBitmap::UseAlpha()
479 {   // TODO
480 }
481
482 // ========================================================================
483 // wxMask
484 // ========================================================================
485
486 IMPLEMENT_DYNAMIC_CLASS(wxMask, wxObject)
487
488 wxMask::wxMask()
489 {
490     m_cocoaNSBitmapImageRep = nil;
491 }
492
493 // Construct a mask from a bitmap and a colour indicating
494 // the transparent area
495 wxMask::wxMask(const wxBitmap& bitmap, const wxColour& colour)
496 {
497     m_cocoaNSBitmapImageRep = nil;
498     Create(bitmap, colour);
499 }
500
501 // Construct a mask from a bitmap and a palette index indicating
502 // the transparent area
503 wxMask::wxMask(const wxBitmap& bitmap, int paletteIndex)
504 {
505     m_cocoaNSBitmapImageRep = nil;
506
507     Create(bitmap, paletteIndex);
508 }
509
510 // Construct a mask from a mono bitmap (copies the bitmap).
511 wxMask::wxMask(const wxBitmap& bitmap)
512 {
513     m_cocoaNSBitmapImageRep = nil;
514
515     Create(bitmap);
516 }
517
518 wxMask::~wxMask()
519 {
520     [m_cocoaNSBitmapImageRep release];
521 }
522
523 // Create a mask from a mono bitmap (copies the bitmap).
524 bool wxMask::Create(const wxBitmap& bitmap)
525 {
526 // TODO
527     return FALSE;
528 }
529
530 // Create a mask from a bitmap and a palette index indicating
531 // the transparent area
532 bool wxMask::Create(const wxBitmap& bitmap, int paletteIndex)
533 {
534 // TODO
535     return FALSE;
536 }
537
538 template <typename PixelData>
539 static bool wxMask_CreateFromBitmapData(PixelData srcData, const wxColour& colour, unsigned char *dstData)
540 {
541     wxCHECK_MSG(dstData,false,wxT("Couldn't access mask data"));
542     typename PixelData::Iterator p(srcData);
543     const int nRows = srcData.GetHeight();
544     const int nCols = srcData.GetWidth();
545     // Total number of bytes per destination column
546     const int dstRowLength = (nCols+7)/8;
547     // Number of source columns that fit into a byte in the destination
548     const int width_aligned = nCols/8*8;
549     for(int y=0; y<nRows; ++y)
550     {
551         typename PixelData::Iterator rowStart(p);
552         unsigned char *dstRow = dstData + y*dstRowLength;
553         for(int x=0; x<width_aligned; x+=8)
554         {
555             unsigned char *dstByte = dstRow + x/8;
556             *dstByte = 0;
557             // Take source RGB, compare it with the wxColour
558             for(int j=0; j<8; ++j, ++p)
559             {
560                 *dstByte +=
561                 (   p.Red()!=colour.Red()
562                 ||  p.Green()!=colour.Green()
563                 ||  p.Blue()!=colour.Blue()
564                 )   << (7-j);
565             }
566         }
567         // Handle the remaining 0-7 pixels in the row
568         unsigned char *dstByte = dstRow + width_aligned/8;
569         if(nCols%8>0)
570             *dstByte = 0;
571         for(int j=0; j<(nCols%8); ++j, ++p)
572         {
573             *dstByte +=
574             (   p.Red()!=colour.Red()
575             ||  p.Green()!=colour.Green()
576             ||  p.Blue()!=colour.Blue()
577             )   << (7-j);
578         }
579         p = rowStart;
580         p.OffsetY(srcData,1);
581     }
582     return true;
583 }
584
585 // Create a mask from a bitmap and a colour indicating
586 // the transparent area
587 bool wxMask::Create(const wxBitmap& bitmap, const wxColour& colour)
588 {
589     wxAutoNSAutoreleasePool pool;
590     if(!bitmap.Ok())
591         return false;
592     int bmpWidth = bitmap.GetWidth();
593     int bmpHeight = bitmap.GetHeight();
594     int dstRowLength = (bmpWidth+7)/8;
595
596     // Create a bitmap image rep with 1-bit per pixel data representing
597     // the alpha channel padded such that rows end on byte boundaries
598     // Since NSBitmapImageRep doesn't have any sort of NSNullColorSpace
599     // we must have at least one channel of non-alpha data.  In order to
600     // make our life easy, we use planar data which results in two
601     // separate arrays.  We don't need to touch the first because it
602     // should never be used.  The second is the 1-bit "alpha" data.
603     NSBitmapImageRep *maskRep = [[[NSBitmapImageRep alloc]
604         initWithBitmapDataPlanes:NULL pixelsWide:bmpWidth
605         pixelsHigh:bmpHeight bitsPerSample:1
606         samplesPerPixel:2 hasAlpha:YES isPlanar:YES
607         colorSpaceName:NSCalibratedWhiteColorSpace
608         bytesPerRow:dstRowLength bitsPerPixel:1] autorelease];
609     wxCHECK(maskRep,false);
610
611     // We need the source NSBitmapImageRep to detemine its pixel format
612     NSBitmapImageRep *srcBitmapRep = const_cast<wxBitmap&>(bitmap).GetNSBitmapImageRep();
613     wxCHECK_MSG(srcBitmapRep,false,wxT("Can't create mask for an uninitialized bitmap"));
614
615     // Get a pointer to the destination data
616     unsigned char *dstPlanes[5] = {NULL,NULL,NULL,NULL,NULL};
617     [maskRep getBitmapDataPlanes:dstPlanes];
618     unsigned char *dstData = dstPlanes[1];
619     // The wxImage format (which we use whenever we imported from wxImage)
620     if([srcBitmapRep bitsPerPixel]==24 && [srcBitmapRep bitsPerSample]==8 && [srcBitmapRep samplesPerPixel]==3 && [srcBitmapRep hasAlpha]==NO)
621     {
622         wxPixelData<wxBitmap,wxNativePixelFormat> pixelData(const_cast<wxBitmap&>(bitmap));
623         wxCHECK_MSG(wxMask_CreateFromBitmapData(pixelData, colour, dstData),
624             false, wxT("Unable to access raw data"));
625     }
626     // 32-bpp RGBx (x=throw away, no alpha)
627     else if([srcBitmapRep bitsPerPixel]==32 && [srcBitmapRep bitsPerSample]==8 && [srcBitmapRep samplesPerPixel]==3 && [srcBitmapRep hasAlpha]==NO)
628     {
629         typedef wxPixelFormat<unsigned char,32,0,1,2> PixelFormat;
630         wxPixelData<wxBitmap,PixelFormat> pixelData(const_cast<wxBitmap&>(bitmap));
631         wxCHECK_MSG(wxMask_CreateFromBitmapData(pixelData, colour, dstData),
632             false, wxT("Unable to access raw data"));
633     }
634     // 32-bpp RGBA
635     else if([srcBitmapRep bitsPerPixel]==32 && [srcBitmapRep bitsPerSample]==8 && [srcBitmapRep samplesPerPixel]==4 && [srcBitmapRep hasAlpha]==YES)
636     {
637         wxPixelData<wxBitmap,wxAlphaPixelFormat> pixelData(const_cast<wxBitmap&>(bitmap));
638         wxCHECK_MSG(wxMask_CreateFromBitmapData(pixelData, colour, dstData),
639             false, wxT("Unable to access raw data"));
640     }
641     else
642     {   wxCHECK_MSG(false,false,wxT("Unimplemented pixel format")); }
643
644     // maskRep was autoreleased in case we had to exit quickly
645     m_cocoaNSBitmapImageRep = [maskRep retain];
646     return true;
647 }
648