akanjs 3.2.0-rc.13 → 3.2.0-rc.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +1 -0
- package/CHANGELOG.md +9 -2
- package/package.json +1 -1
- package/server/akanApp.ts +1 -1
- package/server/gateway/gatewayRooms.ts +7 -0
- package/service/ipcTypes.ts +3 -1
- package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
- package/types/server/gateway/gatewayRooms.d.ts +3 -0
- package/types/service/ipcTypes.d.ts +6 -0
- package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
- package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +7 -4
- package/ui/Data/useViewModal.ts +10 -4
- package/vendor/@akanjs/native/CHANGELOG.md +2 -1
- package/vendor/@akanjs/native/native/desktop/src/external.rs +1 -1
- package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +240 -6
- package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +1 -1
- package/vendor/@akanjs/native/plugins/external-view/src/index.ts +7 -4
package/ARCHITECTURE.md
CHANGED
|
@@ -88,6 +88,7 @@ Declared in [service/ipcTypes.ts](service/ipcTypes.ts).
|
|
|
88
88
|
| `pubsub.publish` | `SolidPubSub` | `AkanApp` |
|
|
89
89
|
| `pubsub.deliver` | `GatewayRooms` | `SolidPubSub` |
|
|
90
90
|
| `pubsub.subscribe` | `SolidPubSub` | `AkanApp` |
|
|
91
|
+
| `pubsub.subscribed` | `GatewayRooms` | `SolidPubSub` |
|
|
91
92
|
| `pubsub.unsubscribe` | `SolidPubSub` | `AkanApp` |
|
|
92
93
|
| `pubsub.snapshot.request` | `GatewayRooms` | `SolidPubSub` |
|
|
93
94
|
| `pubsub.snapshot` | `SolidPubSub` | `AkanApp` |
|
package/CHANGELOG.md
CHANGED
|
@@ -115,6 +115,13 @@
|
|
|
115
115
|
|
|
116
116
|
**`Exception.<Status>.is(error)` type-checks.** `StatusException` now declares `is`, so `Exception.BadRequest.is(error)` narrows `error` to an `Exception` and checks its own class.
|
|
117
117
|
|
|
118
|
+
- d9f5ad5: Behind the gateway, a WebSocket subscribe is now acknowledged once the gateway routes the room to the replica that holds it. The gateway used to learn of the room in a message the replica sent without waiting, so an event or a live-list write handled by another replica right after the ack could reach the gateway first and be dropped.
|
|
119
|
+
|
|
120
|
+
- `SolidPubSub.joinRoom` sends its `pubsub.subscribe` with an `ack` number and resolves when the gateway answers `pubsub.subscribed`. A replica's messages reach the gateway in order, so the answer also covers the live models it reported before the subscribe.
|
|
121
|
+
- The wait ends after 3 s if the gateway does not answer, and at once on shutdown. A server that is not a gateway child (no `AKAN_CHILD_SOCKET`) does not wait: a solo server, a desktop one included.
|
|
122
|
+
|
|
123
|
+
No upgrade step is needed: `AkanIpcMessage` only gains the `pubsub.subscribed` message and an optional `ack` on `pubsub.subscribe`, and `SolidPubSub` an injected `behindGateway` flag it reads from the env.
|
|
124
|
+
|
|
118
125
|
- f314eba: A route guard gets a second argument, `{ path }`: the requested in-app path with its search, in the form `router.push` takes, on the server and in CSR (`undefined` while MCP lists a screen). `signedIn({ path })` from `@libs/shared/webkit` adds `?redirect=<path>` to the sign-in URL, and `signedIn("/login")` still works. Use `path` to build a redirect target only. It must never decide admission: CSR asks a guard again only when the route or an argument it declared changes.
|
|
119
126
|
- d6b3619: Every `Err` is now one class, `Err` from `akanjs/common`. That covers the one an app's or lib's `lib/dict` builds, the one `useClient` returns, `akanjs/dictionary`'s own, and an error restored off the wire. Each is that class typed with its own dictionary's keys, so `Err.is` and the status classes behave the same in the browser and on the server. `instanceof Err` holds within one copy of the module. A page bundle and the framework each carry one, so check across them with `Err.is`.
|
|
120
127
|
|
|
@@ -377,12 +384,12 @@
|
|
|
377
384
|
- **`merge<Model>` marks the open model loading under its own key.** It wrote a literal `modelLoading` key, so `<model>Loading` never showed the merge in flight and the state gained a stray key. The view modal now shows its loading state during a merge.
|
|
378
385
|
- **A failed model action ends the loading it started.** When `create<Model>`, `create<Model>InForm`, `update<Model>`, `update<Model>InForm`, `merge<Model>` or `view<Model>` fails, `<model>Loading` goes back to `false`; when `edit<Model>` fails, `<model>FormLoading` does. That also holds when the request succeeds but the write after it throws. Before, the flag stayed set and the view or edit modal stayed under its loading overlay.
|
|
379
386
|
- **A loading flag is cleared only by the action that set it last.** An action that another one overtook leaves the flag alone, even when both are on the same record. Before, a merge or update landing during a `view<Model>` of the same record showed that view as loaded early.
|
|
380
|
-
- **A model action no longer takes over what `view<Model>`, `edit<Model>` or `new<Model>` opened during its request.** A `Load.View` hydrating a record
|
|
387
|
+
- **A model action no longer takes over what `view<Model>`, `edit<Model>` or `new<Model>` opened during its request.** A `Load.View` hydrating a record, an edit modal filling its form from a page payload, and a list's view modal coming back after an edit opened from it closes or fails to load count as opens too; an app's own `st.set` of those keys does not.
|
|
381
388
|
- `merge<Model>`, `update<Model>` and `update<Model>InForm` write the answer as the open model only while that record is still open.
|
|
382
389
|
- Creates and updates leave the modal alone.
|
|
383
390
|
- `update<Model>InForm` and `create<Model>InForm` leave the form to an `edit<Model>`, a `new<Model>` or an edit modal's payload fill opened meanwhile. A `view<Model>` or a `Load.View` does not take the form, so the saved form is still reset and its draft dropped.
|
|
384
391
|
- A `view<Model>` or `edit<Model>` overtaken by a later one no longer lands its record over the later one.
|
|
385
|
-
- Before, a view of another record was replaced or closed when the write landed,
|
|
392
|
+
- Before, a view of another record was replaced or closed when the write landed, an edit opened during a save lost its form or closed, and when an edit opened from a list's view was closed while saving, or failed to load while another write was in flight, the view came back only for that write to close it.
|
|
386
393
|
- **A form opened under the same draft scope while `create<Model>InForm` or `update<Model>InForm` waits for the server opens without that draft**, so a second new form is not refilled with what the first is creating. The draft stays in storage until the request succeeds, so a reload during the save still restores it, and it is kept when the request fails. On success it is deleted only while it still holds the saved form, so a draft that a form opened meanwhile wrote is kept. A form holding an `undefined` value now compares equal to its stored draft, which drops that value; before, the saved form's own draft was kept and refilled the next new form. A draft discarded or reset during the save stays gone when the save fails. A draft write still pending when the save starts is written first.
|
|
387
394
|
- **A failed `view<Model>` or `edit<Model>` that is still the latest open closes its modal**, unless the modal already shows that record, as when a page payload seeded it. Before, the modal stayed open over the previous record.
|
|
388
395
|
|
package/package.json
CHANGED
package/server/akanApp.ts
CHANGED
|
@@ -255,7 +255,7 @@ export class AkanApp {
|
|
|
255
255
|
this.#rooms.deliverPubsub(idx, message);
|
|
256
256
|
return;
|
|
257
257
|
case "pubsub.subscribe":
|
|
258
|
-
this.#rooms.
|
|
258
|
+
this.#rooms.subscribe(idx, message);
|
|
259
259
|
return;
|
|
260
260
|
case "pubsub.unsubscribe":
|
|
261
261
|
this.#rooms.removeRoomMembership(idx, message.roomId, message.socketId);
|
|
@@ -52,6 +52,13 @@ export class GatewayRooms {
|
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
subscribe(childIdx: number, message: Extract<AkanIpcMessage, { type: "pubsub.subscribe" }>) {
|
|
56
|
+
this.addRoomMembership(childIdx, message.roomId, message.socketId);
|
|
57
|
+
const child = this.#children.get(childIdx);
|
|
58
|
+
if (child && message.ack !== undefined)
|
|
59
|
+
this.#children.send(child, { type: "pubsub.subscribed", ack: message.ack } satisfies AkanIpcMessage);
|
|
60
|
+
}
|
|
61
|
+
|
|
55
62
|
addRoomMembership(childIdx: number, roomId: string, socketId?: string) {
|
|
56
63
|
const roomChildren = this.#roomChildren.get(roomId) ?? new Set<number>();
|
|
57
64
|
roomChildren.add(childIdx);
|
package/service/ipcTypes.ts
CHANGED
|
@@ -149,7 +149,9 @@ export type AkanIpcMessage =
|
|
|
149
149
|
}
|
|
150
150
|
| { type: "pubsub.publish"; roomId: string; data: object | object[]; origin?: string }
|
|
151
151
|
| { type: "pubsub.deliver"; roomId: string; data: object | object[]; origin?: string }
|
|
152
|
-
| { type: "pubsub.subscribe"; roomId: string; socketId?: string; pid?: number }
|
|
152
|
+
| { type: "pubsub.subscribe"; roomId: string; socketId?: string; pid?: number; ack?: number }
|
|
153
|
+
/** Gateway → child: the subscribe carrying `ack`, and whatever the child sent before it, now route to the child. */
|
|
154
|
+
| { type: "pubsub.subscribed"; ack: number }
|
|
153
155
|
| { type: "pubsub.unsubscribe"; roomId: string; socketId?: string; pid?: number }
|
|
154
156
|
| { type: "pubsub.snapshot.request" }
|
|
155
157
|
| { type: "pubsub.snapshot"; rooms: string[]; liveModels?: string[]; pid?: number }
|
|
@@ -22,16 +22,33 @@ export class SolidPubSub
|
|
|
22
22
|
const { appName, environment, operationMode } = getEnv();
|
|
23
23
|
return `${appName}-${environment}-${operationMode}-${process.env.AKAN_REPLICA_IDX ?? "0"}-${process.pid}`;
|
|
24
24
|
}),
|
|
25
|
+
|
|
26
|
+
behindGateway: env(() => !!process.env.AKAN_CHILD_SOCKET),
|
|
25
27
|
}))
|
|
26
28
|
implements WebsocketAdaptor
|
|
27
29
|
{
|
|
30
|
+
|
|
31
|
+
static readonly #ackTimeoutMs = 3_000;
|
|
28
32
|
readonly #socketRooms = new Map<string, Set<string>>();
|
|
33
|
+
readonly #acks = new Map<number, () => void>();
|
|
34
|
+
#lastAck = 0;
|
|
29
35
|
#eventHandler: WsRedisEventHandler | null = null;
|
|
30
36
|
#changeHandler: LiveChangeHandler | null = null;
|
|
31
37
|
#liveModels: string[] = [];
|
|
32
38
|
readonly #messageHandler = (message: unknown) => {
|
|
33
39
|
if (!message || typeof message !== "object") return;
|
|
34
|
-
const data = message as {
|
|
40
|
+
const data = message as {
|
|
41
|
+
type?: string;
|
|
42
|
+
roomId?: string;
|
|
43
|
+
data?: unknown;
|
|
44
|
+
origin?: string;
|
|
45
|
+
change?: LiveChange;
|
|
46
|
+
ack?: number;
|
|
47
|
+
};
|
|
48
|
+
if (data.type === "pubsub.subscribed" && data.ack !== undefined) {
|
|
49
|
+
this.#acks.get(data.ack)?.();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
35
52
|
if (data.type === "pubsub.deliver" && data.roomId && data.origin !== this.serverId) {
|
|
36
53
|
this.#eventHandler?.(data.roomId, data.data);
|
|
37
54
|
return;
|
|
@@ -56,6 +73,8 @@ export class SolidPubSub
|
|
|
56
73
|
|
|
57
74
|
override async onDestroy() {
|
|
58
75
|
process.off("message", this.#messageHandler);
|
|
76
|
+
for (const answer of this.#acks.values()) answer();
|
|
77
|
+
this.#acks.clear();
|
|
59
78
|
this.#eventHandler = null;
|
|
60
79
|
this.#changeHandler = null;
|
|
61
80
|
this.#liveModels = [];
|
|
@@ -92,7 +111,21 @@ export class SolidPubSub
|
|
|
92
111
|
const rooms = this.#socketRooms.get(socketId) ?? new Set<string>();
|
|
93
112
|
rooms.add(room);
|
|
94
113
|
this.#socketRooms.set(socketId, rooms);
|
|
95
|
-
|
|
114
|
+
if (!this.behindGateway || !process.send) {
|
|
115
|
+
sendAkanIpc({ type: "pubsub.subscribe", roomId: room, socketId, pid: process.pid });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const ack = ++this.#lastAck;
|
|
119
|
+
const answered = Promise.withResolvers<void>();
|
|
120
|
+
this.#acks.set(ack, answered.resolve);
|
|
121
|
+
const timer = setTimeout(answered.resolve, SolidPubSub.#ackTimeoutMs);
|
|
122
|
+
sendAkanIpc({ type: "pubsub.subscribe", roomId: room, socketId, pid: process.pid, ack });
|
|
123
|
+
try {
|
|
124
|
+
await answered.promise;
|
|
125
|
+
} finally {
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
this.#acks.delete(ack);
|
|
128
|
+
}
|
|
96
129
|
}
|
|
97
130
|
|
|
98
131
|
async leaveRoom(ws: Bun.ServerWebSocket<unknown>, room: string): Promise<void> {
|
|
@@ -10,6 +10,9 @@ export declare class GatewayRooms {
|
|
|
10
10
|
deliverPubsub(originIdx: number, message: Extract<AkanIpcMessage, {
|
|
11
11
|
type: "pubsub.publish";
|
|
12
12
|
}>): void;
|
|
13
|
+
subscribe(childIdx: number, message: Extract<AkanIpcMessage, {
|
|
14
|
+
type: "pubsub.subscribe";
|
|
15
|
+
}>): void;
|
|
13
16
|
addRoomMembership(childIdx: number, roomId: string, socketId?: string): void;
|
|
14
17
|
removeRoomMembership(childIdx: number, roomId: string, socketId?: string): void;
|
|
15
18
|
replaceRoomSnapshot(childIdx: number, rooms: string[]): void;
|
|
@@ -177,6 +177,12 @@ export type AkanIpcMessage = {
|
|
|
177
177
|
roomId: string;
|
|
178
178
|
socketId?: string;
|
|
179
179
|
pid?: number;
|
|
180
|
+
ack?: number;
|
|
181
|
+
}
|
|
182
|
+
/** Gateway → child: the subscribe carrying `ack`, and whatever the child sent before it, now route to the child. */
|
|
183
|
+
| {
|
|
184
|
+
type: "pubsub.subscribed";
|
|
185
|
+
ack: number;
|
|
180
186
|
} | {
|
|
181
187
|
type: "pubsub.unsubscribe";
|
|
182
188
|
roomId: string;
|
|
@@ -3,6 +3,9 @@ declare const SolidPubSub_base: import("..").AdaptorCls<{}, {
|
|
|
3
3
|
serverId: import("..").InjectInfo<"env", string, {
|
|
4
4
|
[key: string]: any;
|
|
5
5
|
}, never>;
|
|
6
|
+
behindGateway: import("..").InjectInfo<"env", boolean, {
|
|
7
|
+
[key: string]: any;
|
|
8
|
+
}, never>;
|
|
6
9
|
}>;
|
|
7
10
|
export declare class SolidPubSub extends SolidPubSub_base implements WebsocketAdaptor {
|
|
8
11
|
#private;
|
|
@@ -9,9 +9,9 @@ import { type FileRef } from "../../../packages/core/src/index.ts";
|
|
|
9
9
|
* permissions and links another program would open (`mailto:`, a custom scheme) are refused. Listing the plugin in
|
|
10
10
|
* `native.plugins` is what lets an app open one.
|
|
11
11
|
*
|
|
12
|
-
* Windows has every method. Linux has
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* Windows has every method. Linux has every method and sends no `consoleMessage`; there the visible view shown last
|
|
13
|
+
* also holds the keyboard focus inside its window, so the user's own keys reach it, until a click on the page takes the
|
|
14
|
+
* focus or the view is hidden or closed. macOS (14 or later, for its separate profile) has all but `sendKey`,
|
|
15
15
|
* `setMuted` and `capture`, and sends no `loadFailed` or `consoleMessage`. iOS and Android: UNSUPPORTED.
|
|
16
16
|
*/
|
|
17
17
|
export type ExternalViewBounds = "fill" | {
|
|
@@ -90,7 +90,10 @@ export interface ExternalViewApi {
|
|
|
90
90
|
}): Promise<{
|
|
91
91
|
value: unknown;
|
|
92
92
|
}>;
|
|
93
|
-
/**
|
|
93
|
+
/**
|
|
94
|
+
* A trusted key press (`{ key: "z", code: "KeyZ" }`), whether or not the view has the focus. Not on macOS; on Linux
|
|
95
|
+
* UNSUPPORTED while the view's window is hidden.
|
|
96
|
+
*/
|
|
94
97
|
sendKey(args: {
|
|
95
98
|
id: string;
|
|
96
99
|
key: string;
|
package/ui/Data/useViewModal.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { router } from "akanjs/client";
|
|
3
|
-
import { modelNames
|
|
3
|
+
import { modelNames } from "akanjs/common";
|
|
4
4
|
import type { SliceMeta } from "akanjs/fetch";
|
|
5
5
|
import { st } from "akanjs/store";
|
|
6
6
|
import { usePageLocation } from "akanjs/webkit";
|
|
7
7
|
import { useEffect, useRef, useState } from "react";
|
|
8
8
|
|
|
9
|
+
import { openSeqIn, seedOpen } from "../../store/openSeq";
|
|
10
|
+
|
|
9
11
|
type SearchParams = Record<string, string | string[] | undefined>;
|
|
10
12
|
const firstOf = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value);
|
|
11
13
|
|
|
@@ -28,7 +30,7 @@ export const useViewModal = (slice: SliceMeta, { inUrl }: { inUrl: boolean }) =>
|
|
|
28
30
|
const storeDo = st.do as unknown as { [key: string]: (...args: unknown[]) => Promise<void> | void };
|
|
29
31
|
const { refName } = slice;
|
|
30
32
|
const names = modelNames(refName);
|
|
31
|
-
const
|
|
33
|
+
const returnToView = () => seedOpen(st, names.model, "view", { [names.modelModal]: "view" });
|
|
32
34
|
const { searchParams } = usePageLocation() as { searchParams: SearchParams };
|
|
33
35
|
const model = storeUse[names.model]({ agent: false }) as { id: string } | null;
|
|
34
36
|
const modelModal = storeUse[names.modelModal]({ agent: false }) as string | null;
|
|
@@ -48,7 +50,7 @@ export const useViewModal = (slice: SliceMeta, { inUrl }: { inUrl: boolean }) =>
|
|
|
48
50
|
useEffect(() => {
|
|
49
51
|
if (!editedFrom || modelModal === "edit") return;
|
|
50
52
|
setEditedFrom(null);
|
|
51
|
-
if (isReturning)
|
|
53
|
+
if (isReturning) returnToView();
|
|
52
54
|
}, [modelModal]);
|
|
53
55
|
|
|
54
56
|
const agreed = useRef<string | null | undefined>(undefined);
|
|
@@ -69,8 +71,12 @@ export const useViewModal = (slice: SliceMeta, { inUrl }: { inUrl: boolean }) =>
|
|
|
69
71
|
}, [inUrl, urlId, storeId]);
|
|
70
72
|
const editInView = (id: string) => {
|
|
71
73
|
setEditedFrom(id);
|
|
74
|
+
const editing = Promise.resolve(storeDo[names.editModel](id));
|
|
75
|
+
const opened = openSeqIn(st, names.model).open;
|
|
72
76
|
|
|
73
|
-
void
|
|
77
|
+
void editing.catch(() => {
|
|
78
|
+
if (openSeqIn(st, names.model).open === opened) returnToView();
|
|
79
|
+
});
|
|
74
80
|
};
|
|
75
81
|
return { editInView };
|
|
76
82
|
};
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
### Minor Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
7
|
+
- b218a57: The `external-view` plugin's `sendKey` now works on Linux, and `isSupported("sendKey")` is true there. The view gets a keydown and a keyup whose `code` is the one asked for, whatever the keyboard layout, whether the view, the app's page or another window has the focus, while an app dialog is open, and also while the view is hidden; neither the app's page nor its dialog sees the key, and an IBus or Fcitx input method types it as is rather than composing it. Its window must be shown: `sendKey` answers `UNSUPPORTED` while the window is hidden.
|
|
8
|
+
- b602e5e: The `external-view` plugin now works on Linux, on Wayland as well as X11. A view lies over the window's page at its bounds, with a browser profile of its own; its top level stays on the origins it was opened for while its frames load web content from anywhere, and its init script runs in the top document only. A failed load off those origins shows no error page there, a page's `window.close()` leaves the view in place, a hidden view stays hidden when the window is shown again, and an unattended app's views open no file chooser or print dialog. `capture` returns a PNG of the view's content, and `setMuted`, `clearData`, `loadFailed` (`http<status>`, `cannotConnect`, `hostNameNotResolved`, `timeout`, `certificate`, …) and `gone` (`crashed`, `killed` or `oom`; the view loads its page again by itself) work as on Windows. The visible view shown last holds the keyboard focus inside its window — on open, when shown, after a navigation, a reload or a restart, and when the window is focused again — and the page takes it back when the view is hidden or closed. Linux sends no `consoleMessage`: the `console` option is accepted and does nothing there. A plugin's `desktop` entry can now leave methods out of one desktop OS with `"unsupported": { "linux": [...] }`, so `isSupported()` answers per OS: `external-view` now reports `sendKey`, `setMuted` and `capture` unsupported on macOS, where the shell already refused them.
|
|
8
9
|
|
|
9
10
|
### Patch Changes
|
|
10
11
|
|
|
@@ -94,7 +94,7 @@ pub(crate) struct Views {
|
|
|
94
94
|
shows: u64,
|
|
95
95
|
}
|
|
96
96
|
|
|
97
|
-
/// Linux
|
|
97
|
+
/// On Linux the user's own keys reach a view only through the keyboard focus, so a visible view holds it.
|
|
98
98
|
#[cfg(target_os = "linux")]
|
|
99
99
|
impl Views {
|
|
100
100
|
fn raise(&mut self, view: &str) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//! The external-view plugin on WebKitGTK (external.rs). A view lies on a GtkOverlay over its window's page: wry's
|
|
2
|
-
//! build_as_child is X11 only. WebKitGTK has no DevTools Protocol, so `cdp` answers the screenshot
|
|
3
|
-
//! through GTK, a visible view holds the keyboard focus
|
|
4
|
-
//! responses, as navigation.rs does for the page.
|
|
2
|
+
//! build_as_child is X11 only. WebKitGTK has no DevTools Protocol, so `cdp` answers the screenshot and the key events
|
|
3
|
+
//! desktop.ts asks for through GTK, a visible view also holds the keyboard focus for the user's own keys, and frames are
|
|
4
|
+
//! told apart at their responses, as navigation.rs does for the page.
|
|
5
5
|
|
|
6
6
|
use std::{cell::RefCell, rc::Rc};
|
|
7
7
|
|
|
@@ -27,9 +27,31 @@ pub(crate) fn page_layer(vbox: >k::Box) -> gtk::Overlay {
|
|
|
27
27
|
let overlay = gtk::Overlay::new();
|
|
28
28
|
vbox.pack_start(&overlay, true, true, 0);
|
|
29
29
|
overlay.show();
|
|
30
|
+
static SNOOPER: std::sync::Once = std::sync::Once::new();
|
|
31
|
+
// SAFETY: page_layer runs on GTK's thread once GTK is up, and the snooper stays for the process.
|
|
32
|
+
SNOOPER.call_once(|| unsafe {
|
|
33
|
+
gtk::ffi::gtk_key_snooper_install(Some(hand_back), std::ptr::null_mut());
|
|
34
|
+
});
|
|
30
35
|
overlay
|
|
31
36
|
}
|
|
32
37
|
|
|
38
|
+
//? WebKit hands a key the page left unhandled back through gtk_main_do_event, which gives it to the window's page, or
|
|
39
|
+
//? to an app dialog holding a grab, and leaves the view to drop its next key. Key snoopers run before either: a sent
|
|
40
|
+
//? key goes back to its own view, which takes it as the one handed back.
|
|
41
|
+
unsafe extern "C" fn hand_back(_grab: *mut gtk::ffi::GtkWidget, key: *mut gdk::ffi::GdkEventKey, _: glib::ffi::gpointer) -> std::os::raw::c_int {
|
|
42
|
+
use glib::translate::FromGlibPtrBorrow;
|
|
43
|
+
let event = gdk::Event::from_glib_borrow(key.cast::<gdk::ffi::GdkEvent>());
|
|
44
|
+
let Some(window) = event.window().filter(|_| event.is_send_event()) else { return 0 };
|
|
45
|
+
let mut copy = (*event).clone();
|
|
46
|
+
let Some(view) = gtk::event_widget(&mut copy).and_then(|widget| widget.downcast::<webkit2gtk::WebView>().ok()) else { return 0 };
|
|
47
|
+
// SAFETY: only key_window sets KEY_WINDOW, always to a gdk::Window.
|
|
48
|
+
if unsafe { view.data::<gdk::Window>(KEY_WINDOW) }.is_none_or(|own| unsafe { own.as_ref() } != &window) {
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
view.event(©);
|
|
52
|
+
1
|
|
53
|
+
}
|
|
54
|
+
|
|
33
55
|
/// The view in a box of its own on the window's overlay, laid out at `bounds`.
|
|
34
56
|
pub(crate) fn build(builder: WebViewBuilder, window: &tao::window::Window, bounds: Bounds) -> Result<WebView, String> {
|
|
35
57
|
use tao::platform::unix::WindowExtUnix;
|
|
@@ -241,10 +263,11 @@ fn error_name(error: &glib::Error) -> String {
|
|
|
241
263
|
}
|
|
242
264
|
}
|
|
243
265
|
|
|
244
|
-
/// The
|
|
245
|
-
pub(crate) fn cdp(webview: &WebView, method: &str,
|
|
266
|
+
/// The DevTools Protocol methods desktop.ts sends, answered through GTK.
|
|
267
|
+
pub(crate) fn cdp(webview: &WebView, method: &str, params: &str, reply: Reply) {
|
|
246
268
|
match method {
|
|
247
269
|
"Page.captureScreenshot" => capture(webview, reply),
|
|
270
|
+
"Input.dispatchKeyEvent" => reply.send(json::parse(params).and_then(|params| send_key(webview, ¶ms)).map(|()| "{}".into())),
|
|
248
271
|
_ => reply.send(Err(format!("UNSUPPORTED: {method} reaches no view on Linux"))),
|
|
249
272
|
}
|
|
250
273
|
}
|
|
@@ -261,7 +284,169 @@ fn capture(webview: &WebView, reply: Reply) {
|
|
|
261
284
|
});
|
|
262
285
|
}
|
|
263
286
|
|
|
264
|
-
|
|
287
|
+
/// The X keysym of a KeyboardEvent.code a key's text does not name: every key desktop.ts's virtualKey knows.
|
|
288
|
+
pub(crate) fn keysym(code: &str) -> Option<String> {
|
|
289
|
+
if let Some(n) = code.strip_prefix('F').and_then(|n| n.parse::<u8>().ok()).filter(|n| (1..=24).contains(n)) {
|
|
290
|
+
return Some(format!("F{n}"));
|
|
291
|
+
}
|
|
292
|
+
if let Some(digit) = code.strip_prefix("Numpad").filter(|d| d.len() == 1 && d.as_bytes()[0].is_ascii_digit()) {
|
|
293
|
+
return Some(format!("KP_{digit}"));
|
|
294
|
+
}
|
|
295
|
+
let name = match code {
|
|
296
|
+
"Enter" => "Return",
|
|
297
|
+
"NumpadEnter" => "KP_Enter",
|
|
298
|
+
"Escape" => "Escape",
|
|
299
|
+
"Tab" => "Tab",
|
|
300
|
+
"Backspace" => "BackSpace",
|
|
301
|
+
"Delete" => "Delete",
|
|
302
|
+
"ArrowLeft" => "Left",
|
|
303
|
+
"ArrowUp" => "Up",
|
|
304
|
+
"ArrowRight" => "Right",
|
|
305
|
+
"ArrowDown" => "Down",
|
|
306
|
+
"Home" => "Home",
|
|
307
|
+
"End" => "End",
|
|
308
|
+
"PageUp" => "Page_Up",
|
|
309
|
+
"PageDown" => "Page_Down",
|
|
310
|
+
"Space" => "space",
|
|
311
|
+
_ => return None,
|
|
312
|
+
};
|
|
313
|
+
Some(name.into())
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
//? WebKitGTK reads KeyboardEvent.code off the hardware keycode (evdev + 8), so it comes from `code`, never the layout.
|
|
317
|
+
pub(crate) fn evdev(code: &str) -> Option<u16> {
|
|
318
|
+
const LETTERS: &[u8; 26] = b"\x1e\x30\x2e\x20\x12\x21\x22\x23\x17\x24\x25\x26\x32\x31\x18\x19\x10\x13\x1f\x14\x16\x2f\x11\x2d\x15\x2c";
|
|
319
|
+
if let Some(letter) = code.strip_prefix("Key").filter(|l| l.len() == 1 && l.as_bytes()[0].is_ascii_uppercase()) {
|
|
320
|
+
return Some(u16::from(LETTERS[usize::from(letter.as_bytes()[0] - b'A')]));
|
|
321
|
+
}
|
|
322
|
+
if let Some(digit) = code.strip_prefix("Digit").filter(|d| d.len() == 1 && d.as_bytes()[0].is_ascii_digit()) {
|
|
323
|
+
let d = digit.as_bytes()[0] - b'0';
|
|
324
|
+
return Some(if d == 0 { 11 } else { u16::from(d) + 1 });
|
|
325
|
+
}
|
|
326
|
+
if let Some(digit) = code.strip_prefix("Numpad").filter(|d| d.len() == 1 && d.as_bytes()[0].is_ascii_digit()) {
|
|
327
|
+
return Some([82, 79, 80, 81, 75, 76, 77, 71, 72, 73][usize::from(digit.as_bytes()[0] - b'0')]);
|
|
328
|
+
}
|
|
329
|
+
if let Some(n) = code.strip_prefix('F').and_then(|n| n.parse::<u16>().ok()).filter(|n| (1..=24).contains(n)) {
|
|
330
|
+
return Some(match n {
|
|
331
|
+
1..=10 => 58 + n,
|
|
332
|
+
11 | 12 => 76 + n,
|
|
333
|
+
_ => 170 + n,
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
Some(match code {
|
|
337
|
+
"Escape" => 1,
|
|
338
|
+
"Minus" => 12,
|
|
339
|
+
"Equal" => 13,
|
|
340
|
+
"Backspace" => 14,
|
|
341
|
+
"Tab" => 15,
|
|
342
|
+
"BracketLeft" => 26,
|
|
343
|
+
"BracketRight" => 27,
|
|
344
|
+
"Enter" => 28,
|
|
345
|
+
"Semicolon" => 39,
|
|
346
|
+
"Quote" => 40,
|
|
347
|
+
"Backquote" => 41,
|
|
348
|
+
"Backslash" => 43,
|
|
349
|
+
"Comma" => 51,
|
|
350
|
+
"Period" => 52,
|
|
351
|
+
"Slash" => 53,
|
|
352
|
+
"Space" => 57,
|
|
353
|
+
"NumpadEnter" => 96,
|
|
354
|
+
"Home" => 102,
|
|
355
|
+
"ArrowUp" => 103,
|
|
356
|
+
"PageUp" => 104,
|
|
357
|
+
"ArrowLeft" => 105,
|
|
358
|
+
"ArrowRight" => 106,
|
|
359
|
+
"End" => 107,
|
|
360
|
+
"ArrowDown" => 108,
|
|
361
|
+
"PageDown" => 109,
|
|
362
|
+
"Delete" => 111,
|
|
363
|
+
_ => return None,
|
|
364
|
+
})
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/// The keysym the page reads `key` off: `code`'s own when it types the same text (a numpad digit), else `key`'s.
|
|
368
|
+
fn keyval(key: &str, code: &str) -> Option<u32> {
|
|
369
|
+
let named = |name: &str| keysym(name).map(|sym| gdk::keys::Key::from_name(&sym));
|
|
370
|
+
let mut chars = key.chars();
|
|
371
|
+
let sym = match (chars.next(), chars.next()) {
|
|
372
|
+
(Some(c), None) => named(code).filter(|sym| sym.to_unicode() == Some(c)).unwrap_or_else(|| gdk::keys::Key::from_unicode(c)),
|
|
373
|
+
_ => named(key)?,
|
|
374
|
+
};
|
|
375
|
+
Some(*sym)
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
//? IBus's IBUS_IGNORED_MASK and Fcitx's FcitxKeyState_IgnoredMask: both commit such a key's own text, where a
|
|
379
|
+
//? composing input method (Hangul, Pinyin) would make a sent `z` part of a syllable.
|
|
380
|
+
const IM_PASS_THROUGH: u32 = 1 << 25;
|
|
381
|
+
const KEY_WINDOW: &str = "akan-key-window";
|
|
382
|
+
|
|
383
|
+
//? Sent to the view's widget, not the display: it reaches that view alone, focused, hidden or not, and counts as trusted.
|
|
384
|
+
fn send_key(webview: &WebView, params: &json::V) -> Result<(), String> {
|
|
385
|
+
let field = |k: &str| params.get(k).and_then(|v| v.as_str()).unwrap_or("");
|
|
386
|
+
let kind = match field("type") {
|
|
387
|
+
"keyDown" | "rawKeyDown" => gdk::EventType::KeyPress,
|
|
388
|
+
"keyUp" => gdk::EventType::KeyRelease,
|
|
389
|
+
other => return Err(format!("INVALID_ARGS: no key event of type {other}")),
|
|
390
|
+
};
|
|
391
|
+
let (key, code) = (field("key"), field("code"));
|
|
392
|
+
let keyval = keyval(key, code).ok_or_else(|| format!("INVALID_ARGS: key {key} is not one sendKey sends on Linux"))?;
|
|
393
|
+
let keycode = evdev(code).ok_or_else(|| format!("INVALID_ARGS: code {code} is not a key sendKey knows"))? + 8;
|
|
394
|
+
//? GTK's key bindings read a key off its keycode and state: a numpad digit without NumLock (Mod2) is Home, End, ….
|
|
395
|
+
let num_lock = if code.starts_with("Numpad") { gdk::ModifierType::MOD2_MASK.bits() } else { 0 };
|
|
396
|
+
let wv = webview.webview();
|
|
397
|
+
wv.realize();
|
|
398
|
+
let window = key_window(&wv)?;
|
|
399
|
+
if !window.is_viewable() {
|
|
400
|
+
return Err("UNSUPPORTED: sendKey on Linux needs the view's window shown".into());
|
|
401
|
+
}
|
|
402
|
+
let display = window.display();
|
|
403
|
+
let mut native = gdk::Event::new(kind);
|
|
404
|
+
native.set_device(display.default_seat().and_then(|seat| seat.keyboard()).as_ref());
|
|
405
|
+
// SAFETY: Event::new(KeyPress|KeyRelease) allocated a GdkEventKey, which releases the window reference with itself.
|
|
406
|
+
unsafe {
|
|
407
|
+
use glib::translate::{ToGlibPtr, ToGlibPtrMut};
|
|
408
|
+
let raw = ToGlibPtrMut::<*mut gdk::ffi::GdkEvent>::to_glib_none_mut(&mut native).0 as *mut gdk::ffi::GdkEventKey;
|
|
409
|
+
(*raw).window = window.to_glib_full();
|
|
410
|
+
(*raw).time = (glib::monotonic_time() / 1000) as u32;
|
|
411
|
+
(*raw).send_event = 1;
|
|
412
|
+
(*raw).state = IM_PASS_THROUGH | num_lock;
|
|
413
|
+
(*raw).keyval = keyval;
|
|
414
|
+
(*raw).hardware_keycode = keycode;
|
|
415
|
+
}
|
|
416
|
+
wv.event(&native);
|
|
417
|
+
Ok(())
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
//? GTK drops a key press on a window not viewable, a hidden view's own: keys go through an off-screen one routed to it.
|
|
421
|
+
fn key_window(wv: &webkit2gtk::WebView) -> Result<gdk::Window, String> {
|
|
422
|
+
use glib::translate::ToGlibPtr;
|
|
423
|
+
// SAFETY: only key_window sets KEY_WINDOW, always to a gdk::Window.
|
|
424
|
+
if let Some(window) = unsafe { wv.data::<gdk::Window>(KEY_WINDOW) } {
|
|
425
|
+
return Ok(unsafe { window.as_ref() }.clone());
|
|
426
|
+
}
|
|
427
|
+
let top = wv.toplevel().and_then(|top| top.window()).ok_or("UNSUPPORTED: sendKey on Linux needs the view's window shown")?;
|
|
428
|
+
let attrs = gdk::WindowAttr {
|
|
429
|
+
x: Some(-1),
|
|
430
|
+
y: Some(-1),
|
|
431
|
+
width: 1,
|
|
432
|
+
height: 1,
|
|
433
|
+
wclass: gdk::WindowWindowClass::InputOnly,
|
|
434
|
+
window_type: gdk::WindowType::Child,
|
|
435
|
+
..Default::default()
|
|
436
|
+
};
|
|
437
|
+
let window = gdk::Window::new(Some(&top), &attrs);
|
|
438
|
+
// SAFETY: the window names the view as its widget only while the view lives: the view's destroy destroys it.
|
|
439
|
+
unsafe {
|
|
440
|
+
gdk::ffi::gdk_window_set_user_data(window.to_glib_none().0, wv.upcast_ref::<glib::Object>().as_ptr() as *mut _);
|
|
441
|
+
wv.set_data(KEY_WINDOW, window.clone());
|
|
442
|
+
}
|
|
443
|
+
window.show();
|
|
444
|
+
let destroyed = window.clone();
|
|
445
|
+
wv.connect_destroy(move |_| destroyed.destroy());
|
|
446
|
+
Ok(window)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
//? A visible view takes the user's own keys too: their way to a view is the keyboard focus.
|
|
265
450
|
pub(crate) fn focus(webview: &WebView) {
|
|
266
451
|
webview.webview().grab_focus();
|
|
267
452
|
}
|
|
@@ -273,3 +458,52 @@ pub(crate) fn focus_page(any: &WebView) {
|
|
|
273
458
|
page.grab_focus();
|
|
274
459
|
}
|
|
275
460
|
}
|
|
461
|
+
|
|
462
|
+
#[cfg(test)]
|
|
463
|
+
mod tests {
|
|
464
|
+
use super::{evdev, keysym, keyval};
|
|
465
|
+
use gtk::gdk::keys::constants as k;
|
|
466
|
+
|
|
467
|
+
#[test]
|
|
468
|
+
fn the_page_reads_key_and_a_numpad_digit_keeps_its_place() {
|
|
469
|
+
assert_eq!(keyval("z", "KeyZ"), Some(*k::z));
|
|
470
|
+
assert_eq!(keyval("Z", "KeyZ"), Some(*k::Z));
|
|
471
|
+
assert_eq!(keyval(" ", "Space"), Some(*k::space));
|
|
472
|
+
assert_eq!(keyval("7", "Numpad7"), Some(*k::KP_7));
|
|
473
|
+
assert_eq!(keyval("7", "Digit7"), Some(*k::_7));
|
|
474
|
+
assert_eq!(keyval("ArrowLeft", "Numpad4"), Some(*k::Left));
|
|
475
|
+
assert_eq!(keyval("Enter", "NumpadEnter"), Some(*k::Return));
|
|
476
|
+
assert_eq!(keyval("F5", "F5"), Some(*k::F5));
|
|
477
|
+
assert_eq!(keyval("Unidentified", "KeyA"), None);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
#[test]
|
|
481
|
+
fn every_key_virtual_key_knows_but_text_has_a_keysym() {
|
|
482
|
+
for code in ["Enter", "NumpadEnter", "Escape", "Tab", "Backspace", "Delete", "ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown", "Home", "End", "PageUp", "PageDown", "Space"] {
|
|
483
|
+
assert!(keysym(code).is_some(), "{code}");
|
|
484
|
+
}
|
|
485
|
+
assert_eq!(keysym("F1").as_deref(), Some("F1"));
|
|
486
|
+
assert_eq!(keysym("F24").as_deref(), Some("F24"));
|
|
487
|
+
assert_eq!(keysym("Numpad7").as_deref(), Some("KP_7"));
|
|
488
|
+
for code in ["F0", "F25", "Numpad", "KeyA", "Digit1", "Fn"] {
|
|
489
|
+
assert_eq!(keysym(code), None, "{code}");
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
#[test]
|
|
494
|
+
fn every_key_virtual_key_knows_has_its_evdev_keycode() {
|
|
495
|
+
let known = [("KeyA", 30), ("KeyQ", 16), ("KeyZ", 44), ("Digit1", 2), ("Digit0", 11), ("Numpad0", 82), ("Numpad9", 73), ("F1", 59), ("F10", 68), ("F11", 87), ("F12", 88), ("F13", 183), ("F24", 194)];
|
|
496
|
+
for (code, keycode) in known {
|
|
497
|
+
assert_eq!(evdev(code), Some(keycode), "{code}");
|
|
498
|
+
}
|
|
499
|
+
assert_eq!([evdev("Space"), evdev("BracketLeft"), evdev("ArrowLeft"), evdev("Enter")], [Some(57), Some(26), Some(105), Some(28)]);
|
|
500
|
+
let named = ["Space", "Enter", "NumpadEnter", "Escape", "Tab", "Backspace", "Delete", "ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown", "Home", "End", "PageUp", "PageDown", "Slash", "Minus", "Equal", "Period", "Comma", "Semicolon", "Quote", "BracketLeft", "BracketRight", "Backslash", "Backquote"];
|
|
501
|
+
let letters = ('A'..='Z').map(|c| format!("Key{c}"));
|
|
502
|
+
for code in named.map(String::from).into_iter().chain(letters).chain((0..10).map(|d| format!("Digit{d}"))) {
|
|
503
|
+
assert!(evdev(&code).is_some(), "{code}");
|
|
504
|
+
}
|
|
505
|
+
for code in ["F0", "F25", "Keya", "KeyAA", "Digit", "Numpad10", "ShiftLeft"] {
|
|
506
|
+
assert_eq!(evdev(code), None, "{code}");
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
@@ -10,9 +10,9 @@ import { definePlugin, type FileRef } from "../../../packages/core/src/index.ts"
|
|
|
10
10
|
* permissions and links another program would open (`mailto:`, a custom scheme) are refused. Listing the plugin in
|
|
11
11
|
* `native.plugins` is what lets an app open one.
|
|
12
12
|
*
|
|
13
|
-
* Windows has every method. Linux has
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* Windows has every method. Linux has every method and sends no `consoleMessage`; there the visible view shown last
|
|
14
|
+
* also holds the keyboard focus inside its window, so the user's own keys reach it, until a click on the page takes the
|
|
15
|
+
* focus or the view is hidden or closed. macOS (14 or later, for its separate profile) has all but `sendKey`,
|
|
16
16
|
* `setMuted` and `capture`, and sends no `loadFailed` or `consoleMessage`. iOS and Android: UNSUPPORTED.
|
|
17
17
|
*/
|
|
18
18
|
export type ExternalViewBounds = "fill" | { x: number; y: number; width: number; height: number };
|
|
@@ -72,7 +72,10 @@ export interface ExternalViewApi {
|
|
|
72
72
|
* answer within 30 s, as from a page busy in a loop; `sendKey` and `capture` time out the same way.
|
|
73
73
|
*/
|
|
74
74
|
evaluate(args: { id: string; script: string }): Promise<{ value: unknown }>;
|
|
75
|
-
/**
|
|
75
|
+
/**
|
|
76
|
+
* A trusted key press (`{ key: "z", code: "KeyZ" }`), whether or not the view has the focus. Not on macOS; on Linux
|
|
77
|
+
* UNSUPPORTED while the view's window is hidden.
|
|
78
|
+
*/
|
|
76
79
|
sendKey(args: { id: string; key: string; code: string }): Promise<void>;
|
|
77
80
|
/** The view's own sound only; the system volume is the volume plugin's. Not on macOS. */
|
|
78
81
|
setMuted(args: { id: string; muted: boolean }): Promise<void>;
|