aboutsummaryrefslogtreecommitdiffstats
path: root/desktop/companion/Companion.qml
blob: 7f740a327a5de05c17aaa91940793dc99cbc8b7b (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// 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.

import Quickshell
import Quickshell.Io
import Quickshell.Wayland
import Quickshell.Hyprland
import QtQuick
import ".."
import "../NotifyConfig.js" as NC
import "Mood.js" as Mood
import "Lines.js" as Lines

// The desktop companion: a chibi 2B in the bottom-right corner of the
// focused monitor. Inputs and timers live here, the decision in Mood.js,
// the drawing in Figure.qml. See README.md here and
// docs/superpowers/specs/2026-10-23-companion-design.md.
PanelWindow {
    id: root

    required property var asst

    readonly property string art: Quickshell.env("HOME") + "/.local/share/keystone/companion/2b/frames"

    // SUPER+\, through the IPC below.
    property bool present: true

    // The monitor she is on trails the focused one: a change plays her exit
    // here first, and only then moves the window (settled, below).
    readonly property string focused: Hyprland.focusedMonitor?.name ?? ""
    property string here: ""
    property bool hopping: false
    onFocusedChanged: {
        if (root.here === "") root.here = root.focused;
        else if (root.focused !== root.here) root.hopping = true;
    }
    Component.onCompleted: root.here = root.focused

    screen: Quickshell.screens.find(s => s.name === root.here) ?? Quickshell.screens[0]
    anchors { right: true; bottom: true }
    margins { right: 24; bottom: 16 }
    implicitWidth: 760
    implicitHeight: 260
    color: "transparent"
    exclusionMode: ExclusionMode.Ignore
    WlrLayershell.layer: WlrLayer.Top
    WlrLayershell.namespace: "keystone-companion"
    WlrLayershell.keyboardFocus: WlrKeyboardFocus.None
    // Her body only: clicks anywhere else, the bubble included, reach the
    // window below. Out of view the region is empty.
    mask: Region { item: hit }

    // --- inputs ---------------------------------------------------------

    property double now: Date.now()
    Timer { interval: 200; repeat: true; running: root.present; onTriggered: root.now = Date.now() }

    property var clicks: ({ count: 0, at: 0 })
    property double destructAt: 0
    property bool dodging: false
    property double repliedAt: 0
    property double mockAt: 0
    property double typingAt: 0
    property double wakeAt: 0
    property double lastLineAt: 0
    property double lastMonologueAt: 0
    property bool monologue: false

    // Bored, yawning, lying down at 1, 3 and 5 minutes. Inhibitors count,
    // so presentation mode keeps her awake. enabled is set explicitly: left
    // out, it read false on creation.
    IdleMonitor { id: idle1; enabled: true; respectInhibitors: true; timeout: 60 }
    IdleMonitor { id: idle2; enabled: true; respectInhibitors: true; timeout: 180 }
    IdleMonitor { id: idle3; enabled: true; respectInhibitors: true; timeout: 300 }
    readonly property int idle: idle3.isIdle ? 3 : idle2.isIdle ? 2 : idle1.isIdle ? 1 : 0
    property int wasIdle: 0
    onIdleChanged: {
        const t = Date.now();
        if (root.idle === 0 && root.wasIdle > 0) {
            root.wakeAt = t;
            root.say("wake");
        } else if (root.idle === 1 && root.wasIdle === 0) {
            if (Mood.monologue("bored", root.lastMonologueAt, t, Math.random())) root.startMonologue();
            else root.say("bored");
        }
        root.wasIdle = root.idle;
    }

    // 2 is real fullscreen; 1 is maximised, which is most windows here and
    // must not hide her. lastIpcObject is only current after a refresh, and
    // the island measured that it settles a moment after the event.
    property int fullscreen: 0
    Timer {
        id: fsSettle
        interval: 60
        onTriggered: root.fullscreen = Hyprland.activeToplevel?.lastIpcObject?.fullscreen ?? 0
    }

    Connections {
        target: Hyprland
        function onRawEvent(event) {
            if (event.name === "custom") {
                // From hypr-theme's sections/companion.lua.
                const what = event.data.trim();
                const t = Date.now();
                if (what === "keystone-typing") {
                    root.typingAt = t;
                } else if (what === "keystone-delete") {
                    root.typingAt = t;
                    if (Mood.mockAllowed(root.mockAt, t)) {
                        root.mockAt = t;
                        root.say("mock");
                    }
                }
            } else if (["fullscreen", "activewindowv2", "workspacev2"].includes(event.name)) {
                Hyprland.refreshToplevels();
                fsSettle.restart();
            }
        }
    }

    Connections {
        target: root.asst
        function onReplied() {
            root.repliedAt = Date.now();
            root.say("ready");
        }
    }

    // Balloons stack bottom-right of their screen. When that is her corner,
    // any balloon on screen shoves her left past the stack.
    readonly property bool shoved: {
        const place = Notify.config.balloons;
        if (place.screen !== root.here || place.corner !== "bottom-right") return false;
        return (Notify.queue || []).some(n => NC.shown(Notify.config, n, Notify.dnd,
            Notify.drawerOpen, Notify.snoozeUntil, root.now));
    }
    onShovedChanged: if (root.shoved) root.say("shoved")

    // --- state ----------------------------------------------------------

    readonly property var mood: Mood.pick({
        now: root.now, destructAt: root.destructAt, dodging: root.dodging, shoved: root.shoved,
        recording: root.asst.recording, busy: root.asst.busy, repliedAt: root.repliedAt,
        clicks: root.clicks, mockAt: root.mockAt, typingAt: root.typingAt, wakeAt: root.wakeAt,
        monologue: root.monologue, idle: root.idle,
    })
    readonly property string outfit: Mood.outfit(root.destructAt, root.now)
    // Anything above the monologue cuts it short.
    onMoodChanged: if (root.monologue && root.mood.state !== "muse") root.stopMonologue()

    // Hidden: no sprite, no bubble. Away adds the dodge, which hides the
    // sprite but lets its line show.
    readonly property bool hidden: !root.present || root.fullscreen === 2 || root.hopping
    readonly property bool away: root.hidden || root.dodging

    // --- speech ---------------------------------------------------------

    function say(kind, force) {
        const t = Date.now();
        if (root.hidden || (!force && !Mood.canSpeak(root.lastLineAt, t))) return;
        const line = Lines.pick(kind, Math.random());
        if (line === "") return;
        root.lastLineAt = t;
        bubble.show(line, 3000);
    }

    // The opening monologue: about 15 characters a second, one sentence
    // per bubble, 1.5 s between sentences, the last held 4 s.
    property int monoLine: 0
    function startMonologue() {
        if (root.hidden) return;
        root.monologue = true;
        root.lastMonologueAt = Date.now();
        root.lastLineAt = root.lastMonologueAt;
        root.monoLine = 0;
        typer.begin(Lines.monologue[0]);
    }
    function stopMonologue() {
        root.monologue = false;
        typer.stop();
        typerHold.stop();
        bubble.hide();
    }
    Timer {
        id: typer
        property string full: ""
        interval: 66
        repeat: true
        function begin(text) { typer.full = text; bubble.typed(""); typer.restart(); }
        onTriggered: {
            const n = bubble.text.length + 1;
            bubble.typed(typer.full.slice(0, n));
            if (n < typer.full.length) return;
            typer.stop();
            typerHold.interval = root.monoLine === Lines.monologue.length - 1 ? 4000 : 1500;
            typerHold.restart();
        }
    }
    Timer {
        id: typerHold
        onTriggered: {
            root.monoLine++;
            if (root.monoLine >= Lines.monologue.length) root.stopMonologue();
            else typer.begin(Lines.monologue[root.monoLine]);
        }
    }

    // --- clicks and the dodge -------------------------------------------

    function clicked() {
        const t = Date.now();
        root.now = t;
        root.clicks = Mood.click(root.clicks, t);
        if (root.clicks.count >= 7) {
            root.clicks = { count: 0, at: 0 };
            root.stopMonologue();
            root.destructAt = t;
            sprite.explode();
            root.say("destruct", true);
            aftermath.restart();
        } else if (root.clicks.count === 1) {
            root.say("click", true);
        } else if (root.clicks.count === 4) {
            root.say("blush", true);
        }
    }
    Timer { id: aftermath; interval: Mood.T.destruct + 400; onTriggered: root.say("aftermath", true) }

    // She cannot see the pointer coming, only feel it on her: Quickshell has
    // no global pointer and Hyprland sends no motion events. A click before
    // the 0.6 s still reaches her.
    Timer {
        id: hover
        interval: 600
        onTriggered: {
            if (Math.random() < 0.5) root.say("dodge");
            root.dodging = true;
            dodgeBack.restart();
        }
    }
    Timer { id: dodgeBack; interval: 5000; onTriggered: root.dodging = false }

    // --- showing and hiding ----------------------------------------------

    function appear() {
        if (root.present) return;
        root.present = true;
        root.destructAt = 0;          // the skirt is back
        root.now = Date.now();
        greet.restart();
    }
    function dismiss() {
        if (!root.present) return;
        root.stopMonologue();
        bubble.hide();
        root.present = false;
    }
    // After the drop-in has landed.
    Timer {
        id: greet
        interval: 450
        onTriggered: {
            if (Mood.monologue("shown", root.lastMonologueAt, Date.now(), Math.random())) root.startMonologue();
            else root.say("shown", true);
        }
    }

    //   qs -p <desktop> ipc call companion toggle     -> SUPER+\
    IpcHandler {
        target: "companion"
        function toggle() { if (root.present) root.dismiss(); else root.appear(); }
        function show() { root.appear(); }
        function hide() { root.dismiss(); }
    }

    // The exit has played on the old monitor: move, and the entrance plays.
    function settled(out) {
        if (out && root.hopping) {
            root.here = root.focused;
            root.hopping = false;
        }
    }

    // --- drawing --------------------------------------------------------

    // Where she stands: the bottom-right of the window, or left of the
    // balloon stack. 336 = the stack's 340 px plus its 12 px margin
    // (notifications/Balloons.qml), minus this window's 24 px right margin,
    // plus 8 px of air.
    Item {
        id: seat
        width: sprite.width
        height: sprite.height
        anchors.bottom: parent.bottom
        x: root.width - width - (root.shoved ? 336 : 0)
        Behavior on x { NumberAnimation { duration: 260; easing.type: Easing.OutCubic } }
    }

    Figure {
        id: sprite
        x: seat.x
        y: seat.y
        source: `file://${root.art}/${root.outfit}/${root.mood.frame}.png`
        fallback: `file://${root.art}/${root.outfit}/base.png`
        out: root.away
        onSettled: out => root.settled(out)
    }

    Item {
        id: hit
        x: sprite.x
        y: sprite.y
        width: root.away ? 0 : sprite.width
        height: root.away ? 0 : sprite.height
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.PointingHandCursor
            onEntered: hover.restart()
            onExited: hover.stop()
            onClicked: { hover.stop(); root.clicked(); }
        }
    }

    // Up and to the left of her head, anchored to where she stands rather
    // than to the sprite, so a dodge line stays where she was.
    Rectangle {
        id: bubble
        property alias text: label.text
        function show(t, ms) { label.text = t; bubble.opacity = 1; hideTimer.interval = ms; hideTimer.restart(); }
        function typed(t) { label.text = t; bubble.opacity = 1; hideTimer.stop(); }
        function hide() { hideTimer.stop(); bubble.opacity = 0; }

        visible: !root.hidden && opacity > 0 && label.text !== ""
        anchors { right: seat.left; rightMargin: -14; bottom: seat.top; bottomMargin: -22 }
        width: Math.min(260, label.implicitWidth + 24)
        height: label.implicitHeight + 16
        radius: 12
        color: Qt.alpha(Theme.base, 0.92)
        border { width: 1; color: Qt.alpha(Theme.text, 0.25) }
        opacity: 0
        Behavior on opacity { NumberAnimation { duration: 180 } }

        Timer { id: hideTimer; onTriggered: bubble.opacity = 0 }

        Text {
            id: label
            anchors.centerIn: parent
            width: Math.min(236, implicitWidth)
            wrapMode: Text.WordWrap
            color: Theme.text
            font { family: Theme.fontFamily; pixelSize: 13 }
        }
        Rectangle {
            width: 10; height: 10; rotation: 45
            color: bubble.color
            anchors { right: parent.right; rightMargin: 18; bottom: parent.bottom; bottomMargin: -5 }
        }
    }
}