You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

notificator.cpp 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // Copyright (c) 2011-2016 The Starwels developers
  2. // Distributed under the MIT software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include "notificator.h"
  5. #include <QApplication>
  6. #include <QByteArray>
  7. #include <QIcon>
  8. #include <QImageWriter>
  9. #include <QMessageBox>
  10. #include <QMetaType>
  11. #include <QStyle>
  12. #include <QSystemTrayIcon>
  13. #include <QTemporaryFile>
  14. #include <QVariant>
  15. #ifdef USE_DBUS
  16. #include <stdint.h>
  17. #include <QtDBus>
  18. #endif
  19. // Include ApplicationServices.h after QtDbus to avoid redefinition of check().
  20. // This affects at least OSX 10.6. See /usr/include/AssertMacros.h for details.
  21. // Note: This could also be worked around using:
  22. // #define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
  23. #ifdef Q_OS_MAC
  24. #include <ApplicationServices/ApplicationServices.h>
  25. #include "macnotificationhandler.h"
  26. #endif
  27. #ifdef USE_DBUS
  28. // https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
  29. const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;
  30. #endif
  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. Notificator::~Notificator()
  77. {
  78. #ifdef USE_DBUS
  79. delete interface;
  80. #endif
  81. }
  82. #ifdef USE_DBUS
  83. // Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
  84. class FreedesktopImage
  85. {
  86. public:
  87. FreedesktopImage() {}
  88. FreedesktopImage(const QImage &img);
  89. static int metaType();
  90. // Image to variant that can be marshalled over DBus
  91. static QVariant toVariant(const QImage &img);
  92. private:
  93. int width, height, stride;
  94. bool hasAlpha;
  95. int channels;
  96. int bitsPerSample;
  97. QByteArray image;
  98. friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);
  99. friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);
  100. };
  101. Q_DECLARE_METATYPE(FreedesktopImage);
  102. // Image configuration settings
  103. const int CHANNELS = 4;
  104. const int BYTES_PER_PIXEL = 4;
  105. const int BITS_PER_SAMPLE = 8;
  106. FreedesktopImage::FreedesktopImage(const QImage &img):
  107. width(img.width()),
  108. height(img.height()),
  109. stride(img.width() * BYTES_PER_PIXEL),
  110. hasAlpha(true),
  111. channels(CHANNELS),
  112. bitsPerSample(BITS_PER_SAMPLE)
  113. {
  114. // Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
  115. QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
  116. const uint32_t *data = reinterpret_cast<const uint32_t*>(tmp.bits());
  117. unsigned int num_pixels = width * height;
  118. image.resize(num_pixels * BYTES_PER_PIXEL);
  119. for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)
  120. {
  121. image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; // R
  122. image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; // G
  123. image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; // B
  124. image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; // A
  125. }
  126. }
  127. QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)
  128. {
  129. a.beginStructure();
  130. a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
  131. a.endStructure();
  132. return a;
  133. }
  134. const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)
  135. {
  136. a.beginStructure();
  137. a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
  138. a.endStructure();
  139. return a;
  140. }
  141. int FreedesktopImage::metaType()
  142. {
  143. return qDBusRegisterMetaType<FreedesktopImage>();
  144. }
  145. QVariant FreedesktopImage::toVariant(const QImage &img)
  146. {
  147. FreedesktopImage fimg(img);
  148. return QVariant(FreedesktopImage::metaType(), &fimg);
  149. }
  150. void Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
  151. {
  152. Q_UNUSED(cls);
  153. // Arguments for DBus call:
  154. QList<QVariant> args;
  155. // Program Name:
  156. args.append(programName);
  157. // Unique ID of this notification type:
  158. args.append(0U);
  159. // Application Icon, empty string
  160. args.append(QString());
  161. // Summary
  162. args.append(title);
  163. // Body
  164. args.append(text);
  165. // Actions (none, actions are deprecated)
  166. QStringList actions;
  167. args.append(actions);
  168. // Hints
  169. QVariantMap hints;
  170. // If no icon specified, set icon based on class
  171. QIcon tmpicon;
  172. if(icon.isNull())
  173. {
  174. QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
  175. switch(cls)
  176. {
  177. case Information: sicon = QStyle::SP_MessageBoxInformation; break;
  178. case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
  179. case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
  180. default: break;
  181. }
  182. tmpicon = QApplication::style()->standardIcon(sicon);
  183. }
  184. else
  185. {
  186. tmpicon = icon;
  187. }
  188. hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
  189. args.append(hints);
  190. // Timeout (in msec)
  191. args.append(millisTimeout);
  192. // "Fire and forget"
  193. interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
  194. }
  195. #endif
  196. void Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
  197. {
  198. Q_UNUSED(icon);
  199. QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
  200. switch(cls) // Set icon based on class
  201. {
  202. case Information: sicon = QSystemTrayIcon::Information; break;
  203. case Warning: sicon = QSystemTrayIcon::Warning; break;
  204. case Critical: sicon = QSystemTrayIcon::Critical; break;
  205. }
  206. trayIcon->showMessage(title, text, sicon, millisTimeout);
  207. }
  208. // Based on Qt's tray icon implementation
  209. #ifdef Q_OS_MAC
  210. void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
  211. {
  212. const QString script(
  213. "tell application \"%5\"\n"
  214. " set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
  215. " set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
  216. " register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
  217. " notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
  218. "end tell"
  219. );
  220. QString notificationApp(QApplication::applicationName());
  221. if (notificationApp.isEmpty())
  222. notificationApp = "Application";
  223. QPixmap notificationIconPixmap;
  224. if (icon.isNull()) { // If no icon specified, set icon based on class
  225. QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
  226. switch (cls)
  227. {
  228. case Information: sicon = QStyle::SP_MessageBoxInformation; break;
  229. case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
  230. case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
  231. }
  232. notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
  233. }
  234. else {
  235. QSize size = icon.actualSize(QSize(48, 48));
  236. notificationIconPixmap = icon.pixmap(size);
  237. }
  238. QString notificationIcon;
  239. QTemporaryFile notificationIconFile;
  240. if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
  241. QImageWriter writer(&notificationIconFile, "PNG");
  242. if (writer.write(notificationIconPixmap.toImage()))
  243. notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
  244. }
  245. QString quotedTitle(title), quotedText(text);
  246. quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
  247. quotedText.replace("\\", "\\\\").replace("\"", "\\");
  248. QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
  249. MacNotificationHandler::instance()->sendAppleScript(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp));
  250. }
  251. void Notificator::notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon) {
  252. // icon is not supported by the user notification center yet. OSX will use the app icon.
  253. MacNotificationHandler::instance()->showNotification(title, text);
  254. }
  255. #endif
  256. void Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)
  257. {
  258. switch(mode)
  259. {
  260. #ifdef USE_DBUS
  261. case Freedesktop:
  262. notifyDBus(cls, title, text, icon, millisTimeout);
  263. break;
  264. #endif
  265. case QSystemTray:
  266. notifySystray(cls, title, text, icon, millisTimeout);
  267. break;
  268. #ifdef Q_OS_MAC
  269. case UserNotificationCenter:
  270. notifyMacUserNotificationCenter(cls, title, text, icon);
  271. break;
  272. case Growl12:
  273. case Growl13:
  274. notifyGrowl(cls, title, text, icon);
  275. break;
  276. #endif
  277. default:
  278. if(cls == Critical)
  279. {
  280. // Fall back to old fashioned pop-up dialog if critical and no other notification available
  281. QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
  282. }
  283. break;
  284. }
  285. }