diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 5b109c8..05c0c76 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,115 +1,117 @@ include_directories(${PHONON_INCLUDE_DIR}) ecm_create_qm_loader(knotifications_QM_LOADER knotifications5_qt) set(knotifications_SRCS knotification.cpp knotificationmanager.cpp kpassivepopup.cpp kstatusnotifieritem.cpp kstatusnotifieritemdbus_p.cpp knotificationrestrictions.cpp knotifyconfig.cpp - knotifyplugin.cpp + knotificationplugin.cpp notifybypopup.cpp imageconverter.cpp #needed to marshal images for sending over dbus by NotifyByPopup notifybypopupgrowl.cpp notifybyexecute.cpp # notifybylogfile.cpp notifybytaskbar.cpp notifybyaudio.cpp ${knotifications_QM_LOADER} ) find_package(dbusmenu-qt5 CONFIG) set_package_properties(dbusmenu-qt5 PROPERTIES DESCRIPTION "DBusMenuQt" URL "https://launchpad.net/libdbusmenu-qt" TYPE OPTIONAL PURPOSE "Support for notification area menus via the DBusMenu protocol") if (dbusmenu-qt5_FOUND) message("dbusmenu-qt5_FOUND") set(HAVE_DBUSMENUQT 1) include_directories(${dbusmenu-qt5_INCLUDE_DIRS}) else() set(HAVE_DBUSMENUQT 0) endif() qt5_add_dbus_adaptor(knotifications_SRCS org.kde.StatusNotifierItem.xml kstatusnotifieritemdbus_p.h KStatusNotifierItemDBus) set(statusnotifierwatcher_xml org.kde.StatusNotifierWatcher.xml) qt5_add_dbus_interface(knotifications_SRCS ${statusnotifierwatcher_xml} statusnotifierwatcher_interface) set(notifications_xml org.freedesktop.Notifications.xml) qt5_add_dbus_interface(knotifications_SRCS ${notifications_xml} notifications_interface) configure_file(config-knotifications.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-knotifications.h ) add_library(KF5Notifications ${knotifications_SRCS}) generate_export_header(KF5Notifications BASE_NAME KNotifications) add_library(KF5::Notifications ALIAS KF5Notifications) target_include_directories(KF5Notifications INTERFACE "$") target_link_libraries(KF5Notifications PUBLIC Qt5::Widgets ) target_link_libraries(KF5Notifications PRIVATE ${PHONON_LIBRARIES} KF5::CoreAddons KF5::IconThemes KF5::Service KF5::ConfigCore KF5::WindowSystem KF5::Codecs Qt5::DBus ) if(X11_FOUND) target_link_libraries(KF5Notifications PRIVATE ${X11_X11_LIB} Qt5::X11Extras) endif() if(X11_XTest_FOUND) target_link_libraries(KF5Notifications PRIVATE ${X11_XTest_LIB}) endif() if(HAVE_DBUSMENUQT) target_link_libraries(KF5Notifications PRIVATE dbusmenu-qt5) endif() set_target_properties(KF5Notifications PROPERTIES VERSION ${KNOTIFICATIONS_VERSION_STRING} SOVERSION ${KNOTIFICATIONS_SOVERSION} EXPORT_NAME Notifications ) ecm_generate_headers(KNotifications_HEADERS HEADER_NAMES KNotification KPassivePopup KStatusNotifierItem KNotificationRestrictions + KNotificationPlugin REQUIRED_HEADERS KNotifications_HEADERS ) install(TARGETS KF5Notifications EXPORT KF5NotificationsTargets ${KF5_INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/knotifications_export.h ${KNotifications_HEADERS} DESTINATION ${KF5_INCLUDE_INSTALL_DIR}/KNotifications COMPONENT Devel ) install(FILES org.kde.StatusNotifierItem.xml DESTINATION ${DBUS_INTERFACES_INSTALL_DIR} RENAME kf5_org.kde.StatusNotifierItem.xml) install(FILES org.kde.StatusNotifierWatcher.xml DESTINATION ${DBUS_INTERFACES_INSTALL_DIR} RENAME kf5_org.kde.StatusNotifierWatcher.xml) include(ECMGeneratePriFile) ecm_generate_pri_file(BASE_NAME KNotifications LIB_NAME KF5Notifications DEPS "widgets" FILENAME_VAR PRI_FILENAME INCLUDE_INSTALL_DIR ${KF5_INCLUDE_INSTALL_DIR}/KNotifications) install(FILES ${PRI_FILENAME} DESTINATION ${ECM_MKSPECS_INSTALL_DIR}) + diff --git a/src/knotification.h b/src/knotification.h index 6479c54..757adb4 100644 --- a/src/knotification.h +++ b/src/knotification.h @@ -1,653 +1,654 @@ /* This file is part of the KDE libraries Copyright (C) 2005-2006 Olivier Goffart + Copyright (C) 2013-2014 Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KNOTIFICATION_H #define KNOTIFICATION_H #include #include #include #include class QWidget; class QDBusError; /** * KNotification is used to notify the user of an event. * * \section introduction * * There are two main kinds of notifications: * * @li Feedback events: * For notifying the user that he/she just performed an operation, like maximizing a * window. This allows us to play sounds when a dialog appears. * This is an instant notification. It ends automatically after a small timeout. * * @li persistant notifications: * Notify when the user received a new message, or when something else important happened * the user has to know about. This notification has a start and a end. It begins when * the event actually occurs, and finishes when the message is acknowledged or read. * * Example of a persistent notification in an instant messaging application: * The application emits the notification when the message is actually received, and closes it only * when the user has read the message (when the message window has received the focus) using the close() slot * Persistent notifications must have the Persistent flag. * * By default a notification will use the application name as title, but you * can also provide a brief text in the title and a more precise description in * the body text. This is especially useful for notifications coming from * applications which should be considered "part of the system", like a battery * monitor or a network connection manager. * For example a battery indicator could use "Low Battery" as a title and "Only * 12 minutes left." as a body text. * * In order to perform a notification, you need to create a description file, which contains * default parameters of the notification, and use KNotification::event at the place in the * application code where the notification occurs. * The returned KNotification pointer may be used to connect signals or slots * * \section file The global config file * Your application should install a file called knotifications5/appname.notifyrc * in a QStandardPaths::GenericDataLocation directory. * * You can do this with the following CMake command: * install(FILES appname.notifyrc DESTINATION ${KNOTIFYRC_INSTALL_DIR})) * * This file contains mainly 3 parts *
  1. \ref global "Global information"
  2. *
  3. \ref context "Context information"
  4. *
  5. \ref events "Definition of individual events"
* * \subsection global Global information * The global part looks like that *
            [Global]
            IconName=Filename
            Comment=Friendly Name of app
            Name=Name of app
  * 
* The icon filename is just the name, without extension, it's found with the KIconLoader. * The Comment field will be used in KControl to describe the application. * The Name field is optional and may be used as the application name for popup, * if Name is not present, Comment is used instead * * \subsection context Context information * * This part consists of hints for the configuration widget *
            [Context/group]
            Name=Group name
            Comment=The name of the group for contacts
 
            [Context/folder]
            Name=Group name
  *  
* The second part of the groupname is the context identifier. * It should not contain special characters. * The Name field is the one the user will see (and which is translated) * * \subsection events Definition of Events * * The definition of the events forms the most important part of the config file *
            [Event/newmail]
            Name=New email
            Comment=You have got a new email
            Contexts=folder,group
            Action=Sound|Popup
 
            [Event/contactOnline]
            Name=Contact goes online
            Comment=One of your contact has been connected
            Contexts=group
            Sound=filetoplay.ogg
            Action=None
  *  
* These are the default settings for each notifiable event. * Action is the string representing the action. Actions can be added to - * the KNotify daemon as plugins, by deriving from KNotifyPlugin. + * KNotification as plugins, by deriving from KNotificationPlugin. * At the time of writing, the following actions are available: Taskbar, * Sound, Popup, Logfile, KTTS, Execute. * Actions can be combined by seperating them with '|'. * * Contexts is a comma separated list of possible context for this event. * * \section userfile The user's config file * * This is an implementation detail, and is described here for your information. * * In the config file, there are two parts: the event configuration, and the context information * \subsection context Context information * These are hints for the configuration dialog. They contain both the internal id of the context, and the user visible string. *
            [Context/group]
            Values=1:Friends,2:Work,3:Family
  *  
* \subsection event Events configuration * This contains the configuration of events for the user. * It contains the same fields as the description file. * The key of groups is in the form * Event/<EventName>/<ContextName>/<ContextValue> *
            [Event/contactOnline]
            Action=Sound
            Sound=/usr/share/sounds/super.ogg
 
            [Event/contactOnline/group/1]
            Action=Popup|Sound
  * 
* * \section example Example of code * * This portion of code will fire the event for the "contactOnline" event * * @code KNotification *notification= new KNotification ( "contactOnline", widget ); notification->setText( i18n("The contact %1 has gone online", contact->name() ); notification->setPixmap( contact->pixmap() ); notification->setActions( QStringList( i18n( "Open chat" ) ) ); foreach( const QString &group , contact->groups() ) { notification->addContext( "group" , group ) ; } connect(notification, SIGNAL(activated(unsigned int )), contact , SLOT(slotOpenChat()) ); notification->sendEvent(); * @endcode * * @author Olivier Goffart \ */ class KNOTIFICATIONS_EXPORT KNotification : public QObject { Q_OBJECT public: /** * Sometimes the user may want different notifications for the same event, * depending the source of the event. Example, you want to be notified for mails * that arrive in your folder "personal inbox" but not for those in "spam" folder * * A notification context is a pair of two strings. * The first string is a key from what the context is. example "group" or * "filter" (not translated). * The second is the id of the context. In our example, the group id or the * filter id in the applications. * These strings are the ones present in the config file, and are in theory not * shown in the user interface. * * The order of contexts in the list is is important, the most important context * should be placed first. They are processed in that order when the notification occurs. * * @see event */ typedef QPair Context; typedef QList< Context > ContextList; enum NotificationFlag { /** * When the notification is activated, raise the notification's widget. * * This will change the desktop, raise the window, and switch to the tab. * @todo doesn't work yet */ RaiseWidgetOnActivation = 0x01, /** * The notification will be automatically closed after a timeout. (this is the default) */ CloseOnTimeout = 0x00, /** * The notification will NOT be automatically closed after a timeout. * You will have to track the notification, and close it with the * close function manually when the event is done, otherwise there will be a memory leak */ Persistent = 0x02, /** * The notification will be automatically closed if the widget() becomes * activated. * * If the widget is already activated when the notification occurs, the * notification will be closed after a small timeout. * * This only works if the widget is the toplevel widget * @todo make it work with tabulated widget */ CloseWhenWidgetActivated = 0x04, /** * @internal * The event is a standard kde event, and not an event of the application */ DefaultEvent = 0xF000 }; Q_DECLARE_FLAGS(NotificationFlags, NotificationFlag) /** * default events you can use in the event function */ enum StandardEvent { Notification, Warning, Error, Catastrophe }; /** * Create a new notification. * * You have to use sendEvent to show the notification. * * The pointer is automatically deleted when the event is closed. * * Make sure you use one of the NotificationFlags CloseOnTimeOut or * CloseWhenWidgetActivated, if not, * you have to close the notification yourself. * * @param eventId is the name of the event * @param widget is a widget where the notification reports to * @param flags is a bitmask of NotificationFlag */ explicit KNotification(const QString &eventId, QWidget *widget = 0L, const NotificationFlags &flags = CloseOnTimeout); /** * Create a new notification. * * You have to use sendEvent to show the notification. * * The pointer is automatically deleted when the event is closed. * * Make sure you use one of the NotificationFlags CloseOnTimeOut or * CloseWhenWidgetActivated, if not, * you have to close the notification yourself. * * @since 4.4 * * @param eventId is the name of the event * @param flags is a bitmask of NotificationFlag * @param parent parent object */ // KDE5: Clean up this mess // Only this constructor should stay with saner argument order and // defaults. Because of binary and source compatibility issues it has to // stay this way for now. The second argument CANNOT have a default // argument. if someone needs a widget associated with the notification he // should use setWidget after creating the object (or some xyz_cast magic) explicit KNotification(const QString &eventId, const NotificationFlags &flags, QObject *parent = NULL); ~KNotification(); /** * @brief the widget associated to the notification * * If the widget is destroyed, the notification will be automatically cancelled. * If the widget is activated, the notification will be automatically closed if the NotificationFlags specify that * * When the notification is activated, the widget might be raised. * Depending on the configuration, the taskbar entry of the window containing the widget may blink. */ QWidget *widget() const; /** * Set the widget associated to the notification. * The notification is reparented to the new widget. * \see widget() * @param widget the new widget */ void setWidget(QWidget *widget); /** * @return the name of the event */ QString eventId() const; /** * @return the notification title * @see setTitle * @since 4.3 */ QString title() const; /** * Set the title of the notification popup. * If no title is set, the application name will be used. * * @param title the title * @since 4.3 */ void setTitle(const QString &title); /** * @return the notification text * @see setText */ QString text() const; /** * Set the notification text that will appear in the popup. * * The text is shown in a QLabel, you should make sure to escape any html that is needed. * You can use some of the qt basic html tags. * * @param text the text */ void setText(const QString &text); /** * \return the icon shown in the popup * \see setIconName * \since 5.4 */ QString iconName() const; /** * set the icon that will be shown in the popup. * @param icon the icon * @since 5.4 */ void setIconName(const QString &icon); /** * \return the pixmap shown in the popup * \see setPixmap */ QPixmap pixmap() const; /** * set the pixmap that will be shown in the popup. * @param pix the pixmap */ void setPixmap(const QPixmap &pix); /** * @return the list of actions */ QStringList actions() const; /** * Set the list of actions link shown in the popup. * @param actions the list of actions */ void setActions(const QStringList &actions); /** * @return the list of contexts, see KNotification::Context */ ContextList contexts() const; /** * set the list of contexts, see KNotification::Context * * The list of contexts must be set before calling sendEvent; */ void setContexts(const ContextList &contexts); /** * append a context at the list of contexts, see KNotificaiton::Context * @param context the context which is added */ void addContext(const Context &context); /** * @overload * @param context_key is the key of the context * @param context_value is the value of the context */ void addContext(const QString &context_key, const QString &context_value); /** * @return the notification flags. */ NotificationFlags flags() const; /** * Set the notification flags. * should be called before sendEvent(). */ void setFlags(const NotificationFlags &flags); /** * The componentData is used to determine the location of the config file. By default, the app name is used * @param componentName the new component name */ void setComponentName(const QString &componentName); /** * @internal * the id given by the notification manager */ int id(); /** * @internal * appname used for the dbus object */ QString appName() const; Q_SIGNALS: /** * Emit only when the default activation has occurred */ void activated(); /** * Emit when an action has been activated. * @param action will be 0 is the default aciton was activated, or any action id */ void activated(unsigned int action); /** * Convenience signal that is emitted when the first action is activated. */ void action1Activated(); /** * \overload */ void action2Activated(); /** * \overload */ void action3Activated(); /** * Emitted when the notification is closed. Both when it is activated or if it is just ignored. */ void closed(); /** * The notification has been ignored */ void ignored(); public Q_SLOTS: /** * @brief Activate the action specified action * If the action is zero, then the default action is activated */ void activate(unsigned int action = 0); /** * Close the notification without activating it. * * This will delete the notification. */ void close(); /** * @brief Raise the widget. * This will change the desktop, activate the window, and the tab if needed. */ void raiseWidget(); /** * The notification will automatically be closed if all presentations are finished. * if you want to show your own presentation in your application, you should use this * function, so it will not be automatically closed when there is nothing to show. * * don't forgot to deref, or the notification may be never closed if there is no timeout. * @see ref */ void ref(); /** * remove a reference made with ref() * the notification may be closed when calling this. * @see ref */ void deref(); /** * Emit or re-emit the event. */ void sendEvent(); /** * @internal * update the texts, the icon, and the actions of one existing notification */ void update(); private: struct Private; Private *const d; protected: /** * reimplemented for internal reasons */ virtual bool eventFilter(QObject *watched, QEvent *event); public: /** * @brief emit an event * * This method creates the KNotification, setting every parameter, and fire the event. * You don't need to call sendEvent * * A popup may be displayed or a sound may be played, depending the config. * * @return a KNotification . You may use that pointer to connect some signals or slot. * the pointer is automatically deleted when the event is closed. * * Make sure you use one of the CloseOnTimeOut or CloseWhenWidgetActivated, if not, * you have to close yourself the notification. * * @note the text is shown in a QLabel, you should escape HTML, if needed. * * @param eventId is the name of the event * @param title is title of the notification to show in the popup. * @param text is the text of the notification to show in the popup. * @param pixmap is a picture which may be shown in the popup. * @param widget is a widget where the notification reports to * @param flags is a bitmask of NotificationFlag * @param componentName used to determine the location of the config file. by default, appname is used * @since 4.4 */ static KNotification *event(const QString &eventId, const QString &title, const QString &text, const QPixmap &pixmap = QPixmap(), QWidget *widget = 0L, const NotificationFlags &flags = CloseOnTimeout, const QString &componentName = QString()); /** * @brief emit a standard event * * @overload * * This will emit a standard event * * @param eventId is the name of the event * @param text is the text of the notification to show in the popup. * @param pixmap is a picture which may be shown in the popup. * @param widget is a widget where the notification reports to * @param flags is a bitmask of NotificationFlag * @param componentName used to determine the location of the config file. by default, plasma_workspace is used */ static KNotification *event(const QString &eventId, const QString &text = QString(), const QPixmap &pixmap = QPixmap(), QWidget *widget = 0L, const NotificationFlags &flags = CloseOnTimeout, const QString &componentName = QString()); /** * @brief emit a standard event * * @overload * * This will emit a standard event * * @param eventId is the name of the event * @param text is the text of the notification to show in the popup * @param pixmap is a picture which may be shown in the popup * @param widget is a widget where the notification reports to * @param flags is a bitmask of NotificationFlag */ static KNotification *event(StandardEvent eventId, const QString &text = QString(), const QPixmap &pixmap = QPixmap(), QWidget *widget = 0L, const NotificationFlags &flags = CloseOnTimeout); /** * @brief emit a standard event * * @overload * * This will emit a standard event * * @param eventId is the name of the event * @param title is title of the notification to show in the popup. * @param text is the text of the notification to show in the popup * @param pixmap is a picture which may be shown in the popup * @param widget is a widget where the notification reports to * @param flags is a bitmask of NotificationFlag * @since 4.4 */ static KNotification *event(StandardEvent eventId, const QString &title, const QString &text, const QPixmap &pixmap = QPixmap(), QWidget *widget = 0L, const NotificationFlags &flags = CloseOnTimeout); /** * @brief emit a standard event with the possibility of setting an icon by icon name * * @overload * * This will emit a standard event * * @param eventId is the name of the event * @param title is title of the notification to show in the popup. * @param text is the text of the notification to show in the popup * @param iconName a Freedesktop compatible icon name to be shown in the popup * @param widget is a widget where the notification reports to * @param flags is a bitmask of NotificationFlag * @param componentName used to determine the location of the config file. by default, plasma_workspace is used * @since 5.4 */ static KNotification *event(const QString &eventId, const QString &title, const QString &text, const QString &iconName, QWidget *widget = 0L, const NotificationFlags &flags = CloseOnTimeout, const QString &componentName = QString()); /** * This is a simple substitution for QApplication::beep() * * @param reason a short text explaining what has happened (may be empty) * @param widget the widget the notification refers to */ static void beep(const QString &reason = QString(), QWidget *widget = 0L); //prevent warning using QObject::event; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KNotification::NotificationFlags) #endif diff --git a/src/knotificationmanager.cpp b/src/knotificationmanager.cpp index f44c660..b91ecfb 100644 --- a/src/knotificationmanager.cpp +++ b/src/knotificationmanager.cpp @@ -1,208 +1,208 @@ /* This file is part of the KDE libraries Copyright (C) 2005 Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "knotificationmanager_p.h" #include "knotification.h" #include #include #include #include #include #include #include #include "knotifyconfig.h" -#include "knotifyplugin.h" +#include "knotificationplugin.h" #include "notifybypopup.h" #include "notifybyaudio.h" #include "notifybylogfile.h" #include "notifybytaskbar.h" #include "notifybyexecute.h" typedef QHash Dict; struct KNotificationManager::Private { QHash notifications; - QHash notifyPlugins; + QHash notifyPlugins; // incremental ids for notifications int notifyIdCounter; }; class KNotificationManagerSingleton { public: KNotificationManager instance; }; Q_GLOBAL_STATIC(KNotificationManagerSingleton, s_self) KNotificationManager *KNotificationManager::self() { return &s_self()->instance; } KNotificationManager::KNotificationManager() : d(new Private) { d->notifyIdCounter = 0; qDeleteAll(d->notifyPlugins); d->notifyPlugins.clear(); addPlugin(new NotifyByPopup(this)); //FIXME: port and reenable // addPlugin(new NotifyBySound(this)); addPlugin(new NotifyByExecute(this)); // addPlugin(new NotifyByLogfile(this)); addPlugin(new NotifyByAudio(this)); //TODO reactivate on Mac/Win when KWindowSystem::demandAttention will implemented on this system. #ifndef Q_WS_MAC addPlugin(new NotifyByTaskbar(this)); #endif // addPlugin(new NotifyByKTTS(this)); KService::List offers = KServiceTypeTrader::self()->query("KNotify/NotifyMethod"); QVariantList args; QString error; Q_FOREACH (const KService::Ptr service, offers) { - KNotifyPlugin *plugin = service->createInstance(this, args, &error); + KNotificationPlugin *plugin = service->createInstance(this, args, &error); if (plugin) { addPlugin(plugin); } else { qDebug() << "Could not load plugin" << service->name() << "due to:" << error; } } } KNotificationManager::~KNotificationManager() { delete d; } -void KNotificationManager::addPlugin(KNotifyPlugin *notifyPlugin) +void KNotificationManager::addPlugin(KNotificationPlugin *notifyPlugin) { d->notifyPlugins[notifyPlugin->optionName()] = notifyPlugin; connect(notifyPlugin, SIGNAL(finished(KNotification*)), this, SLOT(notifyPluginFinished(KNotification*))); connect(notifyPlugin, SIGNAL(actionInvoked(int, int)), this, SLOT(notificationActivated(int, int))); } void KNotificationManager::notifyPluginFinished(KNotification *notification) { if (!notification || !d->notifications.contains(notification->id())) { return; } notification->deref(); } void KNotificationManager::notificationActivated(int id, int action) { if (d->notifications.contains(id)) { qDebug() << id << " " << action; KNotification *n = d->notifications[id]; n->activate(action); close(id); } } void KNotificationManager::notificationClosed(KNotification *notification) { if (d->notifications.contains(notification->id())) { qDebug() << notification->id(); KNotification *n = d->notifications[notification->id()]; d->notifications.remove(notification->id()); n->close(); } } void KNotificationManager::close(int id, bool force) { if (force || d->notifications.contains(id)) { KNotification *n = d->notifications.take(id); qDebug() << "Closing notification" << id; - Q_FOREACH (KNotifyPlugin *plugin, d->notifyPlugins) { + Q_FOREACH (KNotificationPlugin *plugin, d->notifyPlugins) { plugin->close(n); } } } int KNotificationManager::notify(KNotification *n) { //FIXME: leaking? KNotifyConfig *notifyConfig = new KNotifyConfig(n->appName(), n->contexts(), n->eventId()); QString notifyActions = notifyConfig->readEntry("Action"); if (notifyActions.isEmpty() || notifyActions == QLatin1String("None")) { // this will cause KNotification closing itself fast n->deref(); return -1; } d->notifications.insert(++d->notifyIdCounter, n); Q_FOREACH (const QString &action, notifyActions.split('|')) { if (!d->notifyPlugins.contains(action)) { qDebug() << "No plugin for action" << action; continue; } - KNotifyPlugin *notifyPlugin = d->notifyPlugins[action]; + KNotificationPlugin *notifyPlugin = d->notifyPlugins[action]; n->ref(); qDebug() << "Calling notify on" << notifyPlugin->optionName(); notifyPlugin->notify(n, notifyConfig); } return d->notifyIdCounter; } void KNotificationManager::update(KNotification *n) { QByteArray pixmapData; if (!n->pixmap().isNull()) { QBuffer buffer(&pixmapData); buffer.open(QIODevice::WriteOnly); n->pixmap().save(&buffer, "PNG"); } KNotifyConfig notifyConfig(n->appName(), n->contexts(), n->eventId()); - Q_FOREACH (KNotifyPlugin *p, d->notifyPlugins) { + Q_FOREACH (KNotificationPlugin *p, d->notifyPlugins) { p->update(n, ¬ifyConfig); } } void KNotificationManager::reemit(KNotification *n) { QVariantList contextList; typedef QPair Context; foreach (const Context &ctx, n->contexts()) { QVariantList vl; vl << ctx.first << ctx.second; contextList << vl; } notify(n); } #include "moc_knotificationmanager_p.cpp" diff --git a/src/knotificationmanager_p.h b/src/knotificationmanager_p.h index 19bb823..f8e7df8 100644 --- a/src/knotificationmanager_p.h +++ b/src/knotificationmanager_p.h @@ -1,79 +1,79 @@ /* This file is part of the KDE libraries Copyright (C) 2005 Olivier Goffart Copyright (C) 2006 Thiago Macieira This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KNOTIFICATIONMANAGER_H #define KNOTIFICATIONMANAGER_H #include class KNotification; class QPixmap; class QStringList; -class KNotifyPlugin; +class KNotificationPlugin; /** * @internal * @author Olivier Goffart */ class KNotificationManager : public QObject { Q_OBJECT public: static KNotificationManager *self(); ~KNotificationManager(); - void addPlugin(KNotifyPlugin *notifyPlugin); + void addPlugin(KNotificationPlugin *notifyPlugin); /** * send the dbus call to the knotify server */ int notify(KNotification *n); /** * send the close dcop call to the knotify server for the notification with the identifier @p id . * And remove the notification from the internal map * @param id the id of the notification * @param force if false, only close registered notification */ void close(int id, bool force = false); /** * update one notification text and pixmap and actions */ void update(KNotification *n); /** * re-emit the notification, eventually with new contexts */ void reemit(KNotification *n); private Q_SLOTS: void notificationClosed(KNotification *notification); void notificationActivated(int id, int action); void notifyPluginFinished(KNotification *notification); private: struct Private; Private *const d; KNotificationManager(); friend class KNotificationManagerSingleton; }; #endif diff --git a/src/knotifyplugin.cpp b/src/knotificationplugin.cpp similarity index 75% rename from src/knotifyplugin.cpp rename to src/knotificationplugin.cpp index e2efab9..7315c17 100644 --- a/src/knotifyplugin.cpp +++ b/src/knotificationplugin.cpp @@ -1,56 +1,54 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include -#include "knotifyplugin.h" +#include "knotificationplugin.h" -KNotifyPlugin::KNotifyPlugin(QObject *parent, const QVariantList &args) +KNotificationPlugin::KNotificationPlugin(QObject *parent, const QVariantList &args) : QObject(parent), d(0) { Q_UNUSED(args); } -KNotifyPlugin::~KNotifyPlugin() +KNotificationPlugin::~KNotificationPlugin() { } -void KNotifyPlugin::update(KNotification *notification, KNotifyConfig *config) +void KNotificationPlugin::update(KNotification *notification, KNotifyConfig *config) { Q_UNUSED(notification); Q_UNUSED(config); } -void KNotifyPlugin::close(KNotification *notification) +void KNotificationPlugin::close(KNotification *notification) { emit finished(notification); } -void KNotifyPlugin::finish(KNotification *notification) +void KNotificationPlugin::finish(KNotification *notification) { emit finished(notification); } -#include "knotifyplugin.moc" - diff --git a/src/knotifyplugin.h b/src/knotificationplugin.h similarity index 79% rename from src/knotifyplugin.h rename to src/knotificationplugin.h index 248a66f..ea193fa 100644 --- a/src/knotifyplugin.h +++ b/src/knotificationplugin.h @@ -1,116 +1,110 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ - - -#ifndef KNOTIFYPLUGIN_H -#define KNOTIFYPLUGIN_H +#ifndef KNOTIFICATIONPLUGIN_H +#define KNOTIFICATIONPLUGIN_H #include #include #include "knotifications_export.h" class KNotification; -class KNotifyPluginPrivate; +class KNotificationPluginPrivate; class KNotifyConfig; - /** * @brief abstract class for KNotify actions * - * A KNotifyPlugin is responsible of one presentation. You can subclass it to have your own knotify presentation. + * A KNotificationPlugin is responsible of notification presentation. + * You can subclass it to have your own presentation of a notification. * - * You should reimplement the KNotifyPlugin::notify method to display the notification. + * You should reimplement the KNotificationPlugin::notify method to display the notification. * * @author Olivier Goffart */ -class KNOTIFICATIONS_EXPORT KNotifyPlugin : public QObject +class KNOTIFICATIONS_EXPORT KNotificationPlugin : public QObject { Q_OBJECT public: - KNotifyPlugin(QObject *parent = 0, const QVariantList &args = QVariantList()); - virtual ~KNotifyPlugin(); + KNotificationPlugin(QObject *parent = 0, const QVariantList &args = QVariantList()); + virtual ~KNotificationPlugin(); /** * @brief return the name of this plugin. * - * this is the name that should appear in the .knotifyrc file, + * this is the name that should appear in the .notifyrc file, * in the field Action=... if a notification is set to use this plugin */ virtual QString optionName() = 0; /** * This function is called when the notification is sent. * (or re-sent) * You should implement this function to display a notification * - * for each call to this function (even for re-notification), you MUST call finish(int) + * for each call to this function (even for re-notification), you MUST call finish(KNotification*) * * @param notification is the KNotification object * @param notifyConfig is the configuration of the notification */ virtual void notify(KNotification *notification, KNotifyConfig *notifyConfig) = 0; /** * This function is called when the notification has changed (such as the text or the icon) */ virtual void update(KNotification *notification, KNotifyConfig *config); /** * This function is called when the notification has been closed */ virtual void close(KNotification *notification); protected: /** * emit the finished signal * you MUST call this function for each call to notify(), even if you do nothing there * * call it when the presentation is finished (because the user closed the popup or the sound is finished) * * If your presentation is synchronous, you can even call this function from the notify() call itself */ void finish(KNotification *notification); Q_SIGNALS: /** * the presentation is finished. */ void finished(KNotification *notification); /** * emit this signal if one action was invoked * @param id is the id of the notification * @param action is the action number. zero for the default action */ void actionInvoked(int id , int action); private: - KNotifyPluginPrivate *const d; + KNotificationPluginPrivate *const d; }; -#define K_EXPORT_KNOTIFY_METHOD(libname,classname) \ -K_PLUGIN_FACTORY(KNotifyMethodPluginFactory, registerPlugin();) \ -K_EXPORT_PLUGIN(KNotifyMethodPluginFactory("knotify_method_" #libname)) - #endif diff --git a/src/notifybyaudio.cpp b/src/notifybyaudio.cpp index 99b8027..fcbb2da 100644 --- a/src/notifybyaudio.cpp +++ b/src/notifybyaudio.cpp @@ -1,153 +1,153 @@ /* This file is part of the KDE libraries Copyright 2014 by Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "notifybyaudio.h" #include #include #include #include #include #include #include "knotifyconfig.h" #include "knotification.h" #include #include #include NotifyByAudio::NotifyByAudio(QObject *parent) - : KNotifyPlugin(parent) + : KNotificationPlugin(parent) { m_audioOutput = new Phonon::AudioOutput(Phonon::NotificationCategory, this); } NotifyByAudio::~NotifyByAudio() { qDeleteAll(m_reusablePhonons); delete m_audioOutput; } void NotifyByAudio::notify(KNotification *notification, KNotifyConfig *config) { QString soundFilename = config->readEntry("Sound"); if (soundFilename.isEmpty()) { qWarning() << "Audio notification requested, but no sound file provided in notifyrc file, aborting audio notification"; finish(notification); return; } QUrl soundURL = QUrl(soundFilename); // this CTOR accepts both absolute paths (/usr/share/sounds/blabla.ogg and blabla.ogg) w/o screwing the scheme if (soundURL.isRelative() && !soundURL.toString().startsWith('/')) { // QUrl considers url.scheme.isEmpty() == url.isRelative() soundURL = QUrl::fromLocalFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("sounds/") + soundFilename)); if (soundURL.isEmpty()) { qWarning() << "Audio notification requested, but sound file from notifyrc file was not found, aborting audio notification"; finish(notification); return; } } Phonon::MediaObject *m; if (m_reusablePhonons.isEmpty()) { m = new Phonon::MediaObject(this); connect(m, SIGNAL(finished()), SLOT(onAudioFinished())); connect(m, SIGNAL(stateChanged(Phonon::State,Phonon::State)), SLOT(stateChanged(Phonon::State,Phonon::State))); Phonon::createPath(m, m_audioOutput); } else { m = m_reusablePhonons.takeFirst(); } m->setCurrentSource(soundURL); m->play(); if (notification->flags() & KNotification::Persistent) { // Enqueing essentially prevents the subsystem pipeline from partial teardown // which is the most desired thing in terms of load and delay between loop cycles. // All of this is timing dependent, which is why we want at least one source queued; // in reality the shorter the source the more sources we want to be queued to prevent // the MO from running out of sources. // Point being that all phonon signals are forcefully queued (becuase qthread has problems detecting !pthread threads), // so when you get for example the aboutToFinish signal the MO might already have stopped playing. // // And so we queue it three times at least; doesn't cost anything and keeps us safe. m->enqueue(soundURL); m->enqueue(soundURL); m->enqueue(soundURL); connect(m, SIGNAL(currentSourceChanged(Phonon::MediaSource)), SLOT(onAudioSourceChanged(Phonon::MediaSource))); } m_notifications.insert(m, notification); } void NotifyByAudio::stateChanged(Phonon::State newState, Phonon::State oldState) { qDebug() << "Changing audio state from" << oldState << "to" << newState; } void NotifyByAudio::close(KNotification *notification) { Phonon::MediaObject *m = m_notifications.key(notification); if (!m) { return; } // this should call onAudioFinished() which also does finish() on the notification m->stop(); } void NotifyByAudio::onAudioFinished() { Phonon::MediaObject *m = qobject_cast(sender()); if (!m) { return; } KNotification *notification = m_notifications.value(m); finish(notification); disconnect(m, SIGNAL(currentSourceChanged(Phonon::MediaSource)), this, SLOT(onAudioSourceChanged(Phonon::MediaSource))); m_notifications.remove(m); m_reusablePhonons.append(m); } void NotifyByAudio::onAudioSourceChanged(const Phonon::MediaSource &source) { Phonon::MediaObject *m = qobject_cast(sender()); if (!m) { return; } m->enqueue(source); } #include "notifybyaudio.moc" diff --git a/src/notifybyaudio.h b/src/notifybyaudio.h index 767f1ce..9a2d531 100644 --- a/src/notifybyaudio.h +++ b/src/notifybyaudio.h @@ -1,62 +1,62 @@ /* This file is part of the KDE libraries Copyright 2014 by Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef NOTIFYBYAUDIO_H #define NOTIFYBYAUDIO_H -#include "knotifyplugin.h" +#include "knotificationplugin.h" #include namespace Phonon { // class MediaObject; class MediaSource; class AudioOutput; } class KNotification; -class NotifyByAudio : public KNotifyPlugin +class NotifyByAudio : public KNotificationPlugin { Q_OBJECT public: NotifyByAudio(QObject *parent = 0); virtual ~NotifyByAudio(); virtual QString optionName() { return QStringLiteral("Sound"); } virtual void notify(KNotification *notification, KNotifyConfig *config); virtual void close(KNotification *notification); private Q_SLOTS: void onAudioFinished(); void onAudioSourceChanged(const Phonon::MediaSource &source); void stateChanged(Phonon::State newState, Phonon::State oldState); private: QList m_reusablePhonons; QHash m_notifications; Phonon::AudioOutput *m_audioOutput; }; #endif diff --git a/src/notifybyexecute.cpp b/src/notifybyexecute.cpp index 254341a..8e54ed4 100644 --- a/src/notifybyexecute.cpp +++ b/src/notifybyexecute.cpp @@ -1,73 +1,73 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "notifybyexecute.h" #include #include #include #include #include #include "knotification.h" #include NotifyByExecute::NotifyByExecute(QObject *parent) - : KNotifyPlugin(parent) + : KNotificationPlugin(parent) { } NotifyByExecute::~NotifyByExecute() { } void NotifyByExecute::notify(KNotification *notification, KNotifyConfig *config) { QString command = config->readEntry(QStringLiteral("Execute")); qDebug() << command; if (!command.isEmpty()) { QHash subst; subst.insert('e', notification->eventId()); subst.insert('a', notification->appName()); subst.insert('s', notification->text()); subst.insert('w', QString::number(notification->widget()->topLevelWidget()->winId())); subst.insert('i', QString::number(notification->id())); QString execLine = KMacroExpander::expandMacrosShellQuote(command, subst); if (execLine.isEmpty()) { execLine = command; // fallback } KProcess proc; proc.setShellCommand(execLine.trimmed()); if (!proc.startDetached()) { qDebug() << "KNotify: Could not start process!"; } } finish(notification); } #include "notifybyexecute.moc" diff --git a/src/notifybyexecute.h b/src/notifybyexecute.h index 92781ef..ae362e3 100644 --- a/src/notifybyexecute.h +++ b/src/notifybyexecute.h @@ -1,40 +1,40 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef NOTIFYBYEXECUTE_H #define NOTIFYBYEXECUTE_H -#include "knotifyplugin.h" +#include "knotificationplugin.h" -class NotifyByExecute : public KNotifyPlugin +class NotifyByExecute : public KNotificationPlugin { Q_OBJECT public: NotifyByExecute(QObject *parent = 0); virtual ~NotifyByExecute(); virtual QString optionName() { return QStringLiteral("Execute"); } virtual void notify(KNotification *notification, KNotifyConfig *config); }; #endif diff --git a/src/notifybyktts.cpp b/src/notifybyktts.cpp index 71f9ae5..459df0e 100644 --- a/src/notifybyktts.cpp +++ b/src/notifybyktts.cpp @@ -1,103 +1,103 @@ /* Copyright (C) 2007 by Olivier Goffart Copyright (C) 2009 by Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "notifybyktts.h" #include #include #include #include #include #include #include -NotifyByKTTS::NotifyByKTTS(QObject *parent) : KNotifyPlugin(parent),m_kspeech(0), tryToStartKttsd( false ) +NotifyByKTTS::NotifyByKTTS(QObject *parent) : KNotificationPlugin(parent),m_kspeech(0), tryToStartKttsd( false ) { } NotifyByKTTS::~NotifyByKTTS() { } void NotifyByKTTS::setupKttsd() { m_kspeech = new org::kde::KSpeech("org.kde.kttsd", "/KSpeech", QDBusConnection::sessionBus()); m_kspeech->setParent(this); m_kspeech->setApplicationName("KNotify"); QDBusServiceWatcher *watcher = new QDBusServiceWatcher(this); watcher->setConnection(QDBusConnection::sessionBus()); watcher->setWatchMode(QDBusServiceWatcher::WatchForUnregistration); watcher->addWatchedService("org.kde.kttsd"); connect(watcher, SIGNAL(serviceUnregistered( const QString & ) ), this, SLOT( removeSpeech() )); } void NotifyByKTTS::notify( int id, KNotifyConfig * config ) { if( !m_kspeech) { if ( tryToStartKttsd ) //don't try to restart it all the time. return; // If KTTSD not running, start it. if (!QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kttsd")) { QString error; if (KToolInvocation::startServiceByDesktopName("kttsd", QStringList(), &error)) { KMessageBox::error(0, i18n( "Starting Jovie Text-to-Speech Service Failed"), error ); tryToStartKttsd = true; return; } } setupKttsd(); } QString say = config->readEntry( "KTTS" ); if (!say.isEmpty()) { QHash subst; subst.insert( 'e', config->eventid ); subst.insert( 'a', config->appname ); subst.insert( 's', config->text ); subst.insert( 'w', QString::number( (quintptr)config->winId )); subst.insert( 'i', QString::number( id )); subst.insert( 'm', config->text ); say = KMacroExpander::expandMacrosShellQuote( say, subst ); } if ( say.isEmpty() ) say = config->text; // fallback m_kspeech->setApplicationName(config->appname); m_kspeech->call(QDBus::NoBlock, "say", say, 0); finished(id); } void NotifyByKTTS::removeSpeech() { tryToStartKttsd = false; delete m_kspeech; m_kspeech = 0; } #include "notifybyktts.moc" diff --git a/src/notifybyktts.h b/src/notifybyktts.h index a05eebf..43756f7 100644 --- a/src/notifybyktts.h +++ b/src/notifybyktts.h @@ -1,53 +1,53 @@ /* Copyright (C) 2007 by Olivier Goffart Copyright (C) 2009 by Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef NOTIFYBYKTTS_H #define NOTIFYBYKTTS_H -#include "knotifyplugin.h" +#include "knotificationplugin.h" #include "kspeechinterface.h" -class NotifyByKTTS : public KNotifyPlugin +class NotifyByKTTS : public KNotificationPlugin { Q_OBJECT public: NotifyByKTTS(QObject *parent=0l); virtual ~NotifyByKTTS(); virtual QString optionName() { return "KTTS"; } virtual void notify(int id , KNotifyConfig *config); private slots: void removeSpeech(); private: void setupKttsd(); private: org::kde::KSpeech *m_kspeech; bool tryToStartKttsd; }; #endif diff --git a/src/notifybylogfile.cpp b/src/notifybylogfile.cpp index fa0c103..6a77217 100644 --- a/src/notifybylogfile.cpp +++ b/src/notifybylogfile.cpp @@ -1,76 +1,76 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "notifybylogfile.h" #include #include #include #include #include #include #include "knotifyconfig.h" #include "knotification.h" NotifyByLogfile::NotifyByLogfile(QObject *parent) - : KNotifyPlugin(parent) + : KNotificationPlugin(parent) { } NotifyByLogfile::~NotifyByLogfile() { } void NotifyByLogfile::notify(KNotification *notification, KNotifyConfig *config) { QString file = config->readEntry("Logfile"); if (file.isEmpty()) { finish(notification); return; } // open file in append mode QFile logFile(QUrl(file).path()); if (!logFile.open(QIODevice::WriteOnly | QIODevice::Append)) { finish(notification); return; } QString text = notification->text(); if (text.isEmpty()) { text = config->readEntry(QStringLiteral("Name")); } // append msg QTextStream strm(&logFile); strm << "- KNotify " << QDateTime::currentDateTime().toString() << ": "; strm << text << endl; // close file logFile.close(); finish(notification); } #include "notifybylogfile.moc" diff --git a/src/notifybylogfile.h b/src/notifybylogfile.h index 32a8ae5..6ea2850 100644 --- a/src/notifybylogfile.h +++ b/src/notifybylogfile.h @@ -1,43 +1,43 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef NOTIFYBYLOGFILE_H #define NOTIFYBYLOGFILE_H -#include "knotifyplugin.h" +#include "knotificationplugin.h" class KNotification; -class NotifyByLogfile : public KNotifyPlugin +class NotifyByLogfile : public KNotificationPlugin { Q_OBJECT public: NotifyByLogfile(QObject *parent = 0); virtual ~NotifyByLogfile(); virtual QString optionName() { return QStringLiteral("Logfile"); } virtual void notify(KNotification *notification, KNotifyConfig *config); }; #endif diff --git a/src/notifybypopup.cpp b/src/notifybypopup.cpp index f327a4e..66e593b 100644 --- a/src/notifybypopup.cpp +++ b/src/notifybypopup.cpp @@ -1,777 +1,777 @@ /* Copyright (C) 2005-2009 by Olivier Goffart Copyright (C) 2008 by Dmitry Suzdalev Copyright (C) 2014 by Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "notifybypopup.h" #include "imageconverter.h" #include "notifybypopupgrowl.h" #include "kpassivepopup.h" #include "knotifyconfig.h" #include "knotification.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const char dbusServiceName[] = "org.freedesktop.Notifications"; static const char dbusInterfaceName[] = "org.freedesktop.Notifications"; static const char dbusPath[] = "/org/freedesktop/Notifications"; class NotifyByPopupPrivate { public: NotifyByPopupPrivate(NotifyByPopup *parent) : q(parent) {} /** * @internal * Fills the KPassivePopup with data */ void fillPopup(KPassivePopup *popup, KNotification *notification, KNotifyConfig *config); /** * Make sure a popup is completely supported by the notification backend. * Changes the popup to be compatible if needed. * @param notification the notification data to check */ void ensurePopupCompatibility(KNotification *notification); /** * Removes HTML from a given string. Replaces line breaks with \n and * HTML entities by their 'normal forms'. * @param string the HTML to remove. * @return the cleaned string. */ QString stripHtml(const QString &text); /** * Sends notification to DBus "org.freedesktop.notifications" interface. * @param id knotify-sid identifier of notification * @param config notification data * @param update If true, will request the DBus service to update the notification with new data from \c notification * Otherwise will put new notification on screen * @return true for success or false if there was an error. */ bool sendNotificationToGalagoServer(KNotification *notification, KNotifyConfig *config, bool update = false); /** * Sends request to close Notification with id to DBus "org.freedesktop.notifications" interface * @param id knotify-side notification ID to close */ void closeGalagoNotification(KNotification *notification); /** * Find the caption and the icon name of the application */ void getAppCaptionAndIconName(KNotifyConfig *config, QString *appCaption, QString *iconName); /* * Query the dbus server for notification capabilities * If no DBus server is present, use fallback capabilities for KPassivePopup */ void queryPopupServerCapabilities(); // the y coordinate of the next position popup should appears int nextPosition; int animationTimer; /** * Specifies if DBus Notifications interface exists on session bus */ bool dbusServiceExists; /** * DBus notification daemon capabilities cache. * Do not use this variable. Use #popupServerCapabilities() instead. * @see popupServerCapabilities */ QStringList popupServerCapabilities; /** * In case we still don't know notification server capabilities, * we need to query those first. That's done in an async way * so we queue all notifications while waiting for the capabilities * to return, then process them from this queue */ QList > notificationQueue; /** * Whether the DBus notification daemon capability cache is up-to-date. */ bool dbusServiceCapCacheDirty; /** * Keeps the map of notifications done in KPassivePopup */ QMap passivePopups; /* * As we communicate with the notification server over dbus * we use only ids, this is for fast KNotifications lookup */ QHash galagoNotifications; NotifyByPopup * const q; /** * A class for resolving HTML entities in XML documents (used * during HTML stripping) */ class HtmlEntityResolver : public QXmlStreamEntityResolver { QString resolveUndeclaredEntity(const QString &name); }; }; //--------------------------------------------------------------------------------------- NotifyByPopup::NotifyByPopup(QObject *parent) - : KNotifyPlugin(parent), + : KNotificationPlugin(parent), d(new NotifyByPopupPrivate(this)) { d->animationTimer = 0; d->dbusServiceExists = false; d->dbusServiceCapCacheDirty = true; QRect screen = QApplication::desktop()->availableGeometry(); d->nextPosition = screen.top(); // check if service already exists on plugin instantiation QDBusConnectionInterface *interface = QDBusConnection::sessionBus().interface(); d->dbusServiceExists = interface && interface->isServiceRegistered(dbusServiceName); if (d->dbusServiceExists) { onServiceOwnerChanged(dbusServiceName, QString(), "_"); //connect signals } // to catch register/unregister events from service in runtime QDBusServiceWatcher *watcher = new QDBusServiceWatcher(this); watcher->setConnection(QDBusConnection::sessionBus()); watcher->setWatchMode(QDBusServiceWatcher::WatchForOwnerChange); watcher->addWatchedService(dbusServiceName); connect(watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)), SLOT(onServiceOwnerChanged(QString,QString,QString))); if (!d->dbusServiceExists) { bool startfdo = false; #ifdef Q_WS_WIN startfdo = true; #else if (qgetenv("KDE_FULL_SESSION").isEmpty()) { QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListActivatableNames"); // FIXME - this should be async QDBusReply reply = QDBusConnection::sessionBus().call(message); if (reply.isValid() && reply.value().contains(dbusServiceName)) { startfdo = true; // We need to set d->dbusServiceExists to true because dbus might be too slow // starting the service and the first call to NotifyByPopup::notify // might not have had the service up, by setting this to true we // guarantee it will still go through dbus and dbus will do the correct // thing and wait for the service to go up d->dbusServiceExists = true; } } #endif if (startfdo) { QDBusConnection::sessionBus().interface()->startService(dbusServiceName); } } } NotifyByPopup::~NotifyByPopup() { Q_FOREACH (KPassivePopup *p, d->passivePopups) { p->deleteLater(); } delete d; } void NotifyByPopup::notify(KNotification *notification, KNotifyConfig *notifyConfig) { if (d->passivePopups.contains(notification) || d->galagoNotifications.contains(notification->id())) { // notification is alrady on the screen, do nothing finish(notification); return; } // check if Notifications DBus service exists on bus, use it if it does if (d->dbusServiceExists) { if (d->dbusServiceCapCacheDirty) { // if we don't have the server capabilities yet, we need to query for them first; // as that is an async dbus operation, we enqueue the notification and process them // when we receive dbus reply with the server capabilities d->notificationQueue.append(qMakePair(notification, notifyConfig)); d->queryPopupServerCapabilities(); } else { if (!d->sendNotificationToGalagoServer(notification, notifyConfig)) { finish(notification); //an error ocurred. } } return; } // Persistent => 0 == infinite timeout // CloseOnTimeout => -1 == let the server decide int timeout = notification->flags() & KNotification::Persistent ? 0 : -1; // if Growl can display our popups, use that instead if (NotifyByPopupGrowl::canPopup()) { d->ensurePopupCompatibility(notification); QString appCaption, iconName; d->getAppCaptionAndIconName(notifyConfig, &appCaption, &iconName); //did the user override the icon name? if (!notification->iconName().isEmpty()) { iconName = notification->iconName(); } KIconLoader iconLoader(iconName); QPixmap appIcon = iconLoader.loadIcon(iconName, KIconLoader::Small); NotifyByPopupGrowl::popup(&appIcon, timeout, appCaption, notification->text()); // Finish immediately, because current NotifyByPopupGrowl can't callback finish(notification); delete notifyConfig; return; } // last fallback - display the popup using KPassivePopup KPassivePopup *pop = new KPassivePopup(notification->widget()); d->passivePopups.insert(notification, pop); d->fillPopup(pop, notification, notifyConfig); QRect screen = QApplication::desktop()->availableGeometry(); pop->setAutoDelete(true); connect(pop, SIGNAL(destroyed()), this, SLOT(onPassivePopupDestroyed())); pop->setTimeout(timeout); pop->adjustSize(); pop->show(QPoint(screen.left() + screen.width()/2 - pop->width()/2 , d->nextPosition)); d->nextPosition += pop->height(); } void NotifyByPopup::onPassivePopupDestroyed() { const QObject *destroyedPopup = sender(); if (!destroyedPopup) { return; } QMap::iterator it; for (it = d->passivePopups.begin(); it != d->passivePopups.end(); ++it) { QObject *popup = it.value(); if (popup && popup == destroyedPopup) { finish(it.key()); d->passivePopups.remove(it.key()); break; } } //relocate popup if (!d->animationTimer) { d->animationTimer = startTimer(10); } } void NotifyByPopup::timerEvent(QTimerEvent *event) { if (event->timerId() != d->animationTimer) { - return KNotifyPlugin::timerEvent(event); + return KNotificationPlugin::timerEvent(event); } bool cont = false; QRect screen = QApplication::desktop()->availableGeometry(); d->nextPosition = screen.top(); Q_FOREACH (KPassivePopup *popup, d->passivePopups) { int y = popup->pos().y(); if (y > d->nextPosition) { y = qMax(y - 5, d->nextPosition); d->nextPosition = y + popup->height(); cont = cont || y != d->nextPosition; popup->move(popup->pos().x(), y); } else { d->nextPosition += popup->height(); } } if (!cont) { killTimer(d->animationTimer); d->animationTimer = 0; } } void NotifyByPopup::onPassivePopupLinkClicked(const QString &link) { unsigned int id = link.section('/' , 0 , 0).toUInt(); unsigned int action = link.section('/' , 1 , 1).toUInt(); if (id == 0 || action == 0) { return; } emit actionInvoked(id, action); } void NotifyByPopup::close(KNotification *notification) { if (d->dbusServiceExists) { d->closeGalagoNotification(notification); } if (d->passivePopups.contains(notification)) { // this will call onPassivePopupDestroyed() // which will call finish() on the notification d->passivePopups[notification]->deleteLater(); } } void NotifyByPopup::update(KNotification *notification, KNotifyConfig *notifyConfig) { if (d->passivePopups.contains(notification)) { KPassivePopup *p = d->passivePopups[notification]; d->fillPopup(p, notification, notifyConfig); return; } // if Notifications DBus service exists on bus, // it'll be used instead if (d->dbusServiceExists) { d->sendNotificationToGalagoServer(notification, notifyConfig, true); return; } // otherwise, just display a new Growl notification if (NotifyByPopupGrowl::canPopup()) { notify(notification, notifyConfig); } } void NotifyByPopup::onServiceOwnerChanged(const QString &serviceName, const QString &oldOwner, const QString &newOwner) { // close all notifications we currently hold reference to Q_FOREACH (KNotification *n, d->galagoNotifications.values()) { finished(n); } Q_FOREACH (KNotification *n, d->passivePopups.keys()) { finished(n); } d->galagoNotifications.clear(); d->passivePopups.clear(); d->dbusServiceCapCacheDirty = true; d->popupServerCapabilities.clear(); d->notificationQueue.clear(); if (newOwner.isEmpty()) { d->dbusServiceExists = false; } else if (oldOwner.isEmpty()) { d->dbusServiceExists = true; // connect to action invocation signals bool connected = QDBusConnection::sessionBus().connect(QString(), // from any service dbusPath, dbusInterfaceName, "ActionInvoked", this, SLOT(onGalagoNotificationActionInvoked(uint,QString))); if (!connected) { qWarning() << "warning: failed to connect to ActionInvoked dbus signal"; } connected = QDBusConnection::sessionBus().connect(QString(), // from any service dbusPath, dbusInterfaceName, "NotificationClosed", this, SLOT(onGalagoNotificationClosed(uint,uint))); if (!connected) { qWarning() << "warning: failed to connect to NotificationClosed dbus signal"; } } } void NotifyByPopup::onGalagoNotificationActionInvoked(uint notificationId, const QString &actionKey) { KNotification *n = d->galagoNotifications[notificationId]; if (n == 0) { qWarning() << "Failed to find KNotification id for dbus_id" << notificationId << "- action not triggered"; return; } emit actionInvoked(n->id(), actionKey.toUInt()); // now close notification - similar to popup behaviour // (popups are hidden after link activation - see 'connects' of linkActivated signal above) d->closeGalagoNotification(n); } void NotifyByPopup::onGalagoNotificationClosed(uint dbus_id, uint reason) { Q_UNUSED(reason) KNotification *n = d->galagoNotifications[dbus_id]; if (n == 0) { qWarning() << "Failed to find KNotification for dbus_id" << dbus_id; return; } d->galagoNotifications.remove(dbus_id); finished(n); // The popup bubble is the only user facing part of a notification, // if the user closes the popup, it means he wants to get rid // of the notification completely, including playing sound etc // Therefore we close the KNotification completely after closing // the popup n->close(); } void NotifyByPopup::onGalagoServerReply(QDBusPendingCallWatcher *watcher) { KNotification *notification = watcher->property("notificationObject").value(); if (!notification) { qWarning() << "Invalid notification object passed in DBus reply watcher; notification will probably break"; return; } QDBusPendingReply reply = *watcher; d->galagoNotifications.insert(reply.argumentAt<0>(), notification); watcher->deleteLater(); } void NotifyByPopup::onGalagoServerCapabilitiesReceived(const QStringList &capabilities) { d->popupServerCapabilities = capabilities; d->dbusServiceCapCacheDirty = false; // re-run notify() on all enqueued notifications for (int i = 0; i < d->notificationQueue.size(); i++) { notify(d->notificationQueue.at(i).first, d->notificationQueue.at(i).second); } d->notificationQueue.clear(); } void NotifyByPopupPrivate::getAppCaptionAndIconName(KNotifyConfig *notifyConfig, QString *appCaption, QString *iconName) { KConfigGroup globalgroup(&(*notifyConfig->eventsfile), QString("Global")); *appCaption = globalgroup.readEntry("Name", globalgroup.readEntry("Comment", notifyConfig->appname)); KConfigGroup eventGroup(&(*notifyConfig->eventsfile), QString("Event/%1").arg(notifyConfig->eventid)); if (eventGroup.hasKey("IconName")) { *iconName = eventGroup.readEntry("IconName", notifyConfig->appname); } else { *iconName = globalgroup.readEntry("IconName", notifyConfig->appname); } } void NotifyByPopupPrivate::fillPopup(KPassivePopup *popup, KNotification *notification, KNotifyConfig *notifyConfig) { QString appCaption; QString iconName; getAppCaptionAndIconName(notifyConfig, &appCaption, &iconName); // If we're at this place, it means there's no D-Bus service for notifications // so we don't need to do D-Bus query for the capabilities. // If queryPopupServerCapabilities() finds no service, it sets the KPassivePopup // capabilities immediately, so we don't need to wait for callback as in the case // of galago notifications queryPopupServerCapabilities(); ensurePopupCompatibility(notification); KIconLoader iconLoader(iconName); QPixmap appIcon = iconLoader.loadIcon(iconName, KIconLoader::Small); QWidget *vb = popup->standardView(notification->title().isEmpty() ? appCaption : notification->title(), notification->pixmap().isNull() ? notification->text() : QString(), appIcon); if (!notification->pixmap().isNull()) { const QPixmap pix = notification->pixmap(); QHBoxLayout *hbox = new QHBoxLayout(vb); QLabel *pil = new QLabel(); pil->setPixmap(pix); pil->setScaledContents(true); if (pix.height() > 80 && pix.height() > pix.width()) { pil->setMaximumHeight(80); pil->setMaximumWidth(80 * pix.width() / pix.height()); } else if(pix.width() > 80 && pix.height() <= pix.width()) { pil->setMaximumWidth(80); pil->setMaximumHeight(80*pix.height()/pix.width()); } hbox->addWidget(pil); QVBoxLayout *vb2 = new QVBoxLayout(vb); QLabel *msg = new QLabel(notification->text()); msg->setAlignment(Qt::AlignLeft); vb2->addWidget(msg); hbox->addLayout(vb2); vb->layout()->addItem(hbox); } if (!notification->actions().isEmpty()) { QString linkCode = QString::fromLatin1("

"); int i = 0; Q_FOREACH (const QString &it, notification->actions()) { i++; linkCode += QString::fromLatin1(" %3").arg(QString::number(notification->id()), QString::number(i), it.toHtmlEscaped()); } linkCode += QString::fromLatin1("

"); QLabel *link = new QLabel(linkCode , vb ); link->setTextInteractionFlags(Qt::LinksAccessibleByMouse); link->setOpenExternalLinks(false); //link->setAlignment( AlignRight ); QObject::connect(link, SIGNAL(linkActivated(const QString &)), q, SLOT(onPassivePopupLinkClicked(const QString& ) ) ); QObject::connect(link, SIGNAL(linkActivated(const QString &)), popup, SLOT(hide())); } popup->setView( vb ); } bool NotifyByPopupPrivate::sendNotificationToGalagoServer(KNotification *notification, KNotifyConfig *notifyConfig_nocheck, bool update) { uint updateId = galagoNotifications.key(notification, 0); if (update) { if (updateId == 0) { // we have nothing to update; the notification we're trying to update // has been already closed return false; } } QDBusMessage dbusNotificationMessage = QDBusMessage::createMethodCall(dbusServiceName, dbusPath, dbusInterfaceName, "Notify"); QList args; QString appCaption; QString iconName; getAppCaptionAndIconName(notifyConfig_nocheck, &appCaption, &iconName); //did the user override the icon name? if (!notification->iconName().isEmpty()) { iconName = notification->iconName(); } // FIXME: rename this to something better reflecting what this is doing...maybe ensurePopupCompatibility(notification); args.append(appCaption); // app_name args.append(updateId); // notification to update args.append(iconName); // app_icon args.append(notification->title().isEmpty() ? appCaption : notification->title()); // summary args.append(notification->text()); // body // galago spec defines action list to be list like // (act_id1, action1, act_id2, action2, ...) // // assign id's to actions like it's done in fillPopup() method // (i.e. starting from 1) QStringList actionList; int actId = 0; Q_FOREACH (const QString &actionName, notification->actions()) { actId++; actionList.append(QString::number(actId)); actionList.append(actionName); } args.append(actionList); // actions QVariantMap hintsMap; // Add the application name to the hints. // According to fdo spec, the app_name is supposed to be the applicaton's "pretty name" // but in some places it's handy to know the application name itself if (!notification->appName().isEmpty()) { hintsMap["x-kde-appname"] = notification->appName(); } //FIXME - reenable/fix // let's see if we've got an image, and store the image in the hints map if (!notification->pixmap().isNull()) { QByteArray pixmapData; QBuffer buffer(&pixmapData); buffer.open(QIODevice::WriteOnly); notification->pixmap().save(&buffer, "PNG"); buffer.close(); hintsMap["image_data"] = ImageConverter::variantForImage(QImage::fromData(pixmapData)); } args.append(hintsMap); // hints // Persistent => 0 == infinite timeout // CloseOnTimeout => -1 == let the server decide int timeout = notification->flags() & KNotification::Persistent ? 0 : -1; args.append(timeout); // expire timout dbusNotificationMessage.setArguments(args); QDBusPendingCall notificationCall = QDBusConnection::sessionBus().asyncCall(dbusNotificationMessage, -1); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(notificationCall, q); watcher->setProperty("notificationObject", QVariant::fromValue(notification)); QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), q, SLOT(onGalagoServerReply(QDBusPendingCallWatcher*))); return true; } void NotifyByPopupPrivate::closeGalagoNotification(KNotification *notification) { uint galagoId = galagoNotifications.key(notification, 0); if (galagoId == 0) { qDebug() << "not found dbus id to close" << notification->id(); return; } QDBusMessage m = QDBusMessage::createMethodCall(dbusServiceName, dbusPath, dbusInterfaceName, "CloseNotification"); QList args; args.append(galagoId); m.setArguments(args); // send(..) does not block bool queued = QDBusConnection::sessionBus().send(m); if (!queued) { qWarning() << "Failed to queue dbus message for closing a notification"; } } void NotifyByPopupPrivate::queryPopupServerCapabilities() { if (!dbusServiceExists) { if (NotifyByPopupGrowl::canPopup()) { popupServerCapabilities = NotifyByPopupGrowl::capabilities(); } else { // Return capabilities of the KPassivePopup implementation popupServerCapabilities = QStringList() << "actions" << "body" << "body-hyperlinks" << "body-markup" << "icon-static"; } } if (dbusServiceCapCacheDirty) { QDBusMessage m = QDBusMessage::createMethodCall(dbusServiceName, dbusPath, dbusInterfaceName, "GetCapabilities"); QDBusConnection::sessionBus().callWithCallback(m, q, SLOT(onGalagoServerCapabilitiesReceived(QStringList)), 0, -1); } } void NotifyByPopupPrivate::ensurePopupCompatibility(KNotification *notification) { if (!popupServerCapabilities.contains("actions")) { notification->setActions(QStringList()); } if (!popupServerCapabilities.contains("body-markup")) { if (notification->title().startsWith("")) { notification->setTitle(stripHtml(notification->title())); } if (notification->text().startsWith("")) { notification->setText(stripHtml(notification->text())); } } } QString NotifyByPopupPrivate::stripHtml(const QString &text) { QXmlStreamReader r("" + text + ""); HtmlEntityResolver resolver; r.setEntityResolver(&resolver); QString result; while (!r.atEnd()) { r.readNext(); if (r.tokenType() == QXmlStreamReader::Characters) { result.append(r.text()); } else if (r.tokenType() == QXmlStreamReader::StartElement && r.name() == "br") { result.append("\n"); } } if (r.hasError()) { // XML error in the given text, just return the original string qWarning() << "Notification to send to backend which does " "not support HTML, contains invalid XML:" << r.errorString() << "line" << r.lineNumber() << "col" << r.columnNumber(); return text; } return result; } QString NotifyByPopupPrivate::HtmlEntityResolver::resolveUndeclaredEntity(const QString &name) { QString result = QXmlStreamEntityResolver::resolveUndeclaredEntity(name); if (!result.isEmpty()) { return result; } QChar ent = KCharsets::fromEntity('&' + name); if (ent.isNull()) { qWarning() << "Notification to send to backend which does " "not support HTML, contains invalid entity: " << name; ent = ' '; } return QString(ent); } #include "notifybypopup.moc" diff --git a/src/notifybypopup.h b/src/notifybypopup.h index 36aac1d..a605a77 100644 --- a/src/notifybypopup.h +++ b/src/notifybypopup.h @@ -1,69 +1,69 @@ /* Copyright (C) 2005-2006 by Olivier Goffart Copyright (C) 2008 by Dmitry Suzdalev Copyright (C) 2014 by Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef NOTIFYBYPOPUP_H #define NOTIFYBYPOPUP_H -#include "knotifyplugin.h" +#include "knotificationplugin.h" #include class KNotification; class KPassivePopup; class QDBusPendingCallWatcher; class NotifyByPopupPrivate; -class NotifyByPopup : public KNotifyPlugin +class NotifyByPopup : public KNotificationPlugin { Q_OBJECT public: NotifyByPopup(QObject *parent = 0l); virtual ~NotifyByPopup(); virtual QString optionName() { return "Popup"; } virtual void notify(KNotification *notification, KNotifyConfig *notifyConfig); virtual void close(KNotification *notification); virtual void update(KNotification *notification, KNotifyConfig *config); protected: void timerEvent(QTimerEvent *event); private Q_SLOTS: void onPassivePopupDestroyed(); void onPassivePopupLinkClicked(const QString &link); // slot to catch appearance or dissapearance of Notifications DBus service void onServiceOwnerChanged(const QString &, const QString &, const QString &); // slot which gets called when DBus signals that some notification action was invoked void onGalagoNotificationActionInvoked(uint notificationId, const QString &actionKey); // slot which gets called when DBus signals that some notification was closed void onGalagoNotificationClosed(uint, uint); void onGalagoServerReply(QDBusPendingCallWatcher *callWatcher); void onGalagoServerCapabilitiesReceived(const QStringList &capabilities); private: NotifyByPopupPrivate * const d; }; #endif diff --git a/src/notifybysound.cpp b/src/notifybysound.cpp index f005b99..09a80dd 100644 --- a/src/notifybysound.cpp +++ b/src/notifybysound.cpp @@ -1,326 +1,326 @@ /* Copyright (c) 1997 Christian Esken (esken@kde.org) 2000 Charles Samuels (charles@kde.org) 2000 Stefan Schimanski (1Stein@gmx.de) 2000 Matthias Ettrich (ettrich@kde.org) 2000 Waldo Bastian 2000-2003 Carsten Pfeiffer 2005 Allan Sandfeld Jensen 2005-2006 by Olivier Goffart 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 2, 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "notifybysound.h" // QT headers #include #include #include #include #include #include #include // KDE headers #include #include #include #include #include #include #include #include #include // Phonon headers #include #include #include struct Player { Player() : media(new Phonon::MediaObject), output(new Phonon::AudioOutput(Phonon::NotificationCategory)) { Phonon::createPath(media, output); } inline void play(const QString &file) { media->setCurrentSource(file); media->enqueue(Phonon::MediaSource()); media->play(); } inline void stop() { media->stop(); } inline void setVolume(float volume) { output->setVolume(volume); } ~Player() { output->deleteLater(); media->deleteLater(); } Phonon::MediaObject *const media; Phonon::AudioOutput *const output; }; class PlayerPool { public: PlayerPool() : m_idlePlayer(0), m_volume(1.0) {} Player *getPlayer(); void returnPlayer(Player *); void clear(); void setVolume(float volume); private: Player *m_idlePlayer; QList m_playersInUse; float m_volume; }; Player *PlayerPool::getPlayer() { Player *p = 0; if (!m_idlePlayer) { p = new Player; } else { p = m_idlePlayer; m_idlePlayer = 0; } p->setVolume(m_volume); m_playersInUse << p; return p; } void PlayerPool::returnPlayer(Player *p) { m_playersInUse.removeAll(p); if (m_idlePlayer) { delete p; } else { m_idlePlayer = p; } } void PlayerPool::clear() { delete m_idlePlayer; m_idlePlayer = 0; } void PlayerPool::setVolume(float v) { m_volume = v; foreach (Player *p, m_playersInUse) { p->setVolume(v); } } class NotifyBySound::Private { public: enum { NoSound, UsePhonon, ExternalPlayer } playerMode; QString externalPlayer; QHash processes; QHash playerObjects; QSignalMapper *signalmapper; PlayerPool playerPool; QBasicTimer poolTimer; QQueue closeQueue; int volume; }; -NotifyBySound::NotifyBySound(QObject *parent) : KNotifyPlugin(parent),d(new Private) +NotifyBySound::NotifyBySound(QObject *parent) : KNotificationPlugin(parent),d(new Private) { d->signalmapper = new QSignalMapper(this); connect(d->signalmapper, SIGNAL(mapped(int)), this, SLOT(slotSoundFinished(int))); loadConfig(); } NotifyBySound::~NotifyBySound() { delete d; } void NotifyBySound::loadConfig() { // load external player settings KSharedConfig::Ptr kc = KSharedConfig::openConfig(); KConfigGroup cg(kc, "Sounds"); d->playerMode = Private::UsePhonon; if(cg.readEntry( "Use external player", false )) { d->playerMode = Private::ExternalPlayer; d->externalPlayer = cg.readPathEntry("External player", QString()); // try to locate a suitable player if none is configured if ( d->externalPlayer.isEmpty() ) { QStringList players; players << "wavplay" << "aplay" << "auplay" << "artsplay" << "akodeplay"; QStringList::const_iterator it = players.constBegin(); while ( d->externalPlayer.isEmpty() && it != players.constEnd() ) { d->externalPlayer = KStandardDirs::findExe( *it ); ++it; } } } else if(cg.readEntry( "No sound" , false )) { d->playerMode = Private::NoSound; } // load default volume setVolume( cg.readEntry( "Volume", 100 ) ); } void NotifyBySound::notify( int eventId, KNotifyConfig * config ) { if(d->playerMode == Private::NoSound) { finish( eventId ); return; } if(d->playerObjects.contains(eventId) || d->processes.contains(eventId) ) { //a sound is already playing for this notification, we don't support playing two sounds. finish( eventId ); return; } KUrl soundFileURL = config->readEntry( "Sound" , true ); QString soundFile = soundFileURL.toLocalFile(); if (soundFile.isEmpty()) { finish( eventId ); return; } // get file name if ( KUrl::isRelativeUrl(soundFile) ) { QString search = QString("%1/sounds/%2").arg(config->appname).arg(soundFile); search = KGlobal::mainComponent().dirs()->findResource("data", search); if ( search.isEmpty() ) soundFile = KStandardDirs::locate( "sound", soundFile ); else soundFile = search; } if ( soundFile.isEmpty() ) { finish( eventId ); return; } kDebug() << " going to play " << soundFile; d->poolTimer.stop(); if(d->playerMode == Private::UsePhonon) { Player *player = d->playerPool.getPlayer(); connect(player->media, SIGNAL(finished()), d->signalmapper, SLOT(map())); d->signalmapper->setMapping(player->media, eventId); player->play(soundFile); d->playerObjects.insert(eventId, player); } else if (d->playerMode == Private::ExternalPlayer && !d->externalPlayer.isEmpty()) { // use an external player to play the sound KProcess *proc = new KProcess( this ); connect( proc, SIGNAL(finished(int, QProcess::ExitStatus)), d->signalmapper, SLOT(map()) ); d->signalmapper->setMapping( proc , eventId ); (*proc) << d->externalPlayer << soundFile; proc->start(); } } void NotifyBySound::setVolume( int volume ) { if ( volume<0 ) volume=0; if ( volume>=100 ) volume=100; d->volume = volume; d->playerPool.setVolume(d->volume / 100.0); } void NotifyBySound::timerEvent(QTimerEvent *e) { if (e->timerId() == d->poolTimer.timerId()) { d->poolTimer.stop(); d->playerPool.clear(); return; } - KNotifyPlugin::timerEvent(e); + KNotificationPlugin::timerEvent(e); } void NotifyBySound::slotSoundFinished(int id) { kDebug() << id; if(d->playerObjects.contains(id)) { Player *player=d->playerObjects.take(id); disconnect(player->media, SIGNAL(finished()), d->signalmapper, SLOT(map())); d->playerPool.returnPlayer(player); //d->poolTimer.start(1000, this); } if(d->processes.contains(id)) { d->processes[id]->deleteLater(); d->processes.remove(id); } finish(id); } void NotifyBySound::close(int id) { // close in 1 min - ugly workaround for sounds getting cut off because the close call in kdelibs // is hardcoded to 6 seconds d->closeQueue.enqueue(id); QTimer::singleShot(60000, this, SLOT(closeNow())); } void NotifyBySound::closeNow() { const int id = d->closeQueue.dequeue(); if(d->playerObjects.contains(id)) { Player *p = d->playerObjects.take(id); p->stop(); d->playerPool.returnPlayer(p); //d->poolTimer.start(1000, this); } if(d->processes.contains(id)) { d->processes[id]->kill(); d->processes[id]->deleteLater(); d->processes.remove(id); } } #include "notifybysound.moc" // vim: ts=4 noet diff --git a/src/notifybysound.h b/src/notifybysound.h index 44f6463..1efa620 100644 --- a/src/notifybysound.h +++ b/src/notifybysound.h @@ -1,55 +1,55 @@ /* Copyright (C) 2005-2006 by Olivier Goffart 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 2, 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef NOTIFYBYSOUND_H #define NOTIFYBYSOUND_H -#include "knotifyplugin.h" +#include "knotificationplugin.h" -class NotifyBySound : public KNotifyPlugin +class NotifyBySound : public KNotificationPlugin { Q_OBJECT public: NotifyBySound(QObject *parent=0l); virtual ~NotifyBySound(); virtual QString optionName() { return "Sound"; } virtual void notify(int id , KNotifyConfig *config); virtual void close(int id); private: class Private; Private* const d; void loadConfig(); public: void setVolume( int v ); protected: void timerEvent(QTimerEvent *); private Q_SLOTS: void slotSoundFinished(int id); void closeNow(); }; #endif diff --git a/src/notifybytaskbar.cpp b/src/notifybytaskbar.cpp index 173bbb8..ef51dee 100644 --- a/src/notifybytaskbar.cpp +++ b/src/notifybytaskbar.cpp @@ -1,53 +1,53 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "notifybytaskbar.h" #include "knotifyconfig.h" #include "knotification.h" #include #include #include NotifyByTaskbar::NotifyByTaskbar(QObject *parent) - : KNotifyPlugin(parent) + : KNotificationPlugin(parent) { } NotifyByTaskbar::~NotifyByTaskbar() { } void NotifyByTaskbar::notify(KNotification *notification, KNotifyConfig *config) { qDebug() << notification->id() << notification->widget()->topLevelWidget()->winId(); WId win = notification->widget()->topLevelWidget()->winId(); if (win != 0) { KWindowSystem::demandAttention(win); } finish(notification); } #include "notifybytaskbar.moc" diff --git a/src/notifybytaskbar.h b/src/notifybytaskbar.h index 83d46ce..0908787 100644 --- a/src/notifybytaskbar.h +++ b/src/notifybytaskbar.h @@ -1,40 +1,40 @@ /* Copyright (C) 2005-2006 by Olivier Goffart This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef NOTIFYBYTASKBAR_H #define NOTIFYBYTASKBAR_H -#include "knotifyplugin.h" +#include "knotificationplugin.h" -class NotifyByTaskbar : public KNotifyPlugin +class NotifyByTaskbar : public KNotificationPlugin { Q_OBJECT public: NotifyByTaskbar(QObject *parent = 0); virtual ~NotifyByTaskbar(); virtual QString optionName() { return QStringLiteral("Taskbar"); } virtual void notify(KNotification *notification, KNotifyConfig *config); }; #endif