-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.cpp
305 lines (267 loc) · 9 KB
/
main.cpp
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
/**
* @file main.cpp Main application code
*
* A tray icon which shows the current opening status of the Stratumsphere
*
* @date 2012-05-07
* @author Roland Hieber <[email protected]>
*
* Copyright (C) 2012 Roland Hieber <[email protected]>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include "main.h"
#include <QApplication>
#include <QSystemTrayIcon>
#include <QIcon>
#include <QMenu>
#include <QAction>
#include <QString>
#include <QUrl>
#include <QNetworkRequest>
#include <QDebug>
#include <QTextCodec>
#include <QTimer>
#include <QTranslator>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonValue>
#ifdef HAVE_DBUS
#include "freedesktop-notification.h"
#include <QDBusConnection>
#endif // HAVE_DBUS
/**
* Constructive constructor takes no parameters.
*/
StratumsphereTrayIcon::StratumsphereTrayIcon() : QObject(0), nam_(0),
trayMenu_(0), trayIcon_(0), status_(UNDEFINED), lastStatus_(UNDEFINED),
lastStatusBeforeUndefined_(UNDEFINED), timeoutTimer_(0),
toggleNotifyAction_(0) {
// set up network connection stuff
nam_ = new QNetworkAccessManager(this);
connect(nam_, SIGNAL(finished(QNetworkReply*)), this,
SLOT(reply(QNetworkReply*)));
#ifdef HAVE_DBUS
QDBusConnection conn = QDBusConnection::connectToBus(
QDBusConnection::SystemBus, "org.freedesktop.NetworkManager");
if(!conn.isConnected()) {
qDebug() << "Oh. Connection failed:" << conn.lastError();
} else {
conn.connect("org.freedesktop.NetworkManager",
"/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager",
"StateChanged", "u", this, SLOT(networkStateChanged(uint)));
}
#endif // HAVE_DBUS
// set up icons
int sizes[] = {16, 22, 32, 64, 128, 256};
for(const int size : sizes) {
openIcon_.addFile(QString(":/res/open-%1.png").arg(size));
closedIcon_.addFile(QString(":/res/closed-%1.png").arg(size));
undefinedIcon_.addFile(QString(":/res/undefined-%1.png").arg(size));
}
// set up menu
trayMenu_ = new QMenu;
toggleNotifyAction_ = new QAction(tr("Show ¬ifications"), this);
toggleNotifyAction_->setCheckable(true);
toggleNotifyAction_->setChecked(true);
trayMenu_->addAction(toggleNotifyAction_);
updateAction_ = new QAction(tr("&Update status"), trayMenu_);
connect(updateAction_, SIGNAL(triggered()), this, SLOT(updateStatus()));
trayMenu_->addAction(updateAction_);
QAction * exitAction = new QAction(tr("&Exit"), trayMenu_);
connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
trayMenu_->addAction(exitAction);
// set up tray icon
trayIcon_ = new QSystemTrayIcon(this);
trayIcon_->setContextMenu(trayMenu_);
trayIcon_->setIcon(undefinedIcon_);
trayIcon_->show();
// fire up a timer to poll the status every n minutes
startTimer(updateInterval_ * 1000);
// also set up the timeout timer
timeoutTimer_ = new QTimer(this);
connect(timeoutTimer_, SIGNAL(timeout()), this, SLOT(timeout()));
updateStatus();
}
/**
* Destructive destructor is destructive.
*/
StratumsphereTrayIcon::~StratumsphereTrayIcon() {
if(trayMenu_) {
delete trayMenu_;
}
}
/**
* Update the Stratum 0 opening status and the tray icon
*/
void StratumsphereTrayIcon::updateStatus() {
qDebug() << QDateTime::currentDateTime().toString() << "updating status";
updateAction_->setText(tr("Updating…"));
updateAction_->setEnabled(false);
QString url("https://status.bytespeicher.org/status.json");
qDebug() << "fetching" << url;
nam_->get(QNetworkRequest(QUrl(url)));
// after timeout, just update icon to unspecified state
timeoutTimer_->start(timeoutInterval_ * 1000);
}
/**
* Called when the timeout timer fires. Sets the state to undefined and
* redraws the tray icon.
*/
void StratumsphereTrayIcon::timeout() {
qDebug() << "Uh-oh! Timeout!";
status_ = UNDEFINED;
refresh();
}
/**
* Process network reply and update status settings
*/
void StratumsphereTrayIcon::reply(QNetworkReply* nr) {
qDebug() << "got a reply!";
timeoutTimer_->stop(); // we don't want the timeout to mess up the balloons
QString strReply = (QString)nr->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
if(jsonObject["open"].toBool())
{
status_ = OPEN;
qDebug() << "space is open";
}
else
{
status_ = CLOSED;
qDebug() << "space is closed";
}
lastUpdate_ = QDateTime::currentDateTime();
qDebug() << "status is" << status_;
if(jsonObject["state"].isObject())
{
QJsonObject jsonStatObj = jsonObject["state"].toObject();
QDateTime dt;
dt.setTime_t(jsonStatObj["lastchange"].toInt());
if(!dt.isValid()) {
qDebug() << "Oops, I don't know how to interpret timestamp.";
} else {
since_ = dt;
}
}
nr->deleteLater();
refresh();
};
/**
* Refresh the icon, the context menu and the tooltip text
*/
void StratumsphereTrayIcon::refresh() {
qDebug() << "refreshing tray icon";
updateAction_->setEnabled(true);
updateAction_->setText(tr("&Update status"));
QString statusText, balloonText;
QIcon * icon;
if(status_ == CLOSED) {
icon = &closedIcon_;
statusText = tr("Space is closed");
balloonText = tr("The Bytespeicher has just closed.");
} else if(status_ == OPEN) {
icon = &openIcon_;
statusText = tr("Space is open");
balloonText = tr("The Bytespeicher has just opened!");
} else {
icon = &undefinedIcon_;
statusText = tr("Could not determine opening status");
}
trayIcon_->setIcon(*icon);
qApp->setWindowIcon(*icon);
// set tool tip
QString toolTipText = statusText;
toolTipText.append("\n");
toolTipText.append(tr("Status since: %1").
arg(since_.toString(Qt::DefaultLocaleShortDate)));
toolTipText.append("\n");
toolTipText.append(tr("Last update: %1").
arg(lastUpdate_.toString(Qt::DefaultLocaleShortDate)));
trayIcon_->setToolTip(toolTipText);
// set balloon message
static bool firstTime = true; // don't show at program start
if(toggleNotifyAction_->isChecked() && !firstTime && lastStatus_ != status_ &&
lastStatusBeforeUndefined_ != status_ && // don't re-show after net loss
status_ != UNDEFINED) {
// show tray icon message only if freedesktop notification fails
bool notificationShown = false;
#ifdef HAVE_DBUS
notificationShown = showNotification(statusText, balloonText,
icon->pixmap(128).toImage());
#endif // HAVE_DBUS
if(!notificationShown) {
if(QSystemTrayIcon::supportsMessages()) {
trayIcon_->showMessage(statusText, balloonText);
} else {
qDebug() << "It seems your system does not support "
"QSystemTrayIcon::showMessage(). That's too bad.";
}
}
}
firstTime = false;
if(status_ == UNDEFINED && lastStatus_ != UNDEFINED) {
qDebug() << "saving last before undefined status:" << lastStatus_;
lastStatusBeforeUndefined_ = lastStatus_;
}
lastStatus_ = status_;
}
#ifdef HAVE_DBUS
/**
* Called when NetworkManager changes its state
*/
void StratumsphereTrayIcon::networkStateChanged(uint state) {
QString stateRepr;
switch(state) {
// just ignore these, we don't know anything for sure
case 0: break; // NM_STATE_UNKNOWN
case 1: break; // NM_STATE_ASLEEP
case 2: break; // NM_STATE_CONNECTING
case 3: // NM_STATE_CONNECTED
qDebug() << "NetworkManager state changed to connected";
updateStatus();
break;
case 4: // NM_STATE_DISCONNECTED
qDebug() << "NetworkManager state changed to disconnected";
status_ = UNDEFINED;
refresh();
break;
default:
qDebug() << "NetworkManager state changed to an undefined state o_O" <<
"(this should not happen!)";
break;
}
}
#endif // def HAVE_DBUS
/******************************************************************************/
/* main function */
/******************************************************************************/
int main(int argc, char * argv[]) {
QApplication app(argc, argv);
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
QTranslator translator;
translator.load("lang/main_" + QLocale::system().name());
app.installTranslator(&translator);
StratumsphereTrayIcon *sti = new StratumsphereTrayIcon();
// parse arguments
QStringList args = app.arguments();
if(args.contains("--silent") || args.contains("-s")) {
sti->setNotifications(false);
}
int ret = app.exec();
delete sti;
return ret;
}
// vim: set tw=80 et sw=2 ts=2: