~ubuntu-branches/ubuntu/wily/libkdegames/wily-proposed

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
/*******************************************************************
    Copyright 2007 Dmitry Suzdalev <dimsuz@gmail.com>

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

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ********************************************************************/
#include "kgamepopupitem.h"
#include <QPainter>
#include <QTimeLine>
#include <QTimer>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include <QIcon>

#include <KColorScheme>

// margin on the sides of message box
static const int MARGIN = 15;
// offset of message from start of the scene
static const int SHOW_OFFSET = 5;
// space between pixmap and text
static const int SOME_SPACE = 10;
// width of the border in pixels
static const qreal BORDER_PEN_WIDTH = 1.0;

class TextItemWithOpacity : public QGraphicsTextItem
{
    Q_OBJECT

public:
    TextItemWithOpacity( QGraphicsItem* parent = 0 )
        :QGraphicsTextItem(parent), m_opacity(1.0) {}
    void setOpacity(qreal opa) { m_opacity = opa; }
    void setTextColor(KStatefulBrush brush) { m_brush = brush; }
    virtual void paint( QPainter* p, const QStyleOptionGraphicsItem *option, QWidget* widget );

Q_SIGNALS:
    void mouseClicked();

private:
    void mouseReleaseEvent(QGraphicsSceneMouseEvent*);

private:
    qreal m_opacity;
    KStatefulBrush m_brush;
};

void TextItemWithOpacity::paint( QPainter* p, const QStyleOptionGraphicsItem *option, QWidget* widget )
{
    // hope that it is ok to call this function here - i.e. I hope it won't be too expensive :)
    // we call it here (and not in setTextColor), because KstatefulBrush
    // absolutely needs QWidget parameter :)
    //NOTE from majewsky: For some weird reason, setDefaultTextColor does on some systems not check
    //whether the given color is equal to the one already set. Just calling setDefaultTextColor without
    //this check may result in an infinite loop of paintEvent -> setDefaultTextColor -> update -> paintEvent...
    const QColor textColor = m_brush.brush(widget).color();
    if (textColor != defaultTextColor())
    {
        setDefaultTextColor(textColor);
    }
    //render contents
    p->save();
    p->setOpacity(m_opacity);
    QGraphicsTextItem::paint(p,option,widget);
    p->restore();
}

void TextItemWithOpacity::mouseReleaseEvent(QGraphicsSceneMouseEvent* ev)
{
    // NOTE: this item is QGraphicsTextItem which "eats" mouse events
    // because of interaction with links. Because of that let's make a
    // special signal to indicate mouse click
    emit mouseClicked();
    QGraphicsTextItem::mouseReleaseEvent(ev);
}

class KGamePopupItemPrivate
{
private:
    KGamePopupItemPrivate(const KGamePopupItemPrivate&);
    const KGamePopupItemPrivate& operator=(const KGamePopupItemPrivate&);
public:
    KGamePopupItemPrivate()
        : m_position( KGamePopupItem::BottomLeft ), m_timeout(2000),
          m_opacity(1.0), m_animOpacity(-1), m_hoveredByMouse(false),
          m_hideOnClick(true), m_textChildItem(0),
          m_sharpness(KGamePopupItem::Square), m_linkHovered(false) {}
    /**
     * Timeline for animations
     */
    QTimeLine m_timeLine;
    /**
     * Timer used to start hiding
     */
    QTimer m_timer;
    /**
     * Holds bounding rect of an item
     */
    QRectF m_boundRect;
    /**
     * Position where item will appear
     */
    KGamePopupItem::Position m_position;
    /**
     * Timeout to stay visible on screen
     */
    int m_timeout;
    /**
     * Item opacity
     */
    qreal m_opacity;
    /**
     * Opacity used while animating appearing in center
     */
    qreal m_animOpacity;
    /**
     * Pixmap to display at the left of the text
     */
    QPixmap m_iconPix;
    /**
     * Set to true when mouse hovers the message
     */
    bool m_hoveredByMouse;
    /**
     * Set to true if this popup item hides on mouse click.
     */
    bool m_hideOnClick;
    /**
     * Child of KGamePopupItem used to display text
     */
    TextItemWithOpacity* m_textChildItem;
    /**
     * Part of the scene that is actually visible in QGraphicsView
     * This is needed for item to work correctly when scene is larger than
     * the View
     */
    QRectF m_visibleSceneRect;
    /**
     * Background brush color
     */
    KStatefulBrush m_brush;
    /**
     * popup angles sharpness
     */
    KGamePopupItem::Sharpness m_sharpness;
    /**
     * painter path to draw a frame
     */
    QPainterPath m_path;
    /**
     * Indicates if some link is hovered in text item
     */
    bool m_linkHovered;
};

KGamePopupItem::KGamePopupItem(QGraphicsItem * parent)
    : QGraphicsItem(parent), d(new KGamePopupItemPrivate)
{
    hide();
    d->m_textChildItem = new TextItemWithOpacity(this);
    d->m_textChildItem->setTextInteractionFlags( Qt::LinksAccessibleByMouse );
    // above call said to enable ItemIsFocusable which we don't need.
    // So disabling it
    d->m_textChildItem->setFlag( QGraphicsItem::ItemIsFocusable, false );

    connect(d->m_textChildItem, &TextItemWithOpacity::linkActivated, this, &KGamePopupItem::linkActivated);
    connect(d->m_textChildItem, &TextItemWithOpacity::linkHovered, this, &KGamePopupItem::onLinkHovered);
    connect(d->m_textChildItem, &TextItemWithOpacity::mouseClicked, this, &KGamePopupItem::onTextItemClicked);

    setZValue(100); // is 100 high enough???
    d->m_textChildItem->setZValue(100);

    QIcon infoIcon = QIcon::fromTheme( QLatin1String( "dialog-information" ));
    // default size is 32
    setMessageIcon( infoIcon.pixmap(32, 32) );

    d->m_timer.setSingleShot(true);

    setAcceptHoverEvents(true);
    // ignore scene transformations
    setFlag(QGraphicsItem::ItemIgnoresTransformations, true);

    // setup default colors
    d->m_brush = KStatefulBrush( KColorScheme::Tooltip, KColorScheme::NormalBackground );
    d->m_textChildItem->setTextColor( KStatefulBrush(KColorScheme::Tooltip, KColorScheme::NormalText) );

    connect(&d->m_timeLine, &QTimeLine::frameChanged, this, &KGamePopupItem::animationFrame);
    connect(&d->m_timeLine, &QTimeLine::finished, this, &KGamePopupItem::hideMe);
    connect(&d->m_timer, &QTimer::timeout, this, &KGamePopupItem::playHideAnimation);
}

void KGamePopupItem::paint( QPainter* p, const QStyleOptionGraphicsItem *option, QWidget* widget )
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    p->save();

    QPen pen = p->pen();
    pen.setWidthF( BORDER_PEN_WIDTH );
    p->setPen(pen);

    if( d->m_animOpacity != -1) // playing Center animation
    {
        p->setOpacity(d->m_animOpacity);
    }
    else
    {
        p->setOpacity(d->m_opacity);
    }
    p->setBrush(d->m_brush.brush(widget));
    p->drawPath(d->m_path);
    p->drawPixmap( MARGIN, static_cast<int>(d->m_boundRect.height()/2) - d->m_iconPix.height()/2,
                   d->m_iconPix );
    p->restore();
}

void KGamePopupItem::showMessage( const QString& text, Position pos, ReplaceMode mode )
{
    if(d->m_timeLine.state() == QTimeLine::Running || d->m_timer.isActive())
    {
        if (mode == ReplacePrevious)
        {
            forceHide(InstantHide);
        }
        else
        {
            return;// we're already showing a message
        }
    }

    // NOTE: we blindly take first visible view we found. I.e. we don't support
    // multiple views. If no visible scene is found, we simply pick the first one.
    QGraphicsView *sceneView = 0;
    foreach (QGraphicsView *view, scene()->views()) {
        if (view->isVisible()) {
            sceneView = view;
            break;
        }
    }
    if (!sceneView)
    {
        sceneView = scene()->views().at(0);
    }

    QPolygonF poly = sceneView->mapToScene( sceneView->viewport()->contentsRect() );
    d->m_visibleSceneRect = poly.boundingRect();

    d->m_textChildItem->setHtml(text);

    d->m_position = pos;

    // do as QGS docs say: notify the scene about rect change
    prepareGeometryChange();

    // recalculate bounding rect
    qreal w = d->m_textChildItem->boundingRect().width()+MARGIN*2+d->m_iconPix.width()+SOME_SPACE;
    qreal h = d->m_textChildItem->boundingRect().height()+MARGIN*2;
    if( d->m_iconPix.height() > h )
    {
        h = d->m_iconPix.height() + MARGIN*2;
	}
    d->m_boundRect = QRectF(0, 0, w, h);

    // adjust to take into account the width of the pen
    // used to draw the border
    const qreal borderRadius = BORDER_PEN_WIDTH / 2.0;
    d->m_boundRect.adjust( -borderRadius ,
                           -borderRadius ,
                            borderRadius ,
                            borderRadius );

    QPainterPath roundRectPath;
    roundRectPath.moveTo(w, d->m_sharpness);
    roundRectPath.arcTo(w-(2*d->m_sharpness), 0.0,(2*d->m_sharpness), (d->m_sharpness), 0.0, 90.0);
    roundRectPath.lineTo(d->m_sharpness, 0.0);
    roundRectPath.arcTo(0.0, 0.0, (2*d->m_sharpness), (2*d->m_sharpness), 90.0, 90.0);
    roundRectPath.lineTo(0.0, h-(d->m_sharpness));
    roundRectPath.arcTo(0.0, h-(2*d->m_sharpness), 2*d->m_sharpness, 2*d->m_sharpness, 180.0, 90.0);
    roundRectPath.lineTo(w-(d->m_sharpness), h);
    roundRectPath.arcTo(w-(2*d->m_sharpness), h-(2*d->m_sharpness), (2*d->m_sharpness), (2*d->m_sharpness), 270.0, 90.0);
    roundRectPath.closeSubpath();

    d->m_path = roundRectPath;

    // adjust y-pos of text item so it appears centered
    d->m_textChildItem->setPos( d->m_textChildItem->x(),
                                d->m_boundRect.height()/2 - d->m_textChildItem->boundingRect().height()/2);

    // setup animation
    setupTimeline();

    // move to the start position
    animationFrame(d->m_timeLine.startFrame());
    show();
    d->m_timeLine.start();

    if(d->m_timeout != 0)
    {
        // 300 msec to animate showing message + d->m_timeout to stay visible => then hide
        d->m_timer.start( 300+d->m_timeout );
    }
}

void KGamePopupItem::setupTimeline()
{
    d->m_timeLine.setDirection( QTimeLine::Forward );
    d->m_timeLine.setDuration(300);
    if( d->m_position == TopLeft || d->m_position == TopRight )
    {
        int start = static_cast<int>(d->m_visibleSceneRect.top() - d->m_boundRect.height() - SHOW_OFFSET);
        int end = static_cast<int>(d->m_visibleSceneRect.top() + SHOW_OFFSET);
        d->m_timeLine.setFrameRange( start, end );
    }
    else if( d->m_position == BottomLeft || d->m_position == BottomRight )
    {
        int start = static_cast<int>(d->m_visibleSceneRect.bottom()+SHOW_OFFSET);
        int end = static_cast<int>(d->m_visibleSceneRect.bottom() - d->m_boundRect.height() - SHOW_OFFSET);
        d->m_timeLine.setFrameRange( start, end );
    }
    else if( d->m_position == Center )
    {
        d->m_timeLine.setFrameRange(0, d->m_timeLine.duration());
        setPos( d->m_visibleSceneRect.left() +
                d->m_visibleSceneRect.width()/2 - d->m_boundRect.width()/2,
                d->m_visibleSceneRect.top() +
                d->m_visibleSceneRect.height()/2 - d->m_boundRect.height()/2);
    }

}

void KGamePopupItem::animationFrame(int frame)
{
    if( d->m_position == TopLeft || d->m_position == BottomLeft )
    {
        setPos( d->m_visibleSceneRect.left()+SHOW_OFFSET, frame );
    }
    else if( d->m_position == TopRight || d->m_position == BottomRight )
    {
        setPos( d->m_visibleSceneRect.right()-d->m_boundRect.width()-SHOW_OFFSET, frame );
    }
    else if( d->m_position == Center )
    {
        d->m_animOpacity = frame*d->m_opacity/d->m_timeLine.duration();
        d->m_textChildItem->setOpacity( d->m_animOpacity );
        update();
    }
}

void KGamePopupItem::playHideAnimation()
{
    if( d->m_hoveredByMouse )
    {
        return;
    }
    // let's hide
    d->m_timeLine.setDirection( QTimeLine::Backward );
    d->m_timeLine.start();
}

void KGamePopupItem::setMessageTimeout( int msec )
{
    d->m_timeout = msec;
}

void KGamePopupItem::setHideOnMouseClick( bool hide )
{
    d->m_hideOnClick = hide;
}

bool KGamePopupItem::hidesOnMouseClick() const
{
    return d->m_hideOnClick;
}

void KGamePopupItem::setMessageOpacity( qreal opacity )
{
    d->m_opacity = opacity;
    d->m_textChildItem->setOpacity(opacity);
}

QRectF KGamePopupItem::boundingRect() const
{
    return d->m_boundRect;
}

KGamePopupItem::~KGamePopupItem()
{
    delete d;
}

void KGamePopupItem::hideMe()
{
    d->m_animOpacity = -1;
    // and restore child's opacity too
    d->m_textChildItem->setOpacity(d->m_opacity);

    // if we just got moved out of visibility, let's do more - let's hide :)
    if( d->m_timeLine.direction() == QTimeLine::Backward )
    {
        hide();
        emit hidden();
    }
}

void KGamePopupItem::hoverEnterEvent( QGraphicsSceneHoverEvent* )
{
    d->m_hoveredByMouse = true;
}

void KGamePopupItem::hoverLeaveEvent( QGraphicsSceneHoverEvent* )
{
    d->m_hoveredByMouse = false;

    if( d->m_timeout != 0 && !d->m_timer.isActive() && d->m_timeLine.state() != QTimeLine::Running )
    {
        playHideAnimation(); // let's hide
	}
}

void KGamePopupItem::setMessageIcon( const QPixmap& pix )
{
    d->m_iconPix = pix;
    d->m_textChildItem->setPos( MARGIN+pix.width()+SOME_SPACE, MARGIN );
    // bounding rect is updated in showMessage()
}

int KGamePopupItem::messageTimeout() const
{
    return d->m_timeout;
}

void KGamePopupItem::forceHide(HideType howToHide)
{
    if(!isVisible())
    {
        return;
    }

    if(howToHide == InstantHide)
    {
        d->m_timeLine.stop();
        d->m_timer.stop();
        hide();
        emit hidden();
    }
    else if(howToHide == AnimatedHide)
    {
        // forcefully unset it even if it is set
        // so we'll hide in any event
        d->m_hoveredByMouse = false;
        d->m_timer.stop();
        playHideAnimation();
    }
}

qreal KGamePopupItem::messageOpacity() const
{
    return d->m_opacity;
}

void KGamePopupItem::setBackgroundBrush( const QBrush& brush )
{
    d->m_brush = KStatefulBrush(brush);
}

void KGamePopupItem::setTextColor( const QColor& color )
{
    KStatefulBrush brush(color, d->m_brush.brush(QPalette::Active));
    d->m_textChildItem->setTextColor(brush);
}

void KGamePopupItem::onLinkHovered(const QString& link)
{
    if(link.isEmpty())
    {
        d->m_textChildItem->setCursor( Qt::ArrowCursor );
    }
    else
    {
        d->m_textChildItem->setCursor( Qt::PointingHandCursor );
    }

    d->m_linkHovered = !link.isEmpty();
    emit linkHovered(link);
}

void KGamePopupItem::setSharpness( Sharpness sharpness )
{
    d->m_sharpness = sharpness;
}

KGamePopupItem::Sharpness KGamePopupItem::sharpness() const
{
    return d->m_sharpness;
}

void KGamePopupItem::mousePressEvent( QGraphicsSceneMouseEvent* )
{
    // it is needed to reimplement this function to receive future
    // mouse release events
}

void KGamePopupItem::mouseReleaseEvent( QGraphicsSceneMouseEvent* )
{
    // NOTE: text child item is QGraphicsTextItem which "eats" mouse events
    // because of interaction with links. Because of that TextItemWithOpacity has
    // special signal to indicate mouse click which we catch in a onTextItemClicked()
    // slot
    if (d->m_hideOnClick)
    {
        forceHide();
    }
}

void KGamePopupItem::onTextItemClicked()
{
    // if link is hovered we don't hide as click should go to the link
    if (d->m_hideOnClick && !d->m_linkHovered)
    {
        forceHide();
    }
}

#include "moc_kgamepopupitem.cpp" // For automocing KGamePopupItem
#include "kgamepopupitem.moc" // For automocing TextItemWithOpacity