./0000755000004100000410000000000013035734364011253 5ustar www-datawww-data./CMakeLists.txt0000644000004100000410000000246313035734364014020 0ustar www-datawww-dataproject(sni-qt) cmake_minimum_required(VERSION 2.8.0) # Versions set(sni_qt_VERSION_MAJOR 0) set(sni_qt_VERSION_MINOR 2) set(sni_qt_VERSION_PATCH 6) set(sni_qt_VERSION ${sni_qt_VERSION_MAJOR}.${sni_qt_VERSION_MINOR}.${sni_qt_VERSION_PATCH}) # Packaging set(ARCHIVE_NAME sni-qt-${sni_qt_VERSION}) add_custom_target(dist COMMAND bzr export --root=${ARCHIVE_NAME} ${CMAKE_BINARY_DIR}/${ARCHIVE_NAME}.tar.bz2 WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) add_custom_target(distcheck COMMAND cd ${CMAKE_BINARY_DIR} && rm -rf ${ARCHIVE_NAME} && tar xf ${ARCHIVE_NAME}.tar.bz2 && mkdir ${ARCHIVE_NAME}/build && cd ${ARCHIVE_NAME}/build && cmake -DCMAKE_INSTALL_PREFIX=../install .. && make && make check && make install ) add_dependencies(distcheck dist) # Dependencies find_package(PkgConfig REQUIRED) find_package(Qt4 REQUIRED) pkg_check_modules(DBUSMENUQT REQUIRED dbusmenu-qt) # Build flags set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Woverloaded-virtual -Wall -std=c++0x") # Build with all symbols hidden. The symbols declared by the Q_EXPORT_PLUGIN2 # macro are explicitly marked as visible, so the plugin can be loaded. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") # Source add_subdirectory(src) add_subdirectory(tests/auto) add_subdirectory(tests/manual) ./NEWS0000644000004100000410000000345613035734364011762 0ustar www-datawww-data# 0.2.6 - 2011.10.15 - Abort initialization if temp dir for iconcache cannot be created (bug #874447). - Fix animated icons causing unity-panel-service to eat all CPU (bug #865601). # 0.2.5 - 2011.09.28 - Prefix log output with pid of application. - Use a placeholder menu if there is none defined yet (Fix half of bug #860395). # 0.2.4 - 2011.09.26 - Make sure GTK notices icon updates (bug #812884). - Prevent applications from stealing icons from each others (bug #850139). - Turn debug into a runtime option. # 0.2.3 - 2011.08.04 - Log message when an "Activate" entry is added. - Load Qt translations ourself for the "Activate" entry. - Make sure we fallback to the English version of "Activate". - Move the config file from canonical/sni-qt.conf to sni-qt.conf. - Revert namespace'ification. # 0.2.2 - 2011.08.03 - Add the ability to show an Activate entry to the menu if the app does not provide it. - Survive a restart of the StatusNotifierWatcher process. - Build with -fvisibility=hidden and move all classes into a SniQt namespace to reduce risks of symbol clashes. - Rename _qt_sni_category to _sni_qt_category. - Touch the icon theme dir, so that GTK looks into it and find new icons. # 0.2.1 - 2011.08.02 - Add build-time option to enable debug output - Document the _qt_sni_property hack # 0.2.0 - 2011.07.07 - Added a triming feature to the icon cache to avoid flooding tmp dir - Added support for scroll events - Added manual tests, with a test program based on Qt systray example # 0.1.5 - 2011.07.01 - Add LGPL license and Nokia LGPL exception. # 0.1.4 - 2011.06.27 - Change license to LGPL 3 - Add suppport for notifications # 0.1.3 - 2011.06.09 - Change license to GPL 3 # 0.1.2 - 2011.06.09 - Fix copyright headers # 0.1.1 - 2011.06.09 - Change license to LGPL 2.1 # 0.1.0 - 2011.06.09 - First release ./LGPL_EXCEPTION.txt0000644000004100000410000000224313035734364014171 0ustar www-datawww-dataNokia Qt LGPL Exception version 1.1 As an additional permission to the GNU Lesser General Public License version 2.1, the object code form of a "work that uses the Library" may incorporate material from a header file that is part of the Library. You may distribute such object code under terms of your choice, provided that: (i) the header files of the Library have not been modified; and (ii) the incorporated material is limited to numerical parameters, data structure layouts, accessors, macros, inline functions and templates; and (iii) you comply with the terms of Section 6 of the GNU Lesser General Public License version 2.1. Moreover, you may apply this exception to a modified version of the Library, provided that such modification does not involve copying material from the Library into the modified Library's header files unless such material is limited to (i) numerical parameters; (ii) data structure layouts; (iii) accessors; and (iv) small macros, templates and inline functions of five lines or less in length. Furthermore, you are not required to apply this additional permission to a modified version of the Library. ./README0000644000004100000410000000467213035734364012144 0ustar www-datawww-data# Summary This plugin makes Qt applications use the StatusNotifierItem (SNI) protocol for their system tray icons. It does so by turning system tray icons created with the QSystemTrayIcon class into StatusNotifierItems. This plugin only works when used together with the "qsystemtrayicon-plugin-system-4.7" Qt branch. This branch is available from this repository: http://gitorious.org/~agateau/qt/agateau-qt. For convenience, the patch for Qt 4.7.4 is available in the patches/ dir. # SNI category support QSystemTrayIcon has no concept of categories, so sni-qt will create SNI in the ApplicationStatus category by default. Application developers can override this by setting the "_sni_qt_category" property on their QSystemTrayIcon instance. Valid values for the properties are: - "ApplicationStatus" (the default) - "Communications" - "SystemServices" - "Hardware" So for example to create a "Hardware" SNI, one would write: QSystemTrayIcon* icon = new QSystemTrayIcon(); ... icon->setProperty("_sni_qt_category", "Hardware"); ... # QSystemTrayIcon::Trigger support When sni-qt receives the StatusNotifierItem::Activate() call, it simulates a left-click on the QSystemTrayIcon and emits QSystemTrayIcon::activated(QSystemTrayIcon::Trigger) Some implementations of the SNI protocol call StatusNotifierItem::Activate() on left click and show the context menu on right click. KDE behaves like this. Other implementations (Unity for example), only supports the context menu. This means the action which is normally triggered by left-clicking the icon must also be available in the context menu, otherwise it is not possible for the user to trigger it. In case an application does not provide an entry in its context menu to trigger the same action as left-clicking on the icon, you can tell sni-qt to add an "Activate" action at the top of the menu. This is configured in a file named 'sni-qt.conf'. sni-qt will look for it in '$HOME/.config' and '/etc/xdg'. This file should look like this: [need-activate-action] foo=1 bar=1 Where 'foo' and 'bar' are the binary names of the applications which needs an "Activate" action. Setting the value to '0' will disable the action again (so you can override the system-wide file) # Debug In the configuration file, add: [general] debug=1 To activate debug output to stderr. # Author Canonical DX Team Maintainer: Renato Filho Former maintainer: Aurélien Gâteau ./HEADER0000644000004100000410000000134113035734364012125 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ ./patches/0000755000004100000410000000000013035734364012702 5ustar www-datawww-data./patches/qsystemtrayicon-plugin-system-4.7.4.diff0000644000004100000410000014050013035734364022300 0ustar www-datawww-dataIntroduce a plugin system for QSystemTrayIcon. Designed to be used with sni-qt (https://launchpad.net/sni-qt) diff --git a/examples/desktop/systray/window.cpp b/examples/desktop/systray/window.cpp index 4091358..50c4ca6 100644 --- a/examples/desktop/systray/window.cpp +++ b/examples/desktop/systray/window.cpp @@ -158,15 +158,23 @@ void Window::createIconGroupBox() iconComboBox->addItem(QIcon(":/images/bad.svg"), tr("Bad")); iconComboBox->addItem(QIcon(":/images/heart.svg"), tr("Heart")); iconComboBox->addItem(QIcon(":/images/trash.svg"), tr("Trash")); + iconComboBox->addItem(QIcon::fromTheme("system-file-manager"), tr("File Manager")); showIconCheckBox = new QCheckBox(tr("Show icon")); showIconCheckBox->setChecked(true); +#if defined(Q_WS_X11) + jitToolTipCheckBox = new QCheckBox(tr("Just In Time Tooltip")); +#endif + QHBoxLayout *iconLayout = new QHBoxLayout; iconLayout->addWidget(iconLabel); iconLayout->addWidget(iconComboBox); iconLayout->addStretch(); iconLayout->addWidget(showIconCheckBox); +#if defined(Q_WS_X11) + iconLayout->addWidget(jitToolTipCheckBox); +#endif iconGroupBox->setLayout(iconLayout); } @@ -254,5 +262,37 @@ void Window::createTrayIcon() trayIconMenu->addAction(quitAction); trayIcon = new QSystemTrayIcon(this); + QByteArray category = qgetenv("SNI_CATEGORY"); + if (!category.isEmpty()) { + trayIcon->setProperty("_qt_sni_category", QString::fromLocal8Bit(category)); + } trayIcon->setContextMenu(trayIconMenu); + +#if defined(Q_WS_X11) + trayIcon->installEventFilter(this); +#endif +} + +#if defined(Q_WS_X11) +bool Window::eventFilter(QObject *, QEvent *event) +{ + switch(event->type()) { + case QEvent::ToolTip: + if (jitToolTipCheckBox->isChecked()) { + QString timeString = QTime::currentTime().toString(); + trayIcon->setToolTip(tr("Current Time: %1").arg(timeString)); + } + break; + case QEvent::Wheel: { + QWheelEvent *wheelEvent = static_cast(event); + int delta = wheelEvent->delta() > 0 ? 1 : -1; + int index = (iconComboBox->currentIndex() + delta) % iconComboBox->count(); + iconComboBox->setCurrentIndex(index); + break; + } + default: + break; + } + return false; } +#endif diff --git a/examples/desktop/systray/window.h b/examples/desktop/systray/window.h index 537a8a2..374a623 100644 --- a/examples/desktop/systray/window.h +++ b/examples/desktop/systray/window.h @@ -69,6 +69,9 @@ public: protected: void closeEvent(QCloseEvent *event); +#if defined(Q_WS_X11) + bool eventFilter(QObject *object, QEvent *event); +#endif private slots: void setIcon(int index); @@ -86,6 +89,9 @@ private: QLabel *iconLabel; QComboBox *iconComboBox; QCheckBox *showIconCheckBox; +#if defined(Q_WS_X11) + QCheckBox *jitToolTipCheckBox; +#endif QGroupBox *messageGroupBox; QLabel *typeLabel; diff --git a/src/gui/util/qabstractsystemtrayiconsys.cpp b/src/gui/util/qabstractsystemtrayiconsys.cpp new file mode 100644 index 0000000..0c4f7ae --- /dev/null +++ b/src/gui/util/qabstractsystemtrayiconsys.cpp @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#ifndef QT_NO_SYSTEMTRAYICON + +#include "qabstractsystemtrayiconsys_p.h" + + +QSystemTrayIconSysFactoryInterface::QSystemTrayIconSysFactoryInterface() +{ +} + +///////////////////////////////////////////////// +QAbstractSystemTrayIconSys::QAbstractSystemTrayIconSys(QSystemTrayIcon *icon) +: trayIcon(icon) +{ +} + +QAbstractSystemTrayIconSys::~QAbstractSystemTrayIconSys() +{ +} + +void QAbstractSystemTrayIconSys::sendActivated(QSystemTrayIcon::ActivationReason reason) +{ + qtsystray_sendActivated(trayIcon, reason); +} + +#endif diff --git a/src/gui/util/qabstractsystemtrayiconsys_p.h b/src/gui/util/qabstractsystemtrayiconsys_p.h new file mode 100644 index 0000000..f120bd4 --- /dev/null +++ b/src/gui/util/qabstractsystemtrayiconsys_p.h @@ -0,0 +1,106 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QABSTRACTSYSTEMTRAYICONSYS_P_H +#define QABSTRACTSYSTEMTRAYICONSYS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of a number of Qt sources files. This header file may change from +// version to version without notice, or even be removed. +// +// We mean it. +// + +#ifndef QT_NO_SYSTEMTRAYICON + +#include +#include + +class QAbstractSystemTrayIconSys; + +class Q_GUI_EXPORT QSystemTrayIconSysFactoryInterface : public QObject, public QFactoryInterface +{ + Q_OBJECT +public: + QSystemTrayIconSysFactoryInterface(); + virtual QAbstractSystemTrayIconSys * create(QSystemTrayIcon *) = 0; + virtual bool isAvailable() const = 0; + + // \reimp + virtual QStringList keys() const { return QStringList() << QLatin1String("default"); } + +Q_SIGNALS: + void availableChanged(bool); +}; + +#define QSystemTrayIconSysFactoryInterface_iid "com.nokia.qt.QSystemTrayIconSysFactoryInterface" +Q_DECLARE_INTERFACE(QSystemTrayIconSysFactoryInterface, QSystemTrayIconSysFactoryInterface_iid) + +class QRect; + +class Q_GUI_EXPORT QAbstractSystemTrayIconSys +{ +public: + QAbstractSystemTrayIconSys(QSystemTrayIcon *icon); + virtual ~QAbstractSystemTrayIconSys(); + + virtual QRect geometry() const = 0; + virtual void updateVisibility() = 0; + virtual void updateIcon() = 0; + virtual void updateToolTip() = 0; + virtual void updateMenu() = 0; + virtual void showMessage(const QString &title, const QString &message, + QSystemTrayIcon::MessageIcon icon, int msecs) = 0; + + void sendActivated(QSystemTrayIcon::ActivationReason); + +protected: + QSystemTrayIcon *trayIcon; +}; + +#endif // QT_NO_SYSTEMTRAYICON + +#endif // QABSTRACTSYSTEMTRAYICONSYS_P_H + diff --git a/src/gui/util/qsystemtrayicon.cpp b/src/gui/util/qsystemtrayicon.cpp index 28d4932..96d68fc 100644 --- a/src/gui/util/qsystemtrayicon.cpp +++ b/src/gui/util/qsystemtrayicon.cpp @@ -287,12 +287,6 @@ bool QSystemTrayIcon::isVisible() const */ bool QSystemTrayIcon::event(QEvent *e) { -#if defined(Q_WS_X11) - if (e->type() == QEvent::ToolTip) { - Q_D(QSystemTrayIcon); - return d->sys->deliverToolTipEvent(e); - } -#endif return QObject::event(e); } diff --git a/src/gui/util/qsystemtrayicon_p.h b/src/gui/util/qsystemtrayicon_p.h index 14495ee..2596658 100644 --- a/src/gui/util/qsystemtrayicon_p.h +++ b/src/gui/util/qsystemtrayicon_p.h @@ -62,10 +62,17 @@ #include "QtGui/qpixmap.h" #include "QtCore/qstring.h" #include "QtCore/qpointer.h" +#if defined(Q_WS_X11) +#include "QtCore/qset.h" +#endif QT_BEGIN_NAMESPACE +#if defined(Q_WS_X11) +class QAbstractSystemTrayIconSys; +#else class QSystemTrayIconSys; +#endif class QToolButton; class QLabel; @@ -75,6 +82,9 @@ class QSystemTrayIconPrivate : public QObjectPrivate public: QSystemTrayIconPrivate() : sys(0), visible(false) { } + #if defined(Q_WS_X11) + ~QSystemTrayIconPrivate(); + #endif void install_sys(); void remove_sys(); @@ -90,7 +100,11 @@ public: QPointer menu; QIcon icon; QString toolTip; + #if defined(Q_WS_X11) + QAbstractSystemTrayIconSys *sys; + #else QSystemTrayIconSys *sys; + #endif bool visible; }; @@ -123,60 +137,37 @@ private: }; #if defined(Q_WS_X11) -QT_BEGIN_INCLUDE_NAMESPACE -#include -#include -#include -#include -QT_END_INCLUDE_NAMESPACE - -class QSystemTrayIconSys : public QWidget +class QSystemTrayIconSysFactoryInterface; + +/** + * This class acts as a composite QSystemTrayIconSysFactory: It can create + * instances of QAbstractSystemTrayIconSys* using either a plugin or the + * builtin factory and will cause QSystemTrayIconPrivate to recreate their + * 'sys' instances if the plugin availability changes. + */ +class QSystemTrayIconSysFactory : public QObject { - friend class QSystemTrayIconPrivate; - + Q_OBJECT public: - QSystemTrayIconSys(QSystemTrayIcon *q); - ~QSystemTrayIconSys(); - enum { - SYSTEM_TRAY_REQUEST_DOCK = 0, - SYSTEM_TRAY_BEGIN_MESSAGE = 1, - SYSTEM_TRAY_CANCEL_MESSAGE =2 - }; - - void addToTray(); - void updateIcon(); - XVisualInfo* getSysTrayVisualInfo(); - - // QObject::event is public but QWidget's ::event() re-implementation - // is protected ;( - inline bool deliverToolTipEvent(QEvent *e) - { return QWidget::event(e); } - - static Window sysTrayWindow; - static QList trayIcons; - static QCoreApplication::EventFilter oldEventFilter; - static bool sysTrayTracker(void *message, long *result); - static Window locateSystemTray(); - static Atom sysTraySelection; - static XVisualInfo sysTrayVisual; + QSystemTrayIconSysFactory(); + void registerSystemTrayIconPrivate(QSystemTrayIconPrivate *iconPrivate); + void unregisterSystemTrayIconPrivate(QSystemTrayIconPrivate *iconPrivate); -protected: - void paintEvent(QPaintEvent *pe); - void resizeEvent(QResizeEvent *re); - bool x11Event(XEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseDoubleClickEvent(QMouseEvent *event); -#ifndef QT_NO_WHEELEVENT - void wheelEvent(QWheelEvent *event); -#endif - bool event(QEvent *e); + QAbstractSystemTrayIconSys *create(QSystemTrayIcon *) const; + + bool isAvailable() const; + +private Q_SLOTS: + void refreshTrayIconPrivates(); private: - QPixmap background; - QSystemTrayIcon *q; - Colormap colormap; + QSystemTrayIconSysFactoryInterface *factory() const; + void loadPluginFactory(); + + QSystemTrayIconSysFactoryInterface *pluginFactory; + QSet trayIconPrivates; }; -#endif // Q_WS_X11 +#endif QT_END_NAMESPACE diff --git a/src/gui/util/qsystemtrayicon_x11.cpp b/src/gui/util/qsystemtrayicon_x11.cpp index 86c2749..2047dd2 100644 --- a/src/gui/util/qsystemtrayicon_x11.cpp +++ b/src/gui/util/qsystemtrayicon_x11.cpp @@ -38,311 +38,122 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ +#ifndef QT_NO_SYSTEMTRAYICON + +#include -#include "private/qt_x11_p.h" -#include "qlabel.h" -#include "qx11info_x11.h" -#include "qpainter.h" -#include "qpixmap.h" -#include "qbitmap.h" -#include "qevent.h" -#include "qapplication.h" -#include "qlist.h" -#include "qmenu.h" -#include "qtimer.h" #include "qsystemtrayicon_p.h" -#include "qpaintengine.h" +#include "qabstractsystemtrayiconsys_p.h" +#include "qcoreapplication.h" +#include "qxembedsystemtrayicon_x11_p.h" -#ifndef QT_NO_SYSTEMTRAYICON QT_BEGIN_NAMESPACE -Window QSystemTrayIconSys::sysTrayWindow = XNone; -QList QSystemTrayIconSys::trayIcons; -QCoreApplication::EventFilter QSystemTrayIconSys::oldEventFilter = 0; -Atom QSystemTrayIconSys::sysTraySelection = XNone; -XVisualInfo QSystemTrayIconSys::sysTrayVisual = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +Q_GLOBAL_STATIC(QSystemTrayIconSysFactory, qt_guiSystemTrayIconSysFactory) -// Locate the system tray -Window QSystemTrayIconSys::locateSystemTray() +QSystemTrayIconSysFactory::QSystemTrayIconSysFactory() +: pluginFactory(0) { - Display *display = QX11Info::display(); - if (sysTraySelection == XNone) { - int screen = QX11Info::appScreen(); - QString net_sys_tray = QString::fromLatin1("_NET_SYSTEM_TRAY_S%1").arg(screen); - sysTraySelection = XInternAtom(display, net_sys_tray.toLatin1(), False); - } - - return XGetSelectionOwner(QX11Info::display(), sysTraySelection); } -XVisualInfo* QSystemTrayIconSys::getSysTrayVisualInfo() +void QSystemTrayIconSysFactory::loadPluginFactory() { - Display *display = QX11Info::display(); - - if (!sysTrayVisual.visual) { - Window win = locateSystemTray(); - if (win != XNone) { - Atom actual_type; - int actual_format; - ulong nitems, bytes_remaining; - uchar *data = 0; - int result = XGetWindowProperty(display, win, ATOM(_NET_SYSTEM_TRAY_VISUAL), 0, 1, - False, XA_VISUALID, &actual_type, - &actual_format, &nitems, &bytes_remaining, &data); - VisualID vid = 0; - if (result == Success && data && actual_type == XA_VISUALID && actual_format == 32 && - nitems == 1 && bytes_remaining == 0) - vid = *(VisualID*)data; - if (data) - XFree(data); - if (vid == 0) - return 0; - - uint mask = VisualIDMask; - XVisualInfo *vi, rvi; - int count; - rvi.visualid = vid; - vi = XGetVisualInfo(display, mask, &rvi, &count); - if (vi) { - sysTrayVisual = vi[0]; - XFree((char*)vi); - } - if (sysTrayVisual.depth != 32) - memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); - } + if (pluginFactory) { + return; } - - return sysTrayVisual.visual ? &sysTrayVisual : 0; -} - -bool QSystemTrayIconSys::sysTrayTracker(void *message, long *result) -{ - bool retval = false; - if (QSystemTrayIconSys::oldEventFilter) - retval = QSystemTrayIconSys::oldEventFilter(message, result); - - if (trayIcons.isEmpty()) - return retval; - - Display *display = QX11Info::display(); - XEvent *ev = (XEvent *)message; - if (ev->type == DestroyNotify && ev->xany.window == sysTrayWindow) { - sysTrayWindow = locateSystemTray(); - memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); - for (int i = 0; i < trayIcons.count(); i++) { - if (sysTrayWindow == XNone) { - QBalloonTip::hideBalloon(); - trayIcons[i]->hide(); // still no luck - trayIcons[i]->destroy(); - trayIcons[i]->create(); - } else - trayIcons[i]->addToTray(); // add it to the new tray - } - retval = true; - } else if (ev->type == ClientMessage && sysTrayWindow == XNone) { - static Atom manager_atom = XInternAtom(display, "MANAGER", False); - XClientMessageEvent *cm = (XClientMessageEvent *)message; - if ((cm->message_type == manager_atom) && ((Atom)cm->data.l[1] == sysTraySelection)) { - sysTrayWindow = cm->data.l[2]; - memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); - XSelectInput(display, sysTrayWindow, StructureNotifyMask); - for (int i = 0; i < trayIcons.count(); i++) { - trayIcons[i]->addToTray(); - } - retval = true; - } - } else if (ev->type == PropertyNotify && ev->xproperty.atom == ATOM(_NET_SYSTEM_TRAY_VISUAL) && - ev->xproperty.window == sysTrayWindow) { - memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); - for (int i = 0; i < trayIcons.count(); i++) { - trayIcons[i]->addToTray(); - } +#ifndef QT_NO_LIBRARY + QFactoryLoader loader(QSystemTrayIconSysFactoryInterface_iid, QLatin1String("/systemtrayicon")); + pluginFactory = qobject_cast(loader.instance(QLatin1String("default"))); + if (pluginFactory) { + // Set parent to ensure factory destructor is called when application + // is closed + pluginFactory->setParent(QCoreApplication::instance()); + connect(pluginFactory, SIGNAL(availableChanged(bool)), SLOT(refreshTrayIconPrivates())); } - - return retval; +#endif // QT_NO_LIBRARY } -QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *q) - : QWidget(0, Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint), - q(q), colormap(0) +QSystemTrayIconSysFactoryInterface *QSystemTrayIconSysFactory::factory() const { - setAttribute(Qt::WA_AlwaysShowToolTips); - setAttribute(Qt::WA_QuitOnClose, false); - setAttribute(Qt::WA_NoSystemBackground, true); - setAttribute(Qt::WA_PaintOnScreen); - - static bool eventFilterAdded = false; - Display *display = QX11Info::display(); - if (!eventFilterAdded) { - oldEventFilter = qApp->setEventFilter(sysTrayTracker); - eventFilterAdded = true; - Window root = QX11Info::appRootWindow(); - XWindowAttributes attr; - XGetWindowAttributes(display, root, &attr); - if ((attr.your_event_mask & StructureNotifyMask) != StructureNotifyMask) { - (void) QApplication::desktop(); // lame trick to ensure our event mask is not overridden - XSelectInput(display, root, attr.your_event_mask | StructureNotifyMask); // for MANAGER selection - } + if (!pluginFactory) { + const_cast(this)->loadPluginFactory(); } - if (trayIcons.isEmpty()) { - sysTrayWindow = locateSystemTray(); - if (sysTrayWindow != XNone) - XSelectInput(display, sysTrayWindow, StructureNotifyMask); // track tray events - } - trayIcons.append(this); - setMouseTracking(true); -#ifndef QT_NO_TOOLTIP - setToolTip(q->toolTip()); -#endif - if (sysTrayWindow != XNone) - addToTray(); -} - -QSystemTrayIconSys::~QSystemTrayIconSys() -{ - trayIcons.removeAt(trayIcons.indexOf(this)); - Display *display = QX11Info::display(); - if (trayIcons.isEmpty()) { - if (sysTrayWindow == XNone) - return; - if (display) - XSelectInput(display, sysTrayWindow, 0); // stop tracking the tray - sysTrayWindow = XNone; + if (pluginFactory && pluginFactory->isAvailable()) { + return pluginFactory; } - if (colormap) - XFreeColormap(display, colormap); + static QXEmbedSystemTrayIconSysFactory def; + return def.isAvailable() ? &def : 0; } -void QSystemTrayIconSys::addToTray() +void QSystemTrayIconSysFactory::refreshTrayIconPrivates() { - Q_ASSERT(sysTrayWindow != XNone); - Display *display = QX11Info::display(); - - XVisualInfo *vi = getSysTrayVisualInfo(); - if (vi && vi->visual) { - Window root = RootWindow(display, vi->screen); - Window p = root; - if (QWidget *pw = parentWidget()) - p = pw->effectiveWinId(); - colormap = XCreateColormap(display, root, vi->visual, AllocNone); - XSetWindowAttributes wsa; - wsa.background_pixmap = 0; - wsa.colormap = colormap; - wsa.background_pixel = 0; - wsa.border_pixel = 0; - Window wid = XCreateWindow(display, p, -1, -1, 1, 1, - 0, vi->depth, InputOutput, vi->visual, - CWBackPixmap|CWBackPixel|CWBorderPixel|CWColormap, &wsa); - create(wid); - } else { - XSetWindowBackgroundPixmap(display, winId(), ParentRelative); + Q_FOREACH(QSystemTrayIconPrivate *trayIconPrivate, trayIconPrivates) { + if (trayIconPrivate->sys) { + delete trayIconPrivate->sys; + trayIconPrivate->sys = 0; + } + // When visible is true, sys is usually not 0 but it can be 0 if the + // call to install_sys() failed. + if (trayIconPrivate->visible) { + trayIconPrivate->install_sys(); + } } - - // GNOME, NET WM Specification - static Atom netwm_tray_atom = XInternAtom(display, "_NET_SYSTEM_TRAY_OPCODE", False); - long l[5] = { CurrentTime, SYSTEM_TRAY_REQUEST_DOCK, winId(), 0, 0 }; - XEvent ev; - memset(&ev, 0, sizeof(ev)); - ev.xclient.type = ClientMessage; - ev.xclient.window = sysTrayWindow; - ev.xclient.message_type = netwm_tray_atom; - ev.xclient.format = 32; - memcpy((char *)&ev.xclient.data, (const char *) l, sizeof(l)); - XSendEvent(display, sysTrayWindow, False, 0, &ev); - setMinimumSize(22, 22); // required at least on GNOME -} - -void QSystemTrayIconSys::updateIcon() -{ - update(); } -void QSystemTrayIconSys::resizeEvent(QResizeEvent *re) +void QSystemTrayIconSysFactory::registerSystemTrayIconPrivate(QSystemTrayIconPrivate* trayIconPrivate) { - QWidget::resizeEvent(re); - updateIcon(); + trayIconPrivates.insert(trayIconPrivate); } -void QSystemTrayIconSys::paintEvent(QPaintEvent*) +void QSystemTrayIconSysFactory::unregisterSystemTrayIconPrivate(QSystemTrayIconPrivate* trayIconPrivate) { - QPainter p(this); - if (!getSysTrayVisualInfo()) { - const QRegion oldSystemClip = p.paintEngine()->systemClip(); - const QRect clearedRect = oldSystemClip.boundingRect(); - XClearArea(QX11Info::display(), winId(), clearedRect.x(), clearedRect.y(), - clearedRect.width(), clearedRect.height(), False); - QPaintEngine *pe = p.paintEngine(); - pe->setSystemClip(clearedRect); - q->icon().paint(&p, rect()); - pe->setSystemClip(oldSystemClip); - } else { - p.setCompositionMode(QPainter::CompositionMode_Source); - p.fillRect(rect(), Qt::transparent); - p.setCompositionMode(QPainter::CompositionMode_SourceOver); - q->icon().paint(&p, rect()); - } + trayIconPrivates.remove(trayIconPrivate); } -void QSystemTrayIconSys::mousePressEvent(QMouseEvent *ev) +QAbstractSystemTrayIconSys *QSystemTrayIconSysFactory::create(QSystemTrayIcon *trayIcon) const { - QPoint globalPos = ev->globalPos(); - if (ev->button() == Qt::RightButton && q->contextMenu()) - q->contextMenu()->popup(globalPos); - - if (QBalloonTip::isBalloonVisible()) { - emit q->messageClicked(); - QBalloonTip::hideBalloon(); + QSystemTrayIconSysFactoryInterface *f = factory(); + if (!f) { + qWarning("No systemtrayicon available"); + return 0; } - - if (ev->button() == Qt::LeftButton) - emit q->activated(QSystemTrayIcon::Trigger); - else if (ev->button() == Qt::RightButton) - emit q->activated(QSystemTrayIcon::Context); - else if (ev->button() == Qt::MidButton) - emit q->activated(QSystemTrayIcon::MiddleClick); -} - -void QSystemTrayIconSys::mouseDoubleClickEvent(QMouseEvent *ev) -{ - if (ev->button() == Qt::LeftButton) - emit q->activated(QSystemTrayIcon::DoubleClick); -} - -#ifndef QT_NO_WHEELEVENT -void QSystemTrayIconSys::wheelEvent(QWheelEvent *e) -{ - QApplication::sendEvent(q, e); + return f->create(trayIcon); } -#endif -bool QSystemTrayIconSys::event(QEvent *e) +bool QSystemTrayIconSysFactory::isAvailable() const { - if (e->type() == QEvent::ToolTip) { - return QApplication::sendEvent(q, e); - } - return QWidget::event(e); + return factory(); } -bool QSystemTrayIconSys::x11Event(XEvent *event) +//////////////////////////////////////////////// +QSystemTrayIconPrivate::~QSystemTrayIconPrivate() { - if (event->type == ReparentNotify) - show(); - return QWidget::x11Event(event); + qt_guiSystemTrayIconSysFactory()->unregisterSystemTrayIconPrivate(this); + delete sys; } -//////////////////////////////////////////////////////////////////////////// void QSystemTrayIconPrivate::install_sys() { Q_Q(QSystemTrayIcon); - if (!sys) - sys = new QSystemTrayIconSys(q); + if (!sys) { + // Register ourself even if create() fails: our "sys" will get created + // later by refreshTrayIconPrivates() if a systemtray becomes + // available. This situation can happen for applications which are + // started at login time, while the desktop itself is starting up. + qt_guiSystemTrayIconSysFactory()->registerSystemTrayIconPrivate(this); + sys = qt_guiSystemTrayIconSysFactory()->create(q); + if (!sys) { + return; + } + } + sys->updateVisibility(); } QRect QSystemTrayIconPrivate::geometry_sys() const { - if (!sys) - return QRect(); - return QRect(sys->mapToGlobal(QPoint(0, 0)), sys->size()); + if (!sys || !visible) + return QRect(); + return sys->geometry(); } void QSystemTrayIconPrivate::remove_sys() @@ -350,35 +161,35 @@ void QSystemTrayIconPrivate::remove_sys() if (!sys) return; QBalloonTip::hideBalloon(); - sys->hide(); // this should do the trick, but... - delete sys; // wm may resize system tray only for DestroyEvents - sys = 0; + sys->updateVisibility(); } void QSystemTrayIconPrivate::updateIcon_sys() { - if (!sys) + if (!sys || !visible) return; sys->updateIcon(); } void QSystemTrayIconPrivate::updateMenu_sys() { - + if (!sys || !visible) + return; + sys->updateMenu(); } void QSystemTrayIconPrivate::updateToolTip_sys() { - if (!sys) + if (!sys || !visible) return; #ifndef QT_NO_TOOLTIP - sys->setToolTip(toolTip); + sys->updateToolTip(); #endif } bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys() { - return QSystemTrayIconSys::locateSystemTray() != XNone; + return qt_guiSystemTrayIconSysFactory()->isAvailable(); } bool QSystemTrayIconPrivate::supportsMessages_sys() @@ -389,12 +200,9 @@ bool QSystemTrayIconPrivate::supportsMessages_sys() void QSystemTrayIconPrivate::showMessage_sys(const QString &message, const QString &title, QSystemTrayIcon::MessageIcon icon, int msecs) { - if (!sys) + if (!sys || !visible) return; - QPoint g = sys->mapToGlobal(QPoint(0, 0)); - QBalloonTip::showBalloon(icon, message, title, sys->q, - QPoint(g.x() + sys->width()/2, g.y() + sys->height()/2), - msecs); + sys->showMessage(message, title, icon, msecs); } QT_END_NAMESPACE diff --git a/src/gui/util/qxembedsystemtrayicon_x11.cpp b/src/gui/util/qxembedsystemtrayicon_x11.cpp new file mode 100644 index 0000000..d39bc68 --- /dev/null +++ b/src/gui/util/qxembedsystemtrayicon_x11.cpp @@ -0,0 +1,469 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include "qxembedsystemtrayicon_x11_p.h" + +#ifndef QT_NO_SYSTEMTRAYICON + +#include "private/qt_x11_p.h" +#include "qapplication.h" +#include "qevent.h" +#include "qlist.h" +#include "qmenu.h" +#include "qpainter.h" +#include "qpaintengine.h" +#include "qsystemtrayicon_p.h" +#include "qx11info_x11.h" + +QT_BEGIN_INCLUDE_NAMESPACE +#include +#include +#include +#include +QT_END_INCLUDE_NAMESPACE + +QT_BEGIN_NAMESPACE + +class QSystemTrayIconWidget : public QWidget +{ +public: + QSystemTrayIconWidget(QSystemTrayIcon *q, QXEmbedSystemTrayIconSys *s); + ~QSystemTrayIconWidget(); + + static Window locateSystemTray(); + +protected: + void paintEvent(QPaintEvent *pe); + void resizeEvent(QResizeEvent *re); + bool x11Event(XEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseDoubleClickEvent(QMouseEvent *event); +#ifndef QT_NO_WHEELEVENT + void wheelEvent(QWheelEvent *event); +#endif + bool event(QEvent *e); + +private: + enum { + SYSTEM_TRAY_REQUEST_DOCK = 0, + SYSTEM_TRAY_BEGIN_MESSAGE = 1, + SYSTEM_TRAY_CANCEL_MESSAGE =2 + }; + + void addToTray(); + static XVisualInfo* getSysTrayVisualInfo(); + + static Window sysTrayWindow; + static QList trayIcons; + static QCoreApplication::EventFilter oldEventFilter; + static bool sysTrayTracker(void *message, long *result); + static Atom sysTraySelection; + static XVisualInfo sysTrayVisual; + + QSystemTrayIcon *q; + QXEmbedSystemTrayIconSys *sys; + Colormap colormap; +}; + +Window QSystemTrayIconWidget::sysTrayWindow = XNone; +QList QSystemTrayIconWidget::trayIcons; +QCoreApplication::EventFilter QSystemTrayIconWidget::oldEventFilter = 0; +Atom QSystemTrayIconWidget::sysTraySelection = XNone; +XVisualInfo QSystemTrayIconWidget::sysTrayVisual = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + +QSystemTrayIconWidget::QSystemTrayIconWidget(QSystemTrayIcon* q, QXEmbedSystemTrayIconSys* sys) +: QWidget(0, Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint) +, q(q) +, sys(sys) +, colormap(0) +{ + setAttribute(Qt::WA_AlwaysShowToolTips); + setAttribute(Qt::WA_QuitOnClose, false); + setAttribute(Qt::WA_NoSystemBackground, true); + setAttribute(Qt::WA_PaintOnScreen); + setMouseTracking(true); +#ifndef QT_NO_TOOLTIP + setToolTip(q->toolTip()); +#endif + + static bool eventFilterAdded = false; + Display *display = QX11Info::display(); + if (!eventFilterAdded) { + oldEventFilter = qApp->setEventFilter(sysTrayTracker); + eventFilterAdded = true; + Window root = QX11Info::appRootWindow(); + XWindowAttributes attr; + XGetWindowAttributes(display, root, &attr); + if ((attr.your_event_mask & StructureNotifyMask) != StructureNotifyMask) { + (void) QApplication::desktop(); // lame trick to ensure our event mask is not overridden + XSelectInput(display, root, attr.your_event_mask | StructureNotifyMask); // for MANAGER selection + } + } + if (trayIcons.isEmpty()) { + sysTrayWindow = locateSystemTray(); + if (sysTrayWindow != XNone) + XSelectInput(display, sysTrayWindow, StructureNotifyMask); // track tray events + } + trayIcons.append(this); + if (sysTrayWindow != XNone) + addToTray(); +} + +QSystemTrayIconWidget::~QSystemTrayIconWidget() +{ + trayIcons.removeAt(trayIcons.indexOf(this)); + Display *display = QX11Info::display(); + if (trayIcons.isEmpty()) { + if (sysTrayWindow == XNone) + return; + if (display) + XSelectInput(display, sysTrayWindow, 0); // stop tracking the tray + sysTrayWindow = XNone; + } + if (colormap) + XFreeColormap(display, colormap); +} + +void QSystemTrayIconWidget::resizeEvent(QResizeEvent *re) +{ + QWidget::resizeEvent(re); + update(); +} + +void QSystemTrayIconWidget::paintEvent(QPaintEvent*) +{ + QPainter p(this); + if (!getSysTrayVisualInfo()) { + const QRegion oldSystemClip = p.paintEngine()->systemClip(); + const QRect clearedRect = oldSystemClip.boundingRect(); + XClearArea(QX11Info::display(), winId(), clearedRect.x(), clearedRect.y(), + clearedRect.width(), clearedRect.height(), False); + QPaintEngine *pe = p.paintEngine(); + pe->setSystemClip(clearedRect); + q->icon().paint(&p, rect()); + pe->setSystemClip(oldSystemClip); + } else { + p.setCompositionMode(QPainter::CompositionMode_Source); + p.fillRect(rect(), Qt::transparent); + p.setCompositionMode(QPainter::CompositionMode_SourceOver); + q->icon().paint(&p, rect()); + } +} + +void QSystemTrayIconWidget::mousePressEvent(QMouseEvent *ev) +{ + QPoint globalPos = ev->globalPos(); + if (ev->button() == Qt::RightButton && q->contextMenu()) + q->contextMenu()->popup(globalPos); + + if (QBalloonTip::isBalloonVisible()) { + QMetaObject::invokeMethod(q, "messageClicked"); + QBalloonTip::hideBalloon(); + } + + if (ev->button() == Qt::LeftButton) + qtsystray_sendActivated(q, QSystemTrayIcon::Trigger); + else if (ev->button() == Qt::RightButton) + qtsystray_sendActivated(q, QSystemTrayIcon::Context); + else if (ev->button() == Qt::MidButton) + qtsystray_sendActivated(q, QSystemTrayIcon::MiddleClick); +} + +void QSystemTrayIconWidget::mouseDoubleClickEvent(QMouseEvent *ev) +{ + if (ev->button() == Qt::LeftButton) + qtsystray_sendActivated(q, QSystemTrayIcon::DoubleClick); +} + +#ifndef QT_NO_WHEELEVENT +void QSystemTrayIconWidget::wheelEvent(QWheelEvent *e) +{ + sys->sendWheelEventToTrayIcon(e->delta(), e->orientation()); +} +#endif + +bool QSystemTrayIconWidget::event(QEvent *e) +{ + if (e->type() == QEvent::ToolTip) { + sys->sendToolTipEventToTrayIcon(); + } + return QWidget::event(e); +} + +bool QSystemTrayIconWidget::x11Event(XEvent *event) +{ + if (event->type == ReparentNotify) + show(); + return QWidget::x11Event(event); +} + +// Locate the system tray +Window QSystemTrayIconWidget::locateSystemTray() +{ + Display *display = QX11Info::display(); + if (sysTraySelection == XNone) { + int screen = QX11Info::appScreen(); + QString net_sys_tray = QString::fromLatin1("_NET_SYSTEM_TRAY_S%1").arg(screen); + sysTraySelection = XInternAtom(display, net_sys_tray.toLatin1(), False); + } + + return XGetSelectionOwner(QX11Info::display(), sysTraySelection); +} + +XVisualInfo* QSystemTrayIconWidget::getSysTrayVisualInfo() +{ + Display *display = QX11Info::display(); + + if (!sysTrayVisual.visual) { + Window win = locateSystemTray(); + if (win != XNone) { + Atom actual_type; + int actual_format; + ulong nitems, bytes_remaining; + uchar *data = 0; + int result = XGetWindowProperty(display, win, ATOM(_NET_SYSTEM_TRAY_VISUAL), 0, 1, + False, XA_VISUALID, &actual_type, + &actual_format, &nitems, &bytes_remaining, &data); + VisualID vid = 0; + if (result == Success && data && actual_type == XA_VISUALID && actual_format == 32 && + nitems == 1 && bytes_remaining == 0) + vid = *(VisualID*)data; + if (data) + XFree(data); + if (vid == 0) + return 0; + + uint mask = VisualIDMask; + XVisualInfo *vi, rvi; + int count; + rvi.visualid = vid; + vi = XGetVisualInfo(display, mask, &rvi, &count); + if (vi) { + sysTrayVisual = vi[0]; + XFree((char*)vi); + } + if (sysTrayVisual.depth != 32) + memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); + } + } + + return sysTrayVisual.visual ? &sysTrayVisual : 0; +} + +bool QSystemTrayIconWidget::sysTrayTracker(void *message, long *result) +{ + bool retval = false; + if (QSystemTrayIconWidget::oldEventFilter) + retval = QSystemTrayIconWidget::oldEventFilter(message, result); + + if (trayIcons.isEmpty()) + return retval; + + Display *display = QX11Info::display(); + XEvent *ev = (XEvent *)message; + if (ev->type == DestroyNotify && ev->xany.window == sysTrayWindow) { + sysTrayWindow = locateSystemTray(); + memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); + for (int i = 0; i < trayIcons.count(); i++) { + if (sysTrayWindow == XNone) { + QBalloonTip::hideBalloon(); + trayIcons[i]->hide(); // still no luck + trayIcons[i]->destroy(); + trayIcons[i]->create(); + } else + trayIcons[i]->addToTray(); // add it to the new tray + } + retval = true; + } else if (ev->type == ClientMessage && sysTrayWindow == XNone) { + static Atom manager_atom = XInternAtom(display, "MANAGER", False); + XClientMessageEvent *cm = (XClientMessageEvent *)message; + if ((cm->message_type == manager_atom) && ((Atom)cm->data.l[1] == sysTraySelection)) { + sysTrayWindow = cm->data.l[2]; + memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); + XSelectInput(display, sysTrayWindow, StructureNotifyMask); + for (int i = 0; i < trayIcons.count(); i++) { + trayIcons[i]->addToTray(); + } + retval = true; + } + } else if (ev->type == PropertyNotify && ev->xproperty.atom == ATOM(_NET_SYSTEM_TRAY_VISUAL) && + ev->xproperty.window == sysTrayWindow) { + memset(&sysTrayVisual, 0, sizeof(sysTrayVisual)); + for (int i = 0; i < trayIcons.count(); i++) { + trayIcons[i]->addToTray(); + } + } + + return retval; +} + +void QSystemTrayIconWidget::addToTray() +{ + Q_ASSERT(sysTrayWindow != XNone); + Display *display = QX11Info::display(); + + XVisualInfo *vi = getSysTrayVisualInfo(); + if (vi && vi->visual) { + Window root = RootWindow(display, vi->screen); + Window p = root; + if (QWidget *pw = parentWidget()) + p = pw->effectiveWinId(); + colormap = XCreateColormap(display, root, vi->visual, AllocNone); + XSetWindowAttributes wsa; + wsa.background_pixmap = 0; + wsa.colormap = colormap; + wsa.background_pixel = 0; + wsa.border_pixel = 0; + Window wid = XCreateWindow(display, p, -1, -1, 1, 1, + 0, vi->depth, InputOutput, vi->visual, + CWBackPixmap|CWBackPixel|CWBorderPixel|CWColormap, &wsa); + create(wid); + } else { + XSetWindowBackgroundPixmap(display, winId(), ParentRelative); + } + + // GNOME, NET WM Specification + static Atom netwm_tray_atom = XInternAtom(display, "_NET_SYSTEM_TRAY_OPCODE", False); + long l[5] = { CurrentTime, SYSTEM_TRAY_REQUEST_DOCK, winId(), 0, 0 }; + XEvent ev; + memset(&ev, 0, sizeof(ev)); + ev.xclient.type = ClientMessage; + ev.xclient.window = sysTrayWindow; + ev.xclient.message_type = netwm_tray_atom; + ev.xclient.format = 32; + memcpy((char *)&ev.xclient.data, (const char *) l, sizeof(l)); + XSendEvent(display, sysTrayWindow, False, 0, &ev); + setMinimumSize(22, 22); // required at least on GNOME +} + +//////////////////////////////////////////////////////////////////////////// +QXEmbedSystemTrayIconSys::QXEmbedSystemTrayIconSys(QSystemTrayIcon *q) +: QAbstractSystemTrayIconSys(q) +, widget(0) +{ +} + +QXEmbedSystemTrayIconSys::~QXEmbedSystemTrayIconSys() +{ + delete widget; +} + +QRect QXEmbedSystemTrayIconSys::geometry() const +{ + if (!widget) + return QRect(); + return QRect(widget->mapToGlobal(QPoint(0, 0)), widget->size()); +} + +void QXEmbedSystemTrayIconSys::updateIcon() +{ + if (!widget) + return; + widget->update(); +} + +void QXEmbedSystemTrayIconSys::updateToolTip() +{ + if (!widget) + return; + widget->setToolTip(trayIcon->toolTip()); +} + +void QXEmbedSystemTrayIconSys::showMessage(const QString &message, const QString &title, + QSystemTrayIcon::MessageIcon icon, int msecs) +{ + if (!widget) + return; + QPoint point = geometry().center(); + QBalloonTip::showBalloon(icon, message, title, trayIcon, point, msecs); +} + +void QXEmbedSystemTrayIconSys::updateVisibility() +{ + bool visible = trayIcon->isVisible(); + if (visible && !widget) + widget = new QSystemTrayIconWidget(trayIcon, this); + else if (!visible && widget) { + delete widget; + widget = 0; + } +} + +void QXEmbedSystemTrayIconSys::sendToolTipEventToTrayIcon() +{ +#ifndef QT_NO_TOOLTIP + // Pass the event through QSystemTrayIcon so that it gets a chance to + // update the tooltip, then asks widget to show the tooltip + Q_ASSERT(widget); + QPoint globalPos = QCursor::pos(); + QPoint pos = widget->mapFromGlobal(globalPos); + QHelpEvent event(QEvent::ToolTip, pos, globalPos); + QApplication::sendEvent(trayIcon, &event); +#endif +} + +void QXEmbedSystemTrayIconSys::sendWheelEventToTrayIcon(int delta, Qt::Orientation orientation) +{ +#ifndef QT_NO_WHEELEVENT + Q_ASSERT(widget); + QPoint globalPos = QCursor::pos(); + QPoint pos = widget->mapFromGlobal(globalPos); + QWheelEvent event(pos, globalPos, delta, Qt::NoButton, Qt::NoModifier, orientation); + QApplication::sendEvent(trayIcon, &event); +#endif +} + +void QXEmbedSystemTrayIconSys::updateMenu() +{ +} + +///////////////////////////////////////////////////////////// +QAbstractSystemTrayIconSys * QXEmbedSystemTrayIconSysFactory::create(QSystemTrayIcon *icon) +{ + return new QXEmbedSystemTrayIconSys(icon); +} + +bool QXEmbedSystemTrayIconSysFactory::isAvailable() const +{ + return QSystemTrayIconWidget::locateSystemTray() != XNone; +} + +QT_END_NAMESPACE +#endif //QT_NO_SYSTEMTRAYICON diff --git a/src/gui/util/qxembedsystemtrayicon_x11_p.h b/src/gui/util/qxembedsystemtrayicon_x11_p.h new file mode 100644 index 0000000..9fcc908 --- /dev/null +++ b/src/gui/util/qxembedsystemtrayicon_x11_p.h @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QXEMBEDSYSTEMTRAYICON_X11_P_H +#define QXEMBEDSYSTEMTRAYICON_X11_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of a number of Qt sources files. This header file may change from +// version to version without notice, or even be removed. +// +// We mean it. +// + +#ifndef QT_NO_SYSTEMTRAYICON + +#include "qabstractsystemtrayiconsys_p.h" + +QT_BEGIN_NAMESPACE + +class QSystemTrayIconWidget; + +class QXEmbedSystemTrayIconSys : public QAbstractSystemTrayIconSys +{ +public: + QXEmbedSystemTrayIconSys(QSystemTrayIcon *); + ~QXEmbedSystemTrayIconSys(); + + QRect geometry() const; + + void updateVisibility(); + + void updateIcon(); + + void updateToolTip(); + + void updateMenu(); + + void showMessage(const QString &message, const QString &title, + QSystemTrayIcon::MessageIcon icon, int msecs); + +private: + friend class QSystemTrayIconWidget; + QSystemTrayIconWidget *widget; + + void sendToolTipEventToTrayIcon(); + + void sendWheelEventToTrayIcon(int delta, Qt::Orientation orientation); +}; + +struct QXEmbedSystemTrayIconSysFactory : public QSystemTrayIconSysFactoryInterface +{ + QAbstractSystemTrayIconSys * create(QSystemTrayIcon *trayIcon); + bool isAvailable() const; +}; + + +QT_END_NAMESPACE + +#endif // QT_NO_SYSTEMTRAYICON + +#endif // QXEMBEDSYSTEMTRAYICON_X11_P_H + diff --git a/src/gui/util/util.pri b/src/gui/util/util.pri index d1c4ff8..c225183 100644 --- a/src/gui/util/util.pri +++ b/src/gui/util/util.pri @@ -29,8 +29,13 @@ wince* { } unix:x11 { + HEADERS += \ + util/qabstractsystemtrayiconsys_p.h \ + util/qxembedsystemtrayicon_x11_p.h SOURCES += \ - util/qsystemtrayicon_x11.cpp + util/qabstractsystemtrayiconsys.cpp \ + util/qsystemtrayicon_x11.cpp \ + util/qxembedsystemtrayicon_x11.cpp } embedded { @@ -56,4 +61,4 @@ symbian { } else { DEFINES += USE_SCHEMEHANDLER } -} \ No newline at end of file +} ./COPYING0000644000004100000410000001672713035734364012323 0ustar www-datawww-data GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ./src/0000755000004100000410000000000013035734373012042 5ustar www-datawww-data./src/CMakeLists.txt0000644000004100000410000000175613035734364014613 0ustar www-datawww-data# Source set(sni_qt_SRCS dbusimage.cpp dbustooltip.cpp debug.cpp fsutils.cpp iconcache.cpp settings.cpp statusnotifieritem.cpp statusnotifieritemfactory.cpp ) # Build include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${DBUSMENUQT_INCLUDE_DIRS} ${QT_INCLUDE_DIR} ${QT_QTCORE_INCLUDE_DIR} ${QT_QTDBUS_INCLUDE_DIR} ${QT_QTGUI_INCLUDE_DIR} ) qt4_automoc(${sni_qt_SRCS}) qt4_add_dbus_adaptor(sni_qt_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/org.kde.StatusNotifierItem.xml ${CMAKE_CURRENT_SOURCE_DIR}/statusnotifieritem.h StatusNotifierItem ) add_library(sni-qt MODULE ${sni_qt_SRCS} ) link_directories( ${DBUSMENUQT_LIBRARY_DIRS} ) target_link_libraries(sni-qt ${DBUSMENUQT_LIBRARIES} ${QT_QTCORE_LIBRARIES} ${QT_QTDBUS_LIBRARIES} ${QT_QTGUI_LIBRARIES} ${QT_QTXML_LIBRARIES} ) # Install install(TARGETS sni-qt DESTINATION ${QT_PLUGINS_DIR}/systemtrayicon/ ) ./src/fsutils.cpp0000644000004100000410000000651113035734373014242 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Qt #include #include #include // libc #include #include #include #include #include namespace FsUtils { QString generateTempDir(const QString& prefix) { QDir dir; QString path = QString::fromUtf8(getenv("XDG_RUNTIME_DIR")); if (!path.isEmpty()) { dir.setPath(path); } else if (!getenv("SNAP")) { dir = QDir::temp(); } else { // Try to get the .cache from $XDG_CACHE_HOME, if it's not set, // it has to be in ~/.cache as per XDG standard path = QString::fromUtf8(getenv("XDG_CACHE_HOME")); if (path.isEmpty()) { path = QDir::cleanPath(QDir::homePath() + "/.cache"); } dir.setPath(path); } if (!dir.mkpath(".")) { qCritical("Failed to generate temporary file for prefix %s: could not create %s", qPrintable(prefix), qPrintable(dir.path())); return QString(); } QString tmpl = QDir::cleanPath(dir.path() + '/' + prefix + "-XXXXXX"); QByteArray ba = QFile::encodeName(tmpl); const char* name = mkdtemp(ba.data()); if (!name) { qCritical("Failed to generate temporary file for prefix %s: %s", qPrintable(prefix), strerror(errno)); return QString(); } return QFile::encodeName(name); } bool recursiveRm(const QString& dirName) { if (dirName.isEmpty()) { qCritical("dirName is empty, recursiveRm aborted"); return false; } bool ok; QDir dir(dirName); dir.setFilter(QDir::NoDotAndDotDot | QDir::AllEntries | QDir::Hidden | QDir::System); Q_FOREACH(const QFileInfo& info, dir.entryInfoList()) { if (info.isDir()) { ok = recursiveRm(info.filePath()); if (!ok) { return false; } } else { ok = dir.remove(info.fileName()); if (!ok) { qCritical("Failed to remove file %s", qPrintable(info.filePath())); return false; } } } ok = dir.rmdir(dir.path()); if (!ok) { qCritical("Failed to remove empty dir %s", qPrintable(dir.path())); return false; } return true; } bool touch(const QString& _name, const QDateTime& time) { QByteArray name = QFile::encodeName(_name); struct utimbuf buf; buf.actime = time.toTime_t(); buf.modtime = buf.actime; int ret = utime(name.data(), &buf); if (ret != 0) { qCritical("Failed to touch %s: %s", name.data(), strerror(errno)); return false; } return true; } } // namespace ./src/settings.h0000644000004100000410000000153713035734364014061 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef SETTINGS_H #define SETTINGS_H namespace Settings { bool needsActivateAction(); bool debug(); }; #endif // SETTINGS_H./src/private/0000755000004100000410000000000013035734364013514 5ustar www-datawww-data./src/private/qabstractsystemtrayiconsys_p.h0000644000004100000410000000667413035734364021762 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QABSTRACTSYSTEMTRAYICONSYS_P_H #define QABSTRACTSYSTEMTRAYICONSYS_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of a number of Qt sources files. This header file may change from // version to version without notice, or even be removed. // // We mean it. // #ifndef QT_NO_SYSTEMTRAYICON #include #include class QAbstractSystemTrayIconSys; class Q_GUI_EXPORT QSystemTrayIconSysFactoryInterface : public QObject, public QFactoryInterface { Q_OBJECT public: QSystemTrayIconSysFactoryInterface(); virtual QAbstractSystemTrayIconSys * create(QSystemTrayIcon *) = 0; virtual bool isAvailable() const = 0; // \reimp virtual QStringList keys() const { return QStringList() << QLatin1String("default"); } Q_SIGNALS: void availableChanged(bool); }; #define QSystemTrayIconSysFactoryInterface_iid "com.nokia.qt.QSystemTrayIconSysFactoryInterface" Q_DECLARE_INTERFACE(QSystemTrayIconSysFactoryInterface, QSystemTrayIconSysFactoryInterface_iid) class QRect; class QAbstractSystemTrayIconSys { public: QAbstractSystemTrayIconSys(QSystemTrayIcon *icon) : trayIcon(icon) {} virtual ~QAbstractSystemTrayIconSys() {} virtual QRect geometry() const = 0; virtual void updateVisibility() = 0; virtual void updateIcon() = 0; virtual void updateToolTip() = 0; virtual void updateMenu() = 0; virtual void showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon icon, int msecs) = 0; void sendActivated(QSystemTrayIcon::ActivationReason); protected: QSystemTrayIcon *trayIcon; }; #endif // QT_NO_SYSTEMTRAYICON #endif // QABSTRACTSYSTEMTRAYICONSYS_P_H ./src/dbustooltip.cpp0000644000004100000410000000240213035734364015114 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Qt #include QDBusArgument& operator<<(QDBusArgument& argument, const DBusToolTip& tip) { argument.beginStructure(); argument << tip.iconName << tip.iconPixmap << tip.title << tip.description; argument.endStructure(); return argument; } const QDBusArgument& operator>>(const QDBusArgument& argument, DBusToolTip& tip) { argument.beginStructure(); argument >> tip.iconName >> tip.iconPixmap >> tip.title >> tip.description; argument.endStructure(); return argument; } ./src/statusnotifieritemfactory.h0000644000004100000410000000323013035734364017543 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef STATUSNOTIFIERITEMFACTORY_H #define STATUSNOTIFIERITEMFACTORY_H // Local #include // Qt #include class IconCache; class StatusNotifierItem; class StatusNotifierItemFactory : public QSystemTrayIconSysFactoryInterface { Q_OBJECT Q_INTERFACES(QSystemTrayIconSysFactoryInterface:QFactoryInterface) public: StatusNotifierItemFactory(); ~StatusNotifierItemFactory(); QAbstractSystemTrayIconSys * create(QSystemTrayIcon *trayIcon); bool isAvailable() const; private Q_SLOTS: void slotSnwOwnerChanged(const QString&, const QString&, const QString&); void slotHostRegisteredWithSnw(); void slotItemDestroyed(QObject*); private: QString m_iconCacheDir; IconCache* m_iconCache; bool m_isAvailable; QSet m_items; void connectToSnw(); void registerItem(StatusNotifierItem*); }; #endif /* STATUSNOTIFIERITEMFACTORY_H */ ./src/debug.h0000644000004100000410000000312113035734364013276 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef DEBUG_H #define DEBUG_H // Local #include // Qt #include namespace Debug { enum Level { WarningLevel, InfoLevel, DebugLevel }; QDebug trace(Level level, const char* function); } // namespace // Simple macros to get KDebug like support #define SNI_DEBUG if (Settings::debug()) Debug::trace(Debug::DebugLevel, __PRETTY_FUNCTION__) #define SNI_INFO Debug::trace(Debug::InfoLevel, __PRETTY_FUNCTION__) #define SNI_WARNING Debug::trace(Debug::WarningLevel, __PRETTY_FUNCTION__) // Log a variable name and value #define SNI_VAR(var) SNI_DEBUG << #var ":" << var #define SNI_RETURN_IF_FAIL(cond) if (!(cond)) { \ SNI_WARNING << "Condition failed: " #cond; \ return; \ } #define SNI_RETURN_VALUE_IF_FAIL(cond, value) if (!(cond)) { \ SNI_WARNING << "Condition failed: " #cond; \ return (value); \ } #endif /* DEBUG_H */ ./src/debug.cpp0000644000004100000410000000250613035734364013637 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Qt #include #include namespace Debug { QDebug trace(Level level, const char* function) { static const char* levelStrings[] = { "WARN ", "INFO ", "DEBUG" }; static const QByteArray prefix = QByteArray("sni-qt/") + QByteArray::number(QCoreApplication::applicationPid()); QDebug stream = level == WarningLevel ? qWarning() : qDebug(); stream << prefix << levelStrings[level]; stream << QTime::currentTime().toString("HH:mm:ss.zzz").toUtf8().data(); stream << function; return stream; } } // namespace Debug ./src/fsutils.h0000644000004100000410000000200413035734364013700 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef FSUTILS_H #define FSUTILS_H // Qt #include class QDateTime; namespace FsUtils { QString generateTempDir(const QString& prefix); bool recursiveRm(const QString& dirName); bool touch(const QString& name, const QDateTime& mtime); } // namespace #endif /* FSUTILS_H */ ./src/iconcache.cpp0000644000004100000410000001312513035734364014464 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Local #include #include // Qt #include #include #include #include #include #include const int IconCache::MaxIconCount = 20; static QByteArray hashForPixmap(const QList& extents, const QPixmap& pixmap) { QCryptographicHash hash(QCryptographicHash::Md4); Q_FOREACH(int extent, extents) { hash.addData(QByteArray::number(extent)); } QImage image = pixmap.toImage(); hash.addData(reinterpret_cast(image.constBits()), image.byteCount()); return hash.result().toHex(); } static QString computeKeyForIcon(const QIcon& icon) { static QString prefix = QString("%1_%2_") .arg(QCoreApplication::applicationFilePath().section('/', -1)) .arg(QCoreApplication::applicationPid()); // Get a sorted list of extents QList extents; Q_FOREACH(const QSize& size, icon.availableSizes()) { extents << qMax(size.width(), size.height()); } qSort(extents); if (extents.isEmpty()) { extents << 16 << 22 << 32 << 48; } // Determine the test extent: for our purpose we define it as either the // biggest extent which is <= 32 or, if there is none, the smallest // available int testExtent; auto it = extents.begin(), end = extents.end(); do { testExtent = *it; ++it; } while (testExtent <= 32 && it != end); QByteArray hash = hashForPixmap(extents, icon.pixmap(testExtent)); return prefix + QString::fromAscii(hash); } IconCache::IconCache(const QString& baseDir, QObject* parent) : QObject(parent) , m_themePath(baseDir + "/icons") { QDir dir(baseDir); bool ok = dir.mkdir("icons"); if (!ok) { qCritical("Could not create '%s' dir for SNI icon cache", qPrintable(m_themePath)); m_themePath = QString(); return; } } QString IconCache::themePath(const QIcon& icon) const { if (!icon.isNull() && !icon.name().isEmpty() && QIcon::hasThemeIcon(icon.name())) { QString dataHome = QString::fromUtf8(getenv("XDG_DATA_HOME")); if (dataHome.isEmpty()) { dataHome = QDir::homePath() + "/.local/share"; } return QDir::cleanPath(dataHome + "/icons"); } return m_themePath; } QString IconCache::nameForIcon(const QIcon& icon) const { if (icon.isNull()) { return QString(); } QString key = computeKeyForIcon(icon); QStringList::iterator it = qFind(m_cacheKeys.begin(), m_cacheKeys.end(), key); if (it == m_cacheKeys.end()) { cacheIcon(key, icon); trimCache(); } else { // Place key at the end of list as it is the most recently accessed m_cacheKeys.erase(it); m_cacheKeys.append(key); } return key; } void IconCache::trimCache() const { QDir dir(m_themePath + "/hicolor"); dir.setFilter(QDir::Dirs); while (m_cacheKeys.count() > MaxIconCount) { QString cacheKey = m_cacheKeys.takeFirst(); Q_FOREACH(const QString& sizeDir, dir.entryList()) { QString iconSubPath = QString("%1/apps/%2.png").arg(sizeDir).arg(cacheKey); if (dir.exists(iconSubPath)) { dir.remove(iconSubPath); } } } } void IconCache::cacheIcon(const QString& key, const QIcon& icon) const { QList sizes = icon.availableSizes(); if (sizes.isEmpty()) { // sizes can be empty if icon is an SVG. In this case generate images for a few sizes #define SIZE(x) QSize(x, x) sizes << SIZE(16) << SIZE(22) << SIZE(32) << SIZE(48) ; #undef SIZE } QDir dir(m_themePath); Q_FOREACH(const QSize& size, sizes) { QPixmap pix = icon.pixmap(size); QString dirName = QString("hicolor/%1x%1/apps").arg(size.width()); if (!dir.exists(dirName)) { if (!dir.mkpath(dirName)) { qWarning("Could not create '%s' dir in '%s'", qPrintable(m_themePath), qPrintable(dirName)); continue; } } QString pixPath = QString("%1/%2/%3.png") .arg(m_themePath).arg(dirName).arg(key); if (!pix.save(pixPath, "png")) { qWarning("Could not save icon as '%s'", qPrintable(pixPath)); } } m_cacheKeys << key; // Touch the theme path: GTK icon loading system checks the mtime of the // dir to decide whether it should look for new icons in the theme dir. // // Note: We do not use QDateTime::currentDateTime() as the new time because // if the icon is updated in less than one second, GTK won't notice it. // See https://bugs.launchpad.net/sni-qt/+bug/812884 QFileInfo info(m_themePath); QDateTime mtime = info.lastModified(); FsUtils::touch(m_themePath, mtime.addSecs(1)); } #include ./src/dbusimage.cpp0000644000004100000410000000535113035734364014512 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Qt #include #include #include #include #include // libc #include QDBusArgument& operator<<(QDBusArgument& argument, const DBusImage& image) { argument.beginStructure(); argument << image.width << image.height << image.pixels; argument.endStructure(); return argument; } const QDBusArgument& operator>>(const QDBusArgument& argument, DBusImage& image) { argument.beginStructure(); argument >> image.width >> image.height >> image.pixels; argument.endStructure(); return argument; } DBusImageList DBusImage::createListFromIcon(const QIcon& icon) { if (icon.isNull()) { qWarning("qt-sni: DBusImage::createListFromIcon() icon is null"); return DBusImageList(); } DBusImageList list; QList sizes = icon.availableSizes(); if (sizes.isEmpty()) { // sizes can be empty if icon is an SVG. In this case generate images for a few sizes #define SIZE(x) QSize(x, x) sizes << SIZE(16) << SIZE(22) << SIZE(24) << SIZE(32) << SIZE(48) ; #undef SIZE } Q_FOREACH(const QSize& size, sizes) { list << createFromPixmap(icon.pixmap(size)); } return list; } DBusImage DBusImage::createFromPixmap(const QPixmap& pixmap) { QImage image = pixmap.toImage().convertToFormat(QImage::Format_ARGB32); DBusImage dbusImage; dbusImage.width = pixmap.width(); dbusImage.height = pixmap.height(); dbusImage.pixels.resize(dbusImage.width * dbusImage.height * 4); quint32* dstPtr = reinterpret_cast(dbusImage.pixels.data()); for (int y = 0; y < dbusImage.height; ++y) { const quint32* srcPtr = reinterpret_cast(image.constScanLine(y)); const quint32* srcEnd = srcPtr + dbusImage.width; for (; srcPtr != srcEnd; ++srcPtr, ++dstPtr) { *dstPtr = htonl(*srcPtr); } } return dbusImage; } ./src/statusnotifieritem.cpp0000644000004100000410000002237313035734364016517 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include "statusnotifieritem.h" // Local #include #include #include #include // dbusmenu-qt #include // Qt #include #include #include #include #include #include #include #include #include #if defined(Q_WS_X11) #include #endif static const char* SNI_CATEGORY_PROPERTY = "_sni_qt_category"; static const char* DEFAULT_CATEGORY = "ApplicationStatus"; static const char* NOTIFICATION_INTERFACE = "org.freedesktop.Notifications"; static const char* NOTIFICATION_SERVICE = "org.freedesktop.Notifications"; static const char* NOTIFICATION_PATH = "/org/freedesktop/Notifications"; void registerMetaTypes() { static bool registered = false; if (registered) { return; } qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); } StatusNotifierItem::StatusNotifierItem(QSystemTrayIcon* icon, IconCache* iconCache) : QAbstractSystemTrayIconSys(icon) , m_iconCache(iconCache) , m_activateAction(0) , m_placeholderMenu(new QMenu) { SNI_VAR(this); registerMetaTypes(); static int id = 1; m_serviceName = QString("org.kde.StatusNotifierItem-%1-%2").arg(QCoreApplication::applicationPid()).arg(id++); SNI_VAR(m_serviceName); m_objectPath = QString("/StatusNotifierItem"); SNI_VAR(m_objectPath); new StatusNotifierItemAdaptor(this); QDBusConnection bus = QDBusConnection::sessionBus(); bus.registerService(m_serviceName); bus.registerObject(m_objectPath, this, QDBusConnection::ExportAdaptors); updateMenu(); } StatusNotifierItem::~StatusNotifierItem() { SNI_VAR(this); QDBusConnection bus = QDBusConnection::sessionBus(); bus.unregisterObject(m_objectPath, QDBusConnection::UnregisterTree); bus.unregisterService(m_serviceName); // m_dbusMenuExporter is a child of the menu it exports, so we need to use // a QWeakPointer to track it: // // - If StatusNotifierItem is deleted before menu, we must delete the // exporter (otherwise we can't associate another exporter to it) // // - If the menu is deleted before StatusNotifierItem, then the exporter // will already be gone when we reach this point. delete m_dbusMenuExporter.data(); delete m_placeholderMenu; } QRect StatusNotifierItem::geometry() const { return QRect(); } void StatusNotifierItem::updateVisibility() { SNI_DEBUG << "NewStatus(" << status() << ")"; NewStatus(status()); } void StatusNotifierItem::updateIcon() { SNI_DEBUG; NewIcon(); // ToolTip contains the icon NewToolTip(); } void StatusNotifierItem::updateToolTip() { SNI_DEBUG; NewToolTip(); } void StatusNotifierItem::updateMenu() { // Delete any exporter which could be attached to a previous menu delete m_dbusMenuExporter.data(); QMenu* menu = trayIcon->contextMenu(); SNI_VAR(menu); if (!menu) { // A SNI *must* expose a valid menu. If there is none yet, expose a // placeholder. // See: https://bugs.launchpad.net/ubuntu/+source/hplip/+bug/860395 menu = m_placeholderMenu; } connect(menu, SIGNAL(aboutToShow()), SLOT(slotAboutToShow())); m_dbusMenuExporter = new DBusMenuExporter(menuObjectPath(), menu); } void StatusNotifierItem::showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon icon, int msecs) { SNI_DEBUG << title << message; QString iconString; switch (icon) { case QSystemTrayIcon::NoIcon: break; case QSystemTrayIcon::Information: iconString = "dialog-information"; break; case QSystemTrayIcon::Warning: iconString = "dialog-warning"; break; case QSystemTrayIcon::Critical: iconString = "dialog-error"; break; } QDBusInterface iface(NOTIFICATION_SERVICE, NOTIFICATION_PATH, NOTIFICATION_INTERFACE); iface.asyncCall("Notify", id(), quint32(0), // replaces_id iconString, title, message, QStringList(), // actions QVariantMap(), // hints msecs ); } void StatusNotifierItem::Activate(int, int) { SNI_DEBUG; sendActivatedByTrigger(); } void StatusNotifierItem::ContextMenu(int, int) { SNI_DEBUG; } void StatusNotifierItem::Scroll(int delta, const QString& orientationString) { SNI_DEBUG << "delta=" << delta << "orientationString=" << orientationString; QPoint globalPos = QCursor::pos(); QPoint pos; Qt::Orientation orientation = orientationString == "horizontal" ? Qt::Horizontal : Qt::Vertical; QWheelEvent event(pos, globalPos, delta, Qt::NoButton, Qt::NoModifier, orientation); QApplication::sendEvent(trayIcon, &event); } void StatusNotifierItem::SecondaryActivate(int, int) { SNI_DEBUG; sendActivated(QSystemTrayIcon::MiddleClick); } QString StatusNotifierItem::iconThemePath() const { return m_iconCache->themePath(trayIcon->icon()); } QString StatusNotifierItem::iconName() const { QIcon icon = trayIcon->icon(); if (icon.isNull()) { return QString(); } QString name = icon.name(); if (!name.isEmpty()) { return name; } return m_iconCache->nameForIcon(icon); } QString StatusNotifierItem::serviceName() const { return m_serviceName; } QString StatusNotifierItem::objectPath() const { return m_objectPath; } QString StatusNotifierItem::id() const { return QCoreApplication::applicationFilePath().section('/', -1); } QString StatusNotifierItem::title() const { QString title = QCoreApplication::applicationName(); return title.isEmpty() ? id() : title; } QDBusObjectPath StatusNotifierItem::menu() const { return m_dbusMenuExporter ? QDBusObjectPath(menuObjectPath()) : QDBusObjectPath("/invalid"); } QString StatusNotifierItem::menuObjectPath() const { return objectPath() + "/menu"; } QString StatusNotifierItem::category() const { static QStringList validCategories = QStringList() << "ApplicationStatus" << "Communications" << "SystemServices" << "Hardware" ; QVariant value = trayIcon->property(SNI_CATEGORY_PROPERTY); if (!value.canConvert()) { return DEFAULT_CATEGORY; } QString category = value.toString(); if (!validCategories.contains(category)) { SNI_WARNING << category << "is not a valid value for the" << SNI_CATEGORY_PROPERTY << "property. Valid values are:" << validCategories.join(", ") ; } return category; } QString StatusNotifierItem::status() const { return trayIcon->isVisible() ? "Active" : "Passive"; } DBusToolTip StatusNotifierItem::toolTip() const { DBusToolTip tip; tip.iconName = iconName(); tip.title = trayIcon->toolTip(); return tip; } void StatusNotifierItem::sendActivatedByTrigger() { #if defined(Q_WS_X11) // Workarounds LP: #627195 if (QString::fromUtf8(getenv("XDG_CURRENT_DESKTOP")).split(':').contains("Unity")) { QX11Info::setAppUserTime(0); } #endif sendActivated(QSystemTrayIcon::Trigger); } void StatusNotifierItem::slotAboutToShow() { SNI_DEBUG; if (!m_activateAction) { if (Settings::needsActivateAction()) { SNI_INFO << "Adding an \"Activate\" entry to the StatusNotifierItem context menu"; // Hack: reuse an existing Qt translation so we don't have to add // translations ourself. Note that we use QTranslator without // installing it to ensure we do not trigger any unwanted side-effect // in the application. QTranslator translator; translator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); QString text = translator.translate("QApplication", "Activate"); if (text.isEmpty()) { // QTranslator::translate() does not fallback, do it ourself text = "Activate"; } m_activateAction = new QAction(this); m_activateAction->setText(text); connect(m_activateAction, SIGNAL(triggered(bool)), SLOT(sendActivatedByTrigger())); } } if (!m_activateAction) { return; } QMenu* menu = qobject_cast(sender()); SNI_RETURN_IF_FAIL(menu); if (menu->actions().first() != m_activateAction) { menu->insertAction(menu->actions().first(), m_activateAction); } } #include ./src/statusnotifieritem.h0000644000004100000410000000723213035734364016161 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef STATUSNOTIFIERITEM_H #define STATUSNOTIFIERITEM_H // Local #include #include #include // Qt #include #include class QAction; class QDBusObjectPath; class DBusMenuExporter; class IconCache; class StatusNotifierItem : public QObject, public QAbstractSystemTrayIconSys { Q_OBJECT Q_PROPERTY(QString Category READ category) Q_PROPERTY(QString Id READ id) Q_PROPERTY(QString Title READ title) Q_PROPERTY(QString Status READ status) Q_PROPERTY(quint32 WindowId READ windowId) Q_PROPERTY(QString IconThemePath READ iconThemePath) Q_PROPERTY(QString IconName READ iconName) Q_PROPERTY(DBusImageList IconPixmap READ iconPixmap) Q_PROPERTY(QString OverlayIconName READ overlayIconName) Q_PROPERTY(DBusImageList OverlayIconPixmap READ overlayIconPixmap) Q_PROPERTY(QString AttentionIconName READ attentionIconName) Q_PROPERTY(DBusImageList AttentionIconPixmap READ attentionIconPixmap) Q_PROPERTY(QString AttentionMovieName READ attentionMovieName) Q_PROPERTY(DBusToolTip ToolTip READ toolTip) Q_PROPERTY(QDBusObjectPath Menu READ menu) public: StatusNotifierItem(QSystemTrayIcon*, IconCache*); ~StatusNotifierItem(); QString serviceName() const; QString objectPath() const; // QAbstractSystemTrayIconSys QRect geometry() const; void updateVisibility(); void updateIcon(); void updateToolTip(); void updateMenu(); void showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon icon, int msecs); /// QAbstractSystemTrayIconSys // StatusNotifierItem void Activate(int, int); void ContextMenu(int, int); void Scroll(int, const QString&); void SecondaryActivate(int, int); QString category() const; QString id() const; QString title() const; QString status() const; quint32 windowId() const { return 0; } QString iconThemePath() const; QString iconName() const; DBusImageList iconPixmap() const { return DBusImageList(); } QString overlayIconName() const { return QString(); } DBusImageList overlayIconPixmap() const { return DBusImageList(); } QString attentionIconName() const { return QString(); } DBusImageList attentionIconPixmap() const { return DBusImageList(); } QString attentionMovieName() const { return QString(); } DBusToolTip toolTip() const; QDBusObjectPath menu() const; Q_SIGNALS: void NewStatus(const QString &status); void NewIcon(); void NewToolTip(); // /StatusNotifierItem private Q_SLOTS: void slotAboutToShow(); void sendActivatedByTrigger(); private: QString m_serviceName; QString m_objectPath; IconCache* m_iconCache; QWeakPointer m_dbusMenuExporter; QAction* m_activateAction; QMenu* m_placeholderMenu; QString menuObjectPath() const; }; #endif // STATUSNOTIFIERITEM_H ./src/dbustooltip.h0000644000004100000410000000222013035734364014557 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef DBUSTOOLTIP_H #define DBUSTOOLTIP_H #include // Qt #include class QDBusArgument; struct DBusToolTip { QString iconName; DBusImageList iconPixmap; QString title; QString description; }; Q_DECLARE_METATYPE(DBusToolTip) QDBusArgument& operator<<(QDBusArgument&, const DBusToolTip&); const QDBusArgument& operator>>(const QDBusArgument&, DBusToolTip&); #endif /* DBUSTOOLTIP_H */ ./src/dbusimage.h0000644000004100000410000000246613035734364014163 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef DBUSIMAGE_H #define DBUSIMAGE_H // Qt #include #include #include class QDBusArgument; struct DBusImage; typedef QList DBusImageList; Q_DECLARE_METATYPE(DBusImageList) struct DBusImage { int width; int height; QByteArray pixels; static DBusImage createFromPixmap(const QPixmap&); static DBusImageList createListFromIcon(const QIcon&); }; Q_DECLARE_METATYPE(DBusImage) QDBusArgument& operator<<(QDBusArgument&, const DBusImage&); const QDBusArgument& operator>>(const QDBusArgument&, DBusImage&); #endif /* DBUSIMAGE_H */ ./src/settings.cpp0000644000004100000410000000277613035734364014422 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Qt #include #include namespace Settings { static bool s_initialized = false; static bool s_needsActivateAction; static bool s_debug; static void init() { if (s_initialized) { return; } QSettings settings("sni-qt"); QString binaryName = QCoreApplication::applicationFilePath().section("/", -1); QString key = QString("need-activate-action/%1").arg(binaryName); s_needsActivateAction = settings.value(key).toBool(); // Keys without a group name are picked from the "general" group s_debug = settings.value("debug").toBool(); s_initialized = true; } bool needsActivateAction() { init(); return s_needsActivateAction; } bool debug() { init(); return s_debug; } } // namespace./src/org.kde.StatusNotifierItem.xml0000644000004100000410000000600713035734364017721 0ustar www-datawww-data ./src/iconcache.h0000644000004100000410000000301013035734364014121 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef ICONCACHE_H #define ICONCACHE_H // Qt #include #include #include class QIcon; /** * This class will save pixmaps from icons in a temporary dir on the disk, * making it possible to pass filenames for icons without names. */ class IconCache : public QObject { Q_OBJECT public: IconCache(const QString& baseDir, QObject* parent=0); static const int MaxIconCount; QString themePath(const QIcon& icon = QIcon()) const; QString nameForIcon(const QIcon& icon) const; // Internal, testing only QStringList cacheKeys() const { return m_cacheKeys; } private: QString m_themePath; mutable QStringList m_cacheKeys; void cacheIcon(const QString& key, const QIcon&) const; void trimCache() const; }; #endif /* ICONCACHE_H */ ./src/statusnotifieritemfactory.cpp0000644000004100000410000001137113035734364020103 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Local #include #include #include #include // Qt #include #include #include #include #include #include #include static const char *SNW_SERVICE = "org.kde.StatusNotifierWatcher"; static const char *SNW_IFACE = "org.kde.StatusNotifierWatcher"; static const char *SNW_PATH = "/StatusNotifierWatcher"; StatusNotifierItemFactory::StatusNotifierItemFactory() : m_iconCache(0) , m_isAvailable(false) { QString tempSubDir = QString("sni-qt_%1_%2") .arg(QCoreApplication::applicationFilePath().section('/', -1)) .arg(QCoreApplication::applicationPid()); m_iconCacheDir = FsUtils::generateTempDir(tempSubDir); if (m_iconCacheDir.isEmpty()) { SNI_WARNING << "Failed to create temp dir for icon cache, not starting sni-qt."; return; } SNI_VAR(m_iconCacheDir); m_iconCache = new IconCache(m_iconCacheDir, this); QDBusServiceWatcher* snwWatcher = new QDBusServiceWatcher(this); snwWatcher->addWatchedService(SNW_SERVICE); connect(snwWatcher, SIGNAL(serviceOwnerChanged(const QString&, const QString&, const QString&)), SLOT(slotSnwOwnerChanged(const QString&, const QString&, const QString&))); snwWatcher->setConnection(QDBusConnection::sessionBus()); connectToSnw(); } StatusNotifierItemFactory::~StatusNotifierItemFactory() { SNI_DEBUG; if (!m_iconCacheDir.isEmpty()) { FsUtils::recursiveRm(m_iconCacheDir); } } void StatusNotifierItemFactory::connectToSnw() { SNI_DEBUG; m_isAvailable = false; QDBusInterface snw(SNW_SERVICE, SNW_PATH, SNW_IFACE); if (!snw.isValid()) { SNI_WARNING << "Invalid interface to SNW_SERVICE"; return; } QDBusConnection bus = QDBusConnection::sessionBus(); bus.connect(SNW_SERVICE, SNW_PATH, SNW_IFACE, "StatusNotifierHostRegistered", "", this, SLOT(slotHostRegisteredWithSnw())); // FIXME: Make this async? QVariant value = snw.property("IsStatusNotifierHostRegistered"); if (!value.canConvert()) { SNI_WARNING << "IsStatusNotifierHostRegistered returned something which is not a bool:" << value; return; } m_isAvailable = value.toBool(); SNI_VAR(m_isAvailable); Q_FOREACH(StatusNotifierItem* item, m_items) { registerItem(item); } } QAbstractSystemTrayIconSys *StatusNotifierItemFactory::create(QSystemTrayIcon *trayIcon) { SNI_DEBUG; StatusNotifierItem* item = new StatusNotifierItem(trayIcon, m_iconCache); connect(item, SIGNAL(destroyed(QObject*)), SLOT(slotItemDestroyed(QObject*))); m_items.insert(item); registerItem(item); return item; } bool StatusNotifierItemFactory::isAvailable() const { return m_isAvailable; } void StatusNotifierItemFactory::slotSnwOwnerChanged(const QString&, const QString& oldOwner, const QString& newOwner) { SNI_DEBUG << "oldOwner" << oldOwner << "newOwner" << newOwner; bool oldAvailable = m_isAvailable; if (newOwner.isEmpty()) { m_isAvailable = false; } else { connectToSnw(); } if (oldAvailable != m_isAvailable) { SNI_DEBUG << "Emitting availableChanged(" << m_isAvailable << ")"; availableChanged(m_isAvailable); } } void StatusNotifierItemFactory::slotHostRegisteredWithSnw() { SNI_DEBUG; if (!m_isAvailable) { m_isAvailable = true; SNI_DEBUG << "Emitting availableChanged(true)"; availableChanged(m_isAvailable); } } void StatusNotifierItemFactory::slotItemDestroyed(QObject* obj) { SNI_DEBUG; m_items.remove(static_cast(obj)); } void StatusNotifierItemFactory::registerItem(StatusNotifierItem* item) { SNI_DEBUG; QDBusInterface snw(SNW_SERVICE, SNW_PATH, SNW_IFACE); snw.asyncCall("RegisterStatusNotifierItem", item->serviceName()); } Q_EXPORT_PLUGIN2(statusnotifieritem, StatusNotifierItemFactory) #include ./COPYING.LGPL-2.10000644000004100000410000006364213035734364013354 0ustar www-datawww-data GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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) any later version. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ./RELEASE_CHECK_LIST0000644000004100000410000000062213035734364014006 0ustar www-datawww-data# Verify copy is clean and up to date bzr st bzr pull # Update NEWS vi NEWS r!bzr log --line -r tag:x.y.z-1.. # Bump version number in CMakeLists.txt vi CMakeLists.txt # Commit bzr ci # Create and test tarball make distcheck # Run manual tests view tests/manual/TESTS # If ok, create tag tag=x.y.z bzr tag $tag # Push bzr push # Upload tarball lp-project-upload sni-qt $tag sni-qt-$tag.tar.bz2 ./sni-qt.kdev40000644000004100000410000000005713035734364013427 0ustar www-datawww-data[Project] Manager=KDevCMakeManager Name=sni-qt ./tests/0000755000004100000410000000000013035734364012415 5ustar www-datawww-data./tests/auto/0000755000004100000410000000000013035734373013365 5ustar www-datawww-data./tests/auto/CMakeLists.txt0000644000004100000410000000217613035734364016133 0ustar www-datawww-data# Macros to create "check" target macro(add_test_executable _test) set(_src ${ARGN}) qt4_generate_moc(${_test}.cpp ${_test}.moc) qt4_automoc(${_src}) add_executable(${_test} ${_test}.cpp ${_test}.moc ${_src} ${SRC_DIR}/debug.cpp ${SRC_DIR}/settings.cpp ${test_RC}) target_link_libraries(${_test} ${test_LIBRARIES}) add_test(${_test} ${_test}) add_dependencies(check ${_test}) endmacro(add_test_executable) add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND} --verbose) qt4_add_resources(test_RC test.qrc) set(SRC_DIR "${CMAKE_SOURCE_DIR}/src") include_directories( ${SRC_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${QT_INCLUDE_DIR} ${QT_QTCORE_INCLUDE_DIR} ${QT_QTGUI_INCLUDE_DIR} ${QT_QTTEST_INCLUDE_DIR} ${QT_QTDBUS_INCLUDE_DIR} ) set(test_LIBRARIES ${QT_QTGUI_LIBRARY} ${QT_QTCORE_LIBRARY} ${QT_QTDBUS_LIBRARY} ${QT_QTTEST_LIBRARY} dbusmenu-qt ) enable_testing() add_test_executable(dbusimagetest ${SRC_DIR}/dbusimage.cpp) add_test_executable(fsutilstest ${SRC_DIR}/fsutils.cpp) add_test_executable(iconcachetest ${SRC_DIR}/iconcache.cpp ${SRC_DIR}/fsutils.cpp) ./tests/auto/images/0000755000004100000410000000000013035734364014632 5ustar www-datawww-data./tests/auto/images/trash.svg0000644000004100000410000000610013035734364016471 0ustar www-datawww-data Keep Tidy Inside symbol bin signs_and_symbols clean rubish trash inside garbage sign Martin Owens Martin Owens Martin Owens image/svg+xml en ./tests/auto/images/heart.svg0000644000004100000410000000744113035734364016464 0ustar www-datawww-data Heart Left-Highlight This is a normal valentines day heart. holiday valentines valentine hash(0x8a091c0) hash(0x8a0916c) signs_and_symbols hash(0x8a091f0) day Jon Phillips Jon Phillips Jon Phillips image/svg+xml en ./tests/auto/images/bad.svg0000644000004100000410000000645713035734364016115 0ustar www-datawww-data Irritant produit chimique symbol signs_and_symbols yves GUILLOU yves GUILLOU yves GUILLOU image/svg+xml en ./tests/auto/iconcachetest.cpp0000644000004100000410000001375213035734364016715 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ // Local #include #include // Qt #include #include #include #include #include #include #include static QImage createTestImage(int size, const QColor& color) { QImage img(size, size, QImage::Format_ARGB32); QPainter painter(&img); painter.setPen(color.darker()); painter.setBrush(color); painter.drawRect(img.rect().adjusted(0, 0, -1, -1)); return img; } static QIcon createTestIcon(const QList& sizes, const QColor& color) { QIcon icon; Q_FOREACH(int size, sizes) { QImage image = createTestImage(size, color); icon.addPixmap(QPixmap::fromImage(image)); } return icon; } class IconCacheTest : public QObject { Q_OBJECT private Q_SLOTS: void init() { QDir dir = QDir::current(); m_sandBoxDirName = dir.path() + "/sandbox"; dir.mkdir("sandbox"); } void cleanup() { FsUtils::recursiveRm(m_sandBoxDirName); } void testThemePath() { IconCache cache(m_sandBoxDirName); QString themePath = cache.themePath(); QCOMPARE(themePath, m_sandBoxDirName + "/icons"); QFileInfo info(themePath); QVERIFY(info.isDir()); } void testThemePathForIcon() { QList sizes = QList() << 16 << 22 << 32; QIcon icon = createTestIcon(sizes, Qt::red); IconCache cache(m_sandBoxDirName); QString themePath = cache.themePath(icon); QCOMPARE(themePath, m_sandBoxDirName + "/icons"); QFileInfo info(themePath); QVERIFY(info.isDir()); } void testThemePathForThemedIcons() { IconCache cache(m_sandBoxDirName); QIcon icon = QIcon::fromTheme("indicator-messages"); QString themePath = cache.themePath(icon); if (icon.name().isEmpty()) { QSKIP("Icon has not been found in theme, so there's nothing to test here", SkipSingle); } QCOMPARE(themePath, QDir::homePath() + "/.local/share/icons"); } void testPixmapIcon() { IconCache cache(m_sandBoxDirName); QList sizes = QList() << 16 << 22 << 32; QIcon icon = createTestIcon(sizes, Qt::red); QString name = cache.nameForIcon(icon); Q_FOREACH(int size, sizes) { QString dirName = cache.themePath(icon) + QString("/hicolor/%1x%1/apps").arg(size); QVERIFY(QFile::exists(dirName)); QImage image; QVERIFY(image.load(dirName + "/" + name + ".png")); } } void testTrimCache() { IconCache cache(m_sandBoxDirName); // Create more icons than cache can hold QList sizes = QList() << 16 << 22 << 32; const int extraCount = 4; const int count = IconCache::MaxIconCount + extraCount; QStringList createdIconNames; for (int idx = 0; idx < count; ++idx) { QColor color = QColor::fromHsvF(double(idx) / count, 1., 1.); QIcon icon = createTestIcon(sizes, color); createdIconNames << cache.nameForIcon(icon); } // Create a QSet of the names which should still be there QSet expectedRemainingNames; auto it = createdIconNames.begin() + extraCount; for (; it != createdIconNames.end(); ++it) { expectedRemainingNames << *it + ".png"; } // For each size, check the remaining icons are expectedRemainingNames Q_FOREACH(int size, sizes) { QString dirName = cache.themePath() + QString("/hicolor/%1x%1/apps").arg(size); QVERIFY(QFile::exists(dirName)); QDir dir(dirName); dir.setFilter(QDir::Files); QSet remainingNames = dir.entryList().toSet(); QCOMPARE(remainingNames.count(), IconCache::MaxIconCount); QCOMPARE(remainingNames, expectedRemainingNames); } } void testCacheOrder() { IconCache cache(m_sandBoxDirName); QList sizes = QList() << 16 << 22 << 32; QIcon icon1 = createTestIcon(sizes, Qt::red); QIcon icon2 = createTestIcon(sizes, Qt::green); QIcon icon3 = createTestIcon(sizes, Qt::blue); cache.nameForIcon(icon1); cache.nameForIcon(icon2); cache.nameForIcon(icon3); // cacheKeysBefore should contains keys for icon1, icon2, icon3 QStringList cacheKeysBefore = cache.cacheKeys(); // Access icon1, this should place icon1 at the end of cacheKeys, ie: // icon2, icon3, icon1 cache.nameForIcon(icon1); QStringList expectedCacheKeys = cacheKeysBefore; expectedCacheKeys << expectedCacheKeys.takeFirst(); // Check the result QCOMPARE(cache.cacheKeys(), expectedCacheKeys); } void testDetectDuplicatedImages() { IconCache cache(m_sandBoxDirName); QList sizes = QList() << 16 << 22 << 32; QIcon icon1 = createTestIcon(sizes, Qt::red); QIcon icon2 = createTestIcon(sizes, Qt::red); QString icon1Name = cache.nameForIcon(icon1); QString icon2Name = cache.nameForIcon(icon2); QCOMPARE(icon1Name, icon2Name); } private: QString m_sandBoxDirName; }; QTEST_MAIN(IconCacheTest) #include ./tests/auto/test.qrc0000644000004100000410000000025613035734364015056 0ustar www-datawww-data images/bad.svg images/heart.svg images/trash.svg ./tests/auto/fsutilstest.cpp0000644000004100000410000000673513035734373016475 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ // Local #include // Qt #include #include #include #include #include #include // libc #include static void createEmptyFile(const QString& name) { QFile file(name); QVERIFY(file.open(QIODevice::WriteOnly)); file.close(); QVERIFY(QFile::exists(name)); } class FsUtilsTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase() { m_baseDirName = QDir::currentPath(); } void init() { QDir::setCurrent(m_baseDirName); m_sandBoxDirName = m_baseDirName + "/sandbox"; setenv("XDG_RUNTIME_DIR", m_sandBoxDirName.toLocal8Bit().constData(), 1 /*overwrite*/); setenv("TMPDIR", m_sandBoxDirName.toLocal8Bit().constData(), 1 /*overwrite*/); } void cleanup() { QProcess::execute("/bin/rm", QStringList() << "-r" << m_sandBoxDirName); } void testGenerateTempDir() { QString prefix = "fsutilstest"; QString dirName = FsUtils::generateTempDir(prefix); QFileInfo info(dirName); QVERIFY(info.exists()); QVERIFY(info.isDir()); QVERIFY(info.isAbsolute()); QVERIFY(info.fileName().startsWith(prefix + "-")); } void testRecursiveRm() { QDir dir(m_sandBoxDirName); QVERIFY(dir.mkpath("dir/dir1")); QVERIFY(dir.mkpath("dir/dir2")); QVERIFY(dir.mkpath("dir/.hiddendir")); QString testDir = dir.path() + "/dir"; createEmptyFile(testDir + "/dir1/f1"); createEmptyFile(testDir + "/dir2/f2"); createEmptyFile(testDir + "/dir2/.hidden"); createEmptyFile(testDir + "/.hiddendir/f1"); createEmptyFile(testDir + "/.hiddendir/.hidden"); QVERIFY(FsUtils::recursiveRm(testDir)); QVERIFY(!QFile::exists(testDir)); } void testRecursiveRmEmptyDir() { // Calling recursiveRm() with an empty QString should not do anything // https://bugs.launchpad.net/sni-qt/+bug/874447 QDir dir(m_sandBoxDirName); dir.mkpath("dir"); QString testDir = dir.path() + "/dir"; QVERIFY(QDir::setCurrent(testDir)); QVERIFY(!FsUtils::recursiveRm(QString())); QVERIFY(QFile::exists(testDir)); } void testTouch() { QDir dir(m_sandBoxDirName); dir.mkpath("."); QString testFile = dir.path() + "/test"; createEmptyFile(testFile); QFileInfo info(testFile); QDateTime mtime = info.lastModified(); QVERIFY(FsUtils::touch(testFile, mtime.addSecs(1))); info.refresh(); QVERIFY(mtime.msecsTo(info.lastModified()) == 1000); } private: QString m_baseDirName; QString m_sandBoxDirName; }; QTEST_MAIN(FsUtilsTest) #include ./tests/auto/dbusimagetest.cpp0000644000004100000410000000621613035734364016736 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ // Qt #include // Local #include // Qt #include #include #include // libc #include static QImage qImageFromDBusImage(const DBusImage& dbusImage) { QImage img(dbusImage.width, dbusImage.height, QImage::Format_ARGB32); const quint32* srcPtr = reinterpret_cast(dbusImage.pixels.constData()); for (int y = 0; y < dbusImage.height; ++y) { quint32* dstPtr = reinterpret_cast(img.scanLine(y)); quint32* dstEnd = dstPtr + dbusImage.width; for (; dstPtr != dstEnd; ++dstPtr, ++srcPtr) { *dstPtr = ntohl(*srcPtr); } } return img; } static QImage createTestImage(int width, int height) { QImage img(width, height, QImage::Format_ARGB32); QPainter painter(&img); painter.setPen(Qt::blue); painter.setBrush(Qt::green); painter.drawRect(img.rect().adjusted(0, 0, -1, -1)); return img; } class DBusImageTest : public QObject { Q_OBJECT private Q_SLOTS: void testFromPixmap() { QImage src = createTestImage(16, 16); QPixmap pixmap = QPixmap::fromImage(src); DBusImage dbusImage = DBusImage::createFromPixmap(pixmap); QCOMPARE(dbusImage.width, src.width()); QCOMPARE(dbusImage.height, src.height()); QImage result = qImageFromDBusImage(dbusImage); QCOMPARE(result, src); } void testListFromIcon() { QIcon icon; QImage src16 = createTestImage(16, 16); QImage src22 = createTestImage(22, 22); icon.addPixmap(QPixmap::fromImage(src16)); icon.addPixmap(QPixmap::fromImage(src22)); DBusImageList list = DBusImage::createListFromIcon(icon); QCOMPARE(list.count(), 2); QImage result16 = qImageFromDBusImage(list[0]); QImage result22 = qImageFromDBusImage(list[1]); if (list[0].width == 22) { qSwap(result16, result22); } QCOMPARE(src16, result16); QCOMPARE(src22, result22); } void testListFromSvgIcon() { QIcon icon(":/images/heart.svg"); DBusImageList list = DBusImage::createListFromIcon(icon); QCOMPARE(list.count(), 5); QCOMPARE(list[0].width, 16); QCOMPARE(list[1].width, 22); QCOMPARE(list[2].width, 24); QCOMPARE(list[3].width, 32); QCOMPARE(list[4].width, 48); } }; QTEST_MAIN(DBusImageTest) #include ./tests/manual/0000755000004100000410000000000013035734364013672 5ustar www-datawww-data./tests/manual/CMakeLists.txt0000644000004100000410000000127213035734364016434 0ustar www-datawww-dataproject(systray) include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${QT_INCLUDE_DIR} ${QT_QTCORE_INCLUDE_DIR} ${QT_QTGUI_INCLUDE_DIR} ) qt4_add_resources(tests_RC systray.qrc) # systray set(systray_SRCS main.cpp window.cpp ) qt4_automoc(${systray_SRCS}) add_executable(systray ${systray_SRCS} ${tests_RC}) target_link_libraries(systray ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY} ) # delayedmenu set(delayedmenu_SRCS delayedmenu.cpp) qt4_automoc(${delayedmenu_SRCS}) add_executable(delayedmenu ${delayedmenu_SRCS} ${tests_RC}) target_link_libraries(delayedmenu ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY} ) ./tests/manual/window.cpp0000644000004100000410000002435213035734364015713 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "window.h" #include #include #include //! [0] Window::Window() { iconAnimationTimeLine = new QTimeLine(1000, this); iconAnimationTimeLine->setLoopCount(0); iconAnimationTimeLine->setUpdateInterval(200); iconAnimationTimeLine->setCurveShape(QTimeLine::LinearCurve); connect(iconAnimationTimeLine, SIGNAL(valueChanged(qreal)), SLOT(updateAnimatedIcon())); createIconGroupBox(); createMessageGroupBox(); iconLabel->setMinimumWidth(durationLabel->sizeHint().width()); createActions(); createTrayIcon(); connect(showMessageButton, SIGNAL(clicked()), this, SLOT(showMessage())); connect(showIconCheckBox, SIGNAL(toggled(bool)), trayIcon, SLOT(setVisible(bool))); connect(iconComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setIconFromComboBox(int))); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(iconGroupBox); mainLayout->addWidget(messageGroupBox); setLayout(mainLayout); iconComboBox->setCurrentIndex(1); trayIcon->show(); setWindowTitle(tr("Systray")); resize(400, 300); } //! [0] //! [1] void Window::setVisible(bool visible) { minimizeAction->setEnabled(visible); maximizeAction->setEnabled(!isMaximized()); restoreAction->setEnabled(isMaximized() || !visible); QDialog::setVisible(visible); } //! [1] //! [3] void Window::setIconFromComboBox(int index) { QIcon icon = iconComboBox->itemIcon(index); if (icon.isNull()) { iconAnimationTimeLine->start(); } else { iconAnimationTimeLine->stop(); setIcon(icon); } trayIcon->setToolTip(iconComboBox->itemText(index)); } void Window::setIcon(const QIcon& icon) { trayIcon->setIcon(icon); } void Window::updateAnimatedIcon() { QPixmap pixmap(22, 22); pixmap.fill(Qt::transparent); { QPainter painter(&pixmap); painter.setRenderHint(QPainter::Antialiasing); painter.setBrush(Qt::white); qreal radius = pixmap.width() / 4. - 1; qreal angle = iconAnimationTimeLine->currentValue() * 2 * M_PI; qreal cx = pixmap.width() / 2 + radius * cos(angle); qreal cy = pixmap.height() / 2 + radius * sin(angle); painter.drawEllipse(QPointF(cx, cy), radius, radius); } setIcon(pixmap); } //! [4] void Window::iconActivated(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Trigger: case QSystemTrayIcon::DoubleClick: iconComboBox->setCurrentIndex((iconComboBox->currentIndex() + 1) % iconComboBox->count()); break; case QSystemTrayIcon::MiddleClick: QMessageBox::information(this, QString(), tr("Middle clicked")); break; default: ; } } //! [4] //! [5] void Window::showMessage() { QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon( typeComboBox->itemData(typeComboBox->currentIndex()).toInt()); trayIcon->showMessage(titleEdit->text(), bodyEdit->toPlainText(), icon, durationSpinBox->value() * 1000); } //! [5] void Window::createIconGroupBox() { iconGroupBox = new QGroupBox(tr("Tray Icon")); iconLabel = new QLabel("Icon:"); iconComboBox = new QComboBox; iconComboBox->addItem(QIcon(":/images/bad.svg"), tr("Bad")); iconComboBox->addItem(QIcon(":/images/heart.svg"), tr("Heart")); iconComboBox->addItem(QIcon(":/images/trash.svg"), tr("Trash")); iconComboBox->addItem(QIcon::fromTheme("system-file-manager"), tr("File Manager")); iconComboBox->addItem(tr("Generated")); showIconCheckBox = new QCheckBox(tr("Show icon")); showIconCheckBox->setChecked(true); #if defined(Q_WS_X11) jitToolTipCheckBox = new QCheckBox(tr("Just In Time Tooltip")); #endif QHBoxLayout *iconLayout = new QHBoxLayout; iconLayout->addWidget(iconLabel); iconLayout->addWidget(iconComboBox); iconLayout->addStretch(); iconLayout->addWidget(showIconCheckBox); #if defined(Q_WS_X11) iconLayout->addWidget(jitToolTipCheckBox); #endif iconGroupBox->setLayout(iconLayout); } void Window::createMessageGroupBox() { messageGroupBox = new QGroupBox(tr("Balloon Message")); typeLabel = new QLabel(tr("Type:")); typeComboBox = new QComboBox; typeComboBox->addItem(tr("None"), QSystemTrayIcon::NoIcon); typeComboBox->addItem(style()->standardIcon( QStyle::SP_MessageBoxInformation), tr("Information"), QSystemTrayIcon::Information); typeComboBox->addItem(style()->standardIcon( QStyle::SP_MessageBoxWarning), tr("Warning"), QSystemTrayIcon::Warning); typeComboBox->addItem(style()->standardIcon( QStyle::SP_MessageBoxCritical), tr("Critical"), QSystemTrayIcon::Critical); typeComboBox->setCurrentIndex(1); durationLabel = new QLabel(tr("Duration:")); durationSpinBox = new QSpinBox; durationSpinBox->setRange(5, 60); durationSpinBox->setSuffix(" s"); durationSpinBox->setValue(15); durationWarningLabel = new QLabel(tr("(some systems might ignore this " "hint)")); durationWarningLabel->setIndent(10); titleLabel = new QLabel(tr("Title:")); titleEdit = new QLineEdit(tr("Incoming message")); bodyLabel = new QLabel(tr("Body:")); bodyEdit = new QTextEdit; bodyEdit->setPlainText(tr("John Doe is connected")); showMessageButton = new QPushButton(tr("Show Message")); showMessageButton->setDefault(true); QGridLayout *messageLayout = new QGridLayout; messageLayout->addWidget(typeLabel, 0, 0); messageLayout->addWidget(typeComboBox, 0, 1, 1, 2); messageLayout->addWidget(durationLabel, 1, 0); messageLayout->addWidget(durationSpinBox, 1, 1); messageLayout->addWidget(durationWarningLabel, 1, 2, 1, 3); messageLayout->addWidget(titleLabel, 2, 0); messageLayout->addWidget(titleEdit, 2, 1, 1, 4); messageLayout->addWidget(bodyLabel, 3, 0); messageLayout->addWidget(bodyEdit, 3, 1, 2, 4); messageLayout->addWidget(showMessageButton, 5, 4); messageLayout->setColumnStretch(3, 1); messageLayout->setRowStretch(4, 1); messageGroupBox->setLayout(messageLayout); } void Window::createActions() { minimizeAction = new QAction(tr("Mi&nimize"), this); connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); maximizeAction = new QAction(tr("Ma&ximize"), this); connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized())); restoreAction = new QAction(tr("&Restore"), this); connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal())); quitAction = new QAction(tr("&Quit"), this); quitAction->setIcon(QIcon::fromTheme("application-exit")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void Window::createTrayIcon() { trayIconMenu = new QMenu(this); trayIconMenu->addAction(minimizeAction); trayIconMenu->addAction(maximizeAction); trayIconMenu->addAction(restoreAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); trayIcon = new QSystemTrayIcon(this); QByteArray category = qgetenv("SNI_CATEGORY"); if (!category.isEmpty()) { trayIcon->setProperty("_sni_qt_category", QString::fromLocal8Bit(category)); } trayIcon->setContextMenu(trayIconMenu); #if defined(Q_WS_X11) trayIcon->installEventFilter(this); #endif } #if defined(Q_WS_X11) bool Window::eventFilter(QObject *, QEvent *event) { switch(event->type()) { case QEvent::ToolTip: if (jitToolTipCheckBox->isChecked()) { QString timeString = QTime::currentTime().toString(); trayIcon->setToolTip(tr("Current Time: %1").arg(timeString)); } break; case QEvent::Wheel: { QWheelEvent *wheelEvent = static_cast(event); int delta = wheelEvent->delta() > 0 ? 1 : -1; int index = qBound(0, iconComboBox->currentIndex() + delta, iconComboBox->count() - 1); iconComboBox->setCurrentIndex(index); break; } default: break; } return false; } #endif #include ./tests/manual/delayedmenu.h0000644000004100000410000000177013035734364016344 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #ifndef DELAYEDMENU_H #define DELAYEDMENU_H #include class QSystemTrayIcon; class DelayedMenuApp : public QObject { Q_OBJECT public: DelayedMenuApp(); private Q_SLOTS: void setMenu(); private: QSystemTrayIcon* m_sti; }; #endif /* DELAYEDMENU_H */ ./tests/manual/window.h0000644000004100000410000000702113035734364015352 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef WINDOW_H #define WINDOW_H #include #include QT_BEGIN_NAMESPACE class QAction; class QCheckBox; class QComboBox; class QGroupBox; class QLabel; class QLineEdit; class QMenu; class QPushButton; class QSpinBox; class QTextEdit; class QTimeLine; QT_END_NAMESPACE //! [0] class Window : public QDialog { Q_OBJECT public: Window(); void setVisible(bool visible); protected: #if defined(Q_WS_X11) bool eventFilter(QObject *object, QEvent *event); #endif private slots: void setIconFromComboBox(int index); void iconActivated(QSystemTrayIcon::ActivationReason reason); void showMessage(); void updateAnimatedIcon(); private: void createIconGroupBox(); void createMessageGroupBox(); void createActions(); void createTrayIcon(); void setIcon(const QIcon&); QGroupBox *iconGroupBox; QLabel *iconLabel; QComboBox *iconComboBox; QCheckBox *showIconCheckBox; #if defined(Q_WS_X11) QCheckBox *jitToolTipCheckBox; #endif QGroupBox *messageGroupBox; QLabel *typeLabel; QLabel *durationLabel; QLabel *durationWarningLabel; QLabel *titleLabel; QLabel *bodyLabel; QComboBox *typeComboBox; QSpinBox *durationSpinBox; QLineEdit *titleEdit; QTextEdit *bodyEdit; QPushButton *showMessageButton; QAction *minimizeAction; QAction *maximizeAction; QAction *restoreAction; QAction *quitAction; QSystemTrayIcon *trayIcon; QMenu *trayIconMenu; QTimeLine *iconAnimationTimeLine; }; //! [0] #endif ./tests/manual/delayedmenu.cpp0000644000004100000410000000256713035734364016704 0ustar www-datawww-data/* This file is part of the sni-qt project Copyright 2011 Canonical Author: Aurelien Gateau sni-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; version 3 of the License. sni-qt 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 sni-qt. If not, see . */ #include // Qt #include #include #include #include #include #include DelayedMenuApp::DelayedMenuApp() : m_sti(new QSystemTrayIcon(this)) { m_sti->setIcon(QIcon(":/images/bad.svg")); m_sti->show(); QTimer::singleShot(500, this, SLOT(setMenu())); } void DelayedMenuApp::setMenu() { qDebug() << "Setting menu"; QMenu* menu = new QMenu; menu->addAction("Quit", qApp, SLOT(quit())); m_sti->setContextMenu(menu); } int main(int argc, char** argv) { QApplication app(argc, argv); DelayedMenuApp dmApp; return app.exec(); } #include ./tests/manual/images/0000755000004100000410000000000013035734364015137 5ustar www-datawww-data./tests/manual/images/trash.svg0000644000004100000410000000610013035734364016776 0ustar www-datawww-data Keep Tidy Inside symbol bin signs_and_symbols clean rubish trash inside garbage sign Martin Owens Martin Owens Martin Owens image/svg+xml en ./tests/manual/images/heart.svg0000644000004100000410000000744113035734364016771 0ustar www-datawww-data Heart Left-Highlight This is a normal valentines day heart. holiday valentines valentine hash(0x8a091c0) hash(0x8a0916c) signs_and_symbols hash(0x8a091f0) day Jon Phillips Jon Phillips Jon Phillips image/svg+xml en ./tests/manual/images/bad.svg0000644000004100000410000000645713035734364016422 0ustar www-datawww-data Irritant produit chimique symbol signs_and_symbols yves GUILLOU yves GUILLOU yves GUILLOU image/svg+xml en ./tests/manual/main.cpp0000644000004100000410000000473213035734364015330 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include #include "window.h" int main(int argc, char *argv[]) { Q_INIT_RESOURCE(systray); QApplication app(argc, argv); if (!QSystemTrayIcon::isSystemTrayAvailable()) { QMessageBox::critical(0, QObject::tr("Systray"), QObject::tr("I couldn't detect any system tray " "on this system.")); return 1; } Window window; window.show(); return app.exec(); } ./tests/manual/TESTS0000644000004100000410000000427513035734364014527 0ustar www-datawww-data# Setup - Unity-based SNI host (unity-2d-panel + unity-panel-service or unity 3d) or KDE SNI host (plasma-desktop with systemtray applet) - Started systray test program => heart icon shows in host # Icon support ## changeIcon - Change icon to "Trash" (svg based) => host shows trash icon - Change icon to "File Manager" (name based) => host shows file manager icon - Change icon to "Generated" (dynamic icon) => host shows rotating circle ## changeStatus - Uncheck "Show icon" => host hides icon - Check "Show icon" => host brings back icon # Tooltip support [KDE only] ## changeTooltip - Mouse over SNI icon in SNI host => tooltip appears containing bigger heart icon and "Heart" text - Change icon to "Trash" and mouse over SNI icon => tooltip now contains trash icon and "Trash" text # Mouse support ## showMenu - Trigger menu action (left or right click on unity-panel, right click on plasmoid) => menu shows with following content: - Minimize - Maximize - Restore (disabled) - ---- - Quit - Select Quit => systray test program stops, icons disappear from hosts ## scroll - Scroll with mouse wheel over icon => icon changes ## activate [KDE only] - Left click on icon => icon changes from Heart to Trash ## secondaryActivate [KDE only] - Middle click on icon => message box appears # Notifications ## showNotification - For each "Ballon Message" type: - Click the "Show Message" button => FDO notification appears with icon matching the type combobox # Robustness ## handleSnwRestart - Restart process implementing StatusNotifierWatcher (killall indicator-application-service for Unity, killall kded4 for KDE) => Icon reappears in hosts - Click icon => menu appears - Select Quit => test program exits # ActivateAction - Edit "~/.config/sni-qt.conf", set "need-activate-action/systray" to 1 - Start systray - Click icon => menu appears, with an "Activate" entry - Click "Activate" => icon changes from Heart to trash - Edit "~/.config/sni-qt.conf", set "need-activate-action/systray" to 0 - Restart systray - Click icon => menu appears, without "Activate" entry # DelayedMenu (BUG 860395) - Start delayedmenu test program - Wait for the "Setting menu" message - Click icon => a one-item menu appears ./tests/manual/systray.qrc0000644000004100000410000000025613035734364016122 0ustar www-datawww-data images/bad.svg images/heart.svg images/trash.svg ./release.sh0000755000004100000410000000070513035734364013234 0ustar www-datawww-data#!/bin/sh set -e PROJECT=sni-qt die() { echo "ERROR: $*" >&2 exit 1 } usage() { echo "$0" exit 1 } tag=$(awk 'NR == 1 { print $2 }' ../NEWS) echo -n "Found version '$tag'. Continue? (y/n) " read answer if [ "$answer" != "y" ] ; then die "Cancelled" fi tarball=$PROJECT-$tag.tar.bz2 [ -e $tarball ] || die "'$tarball' does not exist" set -v bzr tag $tag bzr push lp-project-upload $PROJECT $tag $tarball "" /dev/null /dev/null