summaryrefslogtreecommitdiffstats
path: root/kweather/kweather.cpp
blob: eb87f98a47a5c9c406a1447d1784e5cfb707820b (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
/***************************************************************************
                          kweather.cpp  -  description
                             -------------------
    begin                : Wed Jul  5 23:09:02 CDT 2000
    copyright            : (C) 2000-2003 by Ian Reinhart Geiser
                         : (C) 2002-2003 Nadeem Hasan <nhasan@kde.org>
    email                : geiseri@msoe.edu
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <tdeaboutapplication.h>
#include <tdeapplication.h>
#include <kcmultidialog.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <kiconloader.h>
#include <tdemessagebox.h>
#include <tdepopupmenu.h>
#include <tdeconfig.h>
#include <ksettings/dialog.h>
#include <ksettings/dispatcher.h>
#include <dcopclient.h>

#include <tqdatetime.h>
#include <tqfile.h>
#include <tqtimer.h>
#include <tqpalette.h>

#include "kweather.h"
#include "reportview.h"
#include "dockwidget.h"
#include "weatherservice_stub.h"

extern "C"
{
    KDE_EXPORT KPanelApplet* init(TQWidget *parent, const TQString& configFile)
    {
        TDEGlobal::locale()->insertCatalogue("kweather");
        kweather *theApplet = new kweather(configFile, KPanelApplet::Normal,
                0, parent, "kweather");
        return theApplet;
    }
}

kweather::kweather(const TQString& configFile, Type t, int actions,
        TQWidget *parent, const char *name):
        KPanelApplet(configFile, t, actions, parent, name), weatherIface(),
        mFirstRun( false ), mReport( 0 ), mClient( 0 ),
        mContextMenu( 0 ), mWeatherService( 0 ), settingsDialog( 0 ), mTextColor(TQt::black)
{
    kdDebug(12004) << "Constructor " << endl;
    setObjId("weatherIface");

    setBackgroundOrigin( TQWidget::AncestorOrigin );
    loadPrefs();
    initContextMenu();
    initDCOP();

    dockWidget = new dockwidget(reportLocation, this, "dockwidget");
    connect(dockWidget, TQT_SIGNAL(buttonClicked()), TQT_SLOT(doReport()));
    dockWidget->setViewMode(mViewMode);
    setLabelColor();

    timeOut = new TQTimer(this, "timeOut" );
    connect(timeOut, TQT_SIGNAL(timeout()), TQT_SLOT(timeout()));
    timeOut->start(10*60*1000);

    if(mFirstRun)
        preferences();
    else
        timeout();
}

kweather::~kweather()
{
    delete mWeatherService;
}

void kweather::initContextMenu()
{
    mContextMenu = new TDEPopupMenu(this);
    mContextMenu->insertTitle(i18n("KWeather - %1").arg( reportLocation ), -1, 0);
    mContextMenu->insertItem(SmallIcon("viewmag"), i18n("Show &Report"),
        this, TQT_SLOT(doReport()), 0, -1, 1);
    mContextMenu->insertItem(SmallIcon("reload"), i18n("&Update Now"),
        this, TQT_SLOT(slotUpdateNow()), 0, -1, 2);
    mContextMenu->insertSeparator();
    mContextMenu->insertItem(SmallIcon("kweather"), i18n("&About KWeather"), this, TQT_SLOT(about()));
    mContextMenu->insertItem(SmallIcon("configure"),
        i18n("&Configure KWeather..."), this, TQT_SLOT(preferences()));
    setCustomMenu(mContextMenu);
}

void kweather::initDCOP()
{
    if ( !mClient )
        mClient = TDEApplication::dcopClient();

    if(!mClient->isAttached())
        mClient->attach();

    if(!attach())
        return;

    kdDebug(12004) << "attached to the server..." << endl;

    if ( mWeatherService )
        delete mWeatherService;

    mWeatherService = new WeatherService_stub( "KWeatherService", "WeatherService" );

    if (!connectDCOPSignal(0, 0, "fileUpdate(TQString)",
        "refresh(TQString)",false))
        kdDebug(12004) << "Could not attach dcop signal..." << endl;
    else
        kdDebug(12004) << "attached dcop signals..." << endl;
}

/** about box */
void kweather::about(){
    kdDebug(12004) << "Telling about" << endl;
    TDEAboutData aboutData("KWeather", "KWeather", "2.1.0",
            I18N_NOOP("Weather applet for the Kicker"), TDEAboutData::License_GPL_V2);
    aboutData.addAuthor("Ian Reinhart Geiser", "", "geiseri@kde.org",
            "http://www.kde.org/");
    //aboutData.addAuthor("Nadeem Hasan",  "", "nhasan@nadmm.com", "http://www.nadmm.com/");
    aboutData.addCredit("Nadeem Hasan", I18N_NOOP("Lots of bugfixes,"
            " improvements and cleanups."), "nhasan@nadmm.com");
    aboutData.addCredit("Will Andrews", I18N_NOOP("Fixed for BSD port"),
            "wca@users.sourceforge.net", "");
    aboutData.addCredit("Ben Burton", I18N_NOOP("Debian fixes"), "benb@acm.org");
    aboutData.addCredit("Otto Bruggeman", I18N_NOOP("Fixed the i18n stuff and"
            " made sure the indentation was consistent :P"), "bruggie@home.nl");
    aboutData.addCredit( "Carles Carbonell Bernado",
            I18N_NOOP( "Great new weather icons" ), "mail@carlitus.net" );
    aboutData.addCredit( "John Ratke",
            I18N_NOOP( "Improvements and more code cleanups" ), "jratke@comcast.net" );

    TDEAboutApplication about(&aboutData, this, 0);
    about.setProgramLogo( TDEGlobal::instance()->iconLoader()->iconPath( "kweather", -TDEIcon::SizeLarge ) );
    about.exec();
}

/** prefs */
void kweather::preferences()
{
    kdDebug(12004) << "prefs" << endl;

    savePrefs();

    if ( settingsDialog == 0 )
    {
      settingsDialog = new KCMultiDialog( this );
      connect( settingsDialog, TQT_SIGNAL( configCommitted() ), TQT_SLOT( slotPrefsAccepted() ) );

      settingsDialog->addModule( "kcmweather.desktop" );
      settingsDialog->addModule( "kcmweatherservice.desktop" );
    }

    settingsDialog->show();
    settingsDialog->raise();
}

/** The help handler */
void kweather::help()
{
    kapp->invokeHelp(TQString(), TQString::fromLatin1("kweather"));
}

/** Display the current weather report. */
void kweather::doReport()
{
    if ( reportLocation.isEmpty() )
    {
        // no station to display defined -> open settings dialog
        preferences();
        return;
    }

    kdDebug(12004) << "Showing out the report" << endl;
    if ( mReport == 0 )
    {
        mReport = new reportView(reportLocation);

        connect( mReport, TQT_SIGNAL( finished() ), TQT_SLOT( slotReportFinished() ) );
    }

    mReport->show();
    mReport->raise();
}

void kweather::slotReportFinished(){
    mReport->delayedDestruct();
    mReport = 0;
}

/** load the application */
void kweather::loadPrefs(){
    kdDebug(12004) << "Loading Prefs" << endl;
    TDEConfig *kcConfig = config();
    kcConfig->reparseConfiguration();

    if (!kcConfig->hasGroup ("General Options") )
        mFirstRun = true;

    kcConfig->setGroup("General Options");
    logOn = kcConfig->readBoolEntry("logging", false);
    fileName = kcConfig->readPathEntry("log_file_name");
    reportLocation = kcConfig->readEntry("report_location");
    mViewMode = kcConfig->readNumEntry("smallview_mode", dockwidget::ShowAll);

    static TQColor black(TQt::black);
    mTextColor = kcConfig->readColorEntry("textColor", &black);
}

/** Save the application mPrefs. */
void kweather::savePrefs(){
    kdDebug(12004) << "Saving Prefs..." << endl;
    TDEConfig *kcConfig = config();

    kcConfig->setGroup("General Options");
    kcConfig->writeEntry("logging", logOn);
    kcConfig->writeEntry("report_location", reportLocation);
    kcConfig->writeEntry("smallview_mode", mViewMode);
    kcConfig->writePathEntry("log_file_name", fileName );
    kcConfig->sync();
}

void kweather::showWeather()
{
    kdDebug(12004) << "Show weather" << endl;
    dockWidget->showWeather();
    emit updateLayout();
}

void kweather::writeLogEntry()
{
    // Write data line in the CSV format
    if (logOn && !fileName.isEmpty())
    {
        kdDebug(12004)<< "Try log file:" << fileName << endl;
        TQFile logFile(fileName);
        TQTextStream logFileStream(&logFile);
        if (logFile.open(IO_Append | IO_ReadWrite))
        {
            TQString temperature = mWeatherService->temperature(reportLocation );
            TQString wind        = mWeatherService->wind(reportLocation );
            TQString pressure    = mWeatherService->pressure(reportLocation );
            TQString date        = mWeatherService->date(reportLocation );
            TQStringList weather = mWeatherService->weather(reportLocation );
            TQStringList cover   = mWeatherService->cover(reportLocation );
            TQString visibility  = mWeatherService->visibility(reportLocation );
            logFileStream << TDEGlobal::locale()->formatDateTime(TQDateTime::currentDateTime(), false, false) << ",";
            logFileStream << date << ",";
            logFileStream << wind << ",";
            logFileStream << temperature << ",";
            logFileStream << pressure << ",";
            logFileStream << cover.join(";") << ",";
            logFileStream << visibility << ",";
            logFileStream << weather.join(";");
            logFileStream << endl;
        }
        else
        {
            KMessageBox::sorry( this,
                    i18n("For some reason the log file could not be written to.\n"
                    "Please check to see if your disk is full or if you "
                    "have write access to the location you are trying to "
                    "write to."),
                    i18n("KWeather Error"));
        }
        logFile.close();
    }
}

/** get new data */
void kweather::timeout()
{
    if ( !mWeatherService )
        initDCOP();

    if ( mWeatherService )
    {
        // isEmtpy is true for null and 0 length strings
        if ( !reportLocation.isEmpty() )
        {
        kdDebug(12004)<< "Requesting new data for " << reportLocation << endl;
        mWeatherService->update(reportLocation);
        }
    }
}

int kweather::widthForHeight(int h) const
{
    //kdDebug(12004) << "widthForHeight " << h << endl;
    dockWidget->setOrientation(Qt::Horizontal);
    int w = dockWidget->widthForHeight(h);
    return w;
}

int kweather::heightForWidth(int w) const
{
    kdDebug(12004) << "heightForWidth " << w<< endl;
    dockWidget->setOrientation(Qt::Vertical);
    int h = dockWidget->heightForWidth( w );
    return h;
}

void kweather::refresh(TQString stationID)
{
    kdDebug(12004) << "refresh " << stationID << endl;
    if( stationID == reportLocation)
    {
        showWeather();
        writeLogEntry();
    }
}

void kweather::slotPrefsAccepted()
{
    // Preferences have been saved in the config file by the TDECModule,
    // so read them out.
    loadPrefs();

    dockWidget->setLocationCode(reportLocation);
    dockWidget->setViewMode(mViewMode);
    setLabelColor();
    emit updateLayout();

    if (logOn && !fileName.isEmpty())
    {
        TQFile logFile(fileName);
        // Open the file, create it if not already exists
        if (logFile.open(IO_ReadWrite))
        {
            if (logFile.size() == 0)
            {
                // Empty file, put the header
                TQTextStream logFileStream(&logFile);
                logFileStream << "Date,Last Updated,Wind Speed & Direction,Temperature,Pressure,Cover,Visibility,Current Weather" << endl;
            }
            logFile.close();
        }
        else
        {
            kdDebug(12004) << "There was an error opening the file...." << endl;
            KMessageBox::sorry( this,
                    i18n("For some reason a new log file could not be opened.\n"
                    "Please check to see if your disk is full or if you have "
                    "write access to the location you are trying to write to."),
                    i18n("KWeather Error"));
        }
    }

    timeout();
}

void kweather::mousePressEvent(TQMouseEvent *e)
{
    if ( e->button() != Qt::RightButton )
    {
        KPanelApplet::mousePressEvent( e );
        return;
    }

    mContextMenu->exec(e->globalPos());
}

void kweather::slotUpdateNow()
{
    if ( !mWeatherService )
         initDCOP();

    mWeatherService->forceUpdate(reportLocation );
}

bool kweather::attach()
{
    TQString error;
    kdDebug(12004) << "Looking for dcop service..." << endl;
    if (!mClient->isApplicationRegistered("KWeatherService"))
    {
        kdDebug(12004) << "Could not find service so I am starting it..."
            << endl;
        if (!TDEApplication::startServiceByDesktopName("kweatherservice",
            TQStringList(), &error))
        {
            kdDebug(12004) << "Starting KWeatherService failed with message: "
                << error << endl;
            return false;
        }

        kdDebug (12004) << "Service Started..." << endl;
    }
    else
    {
        kdDebug(12004) << "Found weather service..." << endl;
    }

    return true;
}

void kweather::resizeEvent(TQResizeEvent *e)
{
    kdDebug(12004) << "KWeather Resize event " << e->size() << endl;
    dockWidget->resizeView(e->size());
}

void kweather::setLabelColor()
{
    setPaletteForegroundColor(mTextColor);
}

void kweather::paletteChange(const TQPalette &)
{
    setLabelColor();
}

#include "kweather.moc"