]> Git Repo - VerusCoin.git/blob - src/qt/notificator.cpp
qt: add license header to source files
[VerusCoin.git] / src / qt / notificator.cpp
1 // Copyright (c) 2011-2013 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include "notificator.h"
6
7 #include <QApplication>
8 #include <QMetaType>
9 #include <QVariant>
10 #include <QIcon>
11 #include <QStyle>
12 #include <QByteArray>
13 #include <QSystemTrayIcon>
14 #include <QMessageBox>
15 #include <QTemporaryFile>
16 #include <QImageWriter>
17
18 #ifdef USE_DBUS
19 #include <QtDBus>
20 #include <stdint.h>
21 #endif
22
23 #ifdef Q_OS_MAC
24 #include <ApplicationServices/ApplicationServices.h>
25 #include "macnotificationhandler.h"
26 #endif
27
28 // https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
29 const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;
30
31 Notificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):
32     QObject(parent),
33     parent(parent),
34     programName(programName),
35     mode(None),
36     trayIcon(trayicon)
37 #ifdef USE_DBUS
38     ,interface(0)
39 #endif
40 {
41     if(trayicon && trayicon->supportsMessages())
42     {
43         mode = QSystemTray;
44     }
45 #ifdef USE_DBUS
46     interface = new QDBusInterface("org.freedesktop.Notifications",
47           "/org/freedesktop/Notifications", "org.freedesktop.Notifications");
48     if(interface->isValid())
49     {
50         mode = Freedesktop;
51     }
52 #endif
53 #ifdef Q_OS_MAC
54     // check if users OS has support for NSUserNotification
55     if( MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) {
56         mode = UserNotificationCenter;
57     }
58     else {
59         // Check if Growl is installed (based on Qt's tray icon implementation)
60         CFURLRef cfurl;
61         OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
62         if (status != kLSApplicationNotFoundErr) {
63             CFBundleRef bundle = CFBundleCreate(0, cfurl);
64             if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {
65                 if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/")))
66                     mode = Growl13;
67                 else
68                     mode = Growl12;
69             }
70             CFRelease(cfurl);
71             CFRelease(bundle);
72         }
73     }
74 #endif
75 }
76
77 Notificator::~Notificator()
78 {
79 #ifdef USE_DBUS
80     delete interface;
81 #endif
82 }
83
84 #ifdef USE_DBUS
85
86 // Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
87 class FreedesktopImage
88 {
89 public:
90     FreedesktopImage() {}
91     FreedesktopImage(const QImage &img);
92
93     static int metaType();
94
95     // Image to variant that can be marshalled over DBus
96     static QVariant toVariant(const QImage &img);
97
98 private:
99     int width, height, stride;
100     bool hasAlpha;
101     int channels;
102     int bitsPerSample;
103     QByteArray image;
104
105     friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);
106     friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);
107 };
108
109 Q_DECLARE_METATYPE(FreedesktopImage);
110
111 // Image configuration settings
112 const int CHANNELS = 4;
113 const int BYTES_PER_PIXEL = 4;
114 const int BITS_PER_SAMPLE = 8;
115
116 FreedesktopImage::FreedesktopImage(const QImage &img):
117     width(img.width()),
118     height(img.height()),
119     stride(img.width() * BYTES_PER_PIXEL),
120     hasAlpha(true),
121     channels(CHANNELS),
122     bitsPerSample(BITS_PER_SAMPLE)
123 {
124     // Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
125     QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
126     const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.bits());
127
128     unsigned int num_pixels = width * height;
129     image.resize(num_pixels * BYTES_PER_PIXEL);
130
131     for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)
132     {
133         image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R
134         image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8;  // G
135         image[ptr*BYTES_PER_PIXEL+2] = data[ptr];       // B
136         image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A
137     }
138 }
139
140 QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)
141 {
142     a.beginStructure();
143     a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
144     a.endStructure();
145     return a;
146 }
147
148 const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)
149 {
150     a.beginStructure();
151     a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
152     a.endStructure();
153     return a;
154 }
155
156 int FreedesktopImage::metaType()
157 {
158     return qDBusRegisterMetaType<FreedesktopImage>();
159 }
160
161 QVariant FreedesktopImage::toVariant(const QImage &img)
162 {
163     FreedesktopImage fimg(img);
164     return QVariant(FreedesktopImage::metaType(), &fimg);
165 }
166
167 void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
168 {
169     Q_UNUSED(cls);
170     // Arguments for DBus call:
171     QList<QVariant> args;
172
173     // Program Name:
174     args.append(programName);
175
176     // Unique ID of this notification type:
177     args.append(0U);
178
179     // Application Icon, empty string
180     args.append(QString());
181
182     // Summary
183     args.append(title);
184
185     // Body
186     args.append(text);
187
188     // Actions (none, actions are deprecated)
189     QStringList actions;
190     args.append(actions);
191
192     // Hints
193     QVariantMap hints;
194
195     // If no icon specified, set icon based on class
196     QIcon tmpicon;
197     if(icon.isNull())
198     {
199         QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
200         switch(cls)
201         {
202         case Information: sicon = QStyle::SP_MessageBoxInformation; break;
203         case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
204         case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
205         default: break;
206         }
207         tmpicon = QApplication::style()->standardIcon(sicon);
208     }
209     else
210     {
211         tmpicon = icon;
212     }
213     hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
214     args.append(hints);
215
216     // Timeout (in msec)
217     args.append(millisTimeout);
218
219     // "Fire and forget"
220     interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
221 }
222 #endif
223
224 void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
225 {
226     Q_UNUSED(icon);
227     QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
228     switch(cls) // Set icon based on class
229     {
230     case Information: sicon = QSystemTrayIcon::Information; break;
231     case Warning: sicon = QSystemTrayIcon::Warning; break;
232     case Critical: sicon = QSystemTrayIcon::Critical; break;
233     }
234     trayIcon->showMessage(title, text, sicon, millisTimeout);
235 }
236
237 // Based on Qt's tray icon implementation
238 #ifdef Q_OS_MAC
239 void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
240 {
241     const QString script(
242         "tell application \"%5\"\n"
243         "  set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
244         "  set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
245         "  register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
246         "  notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
247         "end tell"
248     );
249
250     QString notificationApp(QApplication::applicationName());
251     if (notificationApp.isEmpty())
252         notificationApp = "Application";
253
254     QPixmap notificationIconPixmap;
255     if (icon.isNull()) { // If no icon specified, set icon based on class
256         QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
257         switch (cls)
258         {
259         case Information: sicon = QStyle::SP_MessageBoxInformation; break;
260         case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
261         case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
262         }
263         notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
264     }
265     else {
266         QSize size = icon.actualSize(QSize(48, 48));
267         notificationIconPixmap = icon.pixmap(size);
268     }
269
270     QString notificationIcon;
271     QTemporaryFile notificationIconFile;
272     if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
273         QImageWriter writer(&notificationIconFile, "PNG");
274         if (writer.write(notificationIconPixmap.toImage()))
275             notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
276     }
277
278     QString quotedTitle(title), quotedText(text);
279     quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
280     quotedText.replace("\\", "\\\\").replace("\"", "\\");
281     QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
282     MacNotificationHandler::instance()->sendAppleScript(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp));
283 }
284
285 void Notificator::notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon) {
286     // icon is not supported by the user notification center yet. OSX will use the app icon.
287     MacNotificationHandler::instance()->showNotification(title, text);
288 }
289
290 #endif
291
292 void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
293 {
294     switch(mode)
295     {
296 #ifdef USE_DBUS
297     case Freedesktop:
298         notifyDBus(cls, title, text, icon, millisTimeout);
299         break;
300 #endif
301     case QSystemTray:
302         notifySystray(cls, title, text, icon, millisTimeout);
303         break;
304 #ifdef Q_OS_MAC
305     case UserNotificationCenter:
306         notifyMacUserNotificationCenter(cls, title, text, icon);
307         break;
308     case Growl12:
309     case Growl13:
310         notifyGrowl(cls, title, text, icon);
311         break;
312 #endif
313     default:
314         if(cls == Critical)
315         {
316             // Fall back to old fashioned pop-up dialog if critical and no other notification available
317             QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
318         }
319         break;
320     }
321 }
This page took 0.043048 seconds and 4 git commands to generate.