~ubuntu-branches/ubuntu/utopic/kde-workspace/utopic-proposed

« back to all changes in this revision

Viewing changes to kcontrol/dateandtime/dtime.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Michał Zając
  • Date: 2011-07-09 08:31:15 UTC
  • Revision ID: james.westby@ubuntu.com-20110709083115-ohyxn6z93mily9fc
Tags: upstream-4.6.90
Import upstream version 4.6.90

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 *  dtime.cpp
 
3
 *
 
4
 *  Copyright (C) 1998 Luca Montecchiani <m.luca@usa.net>
 
5
 *
 
6
 *  Plasma analog-clock drawing code:
 
7
 *
 
8
 *  Copyright 2007 by Aaron Seigo <aseigo@kde.org>
 
9
 *  Copyright 2007 by Riccardo Iaconelli <riccardo@kde.org>
 
10
 *
 
11
 *  This program is free software; you can redistribute it and/or modify
 
12
 *  it under the terms of the GNU General Public License as published by
 
13
 *  the Free Software Foundation; either version 2 of the License, or
 
14
 *  (at your option) any later version.
 
15
 *
 
16
 *  This program is distributed in the hope that it will be useful,
 
17
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
18
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
19
 *  GNU General Public License for more details.
 
20
 *
 
21
 *  You should have received a copy of the GNU General Public License
 
22
 *  along with this program; if not, write to the Free Software
 
23
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
24
 *
 
25
 */
 
26
#include "dtime.h"
 
27
 
 
28
#include <stdlib.h>
 
29
#include <unistd.h>
 
30
#include <time.h>
 
31
#include <sys/types.h>
 
32
 
 
33
#include <QComboBox>
 
34
#include <QtGui/QGroupBox>
 
35
#include <QPushButton>
 
36
#include <QPainter>
 
37
#include <QTimeEdit>
 
38
 
 
39
#include <QCheckBox>
 
40
#include <QPaintEvent>
 
41
#include <QGridLayout>
 
42
#include <QHBoxLayout>
 
43
#include <QVBoxLayout>
 
44
#include <kdebug.h>
 
45
#include <klocale.h>
 
46
#include <kprocess.h>
 
47
#include <kstandarddirs.h>
 
48
#include <kmessagebox.h>
 
49
#include <kdialog.h>
 
50
#include <kconfig.h>
 
51
#include <kcolorscheme.h>
 
52
#include <ksystemtimezone.h>
 
53
#include <KTreeWidgetSearchLine>
 
54
 
 
55
#include <Plasma/Svg>
 
56
 
 
57
#include "dtime.moc"
 
58
 
 
59
#include "helper.h"
 
60
 
 
61
Dtime::Dtime(QWidget * parent)
 
62
  : QWidget(parent)
 
63
{
 
64
  KGlobal::locale()->insertCatalog( "timezones4" );
 
65
  setupUi(this);
 
66
 
 
67
  connect(setDateTimeAuto, SIGNAL(toggled(bool)), this, SLOT(serverTimeCheck()));
 
68
  connect(setDateTimeAuto, SIGNAL(toggled(bool)), SLOT(configChanged()));
 
69
 
 
70
  timeServerList->setEditable(false);
 
71
  connect(timeServerList, SIGNAL(activated(int)), SLOT(configChanged()));
 
72
  connect(timeServerList, SIGNAL(editTextChanged(const QString &)), SLOT(configChanged()));
 
73
  connect(setDateTimeAuto, SIGNAL(toggled(bool)), timeServerList, SLOT(setEnabled(bool)));
 
74
  timeServerList->setEnabled(false);
 
75
  timeServerList->setEditable(true);
 
76
  findNTPutility();
 
77
  if (ntpUtility.isEmpty()) {
 
78
      setDateTimeAuto->setEnabled(false);
 
79
      setDateTimeAuto->setToolTip(i18n("No NTP utility has been found. "
 
80
                                       "Install 'ntpdate' or 'rdate' command to enable automatic "
 
81
                                       "updating of date and time."));
 
82
  }
 
83
 
 
84
  QVBoxLayout *v2 = new QVBoxLayout( timeBox );
 
85
  v2->setMargin( 0 );
 
86
 
 
87
  kclock = new Kclock( timeBox );
 
88
  kclock->setObjectName("Kclock");
 
89
  kclock->setMinimumSize(150,150);
 
90
  v2->addWidget( kclock );
 
91
 
 
92
  v2->addSpacing( KDialog::spacingHint() );
 
93
 
 
94
  QHBoxLayout *v3 = new QHBoxLayout( );
 
95
  v2->addLayout( v3 );
 
96
 
 
97
  v3->addStretch();
 
98
 
 
99
  timeEdit = new QTimeEdit( timeBox );
 
100
  timeEdit->setWrapping(true);
 
101
  timeEdit->setDisplayFormat("HH:mm:ss");
 
102
  v3->addWidget(timeEdit);
 
103
 
 
104
  v3->addStretch();
 
105
 
 
106
  QString wtstr = i18n("Here you can change the system time. Click into the"
 
107
    " hours, minutes or seconds field to change the relevant value, either"
 
108
    " using the up and down buttons to the right or by entering a new value.");
 
109
  timeEdit->setWhatsThis( wtstr );
 
110
 
 
111
  connect( timeEdit, SIGNAL(timeChanged(QTime)), SLOT(set_time()) );
 
112
  connect( cal, SIGNAL(dateChanged(QDate)), SLOT(changeDate(QDate)));
 
113
 
 
114
  connect( &internalTimer, SIGNAL(timeout()), SLOT(timeout()) );
 
115
 
 
116
  kclock->setEnabled(false);
 
117
 
 
118
  //Timezone
 
119
  connect( tzonelist, SIGNAL(itemSelectionChanged()), SLOT(configChanged()) );
 
120
  tzonesearch->setTreeWidget(tzonelist);
 
121
}
 
122
 
 
123
void Dtime::currentZone()
 
124
{
 
125
    QByteArray result(100, '\0');
 
126
 
 
127
    time_t now = ::time(0);
 
128
    tzset();
 
129
    strftime(result.data(), result.size(), "%Z", localtime(&now));
 
130
    m_local->setText(i18n("Current local time zone: %1 (%2)",
 
131
                          KTimeZoneWidget::displayName(KSystemTimeZones::local()),
 
132
                          QLatin1String(result)));
 
133
}
 
134
 
 
135
void Dtime::serverTimeCheck() {
 
136
  bool enabled = !setDateTimeAuto->isChecked();
 
137
  cal->setEnabled(enabled);
 
138
  timeEdit->setEnabled(enabled);
 
139
  //kclock->setEnabled(enabled);
 
140
}
 
141
 
 
142
void Dtime::findNTPutility(){
 
143
  QByteArray envpath = qgetenv("PATH");
 
144
  if (!envpath.isEmpty() && envpath[0] == ':') {
 
145
    envpath = envpath.mid(1);
 
146
  }
 
147
 
 
148
  QString path = "/sbin:/usr/sbin:";
 
149
  if (!envpath.isEmpty()) {
 
150
    path += QString::fromLocal8Bit(envpath);
 
151
  } else {
 
152
    path += QLatin1String("/bin:/usr/bin");
 
153
  }
 
154
 
 
155
  foreach(const QString &possible_ntputility, QStringList() << "ntpdate" << "rdate" ) {
 
156
    if( !((ntpUtility = KStandardDirs::findExe(possible_ntputility, path)).isEmpty()) ) {
 
157
      kDebug() << "ntpUtility = " << ntpUtility;
 
158
      return;
 
159
    }
 
160
  }
 
161
 
 
162
  kDebug() << "ntpUtility not found!";
 
163
}
 
164
 
 
165
void Dtime::set_time()
 
166
{
 
167
  if( ontimeout )
 
168
    return;
 
169
 
 
170
  internalTimer.stop();
 
171
 
 
172
  time = timeEdit->time();
 
173
  kclock->setTime( time );
 
174
 
 
175
  emit timeChanged( true );
 
176
}
 
177
 
 
178
void Dtime::changeDate(const QDate &d)
 
179
{
 
180
  date = d;
 
181
  emit timeChanged( true );
 
182
}
 
183
 
 
184
void Dtime::configChanged(){
 
185
  emit timeChanged( true );
 
186
}
 
187
 
 
188
void Dtime::load()
 
189
{
 
190
  // The config is actually written to the system config, but the user does not have any local config,
 
191
  // since there is nothing writing it.
 
192
  KConfig _config( "kcmclockrc", KConfig::NoGlobals );
 
193
  KConfigGroup config(&_config, "NTP");
 
194
  timeServerList->clear();
 
195
  timeServerList->addItems(config.readEntry("servers",
 
196
    i18n("Public Time Server (pool.ntp.org),\
 
197
asia.pool.ntp.org,\
 
198
europe.pool.ntp.org,\
 
199
north-america.pool.ntp.org,\
 
200
oceania.pool.ntp.org")).split(',', QString::SkipEmptyParts));
 
201
  setDateTimeAuto->setChecked(config.readEntry("enabled", false));
 
202
 
 
203
  // Reset to the current date and time
 
204
  time = QTime::currentTime();
 
205
  date = QDate::currentDate();
 
206
  cal->setDate(date);
 
207
 
 
208
  // start internal timer
 
209
  internalTimer.start( 1000 );
 
210
 
 
211
  timeout();
 
212
 
 
213
  //Timezone
 
214
  currentZone();
 
215
 
 
216
  // read the currently set time zone
 
217
  tzonelist->setSelected(KSystemTimeZones::local().name(), true);
 
218
}
 
219
 
 
220
void Dtime::save( QVariantMap& helperargs )
 
221
{
 
222
  // Save the order, but don't duplicate!
 
223
  QStringList list;
 
224
  if( timeServerList->count() != 0)
 
225
    list.append(timeServerList->currentText());
 
226
  for ( int i=0; i<timeServerList->count();i++ ) {
 
227
    QString text = timeServerList->itemText(i);
 
228
    if( !list.contains(text) )
 
229
      list.append(text);
 
230
    // Limit so errors can go away and not stored forever
 
231
    if( list.count() == 10)
 
232
      break;
 
233
  }
 
234
 
 
235
  helperargs["ntp"] = true;
 
236
  helperargs["ntpServers"] = list;
 
237
  helperargs["ntpEnabled"] = setDateTimeAuto->isChecked();
 
238
  helperargs["ntpUtility"] = ntpUtility;
 
239
 
 
240
  if(setDateTimeAuto->isChecked() && !ntpUtility.isEmpty()){
 
241
    // NTP Time setting - done in helper
 
242
    timeServer = timeServerList->currentText();
 
243
    kDebug() << "Setting date from time server " << timeServer;
 
244
  }
 
245
  else {
 
246
    // User time setting
 
247
    QDateTime dt(date, QTime(timeEdit->time()));
 
248
 
 
249
    kDebug() << "Set date " << dt;
 
250
 
 
251
    helperargs["date"] = true;
 
252
    helperargs["newdate"] = QString::number(dt.toTime_t());
 
253
    helperargs["olddate"] = QString::number(::time(0));
 
254
  }
 
255
 
 
256
  // restart time
 
257
  internalTimer.start( 1000 );
 
258
 
 
259
  QStringList selectedZones(tzonelist->selection());
 
260
 
 
261
  if (selectedZones.count() > 0) {
 
262
    QString selectedzone(selectedZones[0]);
 
263
    helperargs["tz"] = true;
 
264
    helperargs["tzone"] = selectedzone;
 
265
  } else {
 
266
    helperargs["tzreset"] = true; // // make the helper reset the timezone
 
267
  }
 
268
 
 
269
  currentZone();
 
270
}
 
271
 
 
272
void Dtime::processHelperErrors( int code )
 
273
{
 
274
  if( code & ClockHelper::NTPError ) {
 
275
    KMessageBox::error( this, i18n("Unable to contact time server: %1.", timeServer) );
 
276
    setDateTimeAuto->setChecked( false );
 
277
  }
 
278
  if( code & ClockHelper::DateError ) {
 
279
    KMessageBox::error( this, i18n("Can not set date."));
 
280
  }
 
281
  if( code & ClockHelper::TimezoneError)
 
282
    KMessageBox::error( this, i18n("Error setting new time zone."),
 
283
                        i18n("Time zone Error"));
 
284
}
 
285
 
 
286
void Dtime::timeout()
 
287
{
 
288
  // get current time
 
289
  time = QTime::currentTime();
 
290
 
 
291
  ontimeout = true;
 
292
  timeEdit->setTime(time);
 
293
  ontimeout = false;
 
294
 
 
295
  kclock->setTime( time );
 
296
}
 
297
 
 
298
QString Dtime::quickHelp() const
 
299
{
 
300
  return i18n("<h1>Date & Time</h1> This system settings module can be used to set the system date and"
 
301
    " time. As these settings do not only affect you as a user, but rather the whole system, you"
 
302
    " can only change these settings when you start the System Settings as root. If you do not have"
 
303
    " the root password, but feel the system time should be corrected, please contact your system"
 
304
    " administrator.");
 
305
}
 
306
 
 
307
Kclock::Kclock(QWidget *parent)
 
308
    : QWidget(parent)
 
309
{
 
310
    m_theme = new Plasma::Svg(this);
 
311
    m_theme->setImagePath("widgets/clock");
 
312
    m_theme->setContainsMultipleImages(true);
 
313
}
 
314
 
 
315
Kclock::~Kclock()
 
316
{
 
317
    delete m_theme;
 
318
}
 
319
 
 
320
void Kclock::showEvent( QShowEvent *event )
 
321
{
 
322
    setClockSize( size() );
 
323
    QWidget::showEvent( event );
 
324
}
 
325
 
 
326
void Kclock::resizeEvent( QResizeEvent * )
 
327
{
 
328
    setClockSize( size() );
 
329
}
 
330
 
 
331
void Kclock::setClockSize(const QSize &size)
 
332
{
 
333
    int dim = qMin(size.width(), size.height());
 
334
    QSize newSize = QSize(dim, dim);
 
335
 
 
336
    if (newSize != m_faceCache.size()) {
 
337
        m_faceCache = QPixmap(newSize);
 
338
        m_handsCache = QPixmap(newSize);
 
339
        m_glassCache = QPixmap(newSize);
 
340
 
 
341
        m_theme->resize(newSize);
 
342
        m_repaintCache = RepaintAll;
 
343
    }
 
344
}
 
345
 
 
346
void Kclock::setTime(const QTime &time)
 
347
{
 
348
    if (time.minute() != this->time.minute() || time.hour() != this->time.hour()) {
 
349
        if (m_repaintCache == RepaintNone) {
 
350
            m_repaintCache = RepaintHands;
 
351
        }
 
352
    }
 
353
    this->time = time;
 
354
    update();
 
355
}
 
356
 
 
357
void Kclock::drawHand(QPainter *p, const QRect &rect, const qreal verticalTranslation, const qreal rotation, const QString &handName)
 
358
{
 
359
    // this code assumes the following conventions in the svg file:
 
360
    // - the _vertical_ position of the hands should be set with respect to the center of the face
 
361
    // - the _horizontal_ position of the hands does not matter
 
362
    // - the _shadow_ elements should have the same vertical position as their _hand_ element counterpart
 
363
 
 
364
    QRectF elementRect;
 
365
    QString name = handName + "HandShadow";
 
366
    if (m_theme->hasElement(name)) {
 
367
        p->save();
 
368
 
 
369
        elementRect = m_theme->elementRect(name);
 
370
        if( rect.height() < 64 )
 
371
            elementRect.setWidth( elementRect.width() * 2.5 );
 
372
        static const QPoint offset = QPoint(2, 3);
 
373
 
 
374
        p->translate(rect.x() + (rect.width() / 2) + offset.x(), rect.y() + (rect.height() / 2) + offset.y());
 
375
        p->rotate(rotation);
 
376
        p->translate(-elementRect.width()/2, elementRect.y()-verticalTranslation);
 
377
        m_theme->paint(p, QRectF(QPointF(0, 0), elementRect.size()), name);
 
378
 
 
379
        p->restore();
 
380
    }
 
381
 
 
382
    p->save();
 
383
 
 
384
    name = handName + "Hand";
 
385
    elementRect = m_theme->elementRect(name);
 
386
    if (rect.height() < 64) {
 
387
        elementRect.setWidth(elementRect.width() * 2.5);
 
388
    }
 
389
 
 
390
    p->translate(rect.x() + rect.width()/2, rect.y() + rect.height()/2);
 
391
    p->rotate(rotation);
 
392
    p->translate(-elementRect.width()/2, elementRect.y()-verticalTranslation);
 
393
    m_theme->paint(p, QRectF(QPointF(0, 0), elementRect.size()), name);
 
394
 
 
395
    p->restore();
 
396
}
 
397
 
 
398
void Kclock::paintInterface(QPainter *p, const QRect &rect)
 
399
{
 
400
    const bool m_showSecondHand = true;
 
401
 
 
402
    // compute hand angles
 
403
    const qreal minutes = 6.0 * time.minute() - 180;
 
404
    const qreal hours = 30.0 * time.hour() - 180 +
 
405
            ((time.minute() / 59.0) * 30.0);
 
406
    qreal seconds = 0;
 
407
    if (m_showSecondHand) {
 
408
        static const double anglePerSec = 6;
 
409
        seconds = anglePerSec * time.second() - 180;
 
410
    }
 
411
 
 
412
    // paint face and glass cache
 
413
    QRect faceRect = m_faceCache.rect();
 
414
    if (m_repaintCache == RepaintAll) {
 
415
        m_faceCache.fill(Qt::transparent);
 
416
        m_glassCache.fill(Qt::transparent);
 
417
 
 
418
        QPainter facePainter(&m_faceCache);
 
419
        QPainter glassPainter(&m_glassCache);
 
420
        facePainter.setRenderHint(QPainter::SmoothPixmapTransform);
 
421
        glassPainter.setRenderHint(QPainter::SmoothPixmapTransform);
 
422
 
 
423
        m_theme->paint(&facePainter, m_faceCache.rect(), "ClockFace");
 
424
 
 
425
        glassPainter.save();
 
426
        QRectF elementRect = QRectF(QPointF(0, 0), m_theme->elementSize("HandCenterScrew"));
 
427
        glassPainter.translate(faceRect.width() / 2 - elementRect.width() / 2, faceRect.height() / 2 - elementRect.height() / 2);
 
428
        m_theme->paint(&glassPainter, elementRect, "HandCenterScrew");
 
429
        glassPainter.restore();
 
430
 
 
431
        m_theme->paint(&glassPainter, faceRect, "Glass");
 
432
 
 
433
        // get vertical translation, see drawHand() for more details
 
434
        m_verticalTranslation = m_theme->elementRect("ClockFace").center().y();
 
435
    }
 
436
 
 
437
    // paint hour and minute hands cache
 
438
    if (m_repaintCache == RepaintHands || m_repaintCache == RepaintAll) {
 
439
        m_handsCache.fill(Qt::transparent);
 
440
 
 
441
        QPainter handsPainter(&m_handsCache);
 
442
        handsPainter.drawPixmap(faceRect, m_faceCache, faceRect);
 
443
        handsPainter.setRenderHint(QPainter::SmoothPixmapTransform);
 
444
 
 
445
        drawHand(&handsPainter, faceRect, m_verticalTranslation, hours, "Hour");
 
446
        drawHand(&handsPainter, faceRect, m_verticalTranslation, minutes, "Minute");
 
447
    }
 
448
 
 
449
    // reset repaint cache flag
 
450
    m_repaintCache = RepaintNone;
 
451
 
 
452
    // paint caches and second hand
 
453
    QRect targetRect = faceRect;
 
454
    if (targetRect.width() < rect.width()) {
 
455
        targetRect.moveLeft((rect.width() - targetRect.width()) / 2);
 
456
    }
 
457
 
 
458
    p->drawPixmap(targetRect, m_handsCache, faceRect);
 
459
    if (m_showSecondHand) {
 
460
        p->setRenderHint(QPainter::SmoothPixmapTransform);
 
461
        drawHand(p, targetRect, m_verticalTranslation, seconds, "Second");
 
462
    }
 
463
    p->drawPixmap(targetRect, m_glassCache, faceRect);
 
464
}
 
465
 
 
466
void Kclock::paintEvent( QPaintEvent * )
 
467
{
 
468
  QPainter paint(this);
 
469
 
 
470
  paint.setRenderHint(QPainter::Antialiasing);
 
471
  paintInterface(&paint, rect());
 
472
}
 
473