PopupHandler.qml 12.2 KB
Newer Older
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/*
 * Copyright 2019 Kai Uwe Broulik <kde@privat.broulik.de>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License or (at your option) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

pragma Singleton
import QtQuick 2.8
import QtQuick.Layouts 1.1

import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as Components
import org.kde.kquickcontrolsaddons 2.0

import org.kde.notificationmanager 1.0 as NotificationManager

32 33
import ".."

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
34 35 36
QtObject {
    id: popupHandler

37 38 39 40
    // Some parts of the code rely on plasmoid.nativeInterface and since we're in a singleton here
    // this is named "plasmoid", TODO fix?
    property QtObject plasmoid: plasmoids[0]
    // all notification plasmoids
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
41 42
    property var plasmoids: []

43 44
    // This heuristic tries to find a suitable plasmoid to follow when placing popups
    function plasmoidScore(plasmoid) {
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
45 46 47 48
        if (!plasmoid) {
            return 0;
        }

49 50 51 52 53 54 55 56 57
        var score = 0;

        // Prefer plasmoids in a panel, prefer horizontal panels over vertical ones
        if (plasmoid.location === PlasmaCore.Types.LeftEdge
                || plasmoid.location === PlasmaCore.Types.RightEdge) {
            score += 1;
        } else if (plasmoid.location === PlasmaCore.Types.TopEdge
                   || plasmoid.location === PlasmaCore.Types.BottomEdge) {
            score += 2;
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
58
        }
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

        // Prefer iconified plasmoids
        if (!plasmoid.expanded) {
            ++score;
        }

        // Prefer plasmoids on primary screen
        if (plasmoid.nativeInterface && plasmoid.nativeInterface.isPrimaryScreen(plasmoid.screenGeometry)) {
            ++score;
        }

        return score;
    }

    property int popupLocation: {
        switch (notificationSettings.popupPosition) {
        // Auto-determine location based on plasmoid location
        case NotificationManager.Settings.NearWidget:
            if (!plasmoid) {
                return Qt.AlignBottom | Qt.AlignRight; // just in case
            }

            var alignment = 0;
            if (plasmoid.location === PlasmaCore.Types.LeftEdge) {
                alignment |= Qt.AlignLeft;
            } else {
                // would be nice to do plasmoid.compactRepresentationItem.mapToItem(null) and then
                // position the popups depending on the relative position within the panel
                alignment |= Qt.AlignRight;
            }
            if (plasmoid.location === PlasmaCore.Types.TopEdge) {
                alignment |= Qt.AlignTop;
            } else {
                alignment |= Qt.AlignBottom;
            }
            return alignment;

        case NotificationManager.Settings.TopLeft:
            return Qt.AlignTop | Qt.AlignLeft;
        case NotificationManager.Settings.TopCenter:
            return Qt.AlignTop | Qt.AlignHCenter;
        case NotificationManager.Settings.TopRight:
            return Qt.AlignTop | Qt.AlignRight;
        case NotificationManager.Settings.BottomLeft:
            return Qt.AlignBottom | Qt.AlignLeft;
        case NotificationManager.Settings.BottomCenter:
            return Qt.AlignBottom | Qt.AlignHCenter;
        case NotificationManager.Settings.BottomRight:
            return Qt.AlignBottom | Qt.AlignRight;
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
108 109 110 111 112 113 114 115 116
        }
    }

    // The raw width of the popup's content item, the Dialog itself adds some margins
    property int popupWidth: units.gridUnit * 18
    property int popupEdgeDistance: units.largeSpacing
    property int popupSpacing: units.largeSpacing

    // How much vertical screen real estate the notification popups may consume
117
    readonly property real popupMaximumScreenFill: 0.75
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
118 119 120 121 122 123 124 125 126

    property var screenRect: plasmoid.availableScreenRect

    onPopupLocationChanged: Qt.callLater(positionPopups)
    onScreenRectChanged: Qt.callLater(positionPopups)

    function adopt(plasmoid) {
        var newPlasmoids = plasmoids;
        newPlasmoids.push(plasmoid);
127 128 129 130 131 132 133 134 135 136 137 138 139
        newPlasmoids.sort(function (a, b) {
            var scoreA = plasmoidScore(a);
            var scoreB = plasmoidScore(b);
            // Sort descending by score
            if (scoreA < scoreB) {
                return 1;
            } else if (scoreA > scoreB) {
                return -1;
            } else {
                return 0;
            }
        });

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        popupHandler.plasmoids = newPlasmoids;
    }

    function positionPopups() {
        var rect = screenRect;
        if (!rect || rect.width <= 0 || rect.height <= 0) {
            return;
        }

        var y = screenRect.y;
        if (popupLocation & Qt.AlignBottom) {
            y += screenRect.height;
        } else {
            y += popupEdgeDistance;
        }

        var x = screenRect.x;
        if (popupLocation & Qt.AlignLeft) {
            x += popupEdgeDistance;
        }

        for (var i = 0; i < popupInstantiator.count; ++i) {
            var popup = popupInstantiator.objectAt(i);

            if (popupLocation & Qt.AlignHCenter) {
                popup.x = x + (screenRect.width - popup.width) / 2;
            } else if (popupLocation & Qt.AlignRight) {
                popup.x = screenRect.width - popupEdgeDistance - popup.width;
            } else {
                popup.x = x;
            }

            var delta = popupSpacing + popup.height;

            if (popupLocation & Qt.AlignTop) {
                popup.y = y;
                y += delta;
            } else {
                y -= delta;
                popup.y = y;
            }

182
            // don't let notifications take more than popupMaximumScreenFill of the screen
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
183 184 185 186 187 188 189 190 191
            var visible = true;
            if (i > 0) { // however always show at least one popup
                if (popupLocation & Qt.AlignTop) {
                    visible = (popup.y + popup.height < screenRect.y + (screenRect.height * popupMaximumScreenFill));
                } else {
                    visible = (popup.y > screenRect.y + (screenRect.height * (1 - popupMaximumScreenFill)));
                }
            }

192
            // TODO would be nice to hide popups when systray or panel controller is open
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
193 194 195 196
            popup.visible = visible;
        }
    }

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    property QtObject popupNotificationsModel: NotificationManager.Notifications {
        limit: Math.ceil(popupHandler.screenRect.height / (theme.mSize(theme.defaultFont).height * 4))
        showExpired: false
        showDismissed: false
        blacklistedDesktopEntries: notificationSettings.popupBlacklistedApplications
        blacklistedNotifyRcNames: notificationSettings.popupBlacklistedServices
        showJobs: notificationSettings.jobsInNotifications
        sortMode: NotificationManager.Notifications.SortByTypeAndUrgency
        groupMode: NotificationManager.Notifications.GroupDisabled
        urgencies: {
            var urgencies = NotificationManager.Notifications.NormalUrgency | NotificationManager.Notifications.CriticalUrgency;
            if (notificationSettings.lowPriorityPopups) {
                urgencies |=NotificationManager.Notifications.LowUrgency;
            }
            return urgencies;
        }
    }

    property QtObject notificationSettings: NotificationManager.Settings { }

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
217 218 219 220 221 222 223
    property Instantiator popupInstantiator: Instantiator {
        model: popupNotificationsModel
        delegate: NotificationPopup {
            notificationType: model.type

            applicationName: model.applicationName
            applicatonIconSource: model.applicationIconName
224
            deviceName: model.deviceName || ""
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
225 226 227 228 229 230 231 232

            time: model.updated || model.created

            configurable: model.configurable
            // For running jobs instead of offering a "close" button that might lead the user to
            // think that will cancel the job, we offer a "dismiss" button that hides it in the history
            dismissable: model.type === NotificationManager.Notifications.JobType
                && model.jobState !== NotificationManager.Notifications.JobStateStopped
233 234
            // TODO would be nice to be able to "pin" jobs when they autohide
                && notificationSettings.permanentJobPopups
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
235 236 237 238
            closable: model.type === NotificationManager.Notifications.NotificationType
                || model.jobState === NotificationManager.Notifications.JobStateStopped

            summary: model.summary
239
            body: model.body || ""
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
240 241 242
            icon: model.image || model.iconName
            hasDefaultAction: model.hasDefaultAction || false
            timeout: model.timeout
243
            defaultTimeout: notificationSettings.popupTimeout
244 245 246 247 248
            // When configured to not keep jobs open permanently, we autodismiss them after the standard timeout
            dismissTimeout: !notificationSettings.permanentJobPopups
                            && model.type === NotificationManager.Notifications.JobType
                            && model.jobState !== NotificationManager.Notifications.JobStateStopped
                            ? defaultTimeout : 0
249 250

            urls: model.urls || []
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264
            urgency: model.urgency

            jobState: model.jobState || 0
            percentage: model.percentage || 0
            error: model.error || 0
            errorText: model.errorText || ""
            suspendable: !!model.suspendable
            killable: !!model.killable
            jobDetails: model.jobDetails || null

            configureActionLabel: model.configureActionLabel || ""
            actionNames: model.actionNames
            actionLabels: model.actionLabels

265 266
            onExpired: popupNotificationsModel.expire(popupNotificationsModel.index(index, 0))
            onCloseClicked: popupNotificationsModel.close(popupNotificationsModel.index(index, 0))
267
            onDismissClicked: model.dismissed = true
268
            onConfigureClicked: popupNotificationsModel.configure(popupNotificationsModel.index(index, 0))
269 270 271 272 273 274 275 276
            onDefaultActionInvoked: {
                popupNotificationsModel.invokeDefaultAction(popupNotificationsModel.index(index, 0))
                popupNotificationsModel.close(popupNotificationsModel.index(index, 0))
            }
            onActionInvoked: {
                popupNotificationsModel.invokeAction(popupNotificationsModel.index(index, 0), actionName)
                popupNotificationsModel.close(popupNotificationsModel.index(index, 0))
            }
277 278 279 280
            onOpenUrl: {
                Qt.openUrlExternally(url);
                popupNotificationsModel.close(popupNotificationsModel.index(index, 0))
            }
281
            onFileActionInvoked: popupNotificationsModel.close(popupNotificationsModel.index(index, 0))
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
282

283 284 285
            onSuspendJobClicked: popupNotificationsModel.suspendJob(popupNotificationsModel.index(index, 0))
            onResumeJobClicked: popupNotificationsModel.resumeJob(popupNotificationsModel.index(index, 0))
            onKillJobClicked: popupNotificationsModel.killJob(popupNotificationsModel.index(index, 0))
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
286 287 288

            onHeightChanged: Qt.callLater(positionPopups)
            onWidthChanged: Qt.callLater(positionPopups)
289 290 291

            Component.onCompleted: {
                // Register apps that were seen spawning a popup so they can be configured later
292 293
                // Apps with notifyrc can already be configured anyway
                if (model.desktopEntry && !model.notifyRcName) {
294
                    notificationSettings.registerKnownApplication(model.desktopEntry);
295
                    notificationSettings.save();
296 297
                }
            }
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
298 299 300 301 302 303 304 305 306
        }
        onObjectAdded: {
            // also needed for it to correctly layout its contents
            object.visible = true;
            Qt.callLater(positionPopups)
        }
        onObjectRemoved: Qt.callLater(positionPopups)
    }
}