summaryrefslogtreecommitdiff
path: root/vcl/quartz/salbmp.cxx
blob: 50a75135c08283661597e4b2a395ba52b328d947 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */


#include "basebmp/scanlineformats.hxx"
#include "basebmp/color.hxx"

#include "basegfx/vector/b2ivector.hxx"

#include "tools/color.hxx"

#include "vcl/bitmap.hxx"
#include "vcl/salbtype.hxx"

#include "quartz/salbmp.h"

#ifdef MACOSX
#include "osx/saldata.hxx"
#else
#include "saldatabasic.hxx"
#endif

#include "bmpfast.hxx"

static const unsigned long k16BitRedColorMask   = 0x00007c00;
static const unsigned long k16BitGreenColorMask = 0x000003e0;
static const unsigned long k16BitBlueColorMask  = 0x0000001f;

static const unsigned long k32BitRedColorMask   = 0x00ff0000;
static const unsigned long k32BitGreenColorMask = 0x0000ff00;
static const unsigned long k32BitBlueColorMask  = 0x000000ff;



static bool isValidBitCount( sal_uInt16 nBitCount )
{
    return (nBitCount == 1) || (nBitCount == 4) || (nBitCount == 8) || (nBitCount == 16) || (nBitCount == 24) || (nBitCount == 32);
}



QuartzSalBitmap::QuartzSalBitmap()
: mxGraphicContext( NULL )
, mxCachedImage( NULL )
, mnBits(0)
, mnWidth(0)
, mnHeight(0)
, mnBytesPerRow(0)
, maExternalData(NULL)
{
}



QuartzSalBitmap::~QuartzSalBitmap()
{
    Destroy();
}



bool QuartzSalBitmap::Create( CGLayerRef xLayer, int nBitmapBits,
    int nX, int nY, int nWidth, int nHeight )
{
    DBG_ASSERT( xLayer, "QuartzSalBitmap::Create() from non-layered context" );

    // sanitize input parameters
    if( nX < 0 )
        nWidth += nX, nX = 0;
    if( nY < 0 )
        nHeight += nY, nY = 0;
    const CGSize aLayerSize = CGLayerGetSize( xLayer );
    if( nWidth >= (int)aLayerSize.width - nX )
        nWidth = (int)aLayerSize.width - nX;
    if( nHeight >= (int)aLayerSize.height - nY )
        nHeight = (int)aLayerSize.height - nY;
    if( (nWidth < 0) || (nHeight < 0) )
        nWidth = nHeight = 0;

    // initialize properties
    mnWidth  = nWidth;
    mnHeight = nHeight;
    mnBits   = nBitmapBits ? nBitmapBits : 32;

    // initialize drawing context
    CreateContext();

    // copy layer content into the bitmap buffer
    const CGPoint aSrcPoint = { static_cast<CGFloat>(-nX), static_cast<CGFloat>(-nY) };
    if(mxGraphicContext) // remove warning
        CGContextDrawLayerAtPoint( mxGraphicContext, aSrcPoint, xLayer );
    return true;
}



bool QuartzSalBitmap::Create( CGImageRef xImage, int nBitmapBits,
                             int nX, int nY, int nWidth, int nHeight )
{
    DBG_ASSERT( xImage, "QuartzSalBitmap::Create() from null image" );

    // sanitize input parameters
    if( nX < 0 )
        nWidth += nX, nX = 0;
    if( nY < 0 )
        nHeight += nY, nY = 0;
    const CGSize aLayerSize = CGSizeMake(CGImageGetWidth(xImage), CGImageGetHeight(xImage));
    if( nWidth >= (int)aLayerSize.width - nX )
        nWidth = (int)aLayerSize.width - nX;
    if( nHeight >= (int)aLayerSize.height - nY )
        nHeight = (int)aLayerSize.height - nY;
    if( (nWidth < 0) || (nHeight < 0) )
        nWidth = nHeight = 0;

    // initialize properties
    mnWidth  = nWidth;
    mnHeight = nHeight;
    mnBits   = nBitmapBits ? nBitmapBits : 32;

    // initialize drawing context
    CreateContext();

    // copy layer content into the bitmap buffer
    if(mxGraphicContext) // remove warning
    {
        // Flip the image right side up & draw
        CGContextSaveGState(mxGraphicContext);

        CGContextScaleCTM(mxGraphicContext, 1.0, -1.0);
        CGContextTranslateCTM(mxGraphicContext, 0.0, -aLayerSize.height);

        CGContextDrawImage( mxGraphicContext,
                           CGRectMake(static_cast<CGFloat>(-nX),
                                      static_cast<CGFloat>(nY),
                                      aLayerSize.width,
                                      aLayerSize.height),
                           xImage );

        // Restore the context so that the coordinate system is restored
        CGContextRestoreGState(mxGraphicContext);

    }


    return true;
}

bool QuartzSalBitmap::Create( BitmapBuffer& buffer)
{
    // initialize properties
    mnWidth  = buffer.mnWidth;
    mnHeight = buffer.mnHeight;
    mnBits   = buffer.mnBitCount;
    mnBytesPerRow = buffer.mnScanlineSize;
    maExternalData = buffer.mpBits;
    maPalette = buffer.maPalette;

    // initialize drawing context
    CreateContext();

    return true;
}



bool QuartzSalBitmap::Create( const Size& rSize, sal_uInt16 nBits, const BitmapPalette& rBitmapPalette )
{
    if( !isValidBitCount( nBits ) )
        return false;
    maPalette = rBitmapPalette;
    mnBits = nBits;
    mnWidth = rSize.Width();
    mnHeight = rSize.Height();
    return AllocateUserData();
}



bool QuartzSalBitmap::Create( const SalBitmap& rSalBmp )
{
    return Create( rSalBmp, rSalBmp.GetBitCount() );
}



bool QuartzSalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )
{
    return Create( rSalBmp, pGraphics ? pGraphics->GetBitCount() : rSalBmp.GetBitCount() );
}



bool QuartzSalBitmap::Create( const SalBitmap& rSalBmp, sal_uInt16 nNewBitCount )
{
    const QuartzSalBitmap& rSourceBitmap = static_cast<const QuartzSalBitmap&>(rSalBmp);

    if( isValidBitCount( nNewBitCount ) &&  rSourceBitmap.maUserBuffer.get() )
    {
        mnBits = nNewBitCount;
        mnWidth = rSourceBitmap.mnWidth;
        mnHeight = rSourceBitmap.mnHeight;
        maPalette = rSourceBitmap.maPalette;

        if( AllocateUserData() )
        {
            ConvertBitmapData( mnWidth, mnHeight, mnBits, mnBytesPerRow, maPalette, maUserBuffer.get(), rSourceBitmap.mnBits, rSourceBitmap.mnBytesPerRow, rSourceBitmap.maPalette, rSourceBitmap.maUserBuffer.get() );
            return true;
        }
    }
    return false;
}



bool QuartzSalBitmap::Create( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmapCanvas > /*xBitmapCanvas*/, Size& /*rSize*/, bool /*bMask*/ )
{
    return false;
}



void QuartzSalBitmap::Destroy()
{
    DestroyContext();
    maUserBuffer.reset();
    maExternalData = NULL;
}



void QuartzSalBitmap::DestroyContext()
{
    CGImageRelease( mxCachedImage );
    mxCachedImage = NULL;

    if( mxGraphicContext )
    {
        CGContextRelease( mxGraphicContext );
        mxGraphicContext = NULL;
        maContextBuffer.reset();
    }
}



bool QuartzSalBitmap::CreateContext()
{
    DestroyContext();

    // prepare graphics context
    // convert image from user input if available
    const bool bSkipConversion = !maUserBuffer && !maExternalData;
    if( bSkipConversion )
        AllocateUserData();

    // default to RGBA color space
#ifdef IOS
    CGColorSpaceRef aCGColorSpace = CGColorSpaceCreateDeviceRGB();
#else
    CGColorSpaceRef aCGColorSpace = GetSalData()->mxRGBSpace;
#endif
    CGBitmapInfo aCGBmpInfo = kCGImageAlphaNoneSkipFirst;

    // convert data into something accepted by CGBitmapContextCreate()
    size_t bitsPerComponent = (mnBits == 16) ? 5 : 8;
    sal_uInt32 nContextBytesPerRow = mnBytesPerRow;
    if( (mnBits == 16) || (mnBits == 32) )
    {
        if (!maExternalData)
        {
            // no conversion needed for truecolor
            maContextBuffer = maUserBuffer;
        }
    }
    else if( mnBits == 8
#ifndef IOS
            && maPalette.IsGreyPalette()
#endif
            )
    {
        // no conversion needed for grayscale
        if (!maExternalData)
        {
            maContextBuffer = maUserBuffer;
        }
#ifdef IOS
        aCGColorSpace = CGColorSpaceCreateDeviceGray();
#else
        aCGColorSpace = GetSalData()->mxGraySpace;
#endif
        aCGBmpInfo = kCGImageAlphaNone;
        bitsPerComponent = mnBits;
    }
    // TODO: is special handling for 1bit input buffers worth it?
    else
    {
        // convert user data to 32 bit
        nContextBytesPerRow = mnWidth << 2;
        try
        {
            maContextBuffer.reset( new sal_uInt8[ mnHeight * nContextBytesPerRow ] );

            if( !bSkipConversion )
                ConvertBitmapData( mnWidth, mnHeight,
                               32, nContextBytesPerRow, maPalette, maContextBuffer.get(),
                               mnBits, mnBytesPerRow, maPalette, maUserBuffer.get() );
        }
        catch( const std::bad_alloc& )
        {
            mxGraphicContext = 0;
        }
    }

    if(maExternalData)
    {
        mxGraphicContext = ::CGBitmapContextCreate( maExternalData, mnWidth, mnHeight,
                                                   bitsPerComponent, nContextBytesPerRow, aCGColorSpace, aCGBmpInfo );
    }
    else if( maContextBuffer.get() )
    {
        mxGraphicContext = ::CGBitmapContextCreate( maContextBuffer.get(), mnWidth, mnHeight,
            bitsPerComponent, nContextBytesPerRow, aCGColorSpace, aCGBmpInfo );
    }

    if( !mxGraphicContext )
        maContextBuffer.reset();

    return mxGraphicContext != NULL;
}



bool QuartzSalBitmap::AllocateUserData()
{
    Destroy();

    if( mnWidth && mnHeight )
    {
        mnBytesPerRow =  0;

        switch( mnBits )
        {
        case 1:     mnBytesPerRow = (mnWidth + 7) >> 3; break;
        case 4:     mnBytesPerRow = (mnWidth + 1) >> 1; break;
        case 8:     mnBytesPerRow = mnWidth; break;
        case 16:    mnBytesPerRow = mnWidth << 1; break;
        case 24:    mnBytesPerRow = (mnWidth << 1) + mnWidth; break;
        case 32:    mnBytesPerRow = mnWidth << 2; break;
        default:
            OSL_FAIL("vcl::QuartzSalBitmap::AllocateUserData(), illegal bitcount!");
        }
    }

    try
    {
        if( mnBytesPerRow )
            maUserBuffer.reset( new sal_uInt8[mnBytesPerRow * mnHeight] );
    }
    catch( const std::bad_alloc& )
    {
        OSL_FAIL( "vcl::QuartzSalBitmap::AllocateUserData: bad alloc" );
        maUserBuffer.reset( static_cast<sal_uInt8*>(NULL) );
        mnBytesPerRow = 0;
    }

    return maUserBuffer.get() != 0;
}



class ImplPixelFormat
{
protected:
    sal_uInt8* pData;
public:
    static ImplPixelFormat* GetFormat( sal_uInt16 nBits, const BitmapPalette& rPalette );

    virtual void StartLine( sal_uInt8* pLine ) { pData = pLine; }
    virtual void SkipPixel( sal_uInt32 nPixel ) = 0;
    virtual ColorData ReadPixel() = 0;
    virtual void WritePixel( ColorData nColor ) = 0;
    virtual ~ImplPixelFormat() { }
};

class ImplPixelFormat32 : public ImplPixelFormat
// currently ARGB-format for 32bit depth
{
public:
    virtual void SkipPixel( sal_uInt32 nPixel )
    {
        pData += nPixel << 2;
    }
    virtual ColorData ReadPixel()
    {
        const ColorData c = RGB_COLORDATA( pData[1], pData[2], pData[3] );
        pData += 4;
        return c;
    }
    virtual void WritePixel( ColorData nColor )
    {
        *pData++ = 0;
        *pData++ = COLORDATA_RED( nColor );
        *pData++ = COLORDATA_GREEN( nColor );
        *pData++ = COLORDATA_BLUE( nColor );
    }
};

class ImplPixelFormat24 : public ImplPixelFormat
// currently BGR-format for 24bit depth
{
public:
    virtual void SkipPixel( sal_uInt32 nPixel )
    {
        pData += (nPixel << 1) + nPixel;
    }
    virtual ColorData ReadPixel()
    {
        const ColorData c = RGB_COLORDATA( pData[2], pData[1], pData[0] );
        pData += 3;
        return c;
    }
    virtual void WritePixel( ColorData nColor )
    {
        *pData++ = COLORDATA_BLUE( nColor );
        *pData++ = COLORDATA_GREEN( nColor );
        *pData++ = COLORDATA_RED( nColor );
    }
};

class ImplPixelFormat16 : public ImplPixelFormat
// currently R5G6B5-format for 16bit depth
{
protected:
    sal_uInt16* pData16;
public:

    virtual void StartLine( sal_uInt8* pLine )
    {
        pData16 = (sal_uInt16*)pLine;
    }
    virtual void SkipPixel( sal_uInt32 nPixel )
    {
        pData += nPixel;
    }
    virtual ColorData ReadPixel()
    {
        const ColorData c = RGB_COLORDATA( (*pData & 0x7c00) >> 7, (*pData & 0x03e0) >> 2 , (*pData & 0x001f) << 3 );
        pData++;
        return c;
    }
    virtual void WritePixel( ColorData nColor )
    {
        *pData++ =  ((COLORDATA_RED( nColor ) & 0xf8 ) << 7 ) ||
                    ((COLORDATA_GREEN( nColor ) & 0xf8 ) << 2 ) ||
                    ((COLORDATA_BLUE( nColor ) & 0xf8 ) >> 3 );
    }
};

class ImplPixelFormat8 : public ImplPixelFormat
{
private:
    const BitmapPalette& mrPalette;

public:
    ImplPixelFormat8( const BitmapPalette& rPalette )
    : mrPalette( rPalette )
    {
    }
    virtual void SkipPixel( sal_uInt32 nPixel )
    {
        pData += nPixel;
    }
    virtual ColorData ReadPixel()
    {
        return mrPalette[ *pData++ ].operator Color().GetColor();
    }
    virtual void WritePixel( ColorData nColor )
    {
        const BitmapColor aColor( COLORDATA_RED( nColor ), COLORDATA_GREEN( nColor ), COLORDATA_BLUE( nColor ) );
        *pData++ = static_cast< sal_uInt8 >( mrPalette.GetBestIndex( aColor ) );
    }
};

class ImplPixelFormat4 : public ImplPixelFormat
{
private:
    const BitmapPalette& mrPalette;
    sal_uInt32 mnX;
    sal_uInt32 mnShift;

public:
    ImplPixelFormat4( const BitmapPalette& rPalette )
    : mrPalette( rPalette )
    {
    }
    virtual void SkipPixel( sal_uInt32 nPixel )
    {
        mnX += nPixel;
        if( (nPixel & 1) )
            mnShift ^= 4;
    }
    virtual void StartLine( sal_uInt8* pLine )
    {
        pData = pLine;
        mnX = 0;
        mnShift = 4;
    }
    virtual ColorData ReadPixel()
    {
        const BitmapColor& rColor = mrPalette[( pData[mnX >> 1] >> mnShift) & 0x0f];
        mnX++;
        mnShift ^= 4;
        return rColor.operator Color().GetColor();
    }
    virtual void WritePixel( ColorData nColor )
    {
        const BitmapColor aColor( COLORDATA_RED( nColor ), COLORDATA_GREEN( nColor ), COLORDATA_BLUE( nColor ) );
        pData[mnX>>1] &= (0xf0 >> mnShift);
        pData[mnX>>1] |= (static_cast< sal_uInt8 >( mrPalette.GetBestIndex( aColor ) ) & 0x0f);
        mnX++;
        mnShift ^= 4;
    }
};

class ImplPixelFormat1 : public ImplPixelFormat
{
private:
    const BitmapPalette& mrPalette;
    sal_uInt32 mnX;

public:
    ImplPixelFormat1( const BitmapPalette& rPalette )
    : mrPalette( rPalette )
    {
    }
    virtual void SkipPixel( sal_uInt32 nPixel )
    {
        mnX += nPixel;
    }
    virtual void StartLine( sal_uInt8* pLine )
    {
        pData = pLine;
        mnX = 0;
    }
    virtual ColorData ReadPixel()
    {
        const BitmapColor& rColor = mrPalette[ (pData[mnX >> 3 ] >> ( 7 - ( mnX & 7 ) )) & 1];
        mnX++;
        return rColor.operator Color().GetColor();
    }
    virtual void WritePixel( ColorData nColor )
    {
        const BitmapColor aColor( COLORDATA_RED( nColor ), COLORDATA_GREEN( nColor ), COLORDATA_BLUE( nColor ) );
        if( mrPalette.GetBestIndex( aColor ) & 1 )
            pData[ mnX >> 3 ] |= 1 << ( 7 - ( mnX & 7 ) );
        else
            pData[ mnX >> 3 ] &= ~( 1 << ( 7 - ( mnX & 7 ) ) );
        mnX++;
    }
};

ImplPixelFormat* ImplPixelFormat::GetFormat( sal_uInt16 nBits, const BitmapPalette& rPalette )
{
    switch( nBits )
    {
    case 1: return new ImplPixelFormat1( rPalette );
    case 4: return new ImplPixelFormat4( rPalette );
    case 8: return new ImplPixelFormat8( rPalette );
    case 16: return new ImplPixelFormat16;
    case 24: return new ImplPixelFormat24;
    case 32: return new ImplPixelFormat32;
    }

    return 0;
}

void QuartzSalBitmap::ConvertBitmapData( sal_uInt32 nWidth, sal_uInt32 nHeight,
                                       sal_uInt16 nDestBits, sal_uInt32 nDestBytesPerRow, const BitmapPalette& rDestPalette, sal_uInt8* pDestData,
                                       sal_uInt16 nSrcBits, sal_uInt32 nSrcBytesPerRow, const BitmapPalette& rSrcPalette, sal_uInt8* pSrcData )

{
    if( (nDestBytesPerRow == nSrcBytesPerRow) && (nDestBits == nSrcBits) && ((nSrcBits != 8) || (rDestPalette.operator==( rSrcPalette ))) )
    {
        // simple case, same format, so just copy
        memcpy( pDestData, pSrcData, nHeight * nDestBytesPerRow );
        return;
    }

    // try accelerated conversion if possible
    // TODO: are other truecolor conversions except BGR->ARGB worth it?
    bool bConverted = false;
    if( (nSrcBits == 24) && (nDestBits == 32) )
    {
        // TODO: extend bmpfast.cxx with a method that can be directly used here
        BitmapBuffer aSrcBuf;
        aSrcBuf.mnFormat = BMP_FORMAT_24BIT_TC_BGR;
        aSrcBuf.mpBits = pSrcData;
        aSrcBuf.mnBitCount = nSrcBits;
        aSrcBuf.mnScanlineSize = nSrcBytesPerRow;
        BitmapBuffer aDstBuf;
        aDstBuf.mnFormat = BMP_FORMAT_32BIT_TC_ARGB;
        aDstBuf.mpBits = pDestData;
        aSrcBuf.mnBitCount = nDestBits;
        aDstBuf.mnScanlineSize = nDestBytesPerRow;

        aSrcBuf.mnWidth = aDstBuf.mnWidth = nWidth;
        aSrcBuf.mnHeight = aDstBuf.mnHeight = nHeight;

        SalTwoRect aTwoRects;
        aTwoRects.mnSrcX = aTwoRects.mnDestX = 0;
        aTwoRects.mnSrcY = aTwoRects.mnDestY = 0;
        aTwoRects.mnSrcWidth = aTwoRects.mnDestWidth = mnWidth;
        aTwoRects.mnSrcHeight = aTwoRects.mnDestHeight = mnHeight;
        bConverted = ::ImplFastBitmapConversion( aDstBuf, aSrcBuf, aTwoRects );
    }

    if( !bConverted )
    {
        // TODO: this implementation is for clarety, not for speed

        ImplPixelFormat* pD = ImplPixelFormat::GetFormat( nDestBits, rDestPalette );
        ImplPixelFormat* pS = ImplPixelFormat::GetFormat( nSrcBits, rSrcPalette );

        if( pD && pS )
        {
            sal_uInt32 nY = nHeight;
            while( nY-- )
            {
                pD->StartLine( pDestData );
                pS->StartLine( pSrcData );

                sal_uInt32 nX = nWidth;
                while( nX-- )
                    pD->WritePixel( pS->ReadPixel() );

                pSrcData += nSrcBytesPerRow;
                pDestData += nDestBytesPerRow;
            }
        }
        delete pS;
        delete pD;
    }
}



Size QuartzSalBitmap::GetSize() const
{
    return Size( mnWidth, mnHeight );
}



sal_uInt16 QuartzSalBitmap::GetBitCount() const
{
    return mnBits;
}



static struct pal_entry
{
    sal_uInt8 mnRed;
    sal_uInt8 mnGreen;
    sal_uInt8 mnBlue;
}
const aImplSalSysPalEntryAry[ 16 ] =
{
{    0,    0,    0 },
{    0,    0, 0x80 },
{    0, 0x80,    0 },
{    0, 0x80, 0x80 },
{ 0x80,    0,    0 },
{ 0x80,    0, 0x80 },
{ 0x80, 0x80,    0 },
{ 0x80, 0x80, 0x80 },
{ 0xC0, 0xC0, 0xC0 },
{    0,    0, 0xFF },
{    0, 0xFF,    0 },
{    0, 0xFF, 0xFF },
{ 0xFF,    0,    0 },
{ 0xFF,    0, 0xFF },
{ 0xFF, 0xFF,    0 },
{ 0xFF, 0xFF, 0xFF }
};

const BitmapPalette& GetDefaultPalette( int mnBits, bool bMonochrome )
{
    if( bMonochrome )
        return Bitmap::GetGreyPalette( 1U << mnBits );

    // at this point we should provide some kind of default palette
    // since all other platforms do so, too.
    static bool bDefPalInit = false;
    static BitmapPalette aDefPalette256;
    static BitmapPalette aDefPalette16;
    static BitmapPalette aDefPalette2;
    if( ! bDefPalInit )
    {
        bDefPalInit = true;
        aDefPalette256.SetEntryCount( 256 );
        aDefPalette16.SetEntryCount( 16 );
        aDefPalette2.SetEntryCount( 2 );

        // Standard colors
        unsigned int i;
        for( i = 0; i < 16; i++ )
        {
            aDefPalette16[i] =
            aDefPalette256[i] = BitmapColor( aImplSalSysPalEntryAry[i].mnRed,
                                             aImplSalSysPalEntryAry[i].mnGreen,
                                             aImplSalSysPalEntryAry[i].mnBlue );
            }

        aDefPalette2[0] = BitmapColor( 0, 0, 0 );
        aDefPalette2[1] = BitmapColor( 0xff, 0xff, 0xff );

        // own palette (6/6/6)
        const int DITHER_PAL_STEPS = 6;
        const sal_uInt8 DITHER_PAL_DELTA = 51;
        int nB, nG, nR;
        sal_uInt8 nRed, nGreen, nBlue;
        for( nB=0, nBlue=0; nB < DITHER_PAL_STEPS; nB++, nBlue += DITHER_PAL_DELTA )
        {
            for( nG=0, nGreen=0; nG < DITHER_PAL_STEPS; nG++, nGreen += DITHER_PAL_DELTA )
            {
                for( nR=0, nRed=0; nR < DITHER_PAL_STEPS; nR++, nRed += DITHER_PAL_DELTA )
                {
                    aDefPalette256[ i ] = BitmapColor( nRed, nGreen, nBlue );
                    i++;
                }
            }
        }
    }

    // now fill in appropriate palette
    switch( mnBits )
    {
    case 1: return aDefPalette2;
    case 4: return aDefPalette16;
    case 8: return aDefPalette256;
    default: break;
    }

    const static BitmapPalette aEmptyPalette;
    return aEmptyPalette;
}

BitmapBuffer* QuartzSalBitmap::AcquireBuffer( bool /*bReadOnly*/ )
{
    if( !maUserBuffer.get() )
//  || maContextBuffer.get() && (maUserBuffer.get() != maContextBuffer.get()) )
    {
        // fprintf(stderr,"ASB::Acq(%dx%d,d=%d)\n",mnWidth,mnHeight,mnBits);
        // TODO: AllocateUserData();
        return NULL;
    }

    BitmapBuffer* pBuffer = new BitmapBuffer;
    pBuffer->mnWidth = mnWidth;
    pBuffer->mnHeight = mnHeight;
    pBuffer->maPalette = maPalette;
    pBuffer->mnScanlineSize = mnBytesPerRow;
    pBuffer->mpBits = maUserBuffer.get();
    pBuffer->mnBitCount = mnBits;
    switch( mnBits )
    {
    case 1:     pBuffer->mnFormat = BMP_FORMAT_1BIT_MSB_PAL; break;
    case 4:     pBuffer->mnFormat = BMP_FORMAT_4BIT_MSN_PAL; break;
    case 8:     pBuffer->mnFormat = BMP_FORMAT_8BIT_PAL; break;
    case 16:    pBuffer->mnFormat = BMP_FORMAT_16BIT_TC_MSB_MASK;
                pBuffer->maColorMask  = ColorMask( k16BitRedColorMask, k16BitGreenColorMask, k16BitBlueColorMask );
                break;
    case 24:    pBuffer->mnFormat = BMP_FORMAT_24BIT_TC_BGR; break;
    case 32:    pBuffer->mnFormat = BMP_FORMAT_32BIT_TC_ARGB;
                pBuffer->maColorMask  = ColorMask( k32BitRedColorMask, k32BitGreenColorMask, k32BitBlueColorMask );
                break;
    }
    pBuffer->mnFormat |= BMP_FORMAT_BOTTOM_UP;

    // some BitmapBuffer users depend on a complete palette
    if( (mnBits <= 8) && !maPalette )
        pBuffer->maPalette = GetDefaultPalette( mnBits, true );

    return pBuffer;
}



void QuartzSalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, bool bReadOnly )
{
    // invalidate graphic context if we have different data
    if( !bReadOnly )
    {
        maPalette = pBuffer->maPalette;
        if( mxGraphicContext )
            DestroyContext();
    }

    delete pBuffer;
}



CGImageRef QuartzSalBitmap::CreateCroppedImage( int nX, int nY, int nNewWidth, int nNewHeight ) const
{
    if( !mxCachedImage )
    {
        if( !mxGraphicContext )
            if( !const_cast<QuartzSalBitmap*>(this)->CreateContext() )
                return NULL;

        mxCachedImage = CGBitmapContextCreateImage( mxGraphicContext );
    }

    CGImageRef xCroppedImage = NULL;
    // short circuit if there is nothing to crop
    if( !nX && !nY && (mnWidth == nNewWidth) && (mnHeight == nNewHeight) )
    {
          xCroppedImage = mxCachedImage;
          CFRetain( xCroppedImage );
    }
    else
    {
        nY = mnHeight - (nY + nNewHeight); // adjust for y-mirrored context
        const CGRect aCropRect = { { static_cast<CGFloat>(nX), static_cast<CGFloat>(nY) }, { static_cast<CGFloat>(nNewWidth), static_cast<CGFloat>(nNewHeight) } };
        xCroppedImage = CGImageCreateWithImageInRect( mxCachedImage, aCropRect );
    }

    return xCroppedImage;
}



static void CFRTLFree(void* /*info*/, const void* data, size_t /*size*/)
{
    rtl_freeMemory( const_cast<void*>(data) );
}

CGImageRef QuartzSalBitmap::CreateWithMask( const QuartzSalBitmap& rMask,
    int nX, int nY, int nWidth, int nHeight ) const
{
    CGImageRef xImage( CreateCroppedImage( nX, nY, nWidth, nHeight ) );
    if( !xImage )
        return NULL;

    CGImageRef xMask = rMask.CreateCroppedImage( nX, nY, nWidth, nHeight );
    if( !xMask )
        return xImage;

    // CGImageCreateWithMask() only likes masks or greyscale images => convert if needed
    // TODO: isolate in an extra method?
    if( !CGImageIsMask(xMask) || rMask.GetBitCount() != 8)//(CGImageGetColorSpace(xMask) != GetSalData()->mxGraySpace) )
    {
        const CGRect xImageRect=CGRectMake( 0, 0, nWidth, nHeight );//the rect has no offset

        // create the alpha mask image fitting our image
        // TODO: is caching the full mask or the subimage mask worth it?
        int nMaskBytesPerRow = ((nWidth + 3) & ~3);
        void* pMaskMem = rtl_allocateMemory( nMaskBytesPerRow * nHeight );
        CGContextRef xMaskContext = CGBitmapContextCreate( pMaskMem,
            nWidth, nHeight, 8, nMaskBytesPerRow, GetSalData()->mxGraySpace, kCGImageAlphaNone );
        CGContextDrawImage( xMaskContext, xImageRect, xMask );
        CFRelease( xMask );
        CGDataProviderRef xDataProvider( CGDataProviderCreateWithData( NULL,
        pMaskMem, nHeight * nMaskBytesPerRow, &CFRTLFree ) );
        static const CGFloat* pDecode = NULL;
        xMask = CGImageMaskCreate( nWidth, nHeight, 8, 8, nMaskBytesPerRow, xDataProvider, pDecode, false );
        CFRelease( xDataProvider );
        CFRelease( xMaskContext );
    }

    if( !xMask )
        return xImage;

    // combine image and alpha mask
    CGImageRef xMaskedImage = CGImageCreateWithMask( xImage, xMask );
    CFRelease( xMask );
    CFRelease( xImage );
    return xMaskedImage;
}



/** creates an image from the given rectangle, replacing all black pixels with nMaskColor and make all other full transparent */
CGImageRef QuartzSalBitmap::CreateColorMask( int nX, int nY, int nWidth, int nHeight, SalColor nMaskColor ) const
{
    CGImageRef xMask = 0;
    if( maUserBuffer.get() && (nX + nWidth <= mnWidth) && (nY + nHeight <= mnHeight) )
    {
        const sal_uInt32 nDestBytesPerRow = nWidth << 2;
        sal_uInt32* pMaskBuffer = static_cast<sal_uInt32*>( rtl_allocateMemory( nHeight * nDestBytesPerRow ) );
        sal_uInt32* pDest = pMaskBuffer;

        ImplPixelFormat* pSourcePixels = ImplPixelFormat::GetFormat( mnBits, maPalette );

        if( pMaskBuffer && pSourcePixels )
        {
            sal_uInt32 nColor;
            reinterpret_cast<sal_uInt8*>(&nColor)[0] = 0xff;
            reinterpret_cast<sal_uInt8*>(&nColor)[1] = SALCOLOR_RED( nMaskColor );
            reinterpret_cast<sal_uInt8*>(&nColor)[2] = SALCOLOR_GREEN( nMaskColor );
            reinterpret_cast<sal_uInt8*>(&nColor)[3] = SALCOLOR_BLUE( nMaskColor );

            sal_uInt8* pSource = maUserBuffer.get();
            if( nY )
                pSource += nY * mnBytesPerRow;

            int y = nHeight;
            while( y-- )
            {
                pSourcePixels->StartLine( pSource );
                pSourcePixels->SkipPixel(nX);
                sal_uInt32 x = nWidth;
                while( x-- )
                {
                    *pDest++ = ( pSourcePixels->ReadPixel() == 0 ) ? nColor : 0;
                }
                pSource += mnBytesPerRow;
            }

            CGDataProviderRef xDataProvider( CGDataProviderCreateWithData(NULL, pMaskBuffer, nHeight * nDestBytesPerRow, &CFRTLFree) );
            xMask = CGImageCreate(nWidth, nHeight, 8, 32, nDestBytesPerRow, GetSalData()->mxRGBSpace, kCGImageAlphaPremultipliedFirst, xDataProvider, NULL, true, kCGRenderingIntentDefault);
            CFRelease(xDataProvider);
        }
        else
        {
            free(pMaskBuffer);
        }

        delete pSourcePixels;
    }
    return xMask;
}



/** QuartzSalBitmap::GetSystemData Get platform native image data from existing image
 *
 *  @param rData struct BitmapSystemData, defined in vcl/inc/bitmap.hxx
 *  @return true if successful
**/
bool QuartzSalBitmap::GetSystemData( BitmapSystemData& rData )
{
    bool bRet = false;

    if( !mxGraphicContext )
        CreateContext();

    if ( mxGraphicContext )
    {
        bRet = true;

        if ((CGBitmapContextGetBitsPerPixel(mxGraphicContext) == 32) &&
            (CGBitmapContextGetBitmapInfo(mxGraphicContext) & kCGBitmapByteOrderMask) != kCGBitmapByteOrder32Host) {
            /**
             * We need to hack things because VCL does not use kCGBitmapByteOrder32Host, while Cairo requires it.
             */
            OSL_TRACE("QuartzSalBitmap::%s(): kCGBitmapByteOrder32Host not found => inserting it.",__func__);

            CGImageRef xImage = CGBitmapContextCreateImage (mxGraphicContext);

            // re-create the context with single change: include kCGBitmapByteOrder32Host flag.
            CGContextRef mxGraphicContextNew = CGBitmapContextCreate( CGBitmapContextGetData(mxGraphicContext),
                                                                      CGBitmapContextGetWidth(mxGraphicContext),
                                                                      CGBitmapContextGetHeight(mxGraphicContext),
                                                                      CGBitmapContextGetBitsPerComponent(mxGraphicContext),
                                                                      CGBitmapContextGetBytesPerRow(mxGraphicContext),
                                                                      CGBitmapContextGetColorSpace(mxGraphicContext),
                                                                      CGBitmapContextGetBitmapInfo(mxGraphicContext) | kCGBitmapByteOrder32Host);
            CFRelease(mxGraphicContext);

            // Needs to be flipped
            CGContextSaveGState( mxGraphicContextNew );
            CGContextTranslateCTM (mxGraphicContextNew, 0, CGBitmapContextGetHeight(mxGraphicContextNew));
            CGContextScaleCTM (mxGraphicContextNew, 1.0, -1.0);

            CGContextDrawImage(mxGraphicContextNew, CGRectMake( 0, 0, CGImageGetWidth(xImage), CGImageGetHeight(xImage)), xImage);

            // Flip back
            CGContextRestoreGState( mxGraphicContextNew );

            CGImageRelease( xImage );
            mxGraphicContext = mxGraphicContextNew;
        }

        rData.rImageContext = (void *) mxGraphicContext;
        rData.mnWidth = mnWidth;
        rData.mnHeight = mnHeight;
    }

    return bRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */