Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

refactor(desktop): make shortcut press policy explicit

Hampusb6b953cd3217
diff --git a/fluxer_desktop/src/main/GlobalShortcutMatcher.ts b/fluxer_desktop/src/main/GlobalShortcutMatcher.ts
index 197c62e72..cb2d3dcdd 100644
--- a/fluxer_desktop/src/main/GlobalShortcutMatcher.ts
+++ b/fluxer_desktop/src/main/GlobalShortcutMatcher.ts
@@ -68,6 +68,13 @@ export interface ShortcutTransition {
phase: 'press' | 'release';
}
+export const ShortcutPressPolicy = Object.freeze({
+ PRESS_AND_RELEASE: 'press-and-release',
+ RELEASE_ONLY: 'release-only',
+} as const);
+
+type ShortcutPressPolicy = (typeof ShortcutPressPolicy)[keyof typeof ShortcutPressPolicy];
+
type PressRecord = {kind: 'key'; rawKeycode: number} | {kind: 'mouse'; button: number} | {kind: 'modifier-only'};
const MODIFIER_ORDER: ReadonlyArray<ModifierKind> = ['ctrl', 'alt', 'shift', 'meta'];
@@ -164,59 +171,87 @@ export class GlobalShortcutMatcher {
return released;
}
- handleKey(event: HookKeyEvent, allowPress: boolean): Array<ShortcutTransition> {
+ handleKey(event: HookKeyEvent, pressPolicy: ShortcutPressPolicy): Array<ShortcutTransition> {
const heldCode = heldModifierCode(event);
this.reconcileModifierFlags(event, event.type === 'keydown' ? heldCode : null);
- if (event.type === 'keydown') {
- const transitions = this.releaseUnsatisfiedModifierOnly();
- const modifierOnlyBefore = this.satisfiedModifierOnlyBindings();
- if (heldCode !== null) this.heldModifierCodes.add(heldCode);
- if (!allowPress) return transitions;
- for (const binding of this.bindings.values()) {
- if (this.pressed.has(binding.sourceId)) continue;
- const {trigger} = binding;
- if (trigger.kind === 'modifier-only') {
- if (modifierOnlyBefore.has(binding.sourceId) || !this.isModifierOnlySatisfied(trigger)) continue;
- this.pressed.set(binding.sourceId, {kind: 'modifier-only'});
- } else if (trigger.kind === 'key') {
- if (!keyTriggerMatches(trigger, event) || !modifiersMatch(binding.modifiers, event)) continue;
- this.pressed.set(binding.sourceId, {kind: 'key', rawKeycode: event.rawKeycode});
- } else {
+ if (event.type !== 'keydown') {
+ if (heldCode !== null) {
+ this.heldModifierCodes.delete(heldCode);
+ }
+ const transitions: Array<ShortcutTransition> = [];
+ for (const [sourceId, record] of [...this.pressed]) {
+ if (record.kind !== 'key' || record.rawKeycode !== event.rawKeycode) {
continue;
}
- transitions.push({sourceId: binding.sourceId, action: binding.action, phase: 'press'});
+ const binding = this.bindings.get(sourceId);
+ this.pressed.delete(sourceId);
+ if (binding) {
+ transitions.push({sourceId, action: binding.action, phase: 'release'});
+ }
}
+ transitions.push(...this.releaseUnsatisfiedModifierOnly());
return transitions;
}
- if (heldCode !== null) this.heldModifierCodes.delete(heldCode);
- const transitions: Array<ShortcutTransition> = [];
- for (const [sourceId, record] of [...this.pressed]) {
- if (record.kind !== 'key' || record.rawKeycode !== event.rawKeycode) continue;
- const binding = this.bindings.get(sourceId);
- this.pressed.delete(sourceId);
- if (binding) transitions.push({sourceId, action: binding.action, phase: 'release'});
+ const transitions = this.releaseUnsatisfiedModifierOnly();
+ const modifierOnlyBefore = this.satisfiedModifierOnlyBindings();
+ if (heldCode !== null) {
+ this.heldModifierCodes.add(heldCode);
+ }
+ if (pressPolicy === ShortcutPressPolicy.RELEASE_ONLY) {
+ return transitions;
+ }
+ for (const binding of this.bindings.values()) {
+ if (this.pressed.has(binding.sourceId)) {
+ continue;
+ }
+ const {trigger} = binding;
+ if (trigger.kind === 'modifier-only') {
+ if (modifierOnlyBefore.has(binding.sourceId) || !this.isModifierOnlySatisfied(trigger)) {
+ continue;
+ }
+ this.pressed.set(binding.sourceId, {kind: 'modifier-only'});
+ transitions.push({sourceId: binding.sourceId, action: binding.action, phase: 'press'});
+ continue;
+ }
+ if (trigger.kind !== 'key') {
+ continue;
+ }
+ if (!keyTriggerMatches(trigger, event) || !modifiersMatch(binding.modifiers, event)) {
+ continue;
+ }
+ this.pressed.set(binding.sourceId, {kind: 'key', rawKeycode: event.rawKeycode});
+ transitions.push({sourceId: binding.sourceId, action: binding.action, phase: 'press'});
}
- transitions.push(...this.releaseUnsatisfiedModifierOnly());
return transitions;
}
- handleMouse(event: HookMouseEvent, allowPress: boolean): Array<ShortcutTransition> {
+ handleMouse(event: HookMouseEvent, pressPolicy: ShortcutPressPolicy): Array<ShortcutTransition> {
this.reconcileModifierFlags(event, null);
const transitions = this.releaseUnsatisfiedModifierOnly();
if (event.type === 'mouseup') {
for (const [sourceId, record] of [...this.pressed]) {
- if (record.kind !== 'mouse' || record.button !== event.button) continue;
+ if (record.kind !== 'mouse' || record.button !== event.button) {
+ continue;
+ }
const binding = this.bindings.get(sourceId);
this.pressed.delete(sourceId);
- if (binding) transitions.push({sourceId, action: binding.action, phase: 'release'});
+ if (binding) {
+ transitions.push({sourceId, action: binding.action, phase: 'release'});
+ }
}
return transitions;
}
- if (!allowPress) return transitions;
+ if (pressPolicy === ShortcutPressPolicy.RELEASE_ONLY) {
+ return transitions;
+ }
for (const binding of this.bindings.values()) {
const {trigger} = binding;
- if (trigger.kind !== 'mouse' || trigger.button !== event.button) continue;
- if (this.pressed.has(binding.sourceId) || !modifiersMatch(binding.modifiers, event)) continue;
+ if (trigger.kind !== 'mouse' || trigger.button !== event.button) {
+ continue;
+ }
+ if (this.pressed.has(binding.sourceId) || !modifiersMatch(binding.modifiers, event)) {
+ continue;
+ }
this.pressed.set(binding.sourceId, {kind: 'mouse', button: event.button});
transitions.push({sourceId: binding.sourceId, action: binding.action, phase: 'press'});
}
diff --git a/fluxer_desktop/src/main/GlobalShortcutsEngine.ts b/fluxer_desktop/src/main/GlobalShortcutsEngine.ts
index 060545cbc..f1d33369a 100644
--- a/fluxer_desktop/src/main/GlobalShortcutsEngine.ts
+++ b/fluxer_desktop/src/main/GlobalShortcutsEngine.ts
@@ -1,6 +1,8 @@
import {isRecord} from '@fluxer/record_utils/src/RecordGuards';
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {errorMessage} from '@electron/common/ErrorMessage';
+
import {
GLOBAL_SHORTCUT_ACTIONS,
GLOBAL_SHORTCUT_DEFAULT_DESCRIPTIONS,
@@ -24,6 +26,7 @@ import {
type HookKeyEvent,
type HookMouseEvent,
type ShortcutBinding,
+ ShortcutPressPolicy,
type ShortcutTransition,
} from '@electron/main/GlobalShortcutMatcher';
import type {LinuxPortalShortcutsManager, PortalShortcutDefinition} from '@electron/main/LinuxGlobalShortcutsPortal';
@@ -117,7 +120,7 @@ const MAX_ACTION_LENGTH = 100;
const MAX_KEY_LENGTH = 64;
const MAX_MOUSE_BUTTON = 31;
const INPUT_DEVICE_REPROBE_DELAY_MS = 500;
-export const GLOBAL_SHORTCUT_CAPTURE_TIMEOUT_MS = 60000;
+const GLOBAL_SHORTCUT_CAPTURE_TIMEOUT_MS = 60000;
function sanitizeBoundedString(value: unknown, maxLength: number): string | null {
if (typeof value !== 'string') return null;
@@ -177,14 +180,6 @@ export function sanitizeGlobalShortcutsSyncPayload(value: unknown): SanitizedSyn
return {bindings, actions};
}
-export function storedActionsFromSync(actions: ReadonlyArray<SanitizedSyncAction>): Array<StoredGlobalShortcutAction> {
- return actions.map((entry) => ({
- action: entry.action,
- description: entry.description,
- preferredTrigger: entry.preferredCombo === null ? null : comboToXdgTrigger(entry.preferredCombo),
- }));
-}
-
export function portalDefinitionsFromStored(
stored: ReadonlyArray<StoredGlobalShortcutAction>,
): Array<PortalShortcutDefinition> {
@@ -300,7 +295,15 @@ export class GlobalShortcutsEngine {
if (binding !== null) bindings.push(binding);
}
this.emitTransitions(client, client.matcher.setBindings(bindings));
- if (payload.actions.length > 0) this.storeActions(storedActionsFromSync(payload.actions));
+ if (payload.actions.length > 0) {
+ this.storeActions(
+ payload.actions.map((entry) => ({
+ action: entry.action,
+ description: entry.description,
+ preferredTrigger: entry.preferredCombo === null ? null : comboToXdgTrigger(entry.preferredCombo),
+ })),
+ );
+ }
if (bindings.length > 0) this.migrateDirectInput();
if (!this.directInputAvailable) this.reprobeDirectInput();
void this.refreshHooks();
@@ -311,7 +314,7 @@ export class GlobalShortcutsEngine {
if (client) client.paused = paused;
}
- refreshDirectInputAvailability(): void {
+ private refreshDirectInputAvailability(): void {
if (this.deps.linux === null) return;
this.directInputAvailable = this.deps.isDirectInputAvailable();
this.syncPortalActivity();
@@ -370,7 +373,7 @@ export class GlobalShortcutsEngine {
this.refreshDirectInputAvailability();
}
- isDirectInputActive(): boolean {
+ private isDirectInputActive(): boolean {
const linux = this.deps.linux;
if (linux === null || linux.inputHookMode === 'off' || linux.inputHookMode === 'native') return false;
if (!this.directInputAvailable) return false;
@@ -454,7 +457,7 @@ export class GlobalShortcutsEngine {
const run = this.hookQueue.then(() => this.reconcileHooks());
this.hookQueue = run.catch((error: unknown) => {
this.deps.log('Global shortcut hook reconcile failed', {
- message: error instanceof Error ? error.message : String(error),
+ message: errorMessage(error),
});
});
return this.hookQueue;
@@ -511,7 +514,7 @@ export class GlobalShortcutsEngine {
} catch (error) {
this.deps.log('Global shortcut hook start threw', {
backend: desired,
- message: error instanceof Error ? error.message : String(error),
+ message: errorMessage(error),
});
result = 'start-failed';
}
@@ -553,23 +556,34 @@ export class GlobalShortcutsEngine {
} catch (error) {
this.deps.log('Global shortcut hook stop threw', {
backend: backend.kind,
- message: error instanceof Error ? error.message : String(error),
+ message: errorMessage(error),
});
}
}
private dispatchHookEvent(event: HookEvent, backend: HookBackendKind): void {
for (const client of this.clients.values()) {
- const transitions =
- event.native === null
- ? client.matcher.handleMouse(event, !client.paused)
- : client.matcher.handleKey(event, !client.paused);
+ let transitions: Array<ShortcutTransition>;
+ if (event.native === null) {
+ transitions = client.matcher.handleMouse(
+ event,
+ client.paused ? ShortcutPressPolicy.RELEASE_ONLY : ShortcutPressPolicy.PRESS_AND_RELEASE,
+ );
+ } else {
+ transitions = client.matcher.handleKey(
+ event,
+ client.paused ? ShortcutPressPolicy.RELEASE_ONLY : ShortcutPressPolicy.PRESS_AND_RELEASE,
+ );
+ }
this.emitTransitions(client, transitions);
}
- for (const consumer of this.consumers) consumer.handleHookEvent(event, backend);
+ for (const consumer of this.consumers) {
+ consumer.handleHookEvent(event, backend);
+ }
const capture = this.capture;
- if (capture !== null)
+ if (capture !== null) {
this.clients.get(capture.clientId)?.send('global-shortcuts:capture', captureEventFromHook(event));
+ }
}
private emitTransitions(client: SyncClient, transitions: ReadonlyArray<ShortcutTransition>): void {
@@ -647,7 +661,7 @@ export class GlobalShortcutsEngine {
);
}
- syncPortalActivity(): void {
+ private syncPortalActivity(): void {
const portal = this.deps.portal;
if (portal === null) return;
if (this.portalRequested && this.portalApplicable()) {
diff --git a/fluxer_desktop/src/main/GlobalShortcutsNative.ts b/fluxer_desktop/src/main/GlobalShortcutsNative.ts
index 34b10a217..a10f2dd58 100644
--- a/fluxer_desktop/src/main/GlobalShortcutsNative.ts
+++ b/fluxer_desktop/src/main/GlobalShortcutsNative.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createRequire} from 'node:module';
+import {errorMessage} from '@electron/common/ErrorMessage';
import {createChildLogger} from '@electron/common/Logger';
import {
evdevKeyToDomCode,
@@ -102,7 +103,7 @@ function loadModule<T extends {loadError: Error | null}>(name: string): T {
} catch (error) {
throw new Error(
`${name} failed to load; this is a packaging bug, not a runtime fallback case. ` +
- `Original error: ${error instanceof Error ? error.message : String(error)}`,
+ `Original error: ${errorMessage(error)}`,
);
}
moduleCache.set(name, loaded);
@@ -154,7 +155,7 @@ function isNativeMouseEvent(event: NativeHookEvent): event is NativeMouseEvent {
return event.type === 'mousedown' || event.type === 'mouseup';
}
-export function translateNativeHookEvent(kind: HookBackendKind, event: NativeHookEvent): HookEvent | null {
+function translateNativeHookEvent(kind: HookBackendKind, event: NativeHookEvent): HookEvent | null {
const unflaggedModifierCodes = kind === 'x11' ? X11_UNFLAGGED_MODIFIER_CODES : undefined;
if (isNativeMouseEvent(event)) {
return {
diff --git a/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.ts b/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.ts
index ee8fb2790..353adf22c 100644
--- a/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.ts
+++ b/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.ts
@@ -2,7 +2,7 @@
import type {GlobalKeyHookRegisterOptions} from '@electron/common/Types';
import {hookKeyNameToDomCode} from '@electron/main/GlobalShortcutKeys';
-import {GlobalShortcutMatcher, type ShortcutBinding} from '@electron/main/GlobalShortcutMatcher';
+import {GlobalShortcutMatcher, type ShortcutBinding, ShortcutPressPolicy} from '@electron/main/GlobalShortcutMatcher';
import type {
GlobalShortcutsConsumer,
GlobalShortcutsEngine,
@@ -40,30 +40,6 @@ function readLegacyName(value: unknown): string | null {
return value;
}
-export function legacyRegistrationToBinding(options: unknown): ShortcutBinding | null {
- if (options === null || typeof options !== 'object') return null;
- const record = options as Record<string, unknown>;
- const id = record.id;
- if (typeof id !== 'string' || id.length === 0 || id.length > MAX_LEGACY_ID_LENGTH) return null;
- const modifiers = {
- ctrl: record.ctrl === true,
- alt: record.alt === true,
- shift: record.shift === true,
- meta: record.meta === true,
- };
- const mouseButton = record.mouseButton;
- if (typeof mouseButton === 'number' && Number.isInteger(mouseButton)) {
- if (mouseButton < 0 || mouseButton > MAX_LEGACY_MOUSE_BUTTON) return null;
- return {sourceId: id, action: id, trigger: {kind: 'mouse', button: mouseButton}, modifiers};
- }
- const keyName = readLegacyName(record.keyName);
- const physicalKeyName = readLegacyName(record.physicalKeyName);
- const physicalSource = physicalKeyName ?? keyName;
- const code = physicalSource === null ? null : hookKeyNameToDomCode(physicalSource);
- if (keyName === null && code === null) return null;
- return {sourceId: id, action: id, trigger: {kind: 'key', layoutKey: keyName, code}, modifiers};
-}
-
interface LegacyClient {
send: (channel: string, payload: unknown) => void;
starts: number;
@@ -133,14 +109,18 @@ export class LegacyGlobalKeyHookAdapter implements GlobalShortcutsConsumer {
handleHookEvent(event: HookEvent, backend: HookBackendKind): void {
for (const client of this.clients.values()) {
const transitions =
- event.native === null ? client.matcher.handleMouse(event, true) : client.matcher.handleKey(event, true);
+ event.native === null
+ ? client.matcher.handleMouse(event, ShortcutPressPolicy.PRESS_AND_RELEASE)
+ : client.matcher.handleKey(event, ShortcutPressPolicy.PRESS_AND_RELEASE);
for (const transition of transitions) {
client.send('global-keybind-triggered', {
id: transition.sourceId,
type: transition.phase === 'press' ? 'keydown' : 'keyup',
});
}
- if (client.starts === 0) continue;
+ if (client.starts === 0) {
+ continue;
+ }
const modifiers = {
ctrlKey: event.ctrlKey,
altKey: event.altKey,
@@ -176,22 +156,6 @@ export class LegacyGlobalKeyHookAdapter implements GlobalShortcutsConsumer {
}
}
-export function buildLegacyLinuxEvdevStatus(
- host: Pick<LegacyHostEnvironment, 'platform' | 'sandboxed' | 'username'>,
-): LegacyLinuxEvdevStatus {
- const linux = host.platform === 'linux';
- return {
- supported: linux,
- hasAccess: true,
- canPrompt: false,
- sandboxed: linux && host.sandboxed,
- username: host.username,
- totalEventDevices: 0,
- readableEventDevices: 0,
- inInputGroup: false,
- };
-}
-
export function registerLegacyGlobalKeyHookHandlers(
engine: GlobalShortcutsEngine,
adapter: LegacyGlobalKeyHookAdapter,
@@ -231,8 +195,37 @@ export function registerLegacyGlobalKeyHookHandlers(
});
ipcMain.handle('global-key-hook-register', (event, options: GlobalKeyHookRegisterOptions): void => {
requirePrivilegedRendererDocumentSender(event, 'global-key-hook-register');
- const binding = legacyRegistrationToBinding(options);
- if (binding === null) return;
+ if (options === null || typeof options !== 'object') {
+ return;
+ }
+ const record = options;
+ const id = record.id;
+ if (typeof id !== 'string' || id.length === 0 || id.length > MAX_LEGACY_ID_LENGTH) {
+ return;
+ }
+ const modifiers = {
+ ctrl: record.ctrl === true,
+ alt: record.alt === true,
+ shift: record.shift === true,
+ meta: record.meta === true,
+ };
+ const mouseButton = record.mouseButton;
+ let binding: ShortcutBinding;
+ if (typeof mouseButton === 'number' && Number.isInteger(mouseButton)) {
+ if (mouseButton < 0 || mouseButton > MAX_LEGACY_MOUSE_BUTTON) {
+ return;
+ }
+ binding = {sourceId: id, action: id, trigger: {kind: 'mouse', button: mouseButton}, modifiers};
+ } else {
+ const keyName = readLegacyName(record.keyName);
+ const physicalKeyName = readLegacyName(record.physicalKeyName);
+ const physicalSource = physicalKeyName ?? keyName;
+ const code = physicalSource === null ? null : hookKeyNameToDomCode(physicalSource);
+ if (keyName === null && code === null) {
+ return;
+ }
+ binding = {sourceId: id, action: id, trigger: {kind: 'key', layoutKey: keyName, code}, modifiers};
+ }
ensureClient(event.sender);
adapter.register(event.sender.id, binding);
engine.migrateLegacyDirectInput();
@@ -248,6 +241,16 @@ export function registerLegacyGlobalKeyHookHandlers(
});
ipcMain.handle('linux-evdev-status', (event): LegacyLinuxEvdevStatus => {
requirePrivilegedRendererDocumentSender(event, 'linux-evdev-status');
- return buildLegacyLinuxEvdevStatus(host);
+ const linux = host.platform === 'linux';
+ return {
+ supported: linux,
+ hasAccess: true,
+ canPrompt: false,
+ sandboxed: linux && host.sandboxed,
+ username: host.username,
+ totalEventDevices: 0,
+ readableEventDevices: 0,
+ inInputGroup: false,
+ };
});
}
diff --git a/fluxer_desktop/src/main/LinuxGlobalShortcutsPortal.ts b/fluxer_desktop/src/main/LinuxGlobalShortcutsPortal.ts
index c2e9229d0..3b126f69c 100644
--- a/fluxer_desktop/src/main/LinuxGlobalShortcutsPortal.ts
+++ b/fluxer_desktop/src/main/LinuxGlobalShortcutsPortal.ts
@@ -77,9 +77,9 @@ export interface LinuxPortalShortcutsDeps {
log: (message: string, details?: Record<string, unknown>) => void;
}
-export const PORTAL_RECOVERY_BACKOFF_MS: ReadonlyArray<number> = [1000, 2000, 5000, 10000, 30000];
-export const PORTAL_NO_PORTAL_RETRY_WINDOW_MS = 30000;
-export const PORTAL_TOGGLE_REARM_MS = 1500;
+const PORTAL_RECOVERY_BACKOFF_MS: ReadonlyArray<number> = [1000, 2000, 5000, 10000, 30000];
+const PORTAL_NO_PORTAL_RETRY_WINDOW_MS = 30000;
+const PORTAL_TOGGLE_REARM_MS = 1500;
const PORTAL_CLOSED_RECOVERY_WINDOW_MS = 60000;
const NO_PORTAL_ERROR = 'unsupported:no-portal';
const CONFIGURE_UNSUPPORTED_ERROR = 'unsupported:version';
@@ -88,7 +88,7 @@ const RESPONSE_CODE_ERROR = /^unsupported:\d+$/;
type OpenFailure = {kind: 'no-portal' | 'unsupported' | 'identity' | 'timeout' | 'failed'; message: string};
function classifyOpenFailure(error: unknown): OpenFailure {
- const message = error instanceof Error ? error.message : String(error);
+ const message = errorMessage(error);
if (message === NO_PORTAL_ERROR || RESPONSE_CODE_ERROR.test(message)) return {kind: 'no-portal', message};
if (message.startsWith('unsupported:')) return {kind: 'unsupported', message};
if (message.startsWith('identity:')) return {kind: 'identity', message};