8000 Say inbox: another local program can hand Blink one line (off by default) by amy95031 · Pull Request #4 · Arthur031221/Blinkling · GitHub
[go: up one dir, main page]

Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions desktop/character/grumble.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { createGrumbler } from "./grumble.mjs";
import { strings, GRUMBLES } from "../renderer/strings.mjs";
import { LOCALES } from "../shared/i18n.mjs";
import { readFileSync } from "node:fs";

const make = (extra = {}) => createGrumbler({ count: 8, ...extra });

Expand Down Expand Up @@ -45,6 +46,50 @@ test("busy keeps Blink quiet and starts the minute again", () => {
assert.equal(g.tick(150_000, false), null);
});

test("kept busy, as with the switch in Settings off, Blink never says a line", () => {
const g = make({ random: () => 0 });
for (let at = 0; at <= 3_600_000; at += 1000)
assert.equal(g.tick(at, true), null, String(at));
});

test("turned off while a line is on show, the line goes at once and none follows", () => {
const g = make({ random: () => 0 });
assert.equal(g.tick(60_000, false), 0);
for (let at = 61_000; at <= 600_000; at += 1000)
assert.equal(g.tick(at, true), null, String(at));
// Turned on again, the quiet minute starts from that moment.
assert.equal(g.tick(659_000, false), null);
assert.equal(g.tick(660_000, false), 1);
});

test("the switch in Settings reaches the grumbler: stored, sent with the state, read every frame", () => {
const read = (file) => readFileSync(new URL(file, import.meta.url), "utf8");
const shell = read("../main/shell.mjs");
// Main reads the stored choice at start and hears a change from Settings.
assert.match(
shell,
/idleGrumble = settings\.store\.get\(\)\.idleGrumble !== false/,
);
assert.match(
shell,
/idleGrumbleChanged: \(on\) => \{\s*idleGrumble = on;\s*broadcast\(\);/,
);
// It goes to Blink's window in the state every window gets.
const snapshot = shell.slice(
shell.indexOf("const snapshot = () => ({"),
shell.indexOf("function motion("),
);
assert.match(snapshot, /^\s*idleGrumble,$/m);
// Off counts as busy, which is what keeps the grumbler quiet.
const renderer = read("../renderer/index.mjs");
const busy = renderer.slice(
renderer.indexOf("const busy ="),
renderer.indexOf("grumbler.tick(now, busy)"),
);
assert.ok(busy.length > 0, "the grumbler is ticked with busy");
assert.match(busy, /shell\.idleGrumble === false \|\|/);
});

test("a touch takes a shown line away and the quiet starts over", () => {
const g = make({ random: () => 0 });
assert.equal(g.tick(60_000, false), 0);
Expand Down
15 changes: 15 additions & 0 deletions desktop/main/ipc.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { validSayButton, validSayId } from "../say/message.mjs";

const types = new Set([
"state",
"drag",
Expand All @@ -9,6 +11,7 @@ const types = new Set([
"grumble",
"alert",
"swallowed",
"say-line",
]);
export function validCommand(command, bounds) {
if (command?.type === "drag-end" || command?.type === "glide-end")
Expand Down Expand Up @@ -55,6 +58,18 @@ export function validCommand(command, bounds) {
typeof command.value === "boolean" &&
Object.keys(command).every((k) => ["type", "value"].includes(k))
);
// How a line from the say inbox ended, as Blink's window saw it.
if (command.type === "say-line")
return (
validSayId(command.id) &&
["button", "dismissed", "timeout"].includes(command.result) &&
(command.result === "button"
? validSayButton(command.button)
: !("button" in command)) &&
Object.keys(command).every((k) =>
["type", "id", "result", "button"].includes(k),
)
);
if (command.type === "click")
return (
typeof command.permission === "boolean" &&
Expand Down
20 changes: 20 additions & 0 deletions desktop/main/ipc.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,26 @@ test("shell IPC admits only narrow gestures and boolean state, never arbitrary p
])
assert.equal(validCommand(c), false);
});
test("the end of a line from the say inbox is one of three outcomes and a safe button id", () => {
for (const c of [
{ type: "say-line", id: "dots-1", result: "dismissed" },
{ type: "say-line", id: "dots-1", result: "timeout" },
{ type: "say-line", id: "dots-1", result: "button", button: "mute_1h" },
])
assert.equal(validCommand(c), true, JSON.stringify(c));
for (const c of [
{ type: "say-line" },
{ type: "say-line", id: "dots-1" },
{ type: "say-line", id: "dots-1", result: "not_shown" },
{ type: "say-line", id: "dots-1", result: "button" },
{ type: "say-line", id: "dots-1", result: "button", button: "../x" },
{ type: "say-line", id: "dots-1", result: "dismissed", button: "ok" },
{ type: "say-line", id: "../dots", result: "dismissed" },
{ type: "say-line", id: 7, result: "dismissed" },
{ type: "say-line", id: "dots-1", result: "dismissed", text: "hello" },
])
assert.equal(validCommand(c), false, JSON.stringify(c));
});
test("input regions reject nonfinite, unbounded, fractional, oversized and empty rectangles", () => {
const b = { width: 500, height: 500 };
assert.equal(
Expand Down
72 changes: 72 additions & 0 deletions desktop/main/shell.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import { createGuideOffer, SAVE_ACTION } from "../guides/offer.mjs";
import { armHardQuitDeadline, armQuitWatchdog } from "./quit.mjs";
import { createQuitKey } from "./quit-key.mjs";
import { HotkeyStore } from "../capture/hotkey.mjs";
import { createSayInbox } from "../say/inbox.mjs";
let features;
const companionModule = new URL("../companion/host.mjs", import.meta.url);
const companionDirectory = existsSync(fileURLToPath(companionModule))
Expand Down Expand Up @@ -318,6 +319,7 @@ const snapshot = () => ({
chatFocused: !!composer && !composer.isDestroyed() && composer.isFocused(),
autoExplain,
costume: costumeWorn(),
idleGrumble,
debugHit: process.env.BLINKLING_DEBUG_HIT === "1",
theme: nativeTheme.shouldUseDarkColors ? "dark" : "light",
locale,
Expand Down Expand Up @@ -727,6 +729,55 @@ ipcMain.on("blinkling:regions", (event, value, parts = {}) => {
} else if (!drag && process.platform === "win32" && regions.length)
blink.setShape(shapeNow());
});
/** Lines other programs on this computer ask Blink to say (docs/SAY-INBOX.md).
* Off until the switch in Settings is turned on: only then do the two folders
* exist and get looked at. A line is plain text for Blink's own window and is
* never passed to a session. One line is up at a time. */
let sayLine = null;
/** Seconds the window gets, past the time on show, to say how the line ended. */
const SAY_GRACE = 5;
const sayHide = () => {
if (!blink.isDestroyed())
blink.webContents.send("blinkling:shell", { type: "say-line", line: null });
};
const sayEnd = (outcome) => {
if (!sayLine) return;
const { settle, timer } = sayLine;
sayLine = null;
clearTimeout(timer);
settle(outcome);
};
const sayInbox = createSayInbox({
directory: join(app.getPath("userData"), "say"),
show: (message) =>
new Promise((settle) => {
// Never over an open card, and never when Blink cannot be seen.
if (quitting || blink.isDestroyed() || !blink.isVisible() || chatOpen)
return settle({ result: "not_shown" });
// The window reports the end itself; this is for one that never does.
const longest = (message.ttl + SAY_GRACE) * 1000;
const timer = setTimeout(() => {
sayHide();
sayEnd({ result: "timeout" });
}, longest);
sayLine = { id: message.id, settle, timer };
blink.webContents.send("blinkling:shell", {
type: "say-line",
line: {
id: message.id,
text: message.text,
buttons: message.buttons,
ttl: message.ttl,
},
});
}),
});
const sayInboxChanged = (on) => {
if (on) return void sayInbox.start();
sayInbox.stop();
sayHide();
sayEnd({ result: "not_shown" });
};
ipcMain.handle("blinkling:shell", async (event, command) => {
if (!trusted(event) || !validCommand(command, blink.getBounds()))
throw new Error("Invalid shell command");
Expand Down Expand Up @@ -843,6 +894,15 @@ ipcMain.handle("blinkling:shell", async (event, command) => {
} else if (command.type === "fan-labels-seen") {
if (!fromBlink) throw new Error("Invalid fan label report");
uiOnce.take("fan-labels");
} else if (command.type === "say-line") {
if (!fromBlink) throw new Error("Invalid say report");
// Only the line that is up can end; a late or made-up report is dropped.
if (sayLine?.id === command.id)
sayEnd(
command.result === "button"
? { result: "button", button: command.button }
: { result: command.result },
);
}
broadcast();
return snapshot();
Expand Down Expand Up @@ -1162,6 +1222,8 @@ ipcMain.handle("blinkling:send", async (event, turn) => {
/** The costume switch in Settings: on, Blink wears the chosen model's piece and
* plays a scene when the model or the effort changes. */
let costumeEffects = true;
/** The idle chatter switch in Settings: off, Blink never thinks out loud. */
let idleGrumble = true;
/** The family whose piece Blink wears now, or null. */
const costumeWorn = () =>
costumeEffects
Expand Down Expand Up @@ -1684,13 +1746,20 @@ const settings = installSettings({
costumeEffects = on;
broadcast();
},
idleGrumbleChanged: (on) => {
idleGrumble = on;
broadcast();
},
sayInboxChanged,
languageChanged: (chosen) => {
locale = changeSystemLocale({ app, chosen });
broadcast();
},
},
});
costumeEffects = settings.store.get().costumeEffects !== false;
idleGrumble = settings.store.get().idleGrumble !== false;
if (settings.store.get().sayInbox === true) sayInboxChanged(true);
// The image viewer covers the display Blink is on; while it is up the machine
// knows, so Blink holds still behind it.
const viewer = installViewer({
Expand Down Expand Up @@ -1898,6 +1967,9 @@ app.on("before-quit", (event) => {
// The watchdog armed at the first request covers a stuck session or helper
// here and a quit that stalls after disposal.
features.dispose();
// A line still up is answered before the folders stop being looked at.
sayInbox.stop();
sayEnd({ result: "not_shown" });
// Blink waves goodbye while the rest shuts down.
const leaving = showsMotions && !quickQuit && blink.isVisible();
if (leaving) motion("leave");
Expand Down
5 changes: 5 additions & 0 deletions desktop/renderer/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
<button id="permission-close" type="button" hidden data-label="dismiss">
×
</button>
<div id="say" role="status" aria-live="polite" hidden>
<p id="say-text"></p>
<div id="say-buttons"></div>
<button id="say-close" type="button" data-label="dismiss">×</button>
</div>
<script type="module" src="./index.mjs"></script>
</body>
</html>
61 changes: 59 additions & 2 deletions desktop/renderer/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,44 @@ const grumbler = createGrumbler({ count: GRUMBLES });
const grumble = document.querySelector("#grumble");
let grumbling = null;
const status = document.querySelector("#status");
// A line another program asked Blink to say (docs/SAY-INBOX.md): plain text,
// up to three buttons and a close button, beside Blink like the idle thought.
const sayNode = document.querySelector("#say");
const sayText = document.querySelector("#say-text");
const sayButtons = document.querySelector("#say-buttons");
/** The line on show: its id and when its time is up. */
let saying = null;
/** Take the line away. With a result, main is told how it ended. */
function endSay(result, button) {
if (!saying) return;
const { id } = saying;
saying = null;
sayNode.hidden = true;
if (!result) return;
const report = { type: "say-line", id, result };
if (result === "button") report.button = button;
void api.shell(report).catch(() => {});
}
function startSay(line) {
endSay(null);
// Text from outside is only ever text.
sayText.textContent = line.text;
sayButtons.replaceChildren(
...line.buttons.map(({ id, label }) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.addEventListener("click", () => endSay("button", id));
return button;
}),
);
sayButtons.hidden = line.buttons.length === 0;
saying = { id: line.id, until: performance.now() + line.ttl * 1000 };
sayNode.hidden = false;
}
document
.querySelector("#say-close")
.addEventListener("click", () => endSay("dismissed"));
const mutter = createMutter({ node: document.querySelector("#mutter") });
const mutterNode = document.querySelector("#mutter");
// When each one-off motion last started. Main decides when one plays and sends
Expand Down Expand Up @@ -381,8 +419,12 @@ async function action(id) {
grumbling: grumbling !== null,
});
// Idle for a minute, Blink thinks out loud. Anything that keeps it busy
// or any use of the app starts the quiet again.
// or any use of the app starts the quiet again. With the switch in
// Settings off it never does, and a line on show goes away.
if (saying && now >= saying.until) endSay("timeout");
const busy =
shell.idleGrumble === false ||
saying !== null ||
session.expression !== "idle" ||
shell.chatOpen ||
!!shell.drag ||
Expand All @@ -404,6 +446,7 @@ async function action(id) {
status.dataset.shown === "true" ? placeStatus(status, current) : null,
],
[mutterNode, mutter.shown ? placeStatus(mutterNode, current) : null],
[sayNode, saying ? placeGrumble(sayNode) : null],
];
// The machine in main decides when the fan shows: after the pointer has
// rested on Blink, never over an open card.
Expand Down Expand Up @@ -440,6 +483,15 @@ async function action(id) {
...scanlines([roundedRect(x.x, x.y, x.width, x.height, 12)], size),
);
}
// The line's buttons take clicks, so its box is part of the click area.
const said = saying ? sayNode.getBoundingClientRect() : null;
if (said?.width > 0)
all.push(
...scanlines(
[roundedRect(said.x, said.y, said.width, said.height, 20)],
size,
),
);
hit = body;
if (shell.debugHit) {
hitOverlay ??= createHitOverlay(document.body);
Expand Down Expand Up @@ -473,6 +525,10 @@ api.onShell((event) => {
}
}
if (event.type === "picking") picking = event.on === true;
if (event.type === "say-line") {
if (event.line) startSay(event.line);
else endSay(null);
}
if (event.type === "motion") {
const now = performance.now() / 1000;
if (event.name === "leave") leaveAt = now;
Expand All @@ -499,7 +555,8 @@ api.onShell((event) => {
);
});
// A click on the background puts the progress bubble away; it stays away until
// that capture is over. The idle grumble is not part of this.
// that capture is over. The idle grumble is not part of this, and neither is a
// line from the say inbox: a click in some other app is not an answer to it.
let statusPutAway = false;
api.onEvent((event) => {
if (event.type === "bubbles-clear") {
Expand Down
Loading
0