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 9.2KB

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