summaryrefslogtreecommitdiff
path: root/noncore/settings/netsystemtime/mainwindow.cpp
blob: c1cd79656afb47ae579b1db20dfc238a3111aa32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
                             This file is part of the Opie Project

                             Copyright (C) Opie Team <opie-devel@handhelds.org>
              =.
            .=l.
           .>+-=
 _;:,     .>    :=|.         This program is free software; you can
.> <`_,   >  .   <=          redistribute it and/or  modify it under
:`=1 )Y*s>-.--   :           the terms of the GNU Library General Public
.="- .-=="i,     .._         License as published by the Free Software
 - .   .-<_>     .<>         Foundation; either version 2 of the License,
     ._= =}       :          or (at your option) any later version.
    .%`+i>       _;_.
    .i_,=:_.      -<s.       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
..}^=.=       =       ;      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., 59 Temple Place - Suite 330,
                             Boston, MA 02111-1307, USA.
*/

#include "mainwindow.h"
#include "timetabwidget.h"
#include "formattabwidget.h"
#include "settingstabwidget.h"
#include "ntptabwidget.h"
#include "predicttabwidget.h"

#include <qpe/config.h>
#include <qpe/datebookdb.h>
#include <qpe/qpeapplication.h>
#include <qpe/qpedialog.h>

#if ( defined Q_WS_QWS || defined(_WS_QWS_) ) && !defined(QT_NO_COP)
#include <qpe/qcopenvelope_qws.h>
#endif

#include <qlayout.h>
#include <qmessagebox.h>
#include <qsocket.h>
#include <qstring.h>
#include <qtimer.h>

using namespace Opie::Ui;
using namespace Opie::Core;
MainWindow::MainWindow( QWidget *parent , const char *name,  bool modal, WFlags f )
    : QDialog( parent, name, modal, f )
{
    setCaption( tr( "SystemTime" ) );

    QVBoxLayout *layout = new QVBoxLayout( this );
    layout->setMargin( 2 );
    layout->setSpacing( 4 );

    // Create main tabbed control
    mainWidget = new OTabWidget( this );

    // Default object pointers to null
    ntpProcess = 0x0;
    ntpTab = 0x0;
    predictTab = 0x0;

    // Add tab widgets
    mainWidget->addTab( timeTab = new TimeTabWidget( mainWidget ), "netsystemtime/DateTime", tr( "Time" ) );
    mainWidget->addTab( formatTab = new FormatTabWidget( mainWidget ), "netsystemtime/formattab", tr( "Format" ) );
    mainWidget->addTab( settingsTab = new SettingsTabWidget( mainWidget ), "SettingsIcon", tr( "Settings" ) );
    Config config( "ntp" );
    config.setGroup( "settings" );
    slotDisplayNTPTab( config.readBoolEntry( "displayNtpTab", false ) );
    slotDisplayPredictTab( config.readBoolEntry( "displayPredictTab", false ) );

    mainWidget->setCurrentTab( tr( "Time" ) );
    layout->addWidget( mainWidget );

    connect( qApp, SIGNAL(appMessage(const QCString&,const QByteArray&)),
        this, SLOT(slotQCopReceive(const QCString&,const QByteArray&)) );


    // Create NTP socket
    ntpSock = new QSocket( this );
    connect( ntpSock, SIGNAL(error(int)),SLOT(slotCheckNtp(int)) );
    slotProbeNTPServer();

    // Create timer for automatic time lookups
    ntpTimer = new QTimer( this );

    // Connect everything together
    connect( timeTab, SIGNAL(getNTPTime()), this, SLOT(slotGetNTPTime()) );
    connect( timeTab, SIGNAL(tzChanged(const QString&)), predictTab, SLOT(slotTZChanged(const QString&)) );
    connect( timeTab, SIGNAL(getPredictedTime()), predictTab, SLOT(slotSetPredictedTime()) );
    connect( formatTab, SIGNAL(show12HourTime(int)), timeTab, SLOT(slotUse12HourTime(int)) );
    connect( formatTab, SIGNAL(dateFormatChanged(const DateFormat&)),
             timeTab, SLOT(slotDateFormatChanged(const DateFormat&)) );
    connect( formatTab, SIGNAL(weekStartChanged(int)), timeTab, SLOT(slotWeekStartChanged(int)) );
    connect( settingsTab, SIGNAL(ntpDelayChanged(int)), this, SLOT(slotNTPDelayChanged(int)) );
    connect( settingsTab, SIGNAL(displayNTPTab(bool)), this, SLOT(slotDisplayNTPTab(bool)) );
    connect( settingsTab, SIGNAL(displayPredictTab(bool)), this, SLOT(slotDisplayPredictTab(bool)) );
    connect( predictTab, SIGNAL(setTime(const QDateTime&)), this, SLOT(slotSetTime(const QDateTime&)) );

    // Do initial time server check
    slotNTPDelayChanged( config.readNumEntry( "ntpRefreshFreq", 1440 ) );
    slotCheckNtp( -1 );

    // Display app
    //showMaximized();
    (void)new QPEDialogListener(this);
}

MainWindow::~MainWindow()
{
    if ( ntpProcess )
        delete ntpProcess;
}

void MainWindow::accept()
{
    // Turn off the screensaver (Note: needs to be encased in { } so that it deconstructs and sends)
    {
        QCopEnvelope disableScreenSaver( "QPE/System", "setScreenSaverIntervals(int,int,int)" );
        disableScreenSaver << 0 << 0 << 0;
    }

    // Update the systemtime
    timeTab->saveSettings( true );

    // Save format options
    formatTab->saveSettings( true );

    // Save settings options
    settingsTab->saveSettings();

    // Since time has changed quickly load in the DateBookDB to allow the alarm server to get a better
    // grip on itself (example re-trigger alarms for when we travel back in time).
    DateBookDB db;

    // Turn back on the screensaver
    QCopEnvelope enableScreenSaver( "QPE/System", "setScreenSaverIntervals(int,int,int)" );
    enableScreenSaver << -1 << -1 << -1;

    // Exit app
    qApp->quit();
}

void MainWindow::reject()
{
    // Reset time settings
    timeTab->saveSettings( false );

    // Send notifications but do not save settings
    formatTab->saveSettings( false );

    // Exit app
    qApp->quit();
}

void MainWindow::runNTP()
{
    if ( !ntpDelayElapsed() && ntpInteractive )
    {
        QString msg = tr( "You asked for a delay of %1 minutes, but only %2 minutes elapsed since last lookup.<br>Continue?" ).arg( QString::number( ntpDelay ) ).arg( QString::number( _lookupDiff / 60 ) );

        switch (
            QMessageBox::warning( this, tr( "Continue?" ), msg, QMessageBox::Yes, QMessageBox::No )
            )
        {
            case QMessageBox::Yes: break;
            case QMessageBox::No:  return;
            default: return;
        }
    }

    QString srv = settingsTab->ntpServer();

    // Send information to time server tab if enabled
    if ( ntpTabEnabled )
    {
        ntpTab->setStartTime( QDateTime::currentDateTime().toString() );
        QString output = tr( "Running:\nntpdate " );
        output.append( srv );
        ntpTab->addNtpOutput( output );
        ntpTab->setNTPBtnEnabled( false );
    }

    // Disable set time buttons & change app caption to indicate time update is happening
    timeTab->setNTPBtnEnabled( false );
    setCaption( tr( "Retrieving time from network..." ) );

    if ( !ntpProcess )
    {
        ntpProcess = new OProcess();
        connect( ntpProcess, SIGNAL(receivedStdout(Opie::Core::OProcess*,char*,int)),
                 this, SLOT(slotNtpOutput(Opie::Core::OProcess*,char*,int)) );
        connect( ntpProcess, SIGNAL(processExited(Opie::Core::OProcess*)),
                 this, SLOT(slotNtpFinished(Opie::Core::OProcess*)) );
    }

    else
        ntpProcess->clearArguments();

    *ntpProcess << "ntpdate"  << srv;
    bool ret = ntpProcess->start( OProcess::NotifyOnExit, OProcess::AllOutput );
    if ( !ret )
    {
        QMessageBox::critical( this, tr( "Error" ), tr( "Error while getting time from network." ) );
        if ( ntpTabEnabled )
        {
            ntpTab->addNtpOutput( tr( "Error while executing ntpdate" ) );
            ntpTab->setNTPBtnEnabled( true );
        }

        // Re-enable set time buttons & change app caption to indicate time update is happening
        timeTab->setNTPBtnEnabled( true );
        setCaption( tr( "SystemTime" ) );
    }
}

bool MainWindow::ntpDelayElapsed()
{
    // Determine if time elapsed is greater than time delay
    Config config( "ntp" );
    config.setGroup( "lookups" );
    _lookupDiff = TimeConversion::toUTC( QDateTime::currentDateTime() ) - config.readNumEntry( "time", 0 );
    if ( _lookupDiff < 0 )
        return true;
    return ( _lookupDiff - ( ntpDelay * 60) ) > 0;
}

void MainWindow::slotSetTime( const QDateTime &dt )
{
    timeTab->setDateTime( dt );
}

void MainWindow::slotQCopReceive( const QCString &msg, const QByteArray & )
{
    if ( msg == "ntpLookup(QString)" )
    {
        ntpInteractive = false;
        runNTP();
    }
    if ( msg == "setPredictedTime(QString)" )
    {
        //setPredictTime();
    }
}

void MainWindow::slotDisplayNTPTab( bool display )
{
    ntpTabEnabled = display;

    // Create widget if it hasn't needed
    if ( display && !ntpTab )
    {
        ntpTab = new NTPTabWidget( mainWidget );
        connect( ntpTab, SIGNAL(getNTPTime()), this, SLOT(slotGetNTPTime()) );
    }

    // Display/hide tab
    display ? mainWidget->addTab( ntpTab, "netsystemtime/ntptab", tr( "Time Server" ) )
            : mainWidget->removePage( ntpTab );
}

void MainWindow::slotDisplayPredictTab( bool display )
{
    predictTabEnabled = display;

    // Create widget if it hasn't needed
    if ( display && !predictTab )
    {
        predictTab = new PredictTabWidget( mainWidget );
    }
    // Display/hide tab
    display ? mainWidget->addTab( predictTab, "netsystemtime/predicttab", tr( "Predict" ) )
            : mainWidget->removePage( predictTab );
}

void MainWindow::slotGetNTPTime()
{
    ntpInteractive = true;
    runNTP();
}

void MainWindow::slotTimerGetNTPTime()
{
    ntpInteractive = false;
    runNTP();
}

void MainWindow::slotProbeNTPServer()
{
    ntpSock->connectToHost( settingsTab->ntpServer(), 123 );
}

void MainWindow::slotNtpOutput( OProcess *, char *buffer, int buflen )
{
    QString output = QString( buffer ).left( buflen );
    ntpOutput.append( output );

    if ( ntpTabEnabled )
        ntpTab->addNtpOutput( output );
}

void MainWindow::slotNtpFinished( OProcess *p )
{
    QString output;
    QDateTime dt = QDateTime::currentDateTime();

    // Re-enable set time buttons & change app caption to indicate time update is happening
    if ( ntpTabEnabled )
        ntpTab->setNTPBtnEnabled( true );
    timeTab->setNTPBtnEnabled( true );
    setCaption( tr( "SystemTime" ) );

    //  Verify run was successful
    if ( p->exitStatus() != 0 )
    {
        if ( isVisible() && ntpInteractive )
        {
            output = tr( "Error while getting time from\n server: " );
            output.append( settingsTab->ntpServer() );
            QMessageBox::critical(this, tr( "Error" ), output );
        }
    //      slotCheckNtp(-1);
        return;
    }

    // Set controls on time tab to new time value
    timeTab->setDateTime( dt );

    // Write out lookup information
    Config config( "ntp" );
    config.setGroup( "lookups" );
    int lastLookup = config.readNumEntry( "time", 0 );
    int lookupCount = config.readNumEntry( "count", 0 );
    bool lastNtp = config.readBoolEntry( "lastNtp", false );
    int time = TimeConversion::toUTC( QDateTime::currentDateTime() );
    config.writeEntry( "time", time );

    // Calculate new time/time shift
    QString _offset = "offset";
    QString _sec = "sec";
    QRegExp _reOffset = QRegExp( _offset );
    QRegExp _reEndOffset = QRegExp( _sec );
    int posOffset = _reOffset.match(  ntpOutput );
    int posEndOffset = _reEndOffset.match(  ntpOutput, posOffset );
    posOffset += _offset.length() + 1;
    QString diff =  ntpOutput.mid( posOffset, posEndOffset - posOffset - 1 );

    float timeShift = diff.toFloat();
    if ( timeShift == 0.0 )
        return;
    int secsSinceLast = time - lastLookup;
    output = tr( "%1 seconds").arg(QString::number( timeShift ));

    // Display information on time server tab
    if ( ntpTabEnabled )
    {
        ntpTab->setTimeShift( output );
        ntpTab->setNewTime( dt.toString() );
    }

    if ( lastNtp && lastLookup > 0 && secsSinceLast > 60 * ntpDelay )
    {
        QString grpname = QString( "lookup_" ).append( QString::number( lookupCount ) );
        config.setGroup( grpname );
        lookupCount++;
        
        if(predictTab)
        {
            predictTab->setShiftPerSec( (int)(timeShift / secsSinceLast) );
        }

        config.writeEntry( "secsSinceLast", secsSinceLast );
        config.writeEntry( "timeShift", QString::number( timeShift ) );
        config.setGroup( "lookups" );
        config.writeEntry( "count", lookupCount );
        config.writeEntry( "lastNtp", true );
    }
}

void MainWindow::slotNTPDelayChanged( int delay )
{
    ntpTimer->changeInterval( delay * 1000 * 60 );
    ntpDelay = delay;
}

void MainWindow::slotCheckNtp( int i )
{
    if ( i == 0 )
    {
        if ( ntpDelayElapsed() )
        {
            runNTP();
            disconnect( ntpTimer, SIGNAL(timeout()), this, SLOT(slotProbeNTPServer()) );
            connect( ntpTimer, SIGNAL(timeout()), SLOT(slotTimerGetNTPTime()) );
        }
        else
        {
            disconnect(ntpTimer, SIGNAL(timeout()), this, SLOT(slotTimerGetNTPTime()) );
            connect(ntpTimer, SIGNAL(timeout()), SLOT(slotProbeNTPServer()) );
        }
    }
    else
    {
        if(predictTab)
        {
            predictTab->slotPredictTime();
        }

        if ( i > 0 )
        {
            QString output = tr( "Could not connect to server " );
            output.append( settingsTab->ntpServer() );
            ntpOutput.append( output );
            if ( ntpTabEnabled )
                ntpTab->addNtpOutput( output );
        }
        connect( ntpTimer, SIGNAL(timeout()), SLOT(slotProbeNTPServer()) );
    }
}