-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
WeatherApplet.cxx
404 lines (313 loc) · 11.6 KB
/
WeatherApplet.cxx
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
/*
This file is part of liquidshell.
SPDX-FileCopyrightText: 2017 - 2024 Martin Koller <kollix@aon.at>
SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <WeatherApplet.hxx>
#include <WeatherAppletConfigureDialog.hxx>
#include <Moon.hxx>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrl>
#include <QGridLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDir>
#include <QAction>
#include <QDebug>
#include <KConfig>
#include <KConfigGroup>
#include <KLocalizedString>
#include <NetworkManagerQt/Manager>
//--------------------------------------------------------------------------------
QString WeatherApplet::apiKey;
//--------------------------------------------------------------------------------
WeatherApplet::WeatherApplet(QWidget *parent, const QString &theId)
: DesktopApplet(parent, theId)
{
setAutoFillBackground(true);
timer.setInterval(600000); // 10min smallest update interval for free data
connect(&timer, &QTimer::timeout, this, &WeatherApplet::fetchData);
QVBoxLayout *vbox = new QVBoxLayout(this);
cityLabel = new QLabel(this);
cityLabel->setObjectName("city");
cityLabel->setWordWrap(true);
QFont f = font();
f.setPointSizeF(fontInfo().pointSizeF() * 2);
f.setBold(true);
cityLabel->setFont(f);
moonLabel = new QLabel;
moon.load(":/moon_56frames.png", "PNG");
QHBoxLayout *topHbox = new QHBoxLayout;
topHbox->addWidget(cityLabel);
topHbox->addStretch();
topHbox->addWidget(moonLabel);
vbox->addLayout(topHbox);
QGridLayout *grid = new QGridLayout;
vbox->addLayout(grid);
grid->addWidget(new QLabel(i18n("Temperature:"), this), 0, 0);
grid->addWidget(tempLabel = new QLabel, 0, 1);
grid->addWidget(new QLabel(i18n("Pressure:"), this), 1, 0);
grid->addWidget(pressureLabel = new QLabel, 1, 1);
grid->addWidget(new QLabel(i18n("Humidity:"), this), 2, 0);
grid->addWidget(humidityLabel = new QLabel, 2, 1);
grid->addWidget(new QLabel(i18n("Wind Speed:"), this), 3, 0);
grid->addWidget(windSpeedLabel = new QLabel, 3, 1);
grid->addWidget(new QLabel(i18n("Wind Direction:"), this), 4, 0);
grid->addWidget(windDirectionLabel = new QLabel, 4, 1);
for (int i = 0; i < 4; i++)
{
shortForecast[i] = new ForecastWidget(this, false);
grid->addWidget(shortForecast[i], 0, 2 + i, 5, 1, Qt::AlignCenter);
}
QHBoxLayout *hbox = new QHBoxLayout;
vbox->addLayout(hbox);
for (int i = 0; i < 5; i++)
{
forecast[i] = new ForecastWidget(this);
hbox->addWidget(forecast[i]);
if ( i < 4 )
hbox->addStretch();
}
connect(NetworkManager::notifier(), &NetworkManager::Notifier::connectivityChanged, this,
[this](NetworkManager::Connectivity connectivity)
{
if ( connectivity == NetworkManager::Full )
fetchData();
});
}
//--------------------------------------------------------------------------------
QSize WeatherApplet::sizeHint() const
{
return QSize(700, 300);
}
//--------------------------------------------------------------------------------
void WeatherApplet::loadConfig()
{
KConfig config;
KConfigGroup group = config.group("Weather");
apiKey = group.readEntry("apiKey", QString());
group = config.group(id);
cityId = group.readEntry("cityId", QString());
units = group.readEntry("units", QString("metric"));
DesktopApplet::loadConfig();
if ( apiKey.isEmpty() || cityId.isEmpty() )
cityLabel->setText(i18n("Not configured"));
}
//--------------------------------------------------------------------------------
void WeatherApplet::showEvent(QShowEvent *)
{
// only query every 10 minutes, which is the limit for free data
if ( !timer.isActive() )
{
timer.start();
fetchData();
}
}
//--------------------------------------------------------------------------------
void WeatherApplet::fetchData()
{
if ( !isVisible() )
return;
int x = 48 * Moon::phase(QDate::currentDate());
moonLabel->setPixmap(moon.copy(x, 0, 48, 48));
if ( apiKey.isEmpty() || cityId.isEmpty() )
return;
QString url = QString("http://api.openweathermap.org/data/2.5/weather?APPID=%1&units=%2&id=%3")
.arg(apiKey, units, cityId);
KIO::StoredTransferJob *job = KIO::storedGet(QUrl(url), KIO::Reload, KIO::HideProgressInfo);
connect(job, &KIO::Job::result, this, &WeatherApplet::gotData);
url = QString("http://api.openweathermap.org/data/2.5/forecast?APPID=%1&units=%2&id=%3")
.arg(apiKey, units, cityId);
job = KIO::storedGet(QUrl(url), KIO::Reload, KIO::HideProgressInfo);
connect(job, &KIO::Job::result, this, &WeatherApplet::gotData);
}
//--------------------------------------------------------------------------------
void WeatherApplet::gotData(KJob *job)
{
if ( job->error() )
{
cityLabel->setText(job->errorString());
return;
}
QJsonDocument doc = QJsonDocument::fromJson(static_cast<KIO::StoredTransferJob *>(job)->data());
if ( doc.isNull() || !doc.isObject() )
return;
QString tempUnit = i18n("K");
if ( units == "metric" ) tempUnit = i18n("°C");
else if ( units == "imperial" ) tempUnit = i18n("°F");
QJsonObject data = doc.object();
if ( data.contains("city") && data["city"].isObject() )
cityLabel->setText(data["city"].toObject()["name"].toString());
// current
if ( data.contains("main") && data["main"].isObject() )
{
QJsonObject mainData = data["main"].toObject();
double temp = mainData["temp"].toDouble();
tempLabel->setText(i18n("%1 %2", locale().toString(temp, 'f', 1), tempUnit));
double pressure = mainData["pressure"].toDouble();
pressureLabel->setText(i18n("%1 hPa", locale().toString(pressure, 'f', 1)));
double humidity = mainData["humidity"].toDouble();
humidityLabel->setText(i18n("%1 %", locale().toString(humidity, 'f', 1)));
}
if ( data.contains("wind") && data["wind"].isObject() )
{
QJsonObject windData = data["wind"].toObject();
QString speedUnit = "m/s";
if ( units == "imperial" ) speedUnit = "mi/h";
double speed = windData["speed"].toDouble();
windSpeedLabel->setText(i18n("%1 %2", locale().toString(speed, 'f', 0), speedUnit));
double deg = windData["deg"].toDouble();
windDirectionLabel->setText(i18n("%1 °", locale().toString(deg, 'f', 0)));
}
if ( data.contains("weather") && data["weather"].isArray() )
{
QDateTime dt = QDateTime::fromMSecsSinceEpoch(qint64(data["dt"].toInt()) * 1000);
shortForecast[0]->day->setText(locale().toString(dt.time(), QLocale::ShortFormat));
setIcon(shortForecast[0]->icon, data["weather"].toArray()[0].toObject()["icon"].toString());
}
// forecast
if ( data.contains("list") && data["list"].isArray() )
{
for (int i = 0; i < 5; i++)
forecast[i]->hide();
QJsonArray array = data["list"].toArray();
// 3 hours short forecast
for (int i = 0; i < 3; i++)
{
setIcon(shortForecast[1 + i]->icon, array[i].toObject()["weather"].toArray()[0].toObject()["icon"].toString());
QDateTime dt = QDateTime::fromMSecsSinceEpoch(qint64(array[i].toObject()["dt"].toInt()) * 1000);
shortForecast[1 + i]->day->setText(locale().toString(dt.time(), QLocale::ShortFormat));
shortForecast[1 + i]->show();
}
QHash<int, double> minTemp, maxTemp; // key = day
for (QJsonValue value : array)
{
QJsonObject obj = value.toObject();
int day = QDateTime::fromMSecsSinceEpoch(qint64(obj["dt"].toInt()) * 1000).date().dayOfWeek();
double temp = obj["main"].toObject()["temp"].toDouble();
if ( !minTemp.contains(day) )
{
minTemp.insert(day, temp);
maxTemp.insert(day, temp);
}
else
{
if ( temp < minTemp[day] ) minTemp[day] = temp;
if ( temp > maxTemp[day] ) maxTemp[day] = temp;
}
}
int idx = 0;
for (QJsonValue value : array)
{
QJsonObject obj = value.toObject();
if ( obj["dt_txt"].toString().contains("12:00") )
{
QString icon = obj["weather"].toArray()[0].toObject()["icon"].toString();
setIcon(forecast[idx]->icon, icon);
int day = QDateTime::fromMSecsSinceEpoch(qint64(obj["dt"].toInt()) * 1000).date().dayOfWeek();
forecast[idx]->day->setText(locale().dayName(day, QLocale::ShortFormat));
forecast[idx]->min->setText(i18n("%1 %2", locale().toString(minTemp[day], 'f', 1), tempUnit));
forecast[idx]->max->setText(i18n("%1 %2", locale().toString(maxTemp[day], 'f', 1), tempUnit));
forecast[idx]->show();
idx++;
if ( idx == 5 ) break;
}
}
}
timer.start(); // after showEvent make sure to wait another full timeout phase
}
//--------------------------------------------------------------------------------
void WeatherApplet::setIcon(QLabel *label, const QString &icon)
{
QString cacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) +
"/api.openweathermap.org/";
QDir dir;
dir.mkpath(cacheDir);
QString filePath = cacheDir + icon + ".png";
if ( QFile::exists(filePath) )
{
QPixmap pixmap(filePath);
if ( !pixmap.isNull() )
label->setPixmap(pixmap);
}
else
{
KIO::StoredTransferJob *job =
KIO::storedGet(QUrl("http://api.openweathermap.org/img/w/" + icon), KIO::Reload, KIO::HideProgressInfo);
connect(job, &KIO::Job::result, this,
[label, filePath](KJob *job)
{
if ( job->error() )
return;
QPixmap pixmap;
pixmap.loadFromData(static_cast<KIO::StoredTransferJob *>(job)->data());
if ( !pixmap.isNull() )
{
label->setPixmap(pixmap);
pixmap.save(filePath, "PNG");
}
});
}
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
ForecastWidget::ForecastWidget(QWidget *parent, bool showMinMax)
: QWidget(parent)
{
QGridLayout *grid = new QGridLayout(this);
if ( showMinMax )
{
min = new QLabel(this);
max = new QLabel(this);
min->setAlignment(Qt::AlignRight);
max->setAlignment(Qt::AlignRight);
grid->addWidget(max, 0, 1);
grid->addWidget(min, 1, 1);
}
day = new QLabel(this);
icon = new QLabel(this);
day->setAlignment(Qt::AlignCenter);
icon->setFixedSize(64, 64);
icon->setScaledContents(true);
grid->addWidget(day, 2, 0, 1, 2);
grid->addWidget(icon, 0, 0, 2, 1);
setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
}
//--------------------------------------------------------------------------------
void WeatherApplet::configure()
{
if ( dialog )
{
dialog->raise();
dialog->activateWindow();
return;
}
dialog = new WeatherAppletConfigureDialog(this);
dialog->setWindowTitle(i18n("Configure Weather Applet"));
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
connect(dialog.data(), &QDialog::accepted, this,
[this]()
{
saveConfig();
KConfig config;
KConfigGroup group = config.group("Weather");
group.writeEntry("apiKey", apiKey);
group = config.group(id);
group.writeEntry("cityId", cityId);
group.writeEntry("units", units);
if ( !apiKey.isEmpty() && !cityId.isEmpty() )
{
fetchData();
timer.start();
}
else
{
cityLabel->setText(i18n("Not configured"));
}
});
}
//--------------------------------------------------------------------------------