summaryrefslogtreecommitdiff
path: root/basebmp/source/bitmapdevice.cxx
blob: 1e582e7812d4300f301622e7224bb4f4d9fc9fbb (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
/* -*- 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 <sal/config.h>

#include <cassert>
#include <string.h>

#include <basebmp/bitmapdevice.hxx>

#include <compositeiterator.hxx>
#include <iteratortraits.hxx>

#include <accessor.hxx>
#include <accessortraits.hxx>
#include <accessoradapters.hxx>
#include <colorblendaccessoradapter.hxx>

#include <basebmp/color.hxx>
#include <colormisc.hxx>
#include <colortraits.hxx>

#include <greylevelformats.hxx>
#include <paletteformats.hxx>
#include <rgbmaskpixelformats.hxx>
#include <rgb24pixelformats.hxx>

#include <basebmp/scanlineformats.hxx>
#include <fillimage.hxx>
#include <scaleimage.hxx>
#include <genericcolorimageaccessor.hxx>

#include <tools.hxx>
#include "intconversion.hxx"

#include <rtl/alloc.h>
#include <sal/log.hxx>
#include <osl/diagnose.h>
#include <o3tl/enumarray.hxx>

#include <basegfx/tools/tools.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/range/b2ibox.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/range/b2drange.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/point/b2ipoint.hxx>
#include <basegfx/vector/b2ivector.hxx>

#include <vigra/iteratortraits.hxx>
#include <vigra/rgbvalue.hxx>
#include <vigra/copyimage.hxx>
#include <vigra/tuple.hxx>

namespace basebmp
{

static const o3tl::enumarray<Format,sal_uInt8> bitsPerPixel =
{
    0,  // NONE
    1,  // ONE_BIT_MSB_GREY
    1,  // ONE_BIT_LSB_GREY
    1,  // ONE_BIT_MSB_PAL
    1,  // ONE_BIT_LSB_PAL
    4,  // FOUR_BIT_MSB_GREY
    4,  // FOUR_BIT_LSB_GREY
    4,  // FOUR_BIT_MSB_PAL
    4,  // FOUR_BIT_LSB_PAL
    8,  // EIGHT_BIT_PAL
    8,  // EIGHT_BIT_GREY
    16, // SIXTEEN_BIT_LSB_TC_MASK
    16, // SIXTEEN_BIT_MSB_TC_MASK
    24, // TWENTYFOUR_BIT_TC_MASK
    32, // THIRTYTWO_BIT_TC_MASK_BGRA
    32, // THIRTYTWO_BIT_TC_MASK_ARGB
    32, // THIRTYTWO_BIT_TC_MASK_ABGR
    32, // THIRTYTWO_BIT_TC_MASK_RGBA
};

namespace
{
    /** Create the type for an accessor that takes the (mask,bitmap)
        input value generated from a JoinImageAccessorAdapter, and
        pipe that through a mask functor.

        @tpl DestAccessor
        Destination bitmap accessor

        @tpl JoinedAccessor
        Input accessor, is expected to generate a std::pair as the
        value type

        @tpl MaskFunctorMode
        Either FastMask or NoFastMask, depending on whether the mask
        is guaranteed to contain only 0s and 1s.
     */
    template< class    DestAccessor,
              class    JoinedAccessor,
              bool     polarity,
              typename MaskFunctorMode > struct masked_input_splitting_accessor
    {
        typedef BinarySetterFunctionAccessorAdapter<
            DestAccessor,
            BinaryFunctorSplittingWrapper<
                typename outputMaskFunctorSelector<
                         typename JoinedAccessor::value_type::first_type,
                         typename JoinedAccessor::value_type::second_type,
                         polarity,
                         MaskFunctorMode >::type > > type;
    };



    // Actual BitmapDevice implementation (templatized by accessor and iterator)

    /** Implementation of the BitmapDevice interface

        @tpl DestIterator
        Iterator to access bitmap memory

        @tpl RawAccessor
        Raw accessor, to access pixel values directly

        @tpl AccessorSelector
        Accessor adapter selector, which, when applying the nested
        template metafunction wrap_accessor to one of the raw bitmap
        accessors, yields a member type named 'type', which is a
        wrapped accessor that map color values.

        @tpl Masks
        Traits template, containing nested traits
        clipmask_format_traits and alphamask_format_traits, which
        determine what specialized formats are to be used for clip and
        alpha masks. With those mask formats, clipping and alpha
        blending is handled natively.
     */
    template< class DestIterator,
              class RawAccessor,
              class AccessorSelector,
              class Masks > class BitmapRenderer :
                  public BitmapDevice
    {
    public:
        typedef DestIterator                                               dest_iterator_type;
        typedef RawAccessor                                                raw_accessor_type;
        typedef AccessorSelector                                           accessor_selector;

        typedef typename AccessorSelector::template wrap_accessor<
            raw_accessor_type >::type                                      dest_accessor_type;

        typedef AccessorTraits< dest_accessor_type >                       accessor_traits;

        typedef AccessorTraits< raw_accessor_type >                        raw_accessor_traits;
        typedef typename uInt32Converter<
            typename raw_accessor_type::value_type>::to                    to_uint32_functor;


        dest_iterator_type                      maBegin;
        typename accessor_traits::color_lookup  maColorLookup;
        to_uint32_functor                       maToUInt32Converter;
        dest_accessor_type                      maAccessor;
        raw_accessor_type                       maRawAccessor;




        BitmapRenderer( const basegfx::B2IBox&                     rBounds,
                        const basegfx::B2IVector&                  rBufferSize,
                        Format                                     nScanlineFormat,
                        sal_Int32                                  nScanlineStride,
                        sal_uInt8*                                 pFirstScanline,
                        dest_iterator_type                         begin,
                        raw_accessor_type                          rawAccessor,
                        dest_accessor_type                         accessor,
                        const RawMemorySharedArray&                rMem,
                        const PaletteMemorySharedVector&           rPalette ) :
            BitmapDevice( rBounds, rBufferSize, nScanlineFormat,
                          nScanlineStride, pFirstScanline, rMem, rPalette ),
            maBegin( begin ),
            maColorLookup(),
            maToUInt32Converter(),
            maAccessor( accessor ),
            maRawAccessor( rawAccessor )
        {}

    private:

        static std::shared_ptr<BitmapRenderer> getCompatibleBitmap( const BitmapDeviceSharedPtr& bmp )
        {
            return std::dynamic_pointer_cast< BitmapRenderer >( bmp );
        }

        virtual bool isCompatibleBitmap( const BitmapDeviceSharedPtr& bmp ) const override
        {
            // TODO(P1): dynamic_cast usually called twice for
            // compatible formats
            return getCompatibleBitmap(bmp).get() != nullptr;
        }

        virtual Color getPixel_i(const basegfx::B2IPoint& rPt ) override
        {
            const DestIterator pixel( maBegin +
                                      vigra::Diff2D(rPt.getX(),
                                                    rPt.getY()) );
            return maAccessor(pixel);
        }

        virtual sal_uInt32 getPixelData_i( const basegfx::B2IPoint& rPt ) override
        {
            const DestIterator pixel( maBegin +
                                      vigra::Diff2D(rPt.getX(),
                                                    rPt.getY()) );
            return maToUInt32Converter(maRawAccessor(pixel));
        }

        template< typename Iterator, typename RawAcc >
        void implDrawBitmap(const BitmapDeviceSharedPtr& rSrcBitmap,
                            const Iterator&              begin,
                            const RawAcc&                acc)
        {
            const basegfx::B2IVector& rSrcSize( rSrcBitmap->getSize() );
            const basegfx::B2IBox     aRect(0, 0, rSrcSize.getX(),rSrcSize.getY());

            std::shared_ptr<BitmapRenderer> pSrcBmp( getCompatibleBitmap(rSrcBitmap) );
            OSL_ASSERT( pSrcBmp );

            scaleImage(
                srcIterRange(pSrcBmp->maBegin,
                             pSrcBmp->maRawAccessor,
                             aRect),
                destIterRange(begin,
                              acc,
                              aRect),
                isSharedBuffer(rSrcBitmap) );
        }

        template< typename Iterator, typename Acc > static
        void implDrawBitmapGeneric(const BitmapDeviceSharedPtr& rSrcBitmap,
                                   const Iterator&              begin,
                                   const Acc&                   acc)
        {
            const basegfx::B2IVector& rSrcSize( rSrcBitmap->getSize() );
            const basegfx::B2IBox     aRect(0, 0, rSrcSize.getX(),rSrcSize.getY());

            GenericColorImageAccessor aSrcAcc( rSrcBitmap );

            scaleImage(
                srcIterRange(vigra::Diff2D(),
                             aSrcAcc,
                             aRect),
                destIterRange(begin,
                              acc,
                              aRect));
        }

        void implDrawBitmapDirect(const BitmapDeviceSharedPtr& rSrcBitmap)
        {
            const basegfx::B2IVector& rSrcSize(rSrcBitmap->getSize());

            sal_Int32 nSrcWidth = rSrcSize.getX();
            sal_Int32 nSrcHeight = rSrcSize.getY();

            char* dstBuf =  reinterpret_cast<char*>(getBuffer().get());
            char* srcBuf =  reinterpret_cast<char*>(rSrcBitmap->getBuffer().get());
            sal_Int32 dstStride =  getScanlineStride();
            sal_Int32 srcStride =  rSrcBitmap->getScanlineStride();
            sal_Int32 bytesPerPixel = (bitsPerPixel[getScanlineFormat()] + 7) >> 3; // round up to bytes

            char* dstline = dstBuf;
            char* srcline = srcBuf;
            sal_Int32 lineBytes = nSrcWidth * bytesPerPixel;

            for(; 0 < nSrcHeight; nSrcHeight--)
            {
                memmove(dstline, srcline, lineBytes);
                dstline += dstStride;
                srcline += srcStride;
            }
        }

        virtual void copyBitmap_i(const BitmapDeviceSharedPtr& rSrcBitmap) override
        {
            if( isCompatibleBitmap( rSrcBitmap ) )
            {
                if (bitsPerPixel[getScanlineFormat()] >= 8
                         && rSrcBitmap->getScanlineFormat() == getScanlineFormat())
                    implDrawBitmapDirect(rSrcBitmap);
                else
                    implDrawBitmap(rSrcBitmap,
                                   maBegin,
                                   maRawAccessor);
            }
            else
            {
                implDrawBitmapGeneric(rSrcBitmap,
                                      maBegin,
                                      maAccessor);
            }
        }
    };
} // namespace

struct ImplBitmapDevice
{
    /** Bitmap memory plus deleter.

        Always points to the start of the mem
     */
    RawMemorySharedArray      mpMem;

    /// Palette memory plus deleter (might be NULL)
    PaletteMemorySharedVector mpPalette;

    /** Bounds of the device.

        maBounds.getWidth()/getHeight() yield the true size of the
        device (i.e. the rectangle given by maBounds covers the device
        area under the including-the-bottommost-and-rightmost-pixels
        fill rule)
     */
    basegfx::B2IBox           maBounds;

    //// Size of the actual frame buffer
    basegfx::B2IVector        maBufferSize;

    /// Scanline format, as provided at the constructor
    Format                    mnScanlineFormat;

    /// Scanline stride. Negative for bottom-to-top formats
    sal_Int32                 mnScanlineStride;

    /// raw ptr to 0th scanline. used for cloning a generic renderer
    sal_uInt8*                mpFirstScanline;

    /** (Optional) device sharing the same memory, and used for input
        clip masks/alpha masks/bitmaps that don't match our exact
        bitmap format.

        This is to avoid the combinatorial explosion when dealing
        with n bitmap formats, which could be combined with n clip
        masks, alpha masks and bitmap masks (yielding a total of n^4
        combinations). Since each BitmapRenderer is specialized for
        one specific combination of said formats, a lot of duplicate
        code would be generated, most of which probably never
        used. Therefore, only the most common combinations are
        specialized templates, the remainder gets handled by this
        generic renderer (via runtime polymorphism).
     */
    BitmapDeviceSharedPtr     mpGenericRenderer;
};


BitmapDevice::BitmapDevice( const basegfx::B2IBox&           rBounds,
                            const basegfx::B2IVector&        rBufferSize,
                            Format                           nScanlineFormat,
                            sal_Int32                        nScanlineStride,
                            sal_uInt8*                       pFirstScanline,
                            const RawMemorySharedArray&      rMem,
                            const PaletteMemorySharedVector& rPalette ) :
    mpImpl( new ImplBitmapDevice )
{
    mpImpl->mpMem = rMem;
    mpImpl->mpPalette = rPalette;
    mpImpl->maBounds = rBounds;
    mpImpl->maBufferSize = rBufferSize;
    mpImpl->mnScanlineFormat = nScanlineFormat;
    mpImpl->mnScanlineStride = nScanlineStride;
    mpImpl->mpFirstScanline  = pFirstScanline;
}

BitmapDevice::~BitmapDevice()
{
    // outline, because of internal ImplBitmapDevice
    SAL_INFO( "basebmp.bitmapdevice", "~BitmapDevice(" << this << ")" );
}

basegfx::B2IVector BitmapDevice::getSize() const
{
    return basegfx::B2IVector(
        mpImpl->maBounds.getMaxX() - mpImpl->maBounds.getMinX(),
        mpImpl->maBounds.getMaxY() - mpImpl->maBounds.getMinY() );
}

basegfx::B2IVector BitmapDevice::getBufferSize() const
{
    return mpImpl->maBufferSize;
}

Format BitmapDevice::getScanlineFormat() const
{
    return mpImpl->mnScanlineFormat;
}

sal_Int32 BitmapDevice::getScanlineStride() const
{
    return mpImpl->mnScanlineStride < 0 ?
        -mpImpl->mnScanlineStride : mpImpl->mnScanlineStride;
}

RawMemorySharedArray BitmapDevice::getBuffer() const
{
    return mpImpl->mpMem;
}

PaletteMemorySharedVector BitmapDevice::getPalette() const
{
    return mpImpl->mpPalette;
}

bool BitmapDevice::isSharedBuffer( const BitmapDeviceSharedPtr& rOther ) const
{
    return rOther.get()->getBuffer().get() == getBuffer().get();
}

Color BitmapDevice::getPixel( const basegfx::B2IPoint& rPt )
{
    if( mpImpl->maBounds.isInside(rPt) )
        return getPixel_i(rPt);

    return Color();
}

sal_uInt32 BitmapDevice::getPixelData( const basegfx::B2IPoint& rPt )
{
    if( mpImpl->maBounds.isInside(rPt) )
        return getPixelData_i(rPt);

    return 0;
}

void BitmapDevice::copyBitmap( const BitmapDeviceSharedPtr& rSrcBitmap )
{
    copyBitmap_i( rSrcBitmap );
}

/** Standard clip and alpha masks
 */
struct StdMasks
{
    typedef PixelFormatTraits_GREY1_MSB   clipmask_format_traits;
    typedef PixelFormatTraits_GREY8       alphamask_format_traits;

    /// Clipmask: 0 means opaque
    static const bool clipmask_polarity  = false;

    /// Alpha mask: 0 means fully transparent
    static const bool alphamask_polarity = true;
};


/// Produces a specialized renderer for the given pixel format
template< class FormatTraits, class MaskTraits >
BitmapDeviceSharedPtr createRenderer(
    const basegfx::B2IBox&                                       rBounds,
    const basegfx::B2IVector&                                    rBufferSize,
    Format                                                       nScanlineFormat,
    sal_Int32                                                    nScanlineStride,
    sal_uInt8*                                                   pFirstScanline,
    typename FormatTraits::raw_accessor_type const&              rRawAccessor,
    typename FormatTraits::accessor_selector::template wrap_accessor<
          typename FormatTraits::raw_accessor_type>::type const& rAccessor,
    boost::shared_array< sal_uInt8 >                             pMem,
    const PaletteMemorySharedVector&                             pPal )
{
    typedef typename FormatTraits::iterator_type                Iterator;
    typedef BitmapRenderer< Iterator,
                            typename FormatTraits::raw_accessor_type,
                            typename FormatTraits::accessor_selector,
                            MaskTraits >                        Renderer;

    return BitmapDeviceSharedPtr(
        new Renderer( rBounds,
                      rBufferSize,
                      nScanlineFormat,
                      nScanlineStride,
                      pFirstScanline,
                      Iterator(
                          reinterpret_cast<typename Iterator::value_type*>(
                              pFirstScanline),
                          nScanlineStride),
                      rRawAccessor,
                      rAccessor,
                      pMem,
                      pPal ));
}

/// Create standard grey level palette
PaletteMemorySharedVector createStandardPalette(
    const PaletteMemorySharedVector& pPal,
    sal_Int32                        nNumEntries )
{
    if( pPal || nNumEntries <= 0 )
        return pPal;

    std::shared_ptr< std::vector<Color> > pLocalPal(
        new std::vector<Color>(nNumEntries) );

    const sal_Int32 nIncrement( 0x00FFFFFF/nNumEntries );
    --nNumEntries;
    for( sal_Int32 i=0, c=0; i<nNumEntries; ++i,c+=nIncrement )
        pLocalPal->at(i) = Color(0xFF000000 | c);

    pLocalPal->at(nNumEntries) = Color(0xFFFFFFFF);

    return pLocalPal;
}

template< class FormatTraits, class MaskTraits >
BitmapDeviceSharedPtr createRenderer(
    const basegfx::B2IBox&                     rBounds,
    const basegfx::B2IVector&                  rBufferSize,
    Format                                     nScanlineFormat,
    sal_Int32                                  nScanlineStride,
    sal_uInt8*                                 pFirstScanline,
    boost::shared_array< sal_uInt8 >           pMem,
    const PaletteMemorySharedVector&           pPal )
{
    return createRenderer<FormatTraits,
                          MaskTraits>(rBounds,
                                      rBufferSize,
                                      nScanlineFormat,
                                      nScanlineStride,
                                      pFirstScanline,
                                      typename FormatTraits::raw_accessor_type(),
                                      typename FormatTraits::accessor_selector::template
                                      wrap_accessor<
                                          typename FormatTraits::raw_accessor_type>::type(),
                                      pMem,
                                      pPal );
}

template< class FormatTraits, class MaskTraits >
BitmapDeviceSharedPtr createRenderer(
    const basegfx::B2IBox&                     rBounds,
    const basegfx::B2IVector&                  rBufferSize,
    Format                                     nScanlineFormat,
    sal_Int32                                  nScanlineStride,
    sal_uInt8*                                 pFirstScanline,
    boost::shared_array< sal_uInt8 >           pMem,
    PaletteMemorySharedVector                  pPal,
    int                                        nBitsPerPixel )
{
    pPal = createStandardPalette(pPal,
                                 1UL << nBitsPerPixel);

    OSL_ASSERT(pPal);
    return createRenderer<FormatTraits,
                          MaskTraits>(rBounds,
                                      rBufferSize,
                                      nScanlineFormat,
                                      nScanlineStride,
                                      pFirstScanline,
                                      typename FormatTraits::raw_accessor_type(),
                                      typename FormatTraits::accessor_selector::template
                                          wrap_accessor<
                                      typename FormatTraits::raw_accessor_type>::type(
                                          &pPal->at(0),
                                          pPal->size()),
                                      pMem,
                                      pPal );
}

namespace
{
BitmapDeviceSharedPtr createBitmapDeviceImplInner( const basegfx::B2IVector&                  rSize,
                                                   Format                                     nScanlineFormat,
                                                   boost::shared_array< sal_uInt8 >           pMem,
                                                   PaletteMemorySharedVector                  pPal,
                                                   const basegfx::B2IBox*                     pSubset,
                                                   bool bBlack = true)
{
    OSL_ASSERT(rSize.getX() > 0 && rSize.getY() > 0);

    if( nScanlineFormat <= Format::NONE ||
        nScanlineFormat >  Format::LAST )
        return BitmapDeviceSharedPtr();

    sal_uInt8 nBitsPerPixel = bitsPerPixel[nScanlineFormat];
    if (rSize.getX() > (SAL_MAX_INT32-7) / nBitsPerPixel)
    {
        SAL_WARN("basebmp", "suspicious bitmap width " <<
                 rSize.getX() << " for depth " << nBitsPerPixel);
        return BitmapDeviceSharedPtr();
    }

    sal_Int32 nScanlineStride = getBitmapDeviceStrideForWidth(nScanlineFormat, rSize.getX());

    const sal_uInt32 nWidth(nScanlineStride < 0 ? -nScanlineStride : nScanlineStride);
    const sal_uInt32 nHeight(rSize.getY());

    if (nHeight && nWidth && nWidth > SAL_MAX_INT32 / nHeight)
    {
        SAL_WARN( "basebmp", "suspicious massive alloc " << nWidth << " * " << nHeight);
        return BitmapDeviceSharedPtr();
    }

    const std::size_t nMemSize(nWidth * nHeight);

    if( !pMem )
    {
        pMem.reset(
            static_cast<sal_uInt8*>(rtl_allocateMemory( nMemSize )),
            &rtl_freeMemory );
        if (pMem.get() == nullptr && nMemSize != 0)
            return BitmapDeviceSharedPtr();
        if (bBlack)
            memset(pMem.get(), 0, nMemSize);
        else
            memset(pMem.get(), 0xFF, nMemSize);
    }

    sal_uInt8* pFirstScanline = nScanlineStride < 0 ?
        pMem.get() + nMemSize + nScanlineStride : pMem.get();

    // shrink render area to given subset, if given
    basegfx::B2IBox aBounds(0,0,rSize.getX(),rSize.getY());
    if( pSubset )
        aBounds.intersect( *pSubset );

    switch( nScanlineFormat )
    {

        // one bit formats

        case Format::OneBitMsbGrey:
            return createRenderer<PixelFormatTraits_GREY1_MSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::OneBitLsbGrey:
            return createRenderer<PixelFormatTraits_GREY1_LSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::OneBitMsbPal:
            return createRenderer<PixelFormatTraits_PAL1_MSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal,
                bitsPerPixel[nScanlineFormat] );

        case Format::OneBitLsbPal:
            return createRenderer<PixelFormatTraits_PAL1_LSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal,
                bitsPerPixel[nScanlineFormat] );



        // four bit formats

        case Format::FourBitMsbGrey:
            return createRenderer<PixelFormatTraits_GREY4_MSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::FourBitLsbGrey:
            return createRenderer<PixelFormatTraits_GREY4_LSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::FourBitMsbPal:
            return createRenderer<PixelFormatTraits_PAL4_MSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal,
                bitsPerPixel[nScanlineFormat] );

        case Format::FourBitLsbPal:
            return createRenderer<PixelFormatTraits_PAL4_LSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal,
                bitsPerPixel[nScanlineFormat] );



        // eight bit formats

        case Format::EightBitGrey:
            return createRenderer<PixelFormatTraits_GREY8,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::EightBitPal:
            return createRenderer<PixelFormatTraits_PAL8,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal,
                bitsPerPixel[nScanlineFormat] );



        // sixteen bit formats

        case Format::SixteenBitLsbTcMask:
            return createRenderer<PixelFormatTraits_RGB16_565_LSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::SixteenBitMsbTcMask:
            return createRenderer<PixelFormatTraits_RGB16_565_MSB,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        // twentyfour bit formats
        case Format::TwentyFourBitTcMask:
            return createRenderer<PixelFormatTraits_BGR24,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        // thirtytwo bit formats

        case Format::ThirtyTwoBitTcMaskBGRA:
            return createRenderer<PixelFormatTraits_BGRA32_8888,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::ThirtyTwoBitTcMaskARGB:
            return createRenderer<PixelFormatTraits_ARGB32_8888,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::ThirtyTwoBitTcMaskABGR:
            return createRenderer<PixelFormatTraits_ABGR32_8888,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        case Format::ThirtyTwoBitTcMaskRGBA:
            return createRenderer<PixelFormatTraits_RGBA32_8888,StdMasks>(
                aBounds, rSize, nScanlineFormat, nScanlineStride,
                pFirstScanline, pMem, pPal );

        default:
            assert(false); // this cannot happen
    }

    // TODO(F3): other formats not yet implemented
    return BitmapDeviceSharedPtr();
}

BitmapDeviceSharedPtr createBitmapDeviceImpl( const basegfx::B2IVector&                  rSize,
                                              Format                                     nScanlineFormat,
                                              boost::shared_array< sal_uInt8 >           pMem,
                                              PaletteMemorySharedVector                  pPal,
                                              const basegfx::B2IBox*                     pSubset,
                                              bool bBlack = true)
{
    BitmapDeviceSharedPtr result( createBitmapDeviceImplInner( rSize, nScanlineFormat, pMem, pPal, pSubset, bBlack ) );

#ifdef SAL_LOG_INFO
    std::ostringstream subset;

    if (pSubset)
        subset << " subset=" << pSubset->getWidth() << "x" << pSubset->getHeight() << "@(" << pSubset->getMinX() << "," << pSubset->getMinY() << ")";

    SAL_INFO( "basebmp.bitmapdevice",
              "createBitmapDevice: "
              << rSize.getX() << "x" << rSize.getY()
              << subset.str()
              << " = " << result.get() );
#endif
    return result;
}
} // namespace

sal_Int32 getBitmapDeviceStrideForWidth(Format nScanlineFormat, sal_Int32 nWidth)
{
    sal_uInt8 nBitsPerPixel = bitsPerPixel[nScanlineFormat];
    // round up to full 8 bit, divide by 8
    sal_Int32 nScanlineStride = (nWidth*nBitsPerPixel + 7) >> 3;

    // pixman (cairo) and GDI (windows) pad to multiples of 32bits
    // so do the same to be easily compatible
    nScanlineStride = (nScanlineStride + 3) & ~0x3;

    return nScanlineStride;
}

BitmapDeviceSharedPtr createBitmapDevice( const basegfx::B2IVector& rSize,
                                          Format                    nScanlineFormat )
{
    return createBitmapDeviceImpl( rSize,
                                   nScanlineFormat,
                                   boost::shared_array< sal_uInt8 >(),
                                   PaletteMemorySharedVector(),
                                   nullptr );
}

BitmapDeviceSharedPtr createBitmapDevice( const basegfx::B2IVector&        rSize,
                                          Format                           nScanlineFormat,
                                          const PaletteMemorySharedVector& rPalette )
{
    return createBitmapDeviceImpl( rSize,
                                   nScanlineFormat,
                                   boost::shared_array< sal_uInt8 >(),
                                   rPalette,
                                   nullptr );
}

BitmapDeviceSharedPtr createBitmapDevice( const basegfx::B2IVector&        rSize,
                                          Format                           nScanlineFormat,
                                          const RawMemorySharedArray&      rMem,
                                          const PaletteMemorySharedVector& rPalette )
{
    return createBitmapDeviceImpl( rSize,
                                   nScanlineFormat,
                                   rMem,
                                   rPalette,
                                   nullptr );
}

BitmapDeviceSharedPtr cloneBitmapDevice( const basegfx::B2IVector&    rSize,
                                         const BitmapDeviceSharedPtr& rProto )
{
    return createBitmapDeviceImpl( rSize,
                                   rProto->getScanlineFormat(),
                                   boost::shared_array< sal_uInt8 >(),
                                   rProto->getPalette(),
                                   nullptr );
}


/// Clone our device, with GenericImageAccessor to handle all formats
BitmapDeviceSharedPtr BitmapDevice::getGenericRenderer() const
{
    return mpImpl->mpGenericRenderer;
}

} // namespace basebmp

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