File: Clock.pm

package info (click to toggle)
qt4-perl 4.5~~svn1145508-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 5,144 kB
  • ctags: 5,947
  • sloc: perl: 29,224; cpp: 18,849; xml: 98; makefile: 91; sh: 4
file content (475 lines) | stat: -rw-r--r-- 17,731 bytes parent folder | download
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
package Clock;
#/***************************************************************************
# *   Copyright 2007 by Aaron Seigo <aseigo@kde.org>                        *
# *   Copyright 2007 by Riccardo Iaconelli <riccardo@kde.org>               *
# *   Perl translation by Chris Burel <chrisburel@gmail.com>                *
# *                                                                         *
# *   This program 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 .        *
# ***************************************************************************/

use strict;
use warnings;

use QtCore4;
use KDEUi4;
use Plasma4;
use Qt4::isa qw( ClockApplet );
use KDECore4 qw( i18n );
use List::Util qw( max );

use ClockApplet;
use Ui_ClockConfig;

use Qt4::slots
    dataUpdated => ['const QString &', 'const Plasma::DataEngine::Data &'],
    clockConfigAccepted => [],
    repaintNeeded => [],
    moveSecondHand => [];

use constant {
    RepaintNone => 1,
    RepaintAll => 2,
    RepaintHands => 3
};

my $keepme;

sub NEW {
    my ($class, $parent, $args) = @_;
    $args = [map{ Qt4::Variant( $_ ) } @$args];
    $class->SUPER::NEW( $parent, $args );
    $keepme->{please} = this;
    
    this->{m_showSecondHand} = 0;
    this->{m_showTimezoneString} = 0;
    this->{m_showingTimezone} = 0;
    this->{m_tzFrame} = 0;
    this->{m_repaintCache} = RepaintAll;
    this->{m_faceCache} = Qt4::Pixmap();
    this->{m_handsCache} = Qt4::Pixmap();
    this->{m_glassCache} = Qt4::Pixmap();
    this->{m_secondHandUpdateTimer} = 0;
    this->{m_animateSeconds} = 0;
    KDE::Global::locale()->insertCatalog('libplasmaclock');
    # this catalog is only used once on the first start of the clock to translate the timezone in the configuration file
    KDE::Global::locale()->insertCatalog('timezones4');
    this->setHasConfigurationInterface(1);
    this->resize(256, 256);
    this->setAspectRatioMode(Plasma::Square());
    this->setBackgroundHints(Plasma::Applet::NoBackground());

    this->{m_theme} = Plasma::Svg(this);
    this->{m_theme}->setImagePath('widgets/clock');
    this->{m_theme}->setContainsMultipleImages(1);
    this->{m_theme}->resize(size());

    this->{m_animationStart} = 0;
    this->{m_showingTimezone} = 0;
    this->{m_showTimezoneString} = 0;

    this->connect(this->{m_theme}, SIGNAL 'repaintNeeded()', this, SLOT 'repaintNeeded()');
}

sub init
{
    this->SUPER::init();

    my $cg = this->config();
    this->{m_showSecondHand} = $cg->readEntry(Qt4::String('showSecondHand'), Qt4::String(''));
    this->{m_showTimezoneString} = $cg->readEntry(Qt4::String('showTimezoneString'), Qt4::String(''));
    this->{m_showingTimezone} = this->{m_showTimezoneString};
    this->{m_fancyHands} = $cg->readEntry(Qt4::String('fancyHands'), Qt4::String(''));
    this->setCurrentTimezone($cg->readEntry(Qt4::String('timezone'), Qt4::String(this->localTimezone())));

    if (this->{m_showSecondHand}) {
        #We don't need to cache the applet if it update every seconds
        this->setCacheMode(Qt4::GraphicsItem::NoCache());
    } else {
        this->setCacheMode(Qt4::GraphicsItem::DeviceCoordinateCache());
    }

    this->connectToEngine();
    this->invalidateCache();
}

sub connectToEngine
{
    this->{m_lastTimeSeen} = Qt4::Time();

    my $timeEngine = this->dataEngine('time');
    if (this->{m_showSecondHand}) {
        $timeEngine->connectSource(this->currentTimezone(), this, 500);
    } else {
        $timeEngine->connectSource(this->currentTimezone(), this, 6000, Plasma::AlignToMinute());
    }
}

sub constraintsEvent
{
    my ($constraints) = @_;
    this->SUPER::constraintsEvent($constraints);

    if ($constraints & Plasma::SizeConstraint()) {
        this->invalidateCache();
    }

    if ($constraints & Plasma::FormFactorConstraint()) {
        if (this->formFactor() == Plasma::Planar() || this->formFactor() == Plasma::MediaCenter()) {
            this->setPreferredSize(256, 256);
        } else {
            this->setPreferredSize(-1, -1);
        }
    }
}

sub shape
{
    if (this->{m_theme}->hasElement('hint-square-clock')) {
        return Plasma::Applet::shape();
    }

    my $path = Qt4::PainterPath();
    # we adjust by 2px all around to allow for smoothing the jaggies
    # if the ellipse is too small, we'll get a nastily jagged edge around the clock
    $path->addEllipse(this->boundingRect()->adjusted(-2, -2, 2, 2));
    return $path;
}

sub dataUpdated
{
    my ($source, $data) = @_;
    this->{m_time} = $data->{'Time'}->toTime();

    if (this->{m_time}->minute() == this->{m_lastTimeSeen}->minute() &&
        this->{m_time}->second() == this->{m_lastTimeSeen}->second()) {
        # avoid unnecessary repaints
        return;
    }

    if (this->{m_time}->minute() != this->{m_lastTimeSeen}->minute()) {
        this->{m_repaintCache} = RepaintHands;
    }

    if (Plasma::ToolTipManager::self()->isVisible(this)) {
        this->updateTipContent();
    }

    if (this->{m_secondHandUpdateTimer}) {
        this->{m_secondHandUpdateTimer}->stop();
    }

    this->{m_animateSeconds} = 1;
    this->{m_lastTimeSeen} = this->{m_time};
    this->update();

    this->speakTime(this->{m_time});
}

sub createClockConfigurationInterface
{
    my ($parent) = @_;
    #TODO: Make the size settable
    my $widget = Qt4::Widget();
    this->{ui} = Ui_ClockConfig->setupUi($widget);
    $parent->addPage($widget, i18n('Appearance'), 'view-media-visualization');

    this->{ui}->showSecondHandCheckBox->setChecked(this->{m_showSecondHand});
    this->{ui}->showTimezoneStringCheckBox->setChecked(this->{m_showTimezoneString});
}

sub clockConfigAccepted
{
    my $cg = this->config();
    this->{m_showTimezoneString} = this->{ui}->showTimezoneStringCheckBox->isChecked();
    this->{m_showingTimezone} = this->{m_showTimezoneString} || this->shouldDisplayTimezone();
    this->{m_showSecondHand} = this->{ui}->showSecondHandCheckBox->isChecked();

    if (this->{m_showSecondHand}) {
        #We don't need to cache the applet if it update every seconds
        this->setCacheMode(Qt4::GraphicsItem::NoCache());
    } else {
        this->setCacheMode(Qt4::GraphicsItem::DeviceCoordinateCache());
    }

    $cg->writeEntry('showSecondHand', this->{m_showSecondHand});
    $cg->writeEntry('showTimezoneString', this->{m_showTimezoneString});
    this->update();

    this->dataEngine('time')->disconnectSource(this->currentTimezone(), this);
    this->connectToEngine();

    this->constraintsEvent(Plasma::AllConstraints());
    emit this->configNeedsSaving();
}

sub changeEngineTimezone
{
    my ($oldTimezone, $newTimezone) = @_;
    this->dataEngine('time')->disconnectSource($oldTimezone, this);
    my $timeEngine = this->dataEngine('time');

    if (this->{m_showSecondHand}) {
        $timeEngine->connectSource($newTimezone, this, 500);
    } else {
        $timeEngine->connectSource($newTimezone, this, 6000, Plasma::AlignToMinute());
    }

    if (this->{m_showingTimezone} != (this->{m_showTimezoneString} || this->shouldDisplayTimezone())) {
        this->{m_showingTimezone} = !(this->{m_showingTimezone});
        this->constraintsEvent(Plasma::SizeConstraint());
    }
    this->{m_repaintCache} = RepaintAll;
}

sub repaintNeeded
{
    this->{m_repaintCache} = RepaintAll;
    this->update();
}

sub moveSecondHand
{
    #kDebug() << 'moving second hand';
    this->update();
}

sub drawHand
{
    my ($p, $rect, $verticalTranslation, $rotation, $handName) = @_;
    # this code assumes the following conventions in the svg file:
    # - the _vertical_ position of the hands should be set with respect to the center of the face
    # - the _horizontal_ position of the hands does not matter
    # - the _shadow_ elements should have the same vertical position as their _hand_ element counterpart

    my $elementRect = Qt4::RectF();
    my $name = $handName . 'HandShadow';
    if (this->{m_theme}->hasElement($name)) {
        $p->save();

        $elementRect = this->{m_theme}->elementRect($name);
        if( $rect->height() < ${KDE::IconLoader::SizeEnormous()} ) {
            $elementRect->setWidth( $elementRect->width() * 2.5 );
        }
        my $offset = Qt4::Point(2, 3);

        $p->translate($rect->x() + ($rect->width() / 2) + $offset->x(), $rect->y() + ($rect->height() / 2) + $offset->y());
        $p->rotate($rotation);
        $p->translate(-$elementRect->width()/2, $elementRect->y()-$verticalTranslation);
        this->{m_theme}->paint($p, Qt4::RectF(Qt4::PointF(0, 0), $elementRect->size()), $name);

        $p->restore();
    }

    $p->save();

    $name = $handName . 'Hand';
    $elementRect = this->{m_theme}->elementRect($name);
    if ($rect->height() < ${KDE::IconLoader::SizeEnormous()}) {
        $elementRect->setWidth($elementRect->width() * 2.5);
    }

    $p->translate($rect->x() + $rect->width()/2, $rect->y() + $rect->height()/2);
    $p->rotate($rotation);
    $p->translate(-$elementRect->width()/2, $elementRect->y()-$verticalTranslation);
    this->{m_theme}->paint($p, Qt4::RectF(Qt4::PointF(0, 0), $elementRect->size()), $name);

    $p->restore();
}

sub paintInterface
{
    my ($p, $option, $rect) = @_;
    $rect = Qt4::RectF( $rect );

    # compute hand angles
    my $minutes = 6.0 * this->{m_time}->minute() - 180;
    my $hours = 30.0 * this->{m_time}->hour() - 180 +
                        ((this->{m_time}->minute() / 59.0) * 30.0);
    my $seconds = 0;
    if (this->{m_showSecondHand}) {
        my $anglePerSec = 6;
        $seconds = $anglePerSec * this->{m_time}->second() - 180;

        if (this->{m_fancyHands}) {
            if (!defined this->{m_secondHandUpdateTimer}) {
                this->{m_secondHandUpdateTimer} = Qt4::Timer(this);
                this->connect(this->{m_secondHandUpdateTimer}, SIGNAL 'timeout()', this, SLOT 'moveSecondHand()');
            }

            if (this->{m_animateSeconds} && !this->{m_secondHandUpdateTimer}->isActive()) {
                #kDebug() << 'starting second hand movement';
                this->{m_secondHandUpdateTimer}->start(50);
                this->{m_animationStart} = Qt4::Time::currentTime()->msec();
            } else {
                my $runTime = 500;
                my $m = 1; # Mass
                my $b = 1; # Drag coefficient
                my $k = 1.5; # Spring constant
                my $PI = 3.141592653589793; # the universe is irrational
                my $gamma = $b / (2 * $m); # Dampening constant
                my $omega0 = sqrt($k / $m);
                my $omega1 = sqrt($omega0 * $omega0 - $gamma * $gamma);
                my $elapsed = Qt4::Time::currentTime()->msec() - this->{m_animationStart};
                my $t = (4 * $PI) * ($elapsed / $runTime);
                my $val = 1 + exp(-$gamma * $t) * -cos($omega1 * $t);

                if ($elapsed > $runTime) {
                    this->{m_secondHandUpdateTimer}->stop();
                    this->{m_animateSeconds} = 0;
                } else {
                    $seconds += -$anglePerSec + ($anglePerSec * $val);
                }
            }
        } else {
            if (!this->{m_secondHandUpdateTimer}) {
                this->{m_secondHandUpdateTimer} = Qt4::Timer(this);
                this->connect(this->{m_secondHandUpdateTimer}, SIGNAL 'timeout()', this, SLOT 'moveSecondHand()');
            }
            
            if (this->{m_animationStart} != $seconds && !this->{m_secondHandUpdateTimer}->isActive()) {
                this->{m_secondHandUpdateTimer}->start(50);
                this->{m_animationStart} = $seconds; #we don't want to have a second animation if there is a external update (wallpaper etc).
                $seconds += 1;
            } else {
                this->{m_secondHandUpdateTimer}->stop();
            }
        }
    }

    if (this->contentsRect()->size()->toSize() != this->{m_theme}->size()) {
        this->invalidateCache();
    }

    # paint face and glass cache
    my $faceRect = Qt4::RectF(this->{m_faceCache}->rect());
    if (this->{m_repaintCache} == RepaintAll) {
        this->{m_faceCache}->fill(Qt4::Color(Qt4::transparent()));
        this->{m_glassCache}->fill(Qt4::Color(Qt4::transparent()));

        my $facePainter = Qt4::Painter(this->{m_faceCache});
        my $glassPainter = Qt4::Painter(this->{m_glassCache});
        $facePainter->setRenderHint(Qt4::Painter::SmoothPixmapTransform());
        $glassPainter->setRenderHint(Qt4::Painter::SmoothPixmapTransform());

        this->{m_theme}->paint($facePainter, $faceRect, 'ClockFace');

        $glassPainter->save();
        my $elementRect = Qt4::RectF(Qt4::PointF(0, 0), Qt4::SizeF(this->{m_theme}->elementSize('HandCenterScrew')));
        $glassPainter->translate($faceRect->width() / 2 - $elementRect->width() / 2, $faceRect->height() / 2 - $elementRect->height() / 2);
        this->{m_theme}->paint($glassPainter, $elementRect, 'HandCenterScrew');
        $glassPainter->restore();

        this->{m_theme}->paint($glassPainter, $faceRect, 'Glass');

        # get vertical translation, see drawHand() for more details
        this->{m_verticalTranslation} = this->{m_theme}->elementRect('ClockFace')->center()->y();
        $facePainter->end();
        $glassPainter->end();
    }

    # paint hour and minute hands cache
    if (this->{m_repaintCache} == RepaintHands || this->{m_repaintCache} == RepaintAll) {
        this->{m_handsCache}->fill(Qt4::Color(Qt4::transparent()));

        my $handsPainter = Qt4::Painter(this->{m_handsCache});
        $handsPainter->drawPixmap($faceRect, this->{m_faceCache}, $faceRect);
        $handsPainter->setRenderHint(Qt4::Painter::SmoothPixmapTransform());

        this->drawHand($handsPainter, $faceRect, this->{m_verticalTranslation}, $hours, 'Hour');
        this->drawHand($handsPainter, $faceRect, this->{m_verticalTranslation}, $minutes, 'Minute');
        $handsPainter->end();
    }

    # reset repaint cache flag
    this->{m_repaintCache} = RepaintNone;

    # paint caches and second hand
    # We're going to modify this copy of the rect, so make a copy of it.  Just
    # saying $targetRect = $faceRect won't copy it.
    my $targetRect = Qt4::RectF( $faceRect );
    if ($targetRect->width() < $rect->width()) {
        $targetRect->moveLeft(($rect->width() - $targetRect->width()) / 2);
    }
    $targetRect->translate($rect->topLeft());

    $p->drawPixmap($targetRect, this->{m_handsCache}, $faceRect);
    if (this->{m_showSecondHand}) {
        $p->setRenderHint(Qt4::Painter::SmoothPixmapTransform());
        this->drawHand($p, $targetRect, this->{m_verticalTranslation}, $seconds, 'Second');
    }
    $p->drawPixmap($targetRect, this->{m_glassCache}, $faceRect);

    # optionally paint the time string
    if (this->{m_showingTimezone}) {
        my $time = this->prettyTimezone();

        if ($time) {
            my $textRect = this->tzRect();
            this->tzFrame()->paintFrame($p, Qt4::RectF($textRect), Qt4::RectF(Qt4::Point(0, 0), $textRect->size()));

            $p->setPen(Plasma::Theme::defaultTheme()->color(Plasma::Theme::TextColor()));
            $p->setFont(Plasma::Theme::defaultTheme()->font(Plasma::Theme::DefaultFont()));
            $p->drawText($textRect, Qt4::AlignCenter(), $time);
        }
    }
}

sub tzRect
{
    my $rect = this->contentsRect()->toRect();
    my $font = Plasma::Theme::defaultTheme()->font(Plasma::Theme::DefaultFont());
    my $fm = Qt4::FontMetrics($font);
    my ( $left, $top, $right, $bottom ) = (0, 0, 0, 0);
    this->tzFrame()->getMargins($left, $top, $right, $bottom);
    my $height = $top + $bottom + $fm->height();
    return Qt4::Rect(0, $rect->bottom() - $height, $rect->width(), $height);
}

sub tzFrame
{
    if (!this->{m_tzFrame}) {
        this->{m_tzFrame} = Plasma::FrameSvg(this);
        this->{m_tzFrame}->setImagePath('widgets/background');
    }

    return this->{m_tzFrame};
}

sub invalidateCache
{
    this->{m_repaintCache} = RepaintAll;

    my $pixmapSize = this->contentsRect()->size()->toSize();

    if (this->{m_showingTimezone}) {
        my $tzArea = this->tzRect();
        $pixmapSize->setHeight(max(10, $pixmapSize->height() - $tzArea->height()));
        this->tzFrame()->resizeFrame(Qt4::SizeF($tzArea->size()));
    }

    $pixmapSize->setWidth($pixmapSize->height());
    this->{m_faceCache} = Qt4::Pixmap($pixmapSize);
    this->{m_handsCache} = Qt4::Pixmap($pixmapSize);
    this->{m_glassCache} = Qt4::Pixmap($pixmapSize);

    this->{m_faceCache}->fill(Qt4::Color(Qt4::transparent()));
    this->{m_glassCache}->fill(Qt4::Color(Qt4::transparent()));
    this->{m_handsCache}->fill(Qt4::Color(Qt4::transparent()));

    this->{m_theme}->resize(Qt4::SizeF($pixmapSize));
}

1;