KoShape.cpp 35.9 KB
Newer Older
Thomas Zander's avatar
Thomas Zander committed
1
/* This file is part of the KDE project
Thomas Zander's avatar
Thomas Zander committed
2
   Copyright (C) 2006 Casper Boemann Rasmussen <cbr@boemann.dk>
3
   Copyright (C) 2006-2007 Thomas Zander <zander@kde.org>
4
   Copyright (C) 2006-2008 Thorsten Zachmann <zachmann@kde.org>
5
   Copyright (C) 2007 Jan Hambrecht <jaham@gmx.net>
Thomas Zander's avatar
Thomas Zander committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "KoShape.h"
#include "KoShapeContainer.h"
25
#include "KoShapeLayer.h"
26
#include "KoShapeContainerModel.h"
Thomas Zander's avatar
Thomas Zander committed
27
#include "KoSelection.h"
28
#include "KoPointerEvent.h"
Thomas Zander's avatar
Thomas Zander committed
29 30
#include "KoInsets.h"
#include "KoShapeBorderModel.h"
31 32 33 34
#include "KoShapeBackground.h"
#include "KoColorBackground.h"
#include "KoGradientBackground.h"
#include "KoPatternBackground.h"
35
#include "KoShapeManager.h"
36
#include "KoShapeUserData.h"
37
#include "KoShapeApplicationData.h"
38
#include "KoShapeSavingContext.h"
39
#include "KoShapeLoadingContext.h"
40
#include "KoViewConverter.h"
41
#include "KoLineBorder.h"
42
#include "ShapeDeleter_p.h"
43
#include "KoShapeStyleWriter.h"
44
#include "KoShapeShadow.h"
Thorsten Zachmann's avatar
Thorsten Zachmann committed
45 46
#include "KoEventAction.h"
#include "KoEventActionRegistry.h"
Thomas Zander's avatar
Thomas Zander committed
47

48
#include <KoXmlReader.h>
49
#include <KoXmlWriter.h>
50
#include <KoXmlNS.h>
51
#include <KoGenStyle.h>
52
#include <KoGenStyles.h>
53
#include <KoUnit.h>
54
#include <KoOdfStylesReader.h>
55
#include <KoOdfGraphicStyles.h>
56
#include <KoOdfLoadingContext.h>
57

Thomas Zander's avatar
Thomas Zander committed
58
#include <QPainter>
59
#include <QVariant>
Thomas Zander's avatar
Thomas Zander committed
60
#include <QPainterPath>
61
#include <QList>
62
#include <QMap>
63
#include <QByteArray>
Thomas Zander's avatar
Thomas Zander committed
64

65 66
#include <kdebug.h>

67 68
#include <limits>

69
class KoShape::Private {
Thomas Zander's avatar
Thomas Zander committed
70
public:
71
    Private(KoShape *shape)
72
        : size( 50, 50 ),
Thomas Zander's avatar
Thomas Zander committed
73 74 75
        zIndex( 0 ),
        parent( 0 ),
        visible( true ),
76
        printable( true ),
Thomas Zander's avatar
Thomas Zander committed
77 78 79 80 81
        locked( false ),
        keepAspect( false ),
        selectable( true ),
        detectCollision( false ),
        userData(0),
82
        appData(0),
83
        fill(0),
84
        border(0),
85 86
        me(shape),
        shadow(0)
Thomas Zander's avatar
Thomas Zander committed
87 88 89
    {
    }

90
    ~Private() {
91 92
        if( parent )
            parent->removeChild( me );
93 94
        foreach(KoShapeManager *manager, shapeManagers)
            manager->remove(me);
Thomas Zander's avatar
Thomas Zander committed
95 96
        delete userData;
        delete appData;
97 98 99 100 101
        if(border) {
            border->removeUser();
            if(border->useCount() == 0)
                delete border;
        }
102 103
        if( shadow && shadow->removeUser() == 0 )
            delete shadow;
104 105
        if( fill && fill->removeUser() == 0 )
            delete fill;
Thorsten Zachmann's avatar
Thorsten Zachmann committed
106
        qDeleteAll( eventActions );
Thomas Zander's avatar
Thomas Zander committed
107 108
    }

109 110 111 112
    void shapeChanged(ChangeType type) {
        if(parent)
            parent->model()->childChanged(me, type);
        me->shapeChanged(type);
113 114
        foreach( KoShape * shape, dependees )
            shape->notifyShapeChanged( me, type );
115 116
    }

Thomas Zander's avatar
Thomas Zander committed
117 118
    QSizeF size; // size in pt
    QString shapeId;
119
    QString name; ///< the shapes names
Thomas Zander's avatar
Thomas Zander committed
120

121
    QMatrix localMatrix; ///< the shapes local transformation matrix
Thomas Zander's avatar
Thomas Zander committed
122 123 124 125 126 127 128

    QVector<QPointF> connectors; // in pt

    int zIndex;
    KoShapeContainer *parent;

    bool visible;
129
    bool printable;
Thomas Zander's avatar
Thomas Zander committed
130 131 132 133 134 135 136 137
    bool locked;
    bool keepAspect;
    bool selectable;
    bool detectCollision;

    QSet<KoShapeManager *> shapeManagers;
    KoShapeUserData *userData;
    KoShapeApplicationData *appData;
138
    KoShapeBackground * fill; ///< Stands for the background color / fill etc.
139
    KoShapeBorderModel *border; ///< points to a border, or 0 if there is no border
140
    KoShape *me;
141
    QList<KoShape*> dependees; ///< list of shape dependent on this shape
142
    KoShapeShadow * shadow; ///< the current shape shadow
143
    QMap<QByteArray, QString> additionalAttributes;
Thorsten Zachmann's avatar
Thorsten Zachmann committed
144
    QList<KoEventAction *> eventActions; ///< list of event actions the shape has
Thomas Zander's avatar
Thomas Zander committed
145 146
};

Thomas Zander's avatar
Thomas Zander committed
147
KoShape::KoShape()
148
    : d(new Private(this))
Thomas Zander's avatar
Thomas Zander committed
149
{
150 151 152 153 154
    d->connectors.append( QPointF( 0.5, 0.0 ) );
    d->connectors.append( QPointF( 1.0, 0.5 ) );
    d->connectors.append( QPointF( 0.5, 1.0 ) );
    d->connectors.append( QPointF( 0.0, 0.5 ) );

155
    notifyChanged();
Thomas Zander's avatar
Thomas Zander committed
156 157 158 159
}

KoShape::~KoShape()
{
160
    d->shapeChanged( Deleted );
Thomas Zander's avatar
Thomas Zander committed
161
    delete d;
Thomas Zander's avatar
Thomas Zander committed
162 163
}

164
void KoShape::paintDecorations(QPainter &painter, const KoViewConverter &converter, const KoCanvasBase *canvas) {
Thomas Zander's avatar
Thomas Zander committed
165 166 167
    Q_UNUSED(painter);
    Q_UNUSED(converter);
    Q_UNUSED(canvas);
168
/* Since this code is not actually used (kivio is going to be the main user) lets disable instead of fix.
Thomas Zander's avatar
Thomas Zander committed
169 170 171 172 173 174 175
    if ( selected )
    {
        // draw connectors
        QPen pen( Qt::blue );
        pen.setWidth( 0 );
        painter.setPen( pen );
        painter.setBrush( Qt::NoBrush );
Thomas Zander's avatar
Thomas Zander committed
176
        for ( int i = 0; i < d->connectors.size(); ++i )
Thomas Zander's avatar
Thomas Zander committed
177
        {
Thomas Zander's avatar
Thomas Zander committed
178
            QPointF p = converter.documentToView(d->connectors[ i ]);
Thomas Zander's avatar
Thomas Zander committed
179 180 181
            painter.drawLine( QPointF( p.x() - 2, p.y() + 2 ), QPointF( p.x() + 2, p.y() - 2 ) );
            painter.drawLine( QPointF( p.x() + 2, p.y() + 2 ), QPointF( p.x() - 2, p.y() - 2 ) );
        }
182
    }*/
Thomas Zander's avatar
Thomas Zander committed
183 184
}

185
void KoShape::setScale( double sx, double sy )
Thomas Zander's avatar
Thomas Zander committed
186
{
187 188 189 190 191
    QPointF pos = position();
    QMatrix scaleMatrix;
    scaleMatrix.translate( pos.x(), pos.y() );
    scaleMatrix.scale( sx, sy );
    scaleMatrix.translate( -pos.x(), -pos.y() );
192
    d->localMatrix = d->localMatrix * scaleMatrix;
193

194
    notifyChanged();
195
    d->shapeChanged(ScaleChanged);
Thomas Zander's avatar
Thomas Zander committed
196 197 198 199
}

void KoShape::rotate( double angle )
{
200 201 202 203 204
    QPointF center = d->localMatrix.map( QPointF( 0.5*size().width(), 0.5*size().height() ) );
    QMatrix rotateMatrix;
    rotateMatrix.translate( center.x(), center.y() );
    rotateMatrix.rotate( angle );
    rotateMatrix.translate( -center.x(), -center.y() );
205
    d->localMatrix = d->localMatrix * rotateMatrix;
206

207
    notifyChanged();
208
    d->shapeChanged(RotationChanged);
Thomas Zander's avatar
Thomas Zander committed
209 210
}

211
void KoShape::setShear( double sx, double sy )
Thomas Zander's avatar
Thomas Zander committed
212
{
213 214 215 216 217
    QPointF pos = position();
    QMatrix shearMatrix;
    shearMatrix.translate( pos.x(), pos.y() );
    shearMatrix.shear( sx, sy );
    shearMatrix.translate( -pos.x(), -pos.y() );
218
    d->localMatrix = d->localMatrix * shearMatrix;
219

220
    notifyChanged();
221
    d->shapeChanged(ShearChanged);
Thomas Zander's avatar
Thomas Zander committed
222 223
}

224
void KoShape::setSize( const QSizeF &newSize )
Thomas Zander's avatar
Thomas Zander committed
225
{
226 227
    QSizeF oldSize( size() );
    if(oldSize == newSize )
Thomas Zander's avatar
Thomas Zander committed
228
        return;
229

Thomas Zander's avatar
Thomas Zander committed
230
    d->size = newSize;
231

232
    notifyChanged();
233
    d->shapeChanged(SizeChanged);
Thomas Zander's avatar
Thomas Zander committed
234 235
}

236
void KoShape::setPosition( const QPointF &newPosition )
Thomas Zander's avatar
Thomas Zander committed
237
{
238 239
    QPointF currentPos = position();
    if( newPosition == currentPos )
Thomas Zander's avatar
Thomas Zander committed
240
        return;
241
    QMatrix translateMatrix;
242
    translateMatrix.translate( newPosition.x()-currentPos.x(), newPosition.y()-currentPos.y() );
243 244 245
    d->localMatrix = d->localMatrix * translateMatrix;

    notifyChanged();
246
    d->shapeChanged(PositionChanged);
Thomas Zander's avatar
Thomas Zander committed
247 248 249 250
}

bool KoShape::hitTest( const QPointF &position ) const
{
Thomas Zander's avatar
Thomas Zander committed
251
    if(d->parent && d->parent->childClipped(this) && !d->parent->hitTest(position))
Thomas Zander's avatar
Thomas Zander committed
252 253
        return false;

254
    QPointF point = absoluteTransformation(0).inverted().map( position );
255
    QRectF bb( QPointF(), size() );
256
    if(d->border)
257 258
    {
        KoInsets insets;
259
        d->border->borderInsets(this, insets);
260 261 262 263 264 265 266 267
        bb.adjust(-insets.left, -insets.top, insets.right, insets.bottom);
    }
    if( bb.contains( point ) )
        return true;

    // if there is no shadow we can as well just leave
    if( ! d->shadow )
        return false;
Thomas Zander's avatar
Thomas Zander committed
268

269 270 271 272 273
    // the shadow has an offset to the shape, so we simply
    // check if the position minus the shadow offset hits the shape
    point = absoluteTransformation(0).inverted().map( position-d->shadow->offset() );

    return bb.contains( point );
Thomas Zander's avatar
Thomas Zander committed
274 275
}

276
QRectF KoShape::boundingRect() const
Thomas Zander's avatar
Thomas Zander committed
277
{
278
    QRectF bb( QPointF(0, 0), size() );
279 280 281 282 283
    if(d->border) {
        KoInsets insets;
        d->border->borderInsets(this, insets);
        bb.adjust(-insets.left, -insets.top, insets.right, insets.bottom);
    }
284 285 286 287 288 289 290 291
    bb = absoluteTransformation(0).mapRect( bb );
    if( d->shadow )
    {
        KoInsets insets;
        d->shadow->insets( this, insets );
        bb.adjust(-insets.left, -insets.top, insets.right, insets.bottom);
    }
    return bb;
Thomas Zander's avatar
Thomas Zander committed
292 293
}

294
QMatrix KoShape::absoluteTransformation(const KoViewConverter *converter) const {
Thomas Zander's avatar
Thomas Zander committed
295 296
    QMatrix matrix;
    // apply parents matrix to inherit any transformations done there.
297 298 299
    KoShapeContainer * container = d->parent;
    if( container ) {
        if( container->childClipped(this) )
300
            matrix = container->absoluteTransformation(0);
Thomas Zander's avatar
Thomas Zander committed
301
        else {
302 303
            QSizeF containerSize = container->size();
            QPointF containerPos = container->absolutePosition() - QPointF( 0.5*containerSize.width(), 0.5*containerSize.height() );
Thomas Zander's avatar
Thomas Zander committed
304
            if(converter)
305
                containerPos = converter->documentToView(containerPos);
306
            matrix.translate( containerPos.x(), containerPos.y() );
Thomas Zander's avatar
Thomas Zander committed
307 308 309
        }
    }

310
    if(converter) {
Jan Hambrecht's avatar
Jan Hambrecht committed
311
        QPointF pos = d->localMatrix.map( QPointF() );
312 313
        QPointF trans = converter->documentToView( pos ) - pos;
        matrix.translate( trans.x(), trans.y() );
Thomas Zander's avatar
Thomas Zander committed
314
    }
315 316

    return d->localMatrix * matrix;
Thomas Zander's avatar
Thomas Zander committed
317 318
}

319
void KoShape::applyAbsoluteTransformation( const QMatrix &matrix )
320
{
321
    QMatrix globalMatrix = absoluteTransformation(0);
322 323
    // the transformation is relative to the global coordinate system
    // but we want to change the local matrix, so convert the matrix
Thomas Zander's avatar
Thomas Zander committed
324
    // to be relative to the local coordinate system
325
    QMatrix transformMatrix = globalMatrix * matrix * globalMatrix.inverted();
326 327 328 329 330 331
    applyTransformation( transformMatrix );
}

void KoShape::applyTransformation( const QMatrix &matrix )
{
    d->localMatrix = matrix * d->localMatrix;
332
    notifyChanged();
333
    d->shapeChanged(GenericMatrixChange);
334 335 336 337 338 339
}

void KoShape::setTransformation( const QMatrix &matrix )
{
    d->localMatrix = matrix;
    notifyChanged();
340
    d->shapeChanged(GenericMatrixChange);
341
}
Thomas Zander's avatar
Thomas Zander committed
342

343
QMatrix KoShape::transformation() const
344 345 346 347
{
    return d->localMatrix;
}

348
bool KoShape::compareShapeZIndex(KoShape *s1, KoShape *s2) {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    int diff = s1->zIndex() - s2->zIndex();
    if(diff == 0) {
        KoShape *s = s1->parent();
        while(s) {
            if(s == s2) // s1 is a child of s2
                return false; // children are always on top of their parents.
            s = s->parent();
        }
        s = s2->parent();
        while(s) {
            if(s == s1) // s2 is a child of s1
                return true;
            s = s->parent();
        }
    }
    return diff < 0;
Thomas Zander's avatar
Thomas Zander committed
365 366 367
}

void KoShape::setParent(KoShapeContainer *parent) {
368 369 370
    if(d->parent == parent)
        return;
    if(parent && dynamic_cast<KoShape*>(parent) != this) {
371 372
        if (d->parent)
            d->parent->removeChild(this);
Thomas Zander's avatar
Thomas Zander committed
373
        d->parent = parent;
374 375
        parent->addChild(this);
    }
Thomas Zander's avatar
Thomas Zander committed
376
    else
Thomas Zander's avatar
Thomas Zander committed
377
        d->parent = 0;
378
    notifyChanged();
379
    d->shapeChanged(ParentChanged);
Thomas Zander's avatar
Thomas Zander committed
380 381 382 383
}

int KoShape::zIndex() const {
    if(parent()) // we can't be under our parent...
Thomas Zander's avatar
Thomas Zander committed
384 385
        return qMax(d->zIndex, parent()->zIndex());
    return d->zIndex;
Thomas Zander's avatar
Thomas Zander committed
386 387
}

388
void KoShape::update() const {
Thomas Zander's avatar
Thomas Zander committed
389
    if ( !d->shapeManagers.empty() )
390
    {
Thorsten Zachmann's avatar
Thorsten Zachmann committed
391
        QRectF rect( boundingRect() );
Thomas Zander's avatar
Thomas Zander committed
392
        foreach( KoShapeManager * manager, d->shapeManagers )
393
            manager->update( rect, this, true );
Thomas Zander's avatar
Thomas Zander committed
394 395 396
    }
}

397
void KoShape::update(const QRectF &shape) const {
Thomas Zander's avatar
Thomas Zander committed
398
    if ( !d->shapeManagers.empty() && isVisible() )
399
    {
400
        QRectF rect(absoluteTransformation(0).mapRect(shape));
Thomas Zander's avatar
Thomas Zander committed
401
        foreach( KoShapeManager * manager, d->shapeManagers )
402
        {
403
            manager->update(rect);
404 405
        }
    }
Thomas Zander's avatar
Thomas Zander committed
406 407 408 409
}

const QPainterPath KoShape::outline() const {
    QPainterPath path;
410
    path.addRect(QRectF( QPointF(0, 0), QSizeF( qMax(d->size.width(), 0.0001), qMax(d->size.height(), 0.0001) ) ));
Thomas Zander's avatar
Thomas Zander committed
411 412 413
    return path;
}

414 415 416 417
QPointF KoShape::absolutePosition(KoFlake::Position anchor) const {
    QPointF point;
    switch(anchor) {
        case KoFlake::TopLeftCorner: break;
418 419 420
        case KoFlake::TopRightCorner: point = QPointF(size().width(), 0.0); break;
        case KoFlake::BottomLeftCorner: point = QPointF(0.0, size().height()); break;
        case KoFlake::BottomRightCorner: point = QPointF(size().width(), size().height()); break;
Jan Hambrecht's avatar
Jan Hambrecht committed
421
        case KoFlake::CenteredPosition: point = QPointF(size().width() / 2.0, size().height() / 2.0); break;
422
    }
423
    return absoluteTransformation(0).map(point);
Thomas Zander's avatar
Thomas Zander committed
424 425
}

426
void KoShape::setAbsolutePosition(QPointF newPosition, KoFlake::Position anchor) {
427 428
    QPointF currentAbsPosition = absolutePosition( anchor );
    QPointF translate = newPosition - currentAbsPosition;
Jan Hambrecht's avatar
Jan Hambrecht committed
429 430
    QMatrix translateMatrix;
    translateMatrix.translate( translate.x(), translate.y() );
431
    applyAbsoluteTransformation( translateMatrix );
432
    notifyChanged();
433
    d->shapeChanged(PositionChanged);
Thomas Zander's avatar
Thomas Zander committed
434 435
}

Thomas Zander's avatar
Thomas Zander committed
436
void KoShape::copySettings(const KoShape *shape) {
Thomas Zander's avatar
Thomas Zander committed
437 438
    d->size = shape->size();
    d->connectors.clear();
Jan Hambrecht's avatar
Jan Hambrecht committed
439
    foreach(QPointF point, shape->connectionPoints())
Thomas Zander's avatar
Thomas Zander committed
440
        addConnectionPoint(point);
Thomas Zander's avatar
Thomas Zander committed
441 442
    d->zIndex = shape->zIndex();
    d->visible = shape->isVisible();
443 444 445 446 447 448 449
    
    // Ensure printable is true by default
    if (!d->visible)
        d->printable = true;
    else
        d->printable = shape->isPrintable();
        
Thomas Zander's avatar
Thomas Zander committed
450 451
    d->locked = shape->isLocked();
    d->keepAspect = shape->keepAspectRatio();
452
    d->localMatrix = shape->d->localMatrix;
Thomas Zander's avatar
Thomas Zander committed
453 454
}

Thomas Zander's avatar
Thomas Zander committed
455
void KoShape::notifyChanged()
456
{
Thomas Zander's avatar
Thomas Zander committed
457
    foreach( KoShapeManager * manager, d->shapeManagers )
458
    {
Thomas Zander's avatar
Thomas Zander committed
459
        manager->notifyShapeChanged( this );
460 461 462
    }
}

463
void KoShape::setUserData(KoShapeUserData *userData) {
464
    delete d->userData;
Thomas Zander's avatar
Thomas Zander committed
465
    d->userData = userData;
466 467 468
}

KoShapeUserData *KoShape::userData() const {
Thomas Zander's avatar
Thomas Zander committed
469
    return d->userData;
470 471
}

472
void KoShape::setApplicationData(KoShapeApplicationData *appData) {
473
    // appdata is deleted by the application.
Thomas Zander's avatar
Thomas Zander committed
474
    d->appData = appData;
475 476 477
}

KoShapeApplicationData *KoShape::applicationData() const {
Thomas Zander's avatar
Thomas Zander committed
478
    return d->appData;
479 480
}

481
bool KoShape::hasTransparency() {
482
    if( ! d->fill )
Thomas Zander's avatar
Thomas Zander committed
483
        return true;
484 485
    else
        return d->fill->hasTransparency();
Thomas Zander's avatar
Thomas Zander committed
486 487
}

488 489
KoInsets KoShape::borderInsets() const {
    KoInsets answer;
490 491
    if(d->border)
        d->border->borderInsets(this, answer);
492 493 494
    return answer;
}

Thomas Zander's avatar
Thomas Zander committed
495
double KoShape::rotation() const {
496
    // try to extract the rotation angle out of the local matrix
497 498 499 500
    // if it is a pure rotation matrix

    // check if the matrix has shearing mixed in
    if( fabs( fabs(d->localMatrix.m12()) - fabs(d->localMatrix.m21()) ) > 1e-10 )
501
        return std::numeric_limits<double>::quiet_NaN();
502 503
    // check if the matrix has scaling mixed in
    if( fabs( d->localMatrix.m11() - d->localMatrix.m22() ) > 1e-10 )
504
        return std::numeric_limits<double>::quiet_NaN();
505 506

    // calculate the angle from the matrix elements
507
    double angle = atan2( -d->localMatrix.m21(), d->localMatrix.m11() ) * 180.0 / M_PI;
508 509 510 511
    if( angle < 0.0 )
        angle += 360.0;

    return angle;
Thomas Zander's avatar
Thomas Zander committed
512 513 514 515 516 517 518
}

QSizeF KoShape::size () const {
    return d->size;
}

QPointF KoShape::position() const {
519 520 521
    QPointF center( 0.5*size().width(), 0.5*size().height() );
    return d->localMatrix.map( center ) - center;
    //return d->localMatrix.map( QPointF(0,0) );
Thomas Zander's avatar
Thomas Zander committed
522 523 524
}

void KoShape::addConnectionPoint( const QPointF &point ) {
525 526 527
    QSizeF s = size();
    // convert glue point from shape coordinates to factors of size
    d->connectors.append( QPointF( point.x() / s.width(), point.y() / s.height() ) );
Thomas Zander's avatar
Thomas Zander committed
528 529
}

530
QList<QPointF> KoShape::connectionPoints() const {
531 532 533 534 535 536 537
    QList<QPointF> points;
    QSizeF s = size();
    // convert glue points to shape coordinates
    foreach( QPointF cp, d->connectors )
        points.append( QPointF( s.width() * cp.x(), s.height() * cp.y() ) );

    return points;
538 539
}

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
void KoShape::addEventAction( KoEventAction * action )
{
    if ( ! d->eventActions.contains( action ) ) {
        d->eventActions.append( action );
    }
}

void KoShape::removeEventAction( KoEventAction * action )
{
    if ( d->eventActions.contains( action ) ) {
        d->eventActions.removeAll( action );
    }
}

QList<KoEventAction *> KoShape::eventActions() const
{
    return d->eventActions;
}

559 560 561 562 563 564
void KoShape::setBackground( KoShapeBackground * fill ) {
    if(d->fill)
        d->fill->removeUser();
    d->fill = fill;
    if(d->fill)
        d->fill->addUser();
565 566
    d->shapeChanged(BackgroundChanged);
    notifyChanged();
Thomas Zander's avatar
Thomas Zander committed
567 568
}

569 570
KoShapeBackground * KoShape::background() const {
    return d->fill;
Thomas Zander's avatar
Thomas Zander committed
571 572 573
}

void KoShape::setZIndex(int zIndex) {
574
    notifyChanged();
Thomas Zander's avatar
Thomas Zander committed
575 576 577 578 579 580 581
    d->zIndex = zIndex;
}

void KoShape::setVisible(bool on) {
    d->visible = on;
}

582 583 584
bool KoShape::isVisible( bool recursive ) const {
    if( ! recursive )
        return d->visible;
Jan Hambrecht's avatar
Jan Hambrecht committed
585 586 587
    if( recursive && ! d->visible )
        return false;

588 589 590 591 592 593 594 595
    KoShapeContainer * parentShape = parent();
    while( parentShape )
    {
        if( ! parentShape->isVisible() )
            return false;
        parentShape = parentShape->parent();
    }
    return true;
Thomas Zander's avatar
Thomas Zander committed
596 597
}

598 599 600 601
void KoShape::setPrintable(bool on)
{
    d->printable = on;
}
602

603 604
bool KoShape::isPrintable() const
{
605 606 607 608
    if (d->visible)
        return d->printable;
    else
        return false;
609 610
}

Thomas Zander's avatar
Thomas Zander committed
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
void KoShape::setSelectable(bool selectable) {
    d->selectable = selectable;
}

bool KoShape::isSelectable() const {
    return d->selectable;
}

void KoShape::setLocked(bool locked) {
    d->locked = locked;
}

bool KoShape::isLocked() const {
    return d->locked;
}

KoShapeContainer *KoShape::parent() const {
    return d->parent;
}

void KoShape::setKeepAspectRatio(bool keepAspect) {
    d->keepAspect = keepAspect;
}

bool KoShape::keepAspectRatio() const {
    return d->keepAspect;
}

const QString &KoShape::shapeId() const {
    return d->shapeId;
}

void KoShape::setShapeId(const QString &id) {
    d->shapeId = id;
}

void KoShape::setCollisionDetection(bool detect) {
    d->detectCollision = detect;
}

bool KoShape::collisionDetection() {
    return d->detectCollision;
}

void KoShape::addShapeManager( KoShapeManager * manager ) {
    d->shapeManagers.insert( manager );
}

void KoShape::removeShapeManager( KoShapeManager * manager ) {
    d->shapeManagers.remove( manager );
}

663 664 665 666 667
KoShapeBorderModel *KoShape::border() const {
    return d->border;
}

void KoShape::setBorder(KoShapeBorderModel *border) {
668 669
    if(d->border)
        d->border->removeUser();
670
    d->border = border;
671 672
    if(d->border)
        d->border->addUser();
673 674
    d->shapeChanged(BorderChanged);
    notifyChanged();
675 676
}

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
void KoShape::setShadow( KoShapeShadow * shadow )
{
    if( d->shadow )
        d->shadow->removeUser();
    d->shadow = shadow;
    if( d->shadow )
        d->shadow->addUser();
    d->shapeChanged(ShadowChanged);
    notifyChanged();
}

KoShapeShadow * KoShape::shadow() const
{
    return d->shadow;
}

693
const QMatrix& KoShape::matrix() const {
694
    return d->localMatrix;
695 696
}

697
void KoShape::removeConnectionPoint( int index )
698 699 700 701 702
{
    if( index < d->connectors.count() )
        d->connectors.remove( index );
}

703
QString KoShape::name() const {
704 705 706 707 708 709
    return d->name;
}

void KoShape::setName( const QString & name ) {
    d->name = name;
}
710

711 712 713 714 715 716 717
void KoShape::deleteLater() {
    foreach(KoShapeManager *manager, d->shapeManagers)
        manager->remove(this);
    d->shapeManagers.clear();
    new ShapeDeleter(this);
}

718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
bool KoShape::isEditable() const {
    if( !d->visible || d->locked )
        return false;

    KoShapeContainer * p = parent();
    if(p && p->isChildLocked(this))
        return false;
    while( p )
    {
        if( ! p->isVisible() )
            return false;
        p = p->parent();
    }

    return true;
}
734

735
// loading & saving methods
736
QString KoShape::saveStyle( KoGenStyle &style, KoShapeSavingContext &context ) const
737 738 739 740 741 742 743
{
    // and fill the style
    KoShapeBorderModel * b = border();
    if ( b )
    {
        b->fillStyle( style, context );
    }
744 745 746
    KoShapeShadow * s = shadow();
    if( s )
        s->fillStyle( style, context );
747

748 749 750 751 752 753 754
    KoShapeBackground * bg = background();
    if( bg )
        bg->fillStyle( style, context );

    if ( context.isSet( KoShapeSavingContext::AutoStyleInStyleXml ) ) {
        style.setAutoStyleInStylesDotXml( true );
    }
755

756
    return context.mainStyles().lookup( style, context.isSet( KoShapeSavingContext::PresentationShape ) ? "pr" : "gr" );
757 758
}

759 760
void KoShape::loadStyle( const KoXmlElement & element, KoShapeLoadingContext &context )
{
761
    KoStyleStack &styleStack = context.odfLoadingContext().styleStack();
762 763 764 765 766
    styleStack.save();

    // fill the style stack with the shapes style
    if( element.hasAttributeNS( KoXmlNS::draw, "style-name" ) )
    {
767
        context.odfLoadingContext().fillStyleStack( element, KoXmlNS::draw, "style-name", "graphic" );
768 769 770 771
        styleStack.setTypeProperties( "graphic" );
    }
    else if( element.hasAttributeNS( KoXmlNS::presentation, "style-name" ) )
    {
772
        context.odfLoadingContext().fillStyleStack( element, KoXmlNS::presentation, "style-name", "presentation" );
773
        styleStack.setTypeProperties( "graphic" );
774 775
    }

776 777
    setBackground( loadOdfFill( element, context ) );
    setBorder( loadOdfStroke( element, context ) );
778
    setShadow( loadOdfShadow( element, context ) );
779 780

    styleStack.restore();
781 782
}

783 784
bool KoShape::loadOdfAttributes( const KoXmlElement & element, KoShapeLoadingContext &context, int attributes )
{
785 786 787 788 789 790 791 792 793
    if ( attributes & OdfSize ) {
        QPointF pos;
        pos.setX( KoUnit::parseValue( element.attributeNS( KoXmlNS::svg, "x", QString() ) ) );
        pos.setY( KoUnit::parseValue( element.attributeNS( KoXmlNS::svg, "y", QString() ) ) );
        setPosition( pos );

        QSizeF size;
        size.setWidth( KoUnit::parseValue( element.attributeNS( KoXmlNS::svg, "width", QString() ) ) );
        size.setHeight( KoUnit::parseValue( element.attributeNS( KoXmlNS::svg, "height", QString() ) ) );
794
        setSize( size );
795 796
    }

797 798 799 800 801 802 803
    if ( attributes & OdfMandatories ) {
        if ( element.hasAttributeNS( KoXmlNS::draw, "layer" ) ) {
            KoShapeLayer * layer = context.layer( element.attributeNS( KoXmlNS::draw, "layer" ) );
            if ( layer ) {
                setParent( layer );
            }
        }
804 805 806 807 808 809
        if ( element.hasAttributeNS( KoXmlNS::draw, "id" ) ) {
            QString id = element.attributeNS( KoXmlNS::draw, "id" );
            if ( !id.isNull() ) {
                context.addShapeId( this, id );
            }
        }
810
        if ( element.hasAttributeNS( KoXmlNS::draw, "z-index" ) ) {
811
            context.addShapeZIndex( this, element.attributeNS( KoXmlNS::draw, "z-index" ).toInt() );
812
        }
813
        setZIndex( context.zIndex() );
814

815
        if( element.hasAttributeNS( KoXmlNS::draw, "name" ) ) {
Jan Hambrecht's avatar
Jan Hambrecht committed
816
            setName( element.attributeNS( KoXmlNS::draw, "name" ) );
817
        }
Jan Hambrecht's avatar
Jan Hambrecht committed
818

819
        loadStyle( element, context );
820
    }
821

Jan Hambrecht's avatar
 
Jan Hambrecht committed
822 823 824 825
    if( attributes & OdfTransformation )
    {
        QString transform = element.attributeNS( KoXmlNS::draw, "transform", QString() );
        if( ! transform.isEmpty() )
826
            applyAbsoluteTransformation( parseOdfTransform( transform ) );
Jan Hambrecht's avatar
 
Jan Hambrecht committed
827 828
    }

829
    if ( attributes & OdfAdditionalAttributes ) {
830 831 832 833 834
        QSet<KoShapeLoadingContext::AdditionalAttributeData> additionalAttributeData = KoShapeLoadingContext::additionalAttributeData();
        foreach ( KoShapeLoadingContext::AdditionalAttributeData attributeData, additionalAttributeData ) {
            if ( element.hasAttributeNS( attributeData.ns, attributeData.tag ) ) {
                QString value = element.attributeNS( attributeData.ns, attributeData.tag );
                //kDebug(30006) << "load additional attribute" << attributeData.tag << value;
835
                setAdditionalAttribute( attributeData.name, value );
836 837
            }
        }
838 839
    }

Thorsten Zachmann's avatar
Thorsten Zachmann committed
840 841 842 843 844 845 846 847
    if ( attributes & OdfCommonChildElements ) {
        const KoXmlElement eventActionsElement( KoXml::namedItemNS( element, KoXmlNS::office, "event-listeners" ) );
        if ( !eventActionsElement.isNull() ) {
            d->eventActions = KoEventActionRegistry::instance()->createEventActionsFromOdf( eventActionsElement, context );
        }
        // load glue points (connection points)
    }

848 849 850
    return true;
}

851
QString KoShape::getStyleProperty( const char *property, const KoXmlElement & element, KoShapeLoadingContext & context )
852
{
853
    KoStyleStack &styleStack = context.odfLoadingContext().styleStack();
854
    QString value;
855

856 857
    if ( styleStack.hasProperty( KoXmlNS::draw, property ) ) {
        value = styleStack.property( KoXmlNS::draw, property );
858 859
    }

860 861 862
    return value;
}

863
KoShapeBackground * KoShape::loadOdfFill( const KoXmlElement & element, KoShapeLoadingContext & context )
864
{
865
    KoStyleStack &styleStack = context.odfLoadingContext().styleStack();
866
    QString fill = getStyleProperty( "fill", element, context );
867
    KoShapeBackground * bg = 0;
868
    if ( fill == "solid" || fill == "hatch" )
869
        bg = new KoColorBackground();
870
    else if( fill == "gradient" )
871
        bg = new KoGradientBackground( new QLinearGradient() );
872
    else if( fill == "bitmap" )
873 874 875 876 877 878 879 880 881 882
        bg = new KoPatternBackground();

    if( ! bg )
        return 0;

    if( ! bg->loadStyle( context.odfLoadingContext(), size() ) )
    {
        delete bg;
        return 0;
    }
883

884
    return bg;
885 886
}

887 888
KoShapeBorderModel * KoShape::loadOdfStroke( const KoXmlElement & element, KoShapeLoadingContext & context )
{
889
    KoStyleStack &styleStack = context.odfLoadingContext().styleStack();
890
    QString stroke = getStyleProperty( "stroke", element, context );
891
    if( stroke == "solid" || stroke == "dash" )
892
    {
893
        QPen pen = KoOdfGraphicStyles::loadOasisStrokeStyle( styleStack, stroke, context.odfLoadingContext().stylesReader() );
894

895
        KoLineBorder * border = new KoLineBorder();
896
        border->setLineWidth( pen.widthF() );
897 898 899
        border->setColor( pen.color() );
        border->setJoinStyle( pen.joinStyle() );
        border->setLineStyle( pen.style(), pen.dashPattern() );
900

901 902 903 904
        return border;
    }
    else
        return 0;
905 906
}

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
KoShapeShadow * KoShape::loadOdfShadow( const KoXmlElement & element, KoShapeLoadingContext & context )
{
    KoStyleStack &styleStack = context.odfLoadingContext().styleStack();
    QString stroke = getStyleProperty( "shadow", element, context );
    if( stroke == "visible" || stroke == "hidden" )
    {
        KoShapeShadow * shadow = new KoShapeShadow();
        QColor shadowColor( styleStack.property( KoXmlNS::draw, "shadow-color" ) );
        qreal offsetX = KoUnit::parseValue( styleStack.property( KoXmlNS::draw, "shadow-offset-x" ) );
        qreal offsetY = KoUnit::parseValue( styleStack.property( KoXmlNS::draw, "shadow-offset-y" ) );
        shadow->setOffset( QPointF( offsetX, offsetY ) );

        QString opacity = styleStack.property( KoXmlNS::draw, "shadow-opacity" );
        if( ! opacity.isEmpty() && opacity.right( 1 ) == "%" )
            shadowColor.setAlphaF( opacity.left( opacity.length()-1 ).toFloat() / 100.0 );
        shadow->setColor( shadowColor );

        return shadow;
    }
    return 0;
}

Jan Hambrecht's avatar
 
Jan Hambrecht committed
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
QMatrix KoShape::parseOdfTransform( const QString &transform )
{
    QMatrix matrix;

    // Split string for handling 1 transform statement at a time
    QStringList subtransforms = transform.split(')', QString::SkipEmptyParts);
    QStringList::ConstIterator it = subtransforms.begin();
    QStringList::ConstIterator end = subtransforms.end();
    for(; it != end; ++it)
    {
        QStringList subtransform = (*it).split('(', QString::SkipEmptyParts);

        subtransform[0] = subtransform[0].trimmed().toLower();
        subtransform[1] = subtransform[1].simplified();
        QRegExp reg("[,( ]");
        QStringList params = subtransform[1].split(reg, QString::SkipEmptyParts);

Thomas Zander's avatar
Thomas Zander committed
946
        if(subtransform[0].startsWith(';') || subtransform[0].startsWith(','))
Jan Hambrecht's avatar
 
Jan Hambrecht committed
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
            subtransform[0] = subtransform[0].right(subtransform[0].length() - 1);

        if(subtransform[0] == "rotate")
        {
            // TODO find out what oo2 really does when rotating, it seems severly broken
            if(params.count() == 3)
            {
                double x = KoUnit::parseValue( params[1] );
                double y = KoUnit::parseValue( params[2] );

                matrix.translate(x, y);
                // oo2 rotates by radians
                matrix.rotate( params[0].toDouble()*180.0/M_PI );
                matrix.translate(-x, -y);
            }
            else
            {
                // oo2 rotates by radians
                matrix.rotate( params[0].toDouble()*180.0/M_PI );
            }
        }
        else if(subtransform[0] == "translate")
        {
            if(params.count() == 2)
            {
                double x = KoUnit::parseValue( params[0] );
                double y = KoUnit::parseValue( params[1] );
                matrix.translate(x, y);
            }
            else    // Spec : if only one param given, assume 2nd param to be 0
                matrix.translate( KoUnit::parseValue( params[0] ) , 0);
        }
        else if(subtransform[0] == "scale")
        {
            if(params.count() == 2)
                matrix.scale(params[0].toDouble(), params[1].toDouble());
            else    // Spec : if only one param given, assume uniform scaling
                matrix.scale(params[0].toDouble(), params[0].toDouble());
        }
        else if(subtransform[0] == "skewx")
            matrix.shear(tan(params[0].toDouble()), 0.0F);
        else if(subtransform[0] == "skewy")
            matrix.shear(tan(params[0].toDouble()), 0.0F);
        else if(subtransform[0] == "skewy")
            matrix.shear(0.0F, tan(params[0].toDouble()));
        else if(subtransform[0] == "matrix")
        {
            if(params.count() >= 6)
                matrix.setMatrix(params[0].toDouble(), params[1].toDouble(), params[2].toDouble(), params[3].toDouble(), KoUnit::parseValue( params[4] ), KoUnit::parseValue( params[5] ) );
        }
    }

    return matrix;
}

1002
void KoShape::saveOdfAttributes(KoShapeSavingContext &context, int attributes) const {
1003
    if(attributes & OdfMandatories) {
1004
        KoGenStyle style;
1005
        // all items that should be written to 'draw:frame' and any other 'draw:' object that inherits this shape
1006 1007 1008 1009 1010 1011 1012 1013
        if ( context.isSet( KoShapeSavingContext::PresentationShape ) ) {
            style = KoGenStyle( KoGenStyle::StylePresentationAuto, "presentation" );
            context.xmlWriter().addAttribute( "presentation:style-name", saveStyle( style, context ) );
        }
        else {
            style = KoGenStyle( KoGenStyle::StyleGraphicAuto, "graphic" );
            context.xmlWriter().addAttribute( "draw:style-name", saveStyle( style, context ) );
        }
1014

1015
        if ( context.isSet( KoShapeSavingContext::DrawId ) )
1016
        {
1017
            context.xmlWriter().addAttribute( "draw:id", context.drawId( this ) );
1018 1019
        }

Jan Hambrecht's avatar
Jan Hambrecht committed
1020 1021 1022
        if( ! name().isEmpty() )
            context.xmlWriter().addAttribute( "draw:name", name() );

1023
        if(d->parent && dynamic_cast<KoShapeLayer*> (d->parent))
1024
            context.xmlWriter().addAttribute("draw:layer", d->parent->name());
1025 1026
    }

1027 1028
    if(attributes & OdfSize) {
        QSizeF s( size() );
1029 1030
        context.xmlWriter().addAttributePt( "svg:width", s.width() );
        context.xmlWriter().addAttributePt( "svg:height", s.height() );
Jan Hambrecht's avatar
Jan Hambrecht committed
1031 1032 1033
        // the position is hidden in the transformation
        context.xmlWriter().addAttributePt( "svg:x", 0.0 );
        context.xmlWriter().addAttributePt( "svg:y", 0.0 );
1034 1035
    }

1036 1037 1038
    if(attributes & OdfTransformation) {
        // just like in shapes; ODF allows you to manipulate the 'matrix' after setting an
        // ofset on the shape (using the x and y positions).   Lets save them here.
1039
        /*
1040 1041 1042 1043 1044
        bool rotate = qAbs(d->angle) > 1E-6;
        bool skew = qAbs(d->shearX) > 1E-6 || qAbs(d->shearY) > 1E-6;
        bool scale = qAbs(d->scaleX - 1) > 1E-6 || qAbs(d->scaleY -1) > 1E-6;

        if(rotate && (skew || scale)) {
1045
            QMatrix matrix; // can't use absoluteTransformation() as that includes transformation of the container as well.
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
            QSizeF size(this->size());
            if ( d->angle != 0 )
            {
                matrix.translate( size.width() / 2.0 * d->scaleX, size.height() / 2.0 * d->scaleY );
                matrix.translate( size.height() / 2.0 * d->shearX, size.width() / 2.0 * d->shearY );
                matrix.rotate( d->angle );
                matrix.translate( -size.width() / 2.0 * d->scaleX, -size.height() / 2.0 * d->scaleY );
                matrix.translate( -size.height() / 2.0 * d->shearX, -size.width() / 2.0 * d->shearY );
            }
            matrix.shear( d->shearX, d->shearY );
            matrix.scale( d->scaleX, d->scaleY );

            QString m = QString( "matrix(0 0 %3 %4 %5pt %6pt)" ).arg( matrix.m11() ).arg( matrix.m12() )
                .arg( matrix.m21() ).arg( matrix.m22() )
                .arg( matrix.dx() ) .arg( matrix.dy() );
1061
            context.xmlWriter().addAttribute( "draw:transform", m );
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
        }
        else if(rotate || skew || scale) {
            QString transform;
            if(rotate)
                transform = "rotate("+ QString::number(d->angle) +')';
            if(skew)
                transform = "skewX("+ QString::number(d->shearX) +") skewY("+ QString::number(d->shearY) +')';
            if(scale) {
                transform += "scale("+ QString::number(d->scaleX);
                if(d->scaleX != d->scaleY)
                    transform += ','+ QString::number(d->scaleY);
                transform += ')';
            }

1076
            context.xmlWriter().addAttribute( "draw:transform", transform );
1077
        }
1078
        */
1079
        QMatrix matrix = absoluteTransformation(0);
1080
        if( ! matrix.isIdentity() )
1081
        {
Jan Hambrecht's avatar
 
Jan Hambrecht committed
1082
            QString m = QString( "matrix(%1 %2 %3 %4 %5pt %6pt)" )
1083 1084