summaryrefslogtreecommitdiff
path: root/slideshow/source/engine/shapes/viewshape.cxx
blob: 2462ae35aff9fd73bebf4b2f40324793123d2b95 (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
/* -*- 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 <o3tl/clamp.hxx>
#include <tools/diagnose_ex.h>

#include <math.h>

#include <rtl/math.hxx>
#include <sal/log.hxx>

#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/PanoseLetterForm.hpp>
#include <com/sun/star/awt/FontSlant.hpp>

#include <cppuhelper/exc_hlp.hxx>

#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/matrix/b2dhommatrixtools.hxx>

#include <canvas/canvastools.hxx>
#include <cppcanvas/vclfactory.hxx>
#include <cppcanvas/basegfxfactory.hxx>

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

using namespace ::com::sun::star;

namespace slideshow
{
    namespace internal
    {

        // TODO(F2): Provide sensible setup for mtf-related attributes (fill mode,
        // char rotation etc.). Do that via mtf argument at this object

        bool ViewShape::prefetch( RendererCacheEntry&                   io_rCacheEntry,
                                  const ::cppcanvas::CanvasSharedPtr&   rDestinationCanvas,
                                  const GDIMetaFileSharedPtr&           rMtf,
                                  const ShapeAttributeLayerSharedPtr&   rAttr )
        {
            ENSURE_OR_RETURN_FALSE( rMtf,
                               "ViewShape::prefetch(): no valid metafile!" );

            if( rMtf != io_rCacheEntry.mpMtf ||
                rDestinationCanvas != io_rCacheEntry.getDestinationCanvas() )
            {
                // buffered renderer invalid, re-create
                ::cppcanvas::Renderer::Parameters aParms;

                // rendering attribute override parameter struct.  For
                // every valid attribute, the corresponding struct
                // member is filled, which in the metafile renderer
                // forces rendering with the given attribute.
                if( rAttr )
                {
                    if( rAttr->isFillColorValid() )
                    {
                        // convert RGBColor to RGBA32 integer. Note
                        // that getIntegerColor() also truncates
                        // out-of-range values appropriately
                        aParms.maFillColor =
                            rAttr->getFillColor().getIntegerColor();
                    }
                    if( rAttr->isLineColorValid() )
                    {
                        // convert RGBColor to RGBA32 integer. Note
                        // that getIntegerColor() also truncates
                        // out-of-range values appropriately
                        aParms.maLineColor =
                            rAttr->getLineColor().getIntegerColor();
                    }
                    if( rAttr->isCharColorValid() )
                    {
                        // convert RGBColor to RGBA32 integer. Note
                        // that getIntegerColor() also truncates
                        // out-of-range values appropriately
                        aParms.maTextColor =
                            rAttr->getCharColor().getIntegerColor();
                    }
                    if( rAttr->isDimColorValid() )
                    {
                        // convert RGBColor to RGBA32 integer. Note
                        // that getIntegerColor() also truncates
                        // out-of-range values appropriately

                        // dim color overrides all other colors
                        aParms.maFillColor =
                        aParms.maLineColor =
                        aParms.maTextColor =
                            rAttr->getDimColor().getIntegerColor();
                    }
                    if( rAttr->isFontFamilyValid() )
                    {
                        aParms.maFontName =
                            rAttr->getFontFamily();
                    }
                    if( rAttr->isCharScaleValid() )
                    {
                        ::basegfx::B2DHomMatrix aMatrix;

                        // enlarge text by given scale factor. Do that
                        // with the middle of the shape as the center
                        // of scaling.
                        aMatrix.translate( -0.5, -0.5 );
                        aMatrix.scale( rAttr->getCharScale(),
                                       rAttr->getCharScale() );
                        aMatrix.translate( 0.5, 0.5 );

                        aParms.maTextTransformation = aMatrix;
                    }
                    if( rAttr->isCharWeightValid() )
                    {
                        aParms.maFontWeight =
                            static_cast< sal_Int8 >(
                                ::basegfx::fround(
                                    ::std::max( 0.0,
                                                ::std::min( 11.0,
                                                            rAttr->getCharWeight() / 20.0 ) ) ) );
                    }
                    if( rAttr->isCharPostureValid() )
                    {
                        aParms.maFontLetterForm =
                            rAttr->getCharPosture() == sal_Int16(awt::FontSlant_NONE) ?
                            rendering::PanoseLetterForm::ANYTHING :
                            rendering::PanoseLetterForm::OBLIQUE_CONTACT;
                    }
                    if( rAttr->isUnderlineModeValid() )
                    {
                        aParms.maFontUnderline =
                            rAttr->getUnderlineMode();
                    }
                }

                io_rCacheEntry.mpRenderer = ::cppcanvas::VCLFactory::createRenderer( rDestinationCanvas,
                                                                                     *rMtf.get(),
                                                                                     aParms );

                io_rCacheEntry.mpMtf               = rMtf;
                io_rCacheEntry.mpDestinationCanvas = rDestinationCanvas;

                // also invalidate alpha compositing bitmap (created
                // new renderer, which possibly generates different
                // output). Do NOT invalidate, if we're incidentally
                // rendering INTO it.
                if( rDestinationCanvas != io_rCacheEntry.mpLastBitmapCanvas )
                {
                    io_rCacheEntry.mpLastBitmapCanvas.reset();
                    io_rCacheEntry.mpLastBitmap.reset();
                }
            }

            return static_cast< bool >(io_rCacheEntry.mpRenderer);
        }

        bool ViewShape::draw( const ::cppcanvas::CanvasSharedPtr&   rDestinationCanvas,
                              const GDIMetaFileSharedPtr&           rMtf,
                              const ShapeAttributeLayerSharedPtr&   rAttr,
                              const ::basegfx::B2DHomMatrix&        rTransform,
                              const ::basegfx::B2DPolyPolygon*      pClip,
                              const VectorOfDocTreeNodes&           rSubsets ) const
        {
            ::cppcanvas::RendererSharedPtr pRenderer(
                getRenderer( rDestinationCanvas, rMtf, rAttr ) );

            ENSURE_OR_RETURN_FALSE( pRenderer, "ViewShape::draw(): Invalid renderer" );

            pRenderer->setTransformation( rTransform );
#if OSL_DEBUG_LEVEL >= 2
            rendering::RenderState aRenderState;
            ::canvas::tools::initRenderState(aRenderState);
            ::canvas::tools::setRenderStateTransform(aRenderState,
                                                     rTransform);
            aRenderState.DeviceColor.realloc(4);
            aRenderState.DeviceColor[0] = 1.0;
            aRenderState.DeviceColor[1] = 0.0;
            aRenderState.DeviceColor[2] = 0.0;
            aRenderState.DeviceColor[3] = 1.0;

            try
            {
                rDestinationCanvas->getUNOCanvas()->drawLine( geometry::RealPoint2D(0.0,0.0),
                                                              geometry::RealPoint2D(1.0,1.0),
                                                              rDestinationCanvas->getViewState(),
                                                              aRenderState );
                rDestinationCanvas->getUNOCanvas()->drawLine( geometry::RealPoint2D(1.0,0.0),
                                                              geometry::RealPoint2D(0.0,1.0),
                                                              rDestinationCanvas->getViewState(),
                                                              aRenderState );
            }
            catch( uno::Exception& )
            {
                DBG_UNHANDLED_EXCEPTION("slideshow");
            }
#endif
            if( pClip )
                pRenderer->setClip( *pClip );
            else
                pRenderer->setClip();

            if( rSubsets.empty() )
            {
                return pRenderer->draw();
            }
            else
            {
                // render subsets of whole metafile


                bool bRet(true);
                for( const auto& rSubset : rSubsets )
                {
                    if( !pRenderer->drawSubset( rSubset.getStartIndex(),
                                                rSubset.getEndIndex() ) )
                        bRet = false;
                }

                return bRet;
            }
        }

        namespace
        {
            /// Convert untransformed shape update area to device pixel.
            ::basegfx::B2DRectangle shapeArea2AreaPixel( const ::basegfx::B2DHomMatrix& rCanvasTransformation,
                                                         const ::basegfx::B2DRectangle& rUntransformedArea      )
            {
                // convert area to pixel, and add anti-aliasing border

                // TODO(P1): Should the view transform some
                // day contain rotation/shear, transforming
                // the original bounds with the total
                // transformation might result in smaller
                // overall bounds.

                ::basegfx::B2DRectangle aBoundsPixel;
                ::canvas::tools::calcTransformedRectBounds( aBoundsPixel,
                                                            rUntransformedArea,
                                                            rCanvasTransformation );

                // add antialiasing border around the shape (AA
                // touches pixel _outside_ the nominal bound rect)
                aBoundsPixel.grow( ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE );

                return aBoundsPixel;
            }

            /// Convert shape unit rect to device pixel.
            ::basegfx::B2DRectangle calcUpdateAreaPixel( const ::basegfx::B2DRectangle&         rUnitBounds,
                                                         const ::basegfx::B2DHomMatrix&         rShapeTransformation,
                                                         const ::basegfx::B2DHomMatrix&         rCanvasTransformation,
                                                         const ShapeAttributeLayerSharedPtr&    pAttr                   )
            {
                // calc update area for whole shape (including
                // character scaling)
                return shapeArea2AreaPixel( rCanvasTransformation,
                                            getShapeUpdateArea( rUnitBounds,
                                                                rShapeTransformation,
                                                                pAttr ) );
            }
        }

        bool ViewShape::renderSprite( const ViewLayerSharedPtr&             rViewLayer,
                                      const GDIMetaFileSharedPtr&           rMtf,
                                      const ::basegfx::B2DRectangle&        rOrigBounds,
                                      const ::basegfx::B2DRectangle&        rBounds,
                                      const ::basegfx::B2DRectangle&        rUnitBounds,
                                      UpdateFlags                           nUpdateFlags,
                                      const ShapeAttributeLayerSharedPtr&   pAttr,
                                      const VectorOfDocTreeNodes&           rSubsets,
                                      double                                nPrio,
                                      bool                                  bIsVisible ) const
        {
            // TODO(P1): For multiple views, it might pay off to reorg Shape and ViewShape,
            // in that all the common setup steps here are refactored to Shape (would then
            // have to be performed only _once_ per Shape paint).

            if( !bIsVisible ||
                rUnitBounds.isEmpty() ||
                rOrigBounds.isEmpty() ||
                rBounds.isEmpty() )
            {
                // shape is invisible or has zero size, no need to
                // update anything.
                if( mpSprite )
                    mpSprite->hide();

                return true;
            }


            // calc sprite position, size and content transformation
            // =====================================================

            // the shape transformation for a sprite is always a
            // simple scale-up to the nominal shape size. Everything
            // else is handled via the sprite transformation
            ::basegfx::B2DHomMatrix aNonTranslationalShapeTransformation;
            aNonTranslationalShapeTransformation.scale( rOrigBounds.getWidth(),
                                                        rOrigBounds.getHeight() );
            ::basegfx::B2DHomMatrix aShapeTransformation( aNonTranslationalShapeTransformation );
            aShapeTransformation.translate( rOrigBounds.getMinX(),
                                            rOrigBounds.getMinY() );

            const ::basegfx::B2DHomMatrix& rCanvasTransform(
                rViewLayer->getSpriteTransformation() );

            // area actually needed for the sprite
            const ::basegfx::B2DRectangle& rSpriteBoundsPixel(
                calcUpdateAreaPixel( rUnitBounds,
                                     aShapeTransformation,
                                     rCanvasTransform,
                                     pAttr ) );

            // actual area for the shape (without subsetting, but
            // including char scaling)
            const ::basegfx::B2DRectangle& rShapeBoundsPixel(
                calcUpdateAreaPixel( ::basegfx::B2DRectangle(0.0,0.0,1.0,1.0),
                                     aShapeTransformation,
                                     rCanvasTransform,
                                     pAttr ) );

            // nominal area for the shape (without subsetting, without
            // char scaling). NOTE: to cancel the shape translation,
            // contained in rSpriteBoundsPixel, this is _without_ any
            // translational component.
            ::basegfx::B2DRectangle        aLogShapeBounds;
            const ::basegfx::B2DRectangle& rNominalShapeBoundsPixel(
                shapeArea2AreaPixel( rCanvasTransform,
                                     ::canvas::tools::calcTransformedRectBounds(
                                         aLogShapeBounds,
                                         ::basegfx::B2DRectangle(0.0,0.0,1.0,1.0),
                                         aNonTranslationalShapeTransformation ) ) );

            // create (or resize) sprite with sprite's pixel size, if
            // not done already
            const ::basegfx::B2DSize& rSpriteSizePixel(rSpriteBoundsPixel.getRange());
            if( !mpSprite )
            {
                mpSprite.reset(
                    new AnimatedSprite( mpViewLayer,
                                        rSpriteSizePixel,
                                        nPrio ));
            }
            else
            {
                // TODO(F2): when the sprite _actually_ gets resized,
                // content needs a repaint!
                mpSprite->resize( rSpriteSizePixel );
            }

            ENSURE_OR_RETURN_FALSE( mpSprite, "ViewShape::renderSprite(): No sprite" );

            SAL_INFO("slideshow", "ViewShape::renderSprite(): Rendering sprite " <<
                           mpSprite.get() );


            // always show the sprite (might have been hidden before)
            mpSprite->show();

            // determine center of sprite output position in pixel
            // (assumption here: all shape transformations have the
            // shape center as the pivot point). From that, subtract
            // distance of rSpriteBoundsPixel's left, top edge from
            // rShapeBoundsPixel's center. This moves the sprite at
            // the appropriate output position within the virtual
            // rShapeBoundsPixel area.
            ::basegfx::B2DPoint aSpritePosPixel( rBounds.getCenter() );
            aSpritePosPixel *= rCanvasTransform;
            aSpritePosPixel -= rShapeBoundsPixel.getCenter() - rSpriteBoundsPixel.getMinimum();

            // the difference between rShapeBoundsPixel and
            // rSpriteBoundsPixel upper, left corner is: the offset we
            // have to move sprite output to the right, top (to make
            // the desired subset content visible at all)
            const ::basegfx::B2DSize& rSpriteCorrectionOffset(
                rSpriteBoundsPixel.getMinimum() - rNominalShapeBoundsPixel.getMinimum() );

            // offset added top, left for anti-aliasing (otherwise,
            // shapes fully filling the sprite will have anti-aliased
            // pixel cut off)
            const ::basegfx::B2DSize aAAOffset(
                ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE,
                ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE );

            // set pixel output offset to sprite: we always leave
            // ANTIALIASING_EXTRA_SIZE room atop and to the left, and,
            // what's more, for subsetted shapes, we _have_ to cancel
            // the effect of the shape renderer outputting the subset
            // at its absolute position inside the shape, instead of
            // at the origin.
            // NOTE: As for now, sprites are always positioned on
            // integer pixel positions on screen, have to round to
            // nearest integer here, too
            mpSprite->setPixelOffset(
                aAAOffset - ::basegfx::B2DSize(
                    ::basegfx::fround( rSpriteCorrectionOffset.getX() ),
                    ::basegfx::fround( rSpriteCorrectionOffset.getY() ) ) );

            // always set sprite position and transformation, since
            // they do not relate directly to the update flags
            // (e.g. sprite position changes when sprite size changes)
            mpSprite->movePixel( aSpritePosPixel );
            mpSprite->transform( getSpriteTransformation( rSpriteSizePixel,
                                                          rOrigBounds.getRange(),
                                                          pAttr ) );


            // process flags
            // =============

            bool bRedrawRequired( mbForceUpdate || (nUpdateFlags & UpdateFlags::Force) );

            if( mbForceUpdate || (nUpdateFlags & UpdateFlags::Alpha) )
            {
                mpSprite->setAlpha( (pAttr && pAttr->isAlphaValid()) ?
                                    o3tl::clamp(pAttr->getAlpha(),
                                                     0.0,
                                                     1.0) :
                                    1.0 );
            }
            if( mbForceUpdate || (nUpdateFlags & UpdateFlags::Clip) )
            {
                if( pAttr && pAttr->isClipValid() )
                {
                    ::basegfx::B2DPolyPolygon aClipPoly( pAttr->getClip() );

                    // extract linear part of canvas view transformation
                    // (linear means: without translational components)
                    ::basegfx::B2DHomMatrix aViewTransform(
                        mpViewLayer->getTransformation() );
                    aViewTransform.set( 0, 2, 0.0 );
                    aViewTransform.set( 1, 2, 0.0 );

                    // make the clip 2*ANTIALIASING_EXTRA_SIZE larger
                    // such that it's again centered over the sprite.
                    aViewTransform.scale(rSpriteSizePixel.getX()/
                                         (rSpriteSizePixel.getX()-2*::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE),
                                         rSpriteSizePixel.getY()/
                                         (rSpriteSizePixel.getY()-2*::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE));

                    // transform clip polygon from view to device
                    // coordinate space
                    aClipPoly.transform( aViewTransform );

                    mpSprite->clip( aClipPoly );
                }
                else
                    mpSprite->clip();
            }
            if( mbForceUpdate || (nUpdateFlags & UpdateFlags::Content) )
            {
                bRedrawRequired = true;

                // TODO(P1): maybe provide some appearance change methods at
                // the Renderer interface

                // force the renderer to be regenerated below, for the
                // different attributes to take effect
                invalidateRenderer();
            }

            mbForceUpdate = false;

            if( !bRedrawRequired )
                return true;


            // sprite needs repaint - output to sprite canvas
            // ==============================================

            ::cppcanvas::CanvasSharedPtr pContentCanvas( mpSprite->getContentCanvas() );

            return draw( pContentCanvas,
                         rMtf,
                         pAttr,
                         aShapeTransformation,
                         nullptr, // clipping is done via Sprite::clip()
                         rSubsets );
        }

        bool ViewShape::render( const ::cppcanvas::CanvasSharedPtr& rDestinationCanvas,
                                const GDIMetaFileSharedPtr&         rMtf,
                                const ::basegfx::B2DRectangle&      rBounds,
                                const ::basegfx::B2DRectangle&      rUpdateBounds,
                                UpdateFlags                         nUpdateFlags,
                                const ShapeAttributeLayerSharedPtr& pAttr,
                                const VectorOfDocTreeNodes&         rSubsets,
                                bool                                bIsVisible ) const
        {
            // TODO(P1): For multiple views, it might pay off to reorg Shape and ViewShape,
            // in that all the common setup steps here are refactored to Shape (would then
            // have to be performed only _once_ per Shape paint).

            if( !bIsVisible )
            {
                SAL_INFO("slideshow", "ViewShape::render(): skipping shape " << this );

                // shape is invisible, no need to update anything.
                return true;
            }

            // since we have no sprite here, _any_ update request
            // translates into a required redraw.
            bool bRedrawRequired( mbForceUpdate || nUpdateFlags != UpdateFlags::NONE );

            if( nUpdateFlags & UpdateFlags::Content )
            {
                // TODO(P1): maybe provide some appearance change methods at
                // the Renderer interface

                // force the renderer to be regenerated below, for the
                // different attributes to take effect
                invalidateRenderer();
            }

            mbForceUpdate = false;

            if( !bRedrawRequired )
                return true;

            SAL_INFO( "slideshow", "ViewShape::render(): rendering shape " <<
                      this <<
                      " at position (" <<
                      rBounds.getMinX() << "," <<
                      rBounds.getMinY() << ")" );


            // shape needs repaint - setup all that's needed


            boost::optional<basegfx::B2DPolyPolygon> aClip;

            if( pAttr )
            {
                // setup clip poly
                if( pAttr->isClipValid() )
                    aClip = pAttr->getClip();

                // emulate global shape alpha by first rendering into
                // a temp bitmap, and then to screen (this would have
                // been much easier if we'd be currently a sprite -
                // see above)
                if( pAttr->isAlphaValid() )
                {
                    const double nAlpha( pAttr->getAlpha() );

                    if( !::basegfx::fTools::equalZero( nAlpha ) &&
                        !::rtl::math::approxEqual(nAlpha, 1.0) )
                    {
                        // render with global alpha - have to prepare
                        // a bitmap, and render that with modulated
                        // alpha


                        const ::basegfx::B2DHomMatrix aTransform(
                            getShapeTransformation( rBounds,
                                                    pAttr ) );

                        // TODO(P1): Should the view transform some
                        // day contain rotation/shear, transforming
                        // the original bounds with the total
                        // transformation might result in smaller
                        // overall bounds.

                        // determine output rect of _shape update
                        // area_ in device pixel
                        const ::basegfx::B2DHomMatrix aCanvasTransform(
                            rDestinationCanvas->getTransformation() );
                        ::basegfx::B2DRectangle aTmpRect;
                        ::canvas::tools::calcTransformedRectBounds( aTmpRect,
                                                                    rUpdateBounds,
                                                                    aCanvasTransform );

                        // pixel size of cache bitmap: round up to
                        // nearest int
                        const ::basegfx::B2ISize aBmpSize( static_cast<sal_Int32>( aTmpRect.getWidth() )+1,
                                                           static_cast<sal_Int32>( aTmpRect.getHeight() )+1 );

                        // try to fetch temporary surface for alpha
                        // compositing (to achieve the global alpha
                        // blend effect, have to first render shape as
                        // a whole, then blit that surface with global
                        // alpha to the destination)
                        const RendererCacheVector::iterator aCompositingSurface(
                            getCacheEntry( rDestinationCanvas ) );

                        if( !aCompositingSurface->mpLastBitmapCanvas ||
                            aCompositingSurface->mpLastBitmapCanvas->getSize() != aBmpSize )
                        {
                            // create a bitmap of appropriate size
                            ::cppcanvas::BitmapSharedPtr pBitmap(
                                ::cppcanvas::BaseGfxFactory::createAlphaBitmap(
                                    rDestinationCanvas,
                                    aBmpSize ) );

                            ENSURE_OR_THROW(pBitmap,
                                             "ViewShape::render(): Could not create compositing surface");

                            aCompositingSurface->mpDestinationCanvas = rDestinationCanvas;
                            aCompositingSurface->mpLastBitmap        = pBitmap;
                            aCompositingSurface->mpLastBitmapCanvas  = pBitmap->getBitmapCanvas();
                        }

                        // buffer aCompositingSurface iterator content
                        // - said one might get invalidated during
                        // draw() below.
                        ::cppcanvas::BitmapCanvasSharedPtr pBitmapCanvas(
                            aCompositingSurface->mpLastBitmapCanvas );

                        ::cppcanvas::BitmapSharedPtr pBitmap(
                            aCompositingSurface->mpLastBitmap);

                        // setup bitmap canvas transformation -
                        // which happens to be the destination
                        // canvas transformation without any
                        // translational components.

                        // But then, the render transformation as
                        // calculated by getShapeTransformation()
                        // above outputs the shape at its real
                        // destination position. Thus, we have to
                        // offset the output back to the origin,
                        // for which we simply plug in the
                        // negative position of the left, top edge
                        // of the shape's bound rect in device
                        // pixel into aLinearTransform below.
                        ::basegfx::B2DHomMatrix aAdjustedCanvasTransform( aCanvasTransform );
                        aAdjustedCanvasTransform.translate( -aTmpRect.getMinX(),
                                                            -aTmpRect.getMinY() );

                        pBitmapCanvas->setTransformation( aAdjustedCanvasTransform );

                        // TODO(P2): If no update flags, or only
                        // alpha_update is set, we can save us the
                        // rendering into the bitmap (uh, it's not
                        // _that_ easy - for a forced redraw,
                        // e.g. when ending an animation, we always
                        // get UPDATE_FORCE here).

                        // render into this bitmap
                        if( !draw( pBitmapCanvas,
                                   rMtf,
                                   pAttr,
                                   aTransform,
                                   !aClip ? nullptr : &(*aClip),
                                   rSubsets ) )
                        {
                            return false;
                        }

                        // render bitmap to screen, with given global
                        // alpha. Since the bitmap already contains
                        // pixel-equivalent output, we have to use the
                        // inverse view transformation, adjusted with
                        // the final shape output position (note:
                        // cannot simply change the view
                        // transformation here, as that would affect a
                        // possibly set clip!)
                        ::basegfx::B2DHomMatrix aBitmapTransform( aCanvasTransform );
                        OSL_ENSURE( aBitmapTransform.isInvertible(),
                                    "ViewShape::render(): View transformation is singular!" );

                        aBitmapTransform.invert();

                        const basegfx::B2DHomMatrix aTranslation(basegfx::utils::createTranslateB2DHomMatrix(
                            aTmpRect.getMinX(), aTmpRect.getMinY()));

                        aBitmapTransform = aBitmapTransform * aTranslation;
                        pBitmap->setTransformation( aBitmapTransform );

                        // finally, render bitmap alpha-modulated
                        pBitmap->drawAlphaModulated( nAlpha );

                        return true;
                    }
                }
            }

            // retrieve shape transformation, _with_ shape translation
            // to actual page position.
            const ::basegfx::B2DHomMatrix aTransform(
                getShapeTransformation( rBounds,
                                        pAttr ) );

            return draw( rDestinationCanvas,
                         rMtf,
                         pAttr,
                         aTransform,
                         !aClip ? nullptr : &(*aClip),
                         rSubsets );
        }


        ViewShape::ViewShape( const ViewLayerSharedPtr& rViewLayer ) :
            mpViewLayer( rViewLayer ),
            maRenderers(),
            mpSprite(),
            mbAnimationMode( false ),
            mbForceUpdate( true )
        {
            ENSURE_OR_THROW( mpViewLayer, "ViewShape::ViewShape(): Invalid View" );
        }

        const ViewLayerSharedPtr& ViewShape::getViewLayer() const
        {
            return mpViewLayer;
        }

        ViewShape::RendererCacheVector::iterator ViewShape::getCacheEntry( const ::cppcanvas::CanvasSharedPtr&  rDestinationCanvas ) const
        {
            // lookup destination canvas - is there already a renderer
            // created for that target?
            RendererCacheVector::iterator       aIter;
            const RendererCacheVector::iterator aEnd( maRenderers.end() );

            // already there?
            if( (aIter=::std::find_if( maRenderers.begin(),
                                       aEnd,
                                       [&rDestinationCanvas]( const RendererCacheEntry& rCacheEntry )
                                       { return rDestinationCanvas == rCacheEntry.getDestinationCanvas(); } ) ) == aEnd )
            {
                if( maRenderers.size() >= MAX_RENDER_CACHE_ENTRIES )
                {
                    // cache size exceeded - prune entries. For now,
                    // simply remove the first one, which of course
                    // breaks for more complex access schemes. But in
                    // general, this leads to most recently used
                    // entries to reside at the end of the vector.
                    maRenderers.erase( maRenderers.begin() );

                    // ATTENTION: after this, both aIter and aEnd are
                    // invalid!
                }

                // not yet in cache - add default-constructed cache
                // entry, to have something to return
                maRenderers.emplace_back( );
                aIter = maRenderers.end()-1;
            }

            return aIter;
        }

        ::cppcanvas::RendererSharedPtr ViewShape::getRenderer( const ::cppcanvas::CanvasSharedPtr&  rDestinationCanvas,
                                                               const GDIMetaFileSharedPtr&          rMtf,
                                                               const ShapeAttributeLayerSharedPtr&  rAttr ) const
        {
            // lookup destination canvas - is there already a renderer
            // created for that target?
            const RendererCacheVector::iterator aIter(
                getCacheEntry( rDestinationCanvas ) );

            // now we have a valid entry, either way. call prefetch()
            // on it, nevertheless - maybe the metafile changed, and
            // the renderer still needs an update (prefetch() will
            // detect that)
            if( prefetch( *aIter,
                          rDestinationCanvas,
                          rMtf,
                          rAttr ) )
            {
                return aIter->mpRenderer;
            }
            else
            {
                // prefetch failed - renderer is invalid
                return ::cppcanvas::RendererSharedPtr();
            }
        }

        void ViewShape::invalidateRenderer() const
        {
            // simply clear the cache. Subsequent getRenderer() calls
            // will regenerate the Renderers.
            maRenderers.clear();
        }

        ::basegfx::B2DSize ViewShape::getAntialiasingBorder() const
        {
            ENSURE_OR_THROW( mpViewLayer->getCanvas(),
                              "ViewShape::getAntialiasingBorder(): Invalid ViewLayer canvas" );

            const ::basegfx::B2DHomMatrix& rViewTransform(
                mpViewLayer->getTransformation() );

            // TODO(F1): As a quick shortcut (did not want to invert
            // whole matrix here), taking only scale components of
            // view transformation matrix. This will be wrong when
            // e.g. shearing is involved.
            const double nXBorder( ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE / rViewTransform.get(0,0) );
            const double nYBorder( ::cppcanvas::Canvas::ANTIALIASING_EXTRA_SIZE / rViewTransform.get(1,1) );

            return ::basegfx::B2DSize( nXBorder,
                                       nYBorder );
        }

        void ViewShape::enterAnimationMode()
        {
            mbForceUpdate   = true;
            mbAnimationMode = true;
        }

        void ViewShape::leaveAnimationMode()
        {
            mpSprite.reset();
            mbAnimationMode = false;
            mbForceUpdate   = true;
        }

        bool ViewShape::update( const GDIMetaFileSharedPtr& rMtf,
                                const RenderArgs&           rArgs,
                                UpdateFlags                 nUpdateFlags,
                                bool                        bIsVisible ) const
        {
            ENSURE_OR_RETURN_FALSE( mpViewLayer->getCanvas(), "ViewShape::update(): Invalid layer canvas" );

            // Shall we render to a sprite, or to a plain canvas?
            if( mbAnimationMode )
                return renderSprite( mpViewLayer,
                                     rMtf,
                                     rArgs.maOrigBounds,
                                     rArgs.maBounds,
                                     rArgs.maUnitBounds,
                                     nUpdateFlags,
                                     rArgs.mrAttr,
                                     rArgs.mrSubsets,
                                     rArgs.mnShapePriority,
                                     bIsVisible );
            else
                return render( mpViewLayer->getCanvas(),
                               rMtf,
                               rArgs.maBounds,
                               rArgs.maUpdateBounds,
                               nUpdateFlags,
                               rArgs.mrAttr,
                               rArgs.mrSubsets,
                               bIsVisible );
        }

    }
}

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