Skip to content

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

TypeScript fluxerfluxerapp

feat(desktop): switch accounts from shell menus, gate DM task

Hampus4e98237847d7
diff --git a/fluxer_desktop/src/common/BidiIsolation.ts b/fluxer_desktop/src/common/BidiIsolation.ts
new file mode 100644
index 000000000..7c689786c
--- /dev/null
+++ b/fluxer_desktop/src/common/BidiIsolation.ts
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+const BIDI_FIRST_STRONG_ISOLATE = '\u2068';
+const BIDI_POP_DIRECTIONAL_ISOLATE = '\u2069';
+
+export function isolateBidiText(value: string): string {
+ return `${BIDI_FIRST_STRONG_ISOLATE}${value}${BIDI_POP_DIRECTIONAL_ISOLATE}`;
+}
diff --git a/fluxer_desktop/src/common/GlobalShortcutActions.ts b/fluxer_desktop/src/common/GlobalShortcutActions.ts
index 5e109bb61..ddf1f5cf8 100644
--- a/fluxer_desktop/src/common/GlobalShortcutActions.ts
+++ b/fluxer_desktop/src/common/GlobalShortcutActions.ts
@@ -11,6 +11,7 @@ export const GLOBAL_SHORTCUT_ACTIONS = [
'voice_toggle_camera',
'voice_switch_channel',
'voice_disconnect',
+ 'system_open_account_switcher',
] as const;
export type GlobalShortcutAction = (typeof GLOBAL_SHORTCUT_ACTIONS)[number];
@@ -33,8 +34,19 @@ export const GLOBAL_SHORTCUT_DEFAULT_DESCRIPTIONS: Readonly<Record<GlobalShortcu
voice_toggle_camera: 'Toggle camera',
voice_switch_channel: 'Switch voice channel',
voice_disconnect: 'Disconnect from voice',
+ system_open_account_switcher: 'Open the account switcher',
};
+const GLOBAL_SHORTCUT_WINDOW_ACTIONS: ReadonlySet<GlobalShortcutAction> = new Set(['system_open_account_switcher']);
+
+export function globalShortcutEventRevealsWindow(channel: string, payload: unknown): boolean {
+ if (channel !== 'global-shortcut-event' || typeof payload !== 'object' || payload === null) return false;
+ const event = payload as {action?: unknown; phase?: unknown};
+ return (
+ event.phase === 'press' && isGlobalShortcutAction(event.action) && GLOBAL_SHORTCUT_WINDOW_ACTIONS.has(event.action)
+ );
+}
+
export const GLOBAL_SHORTCUT_DESCRIPTION_MAX_LENGTH = 200;
export function isGlobalShortcutAction(value: unknown): value is GlobalShortcutAction {
diff --git a/fluxer_desktop/src/main/AccountMenu.ts b/fluxer_desktop/src/main/AccountMenu.ts
new file mode 100644
index 000000000..5cdcd3db2
--- /dev/null
+++ b/fluxer_desktop/src/main/AccountMenu.ts
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {isolateBidiText} from '@electron/common/BidiIsolation';
+import type {AccountEngineLabel} from '@electron/main/AccountEngineHost';
+import type {AccountEngineAccountSummary} from '@fluxer/desktop_ipc/src/AccountEngineContract';
+
+interface AccountMenuEntry {
+ readonly accountKey: string;
+ readonly label: string;
+ readonly checked: boolean;
+}
+
+interface AccountMenuActions {
+ readonly switchAccount: (accountKey: string) => void;
+ readonly openAccountSwitcher: () => void;
+}
+
+type Translate = (key: string, vars?: Record<string, string>) => string;
+
+function accountUserId(accountKey: string): string {
+ const index = accountKey.lastIndexOf('::');
+ return index === -1 ? accountKey : accountKey.slice(index + 2);
+}
+
+function compareSwitcherOrder(a: AccountEngineLabel, b: AccountEngineLabel): number {
+ if (a.switcherPosition !== null && b.switcherPosition !== null && a.switcherPosition !== b.switcherPosition) {
+ return a.switcherPosition - b.switcherPosition;
+ }
+ if (a.switcherPosition !== null && b.switcherPosition === null) {
+ return -1;
+ }
+ if (a.switcherPosition === null && b.switcherPosition !== null) {
+ return 1;
+ }
+ return compareAccountAge(a, b);
+}
+
+function compareAccountAge(a: AccountEngineLabel, b: AccountEngineLabel): number {
+ const aUserId = accountUserId(a.accountKey);
+ const bUserId = accountUserId(b.accountKey);
+ if (aUserId.length !== bUserId.length) {
+ return aUserId.length - bUserId.length;
+ }
+ if (aUserId !== bUserId) {
+ return aUserId < bUserId ? -1 : 1;
+ }
+ if (a.accountKey === b.accountKey) {
+ return 0;
+ }
+ return a.accountKey < b.accountKey ? -1 : 1;
+}
+
+export function buildAccountMenuEntries(
+ labels: ReadonlyArray<AccountEngineLabel>,
+ summaries: ReadonlyArray<AccountEngineAccountSummary>,
+ translate: Translate,
+ {hidePersonalInformation = false}: {hidePersonalInformation?: boolean} = {},
+): ReadonlyArray<AccountMenuEntry> {
+ if (labels.length < 2) {
+ return [];
+ }
+ if (hidePersonalInformation) {
+ return [...labels].sort(compareSwitcherOrder).map((entry, index) => ({
+ accountKey: entry.accountKey,
+ label: translate('desktop.tray.accountNumbered', {number: String(index + 1)}),
+ checked: entry.isForeground,
+ }));
+ }
+ const severalInstances = new Set(labels.map((label) => label.instanceHost)).size > 1;
+ const mentionsByAccount = new Map(summaries.map((summary) => [summary.accountKey, summary.mentionCount]));
+ return [...labels].sort(compareSwitcherOrder).map((entry) => {
+ const name = isolateBidiText(entry.displayName);
+ const named = severalInstances
+ ? translate('desktop.tray.accountWithHost', {name, host: isolateBidiText(entry.instanceHost)})
+ : name;
+ const mentions = entry.isForeground ? 0 : (mentionsByAccount.get(entry.accountKey) ?? 0);
+ return {
+ accountKey: entry.accountKey,
+ label:
+ mentions > 0 ? translate('desktop.tray.accountWithMentions', {label: named, count: String(mentions)}) : named,
+ checked: entry.isForeground,
+ };
+ });
+}
+
+export function buildAccountMenuItems(
+ entries: ReadonlyArray<AccountMenuEntry>,
+ actions: AccountMenuActions,
+ translate: Translate,
+): Array<Electron.MenuItemConstructorOptions> {
+ if (entries.length === 0) {
+ return [];
+ }
+ return [
+ ...entries.map(
+ (entry): Electron.MenuItemConstructorOptions => ({
+ label: entry.label,
+ type: 'radio',
+ checked: entry.checked,
+ click: () => actions.switchAccount(entry.accountKey),
+ }),
+ ),
+ {type: 'separator'},
+ {label: translate('desktop.tray.chooseAccount'), click: actions.openAccountSwitcher},
+ ];
+}
+
+export function createRefreshThrottle(
+ refresh: () => void,
+ intervalMs: number,
+): {schedule: () => void; cancel: () => void} {
+ let timer: NodeJS.Timeout | null = null;
+ let pending = false;
+ const arm = (): void => {
+ timer = setTimeout(() => {
+ timer = null;
+ if (!pending) {
+ return;
+ }
+ pending = false;
+ refresh();
+ arm();
+ }, intervalMs);
+ timer.unref?.();
+ };
+ return {
+ schedule: () => {
+ if (timer !== null) {
+ pending = true;
+ return;
+ }
+ refresh();
+ arm();
+ },
+ cancel: () => {
+ if (timer !== null) {
+ clearTimeout(timer);
+ }
+ timer = null;
+ pending = false;
+ },
+ };
+}
diff --git a/fluxer_desktop/src/main/DeepLinks.ts b/fluxer_desktop/src/main/DeepLinks.ts
index fa9016bd1..7682c96f6 100644
--- a/fluxer_desktop/src/main/DeepLinks.ts
+++ b/fluxer_desktop/src/main/DeepLinks.ts
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {APP_PROTOCOL} from '@electron/common/Constants';
+import {requestAccountSwitcher} from '@electron/main/DesktopTray';
import {updateFromCommandLine} from '@electron/main/DesktopUpdatePrompt';
-import {parseJumpListTaskFromArgv} from '@electron/main/JumpList';
+import {type JumpListTaskId, parseJumpListTaskFromArgv} from '@electron/main/JumpList';
import {isDesktopUpdateRequested} from '@electron/main/LaunchOptions';
import {getMainWindow, isMainWindowTakenOver, onMainWindowTakeoverEnded, showWindow} from '@electron/main/Window';
import {app, ipcMain} from 'electron';
@@ -32,7 +33,7 @@ function designationKey(name: string): string {
return name.toLowerCase().replace(/[^a-z0-9]/gu, '');
}
-export function findInstanceDesignation(url: URL): string | null {
+function findInstanceDesignation(url: URL): string | null {
if (INSTANCE_DESIGNATING_KEYS.has(designationKey(url.hostname))) {
return url.hostname;
}
@@ -196,7 +197,11 @@ function dispatchDeepLink(url: string): void {
}
}
-function dispatchJumpListTask(taskId: 'open-settings' | 'new-dm'): void {
+function dispatchJumpListTask(taskId: JumpListTaskId): void {
+ if (taskId === 'open-account-switcher') {
+ requestAccountSwitcher();
+ return;
+ }
const mainWindow = getMainWindow();
if (!mainWindow || mainWindow.isDestroyed()) return;
showWindow();
@@ -237,7 +242,12 @@ export function handleSecondInstance(argv: Array<string>): void {
}
export function consumeInitialJumpListTask(): 'open-settings' | 'new-dm' | null {
- return parseJumpListTaskFromArgv(process.argv);
+ const task = parseJumpListTaskFromArgv(process.argv);
+ if (task === 'open-account-switcher') {
+ requestAccountSwitcher();
+ return null;
+ }
+ return task;
}
function recordRecentDeepLink(url: string): void {
diff --git a/fluxer_desktop/src/main/DesktopTray.ts b/fluxer_desktop/src/main/DesktopTray.ts
index 47bb4f1b0..70014f775 100644
--- a/fluxer_desktop/src/main/DesktopTray.ts
+++ b/fluxer_desktop/src/main/DesktopTray.ts
@@ -2,6 +2,7 @@
import fs from 'node:fs';
import path from 'node:path';
+import {isolateBidiText} from '@electron/common/BidiIsolation';
import {BUILD_CHANNEL, type BuildChannel} from '@electron/common/BuildChannel';
import {getDesktopWindowBehaviorSettings} from '@electron/common/DesktopConfig';
import {DESKTOP_APP_NAME} from '@electron/common/DesktopIdentity';
@@ -11,6 +12,12 @@ import type {
TrayActionPayload,
TrayRuntimeStatePayload,
} from '@electron/common/Types';
+import {
+ getAccountEngineLabels,
+ getAccountEngineSummaries,
+ onAccountEngineSummaries,
+} from '@electron/main/AccountEngineHost';
+import {buildAccountMenuEntries, buildAccountMenuItems, createRefreshThrottle} from '@electron/main/AccountMenu';
import {getDesktopUpdateState, observeDesktopUpdateState} from '@electron/main/DesktopUpdateGate';
import {checkForUpdatesFromShell, startDesktopUpdateFromShell} from '@electron/main/DesktopUpdatePrompt';
import {shouldDisableModuleUpdatesForLaunch} from '@electron/main/LaunchOptions';
@@ -60,9 +67,8 @@ let trayBaseIcon: Electron.NativeImage | null = null;
let appliedTrayIconKey: string | null = null;
const trayIconCache = new Map<string, Electron.NativeImage>();
-const BIDI_FIRST_STRONG_ISOLATE = '\u2068';
-const BIDI_POP_DIRECTIONAL_ISOLATE = '\u2069';
const MAX_PENDING_TRAY_ACTIONS = 16;
+const ACCOUNT_MENU_REFRESH_INTERVAL_MS = 1000;
const LINUX_TRAY_MENU_ACTION_DELAY_MS = 25;
const TRAY_FORCED_EXIT_DELAY_MS = 5000;
@@ -75,8 +81,16 @@ const trayState: TrayRuntimeStatePayload = {
selfDeaf: false,
presenceStatus: null,
buildInfo: null,
+ hidePersonalInformation: false,
};
+const privacyListeners = new Set<() => void>();
+
+export function onAccountMenuPrivacyChange(listener: () => void): () => void {
+ privacyListeners.add(listener);
+ return () => privacyListeners.delete(listener);
+}
+
export function updateTrayRuntimeState(update: Partial<TrayRuntimeStatePayload>, webContentsId?: number): void {
if (webContentsId !== undefined) {
trayActionBridgeWebContentsId = webContentsId;
@@ -84,8 +98,14 @@ export function updateTrayRuntimeState(update: Partial<TrayRuntimeStatePayload>,
if (typeof update.buildInfo === 'string' && update.buildInfo !== trayState.buildInfo) {
logger.info(`The renderer reported its build: ${update.buildInfo}`);
}
+ const privacyChanged =
+ typeof update.hidePersonalInformation === 'boolean' &&
+ update.hidePersonalInformation !== trayState.hidePersonalInformation;
Object.assign(trayState, update);
refreshDesktopTrayMenu();
+ if (privacyChanged) {
+ for (const listener of Array.from(privacyListeners)) listener();
+ }
schedulePendingTrayActionFlush();
}
@@ -173,6 +193,30 @@ function dispatchTrayAction(payload: TrayActionPayload): void {
}
}
+function requestAccountSwitch(accountKey: string): void {
+ ensureMainWindowVisible();
+ dispatchTrayAction({action: 'switch-account', accountKey});
+}
+
+export function requestAccountSwitcher(): void {
+ ensureMainWindowVisible();
+ dispatchTrayAction({action: 'open-account-switcher'});
+}
+
+export function buildAccountSwitchMenuItems(): Array<Electron.MenuItemConstructorOptions> {
+ const entries = buildAccountMenuEntries(getAccountEngineLabels(), getAccountEngineSummaries(), t, {
+ hidePersonalInformation: trayState.hidePersonalInformation,
+ });
+ return buildAccountMenuItems(
+ entries,
+ {
+ switchAccount: (accountKey) => runTrayMenuAction(() => requestAccountSwitch(accountKey)),
+ openAccountSwitcher: () => runTrayMenuAction(requestAccountSwitcher),
+ },
+ t,
+ );
+}
+
export function hasActiveDesktopTray(): boolean {
return Boolean(tray && !tray.isDestroyed());
}
@@ -359,10 +403,6 @@ function runTrayMenuAction(action: () => void): void {
timeout.unref?.();
}
-function isolateUserText(value: string): string {
- return `${BIDI_FIRST_STRONG_ISOLATE}${value}${BIDI_POP_DIRECTIONAL_ISOLATE}`;
-}
-
function buildTrayMenu(): Menu {
const mainWindow = controller?.getMainWindow() ?? null;
const visible = Boolean(
@@ -423,6 +463,10 @@ function buildTrayMenu(): Menu {
],
},
];
+ const accountItems = buildAccountSwitchMenuItems();
+ if (accountItems.length > 0) {
+ menuTemplate.push({label: t('desktop.tray.accounts'), submenu: accountItems});
+ }
if (trayState.voiceConnected) {
menuTemplate.push({type: 'separator'});
menuTemplate.push({
@@ -435,7 +479,7 @@ function buildTrayMenu(): Menu {
});
menuTemplate.push({
label: trayState.voiceChannelLabel
- ? t('desktop.tray.disconnectFrom', {channel: isolateUserText(trayState.voiceChannelLabel)})
+ ? t('desktop.tray.disconnectFrom', {channel: isolateBidiText(trayState.voiceChannelLabel)})
: t('desktop.tray.disconnectVoice'),
click: () => runTrayMenuAction(() => dispatchTrayAction({action: 'disconnect-voice'})),
});
@@ -581,6 +625,7 @@ export function desktopTrayChangePendingRestart(): boolean {
}
let trayLocaleSubscribed = false;
+const accountMenuRefresh = createRefreshThrottle(() => refreshDesktopTrayMenu(), ACCOUNT_MENU_REFRESH_INTERVAL_MS);
export function initializeDesktopTray(nextController: DesktopTrayController): void {
controller = nextController;
@@ -597,6 +642,7 @@ export function initializeDesktopTray(nextController: DesktopTrayController): vo
nativeTheme.on('updated', () => syncTrayIcon(false));
}
observeDesktopUpdateState(refreshDesktopTrayMenu);
+ onAccountEngineSummaries(accountMenuRefresh.schedule);
}
}
@@ -606,6 +652,7 @@ export function destroyDesktopTray(): void {
controller = null;
trayActionBridgeWebContentsId = null;
pendingTrayActions = [];
+ accountMenuRefresh.cancel();
if (pendingTrayMenuRefresh) {
clearTimeout(pendingTrayMenuRefresh);
pendingTrayMenuRefresh = null;
diff --git a/fluxer_desktop/src/main/DockMenu.ts b/fluxer_desktop/src/main/DockMenu.ts
index b57a05483..c522cb2fb 100644
--- a/fluxer_desktop/src/main/DockMenu.ts
+++ b/fluxer_desktop/src/main/DockMenu.ts
@@ -1,6 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createChildLogger} from '@electron/common/Logger';
+import {onAccountEngineSummaries} from '@electron/main/AccountEngineHost';
+import {createRefreshThrottle} from '@electron/main/AccountMenu';
+import {buildAccountSwitchMenuItems, onAccountMenuPrivacyChange} from '@electron/main/DesktopTray';
+import {isDirectMessagesAvailable, onDirectMessagesAvailabilityChange} from '@electron/main/JumpList';
import {onLocaleChange, t} from '@electron/main/MainI18n';
import {getMainWindow, showWindow} from '@electron/main/Window';
import {app, Menu} from 'electron';
@@ -16,16 +20,22 @@ function dispatchToRenderer(channel: string): void {
}
function buildDockMenu(): Menu {
- return Menu.buildFromTemplate([
+ const accountItems = buildAccountSwitchMenuItems();
+ const items: Array<Electron.MenuItemConstructorOptions> = [
+ ...accountItems,
+ ...(accountItems.length > 0 ? [{type: 'separator' as const}] : []),
{
label: t('desktop.jumpList.openSettings'),
click: () => dispatchToRenderer('open-settings'),
},
- {
+ ];
+ if (isDirectMessagesAvailable()) {
+ items.push({
label: t('desktop.jumpList.newDirectMessage'),
click: () => dispatchToRenderer('jump-list-new-dm'),
- },
- ]);
+ });
+ }
+ return Menu.buildFromTemplate(items);
}
function refreshDockMenu(): void {
@@ -46,4 +56,7 @@ export function initializeDockMenu(): void {
installed = true;
refreshDockMenu();
onLocaleChange(refreshDockMenu);
+ onDirectMessagesAvailabilityChange(refreshDockMenu);
+ onAccountEngineSummaries(createRefreshThrottle(refreshDockMenu, 1000).schedule);
+ onAccountMenuPrivacyChange(refreshDockMenu);
}
diff --git a/fluxer_desktop/src/main/GlobalShortcutsIpc.ts b/fluxer_desktop/src/main/GlobalShortcutsIpc.ts
index c3f097c1c..f2f82b0aa 100644
--- a/fluxer_desktop/src/main/GlobalShortcutsIpc.ts
+++ b/fluxer_desktop/src/main/GlobalShortcutsIpc.ts
@@ -4,6 +4,8 @@ import {watch} from 'node:fs';
import {userInfo} from 'node:os';
import {getGlobalShortcutsSettings, setGlobalShortcutsSettings} from '@electron/common/DesktopConfig';
import {LINUX_DESKTOP_ENTRY_ID, LINUX_PORTAL_SESSION_TOKEN} from '@electron/common/DesktopIdentity';
+import {errorMessage} from '@electron/common/ErrorMessage';
+import {globalShortcutEventRevealsWindow} from '@electron/common/GlobalShortcutActions';
import {createChildLogger} from '@electron/common/Logger';
import type {GlobalShortcutsStatus} from '@electron/common/Types';
import {
@@ -28,7 +30,7 @@ import {LinuxPortalShortcutsManager} from '@electron/main/LinuxGlobalShortcutsPo
import {getFlatpakAppId, isFlatpakRuntime} from '@electron/main/LinuxSandbox';
import {getLinuxDesktop, getLinuxSessionType, isKdePlasma5Session} from '@electron/main/LinuxSession';
import {requirePrivilegedRendererDocumentSender} from '@electron/main/PrivilegedRendererDocuments';
-import {getMainWindow} from '@electron/main/Window';
+import {getMainWindow, showWindow} from '@electron/main/Window';
import {app, ipcMain, powerMonitor} from 'electron';
const logger = createChildLogger('GlobalShortcuts');
@@ -115,7 +117,7 @@ function watchLinuxInputDevices(onChange: () => void): InputDeviceWatch | null {
});
return {close: () => watcher.close()};
} catch (error) {
- log('Input device watch unavailable', {message: error instanceof Error ? error.message : String(error)});
+ log('Input device watch unavailable', {message: errorMessage(error)});
return null;
}
}
@@ -213,7 +215,9 @@ function ensureClient(event: Electron.IpcMainInvokeEvent, channel: string): numb
const senderId = sender.id;
if (!current.hasClient(senderId)) {
current.attachClient(senderId, (eventChannel, payload) => {
- if (!sender.isDestroyed()) sender.send(eventChannel, payload);
+ if (sender.isDestroyed()) return;
+ if (globalShortcutEventRevealsWindow(eventChannel, payload)) showWindow();
+ sender.send(eventChannel, payload);
});
watchSender(sender, () => engine?.detachClient(senderId));
}
diff --git a/fluxer_desktop/src/main/JumpList.ts b/fluxer_desktop/src/main/JumpList.ts
index f08731c5e..d5c8ad5ba 100644
--- a/fluxer_desktop/src/main/JumpList.ts
+++ b/fluxer_desktop/src/main/JumpList.ts
@@ -7,11 +7,40 @@ import {app} from 'electron';
const logger = createChildLogger('JumpList');
export const TASK_ARG_PREFIX = '--fluxer-task=';
-type JumpListTaskId = 'open-settings' | 'new-dm';
+export type JumpListTaskId = 'open-settings' | 'new-dm' | 'open-account-switcher';
+
+const JUMP_LIST_TASK_IDS: ReadonlySet<string> = new Set<JumpListTaskId>([
+ 'open-settings',
+ 'new-dm',
+ 'open-account-switcher',
+]);
+
+let directMessagesAvailable = true;
+const availabilitySubscribers = new Set<() => void>();
+
+export function isDirectMessagesAvailable(): boolean {
+ return directMessagesAvailable;
+}
+
+export function setDirectMessagesAvailable(available: boolean): void {
+ if (available === directMessagesAvailable) return;
+ directMessagesAvailable = available;
+ for (const subscriber of availabilitySubscribers) {
+ try {
+ subscriber();
+ } catch (error) {
+ logger.warn('Direct message availability subscriber threw', {error});
+ }
+ }
+}
+
+export function onDirectMessagesAvailabilityChange(callback: () => void): void {
+ availabilitySubscribers.add(callback);
+}
function buildTasks(): Array<Electron.Task> {
const exePath = process.execPath;
- return [
+ const tasks: Array<Electron.Task> = [
{
program: exePath,
arguments: `${TASK_ARG_PREFIX}open-settings`,
@@ -20,15 +49,26 @@ function buildTasks(): Array<Electron.Task> {
title: t('desktop.jumpList.openSettings'),
description: t('desktop.jumpList.openSettingsDescription'),
},
- {
+ ];
+ if (directMessagesAvailable) {
+ tasks.push({
program: exePath,
arguments: `${TASK_ARG_PREFIX}new-dm`,
iconPath: exePath,
iconIndex: 0,
title: t('desktop.jumpList.newDirectMessage'),
description: t('desktop.jumpList.newDirectMessageDescription'),
- },
- ];
+ });
+ }
+ tasks.push({
+ program: exePath,
+ arguments: `${TASK_ARG_PREFIX}open-account-switcher`,
+ iconPath: exePath,
+ iconIndex: 0,
+ title: t('desktop.jumpList.chooseAccount'),
+ description: t('desktop.jumpList.chooseAccountDescription'),
+ });
+ return tasks;
}
let installed = false;
@@ -51,13 +91,14 @@ export function initializeJumpList(): void {
installed = true;
refreshJumpList();
onLocaleChange(refreshJumpList);
+ onDirectMessagesAvailabilityChange(refreshJumpList);
}
export function parseJumpListTaskFromArgv(argv: ReadonlyArray<string>): JumpListTaskId | null {
for (const arg of argv) {
if (!arg.startsWith(TASK_ARG_PREFIX)) continue;
const id = arg.slice(TASK_ARG_PREFIX.length);
- if (id === 'open-settings' || id === 'new-dm') return id;
+ if (JUMP_LIST_TASK_IDS.has(id)) return id as JumpListTaskId;
}
return null;
}
diff --git a/fluxer_desktop/src/main/LinuxDesktopEntry.ts b/fluxer_desktop/src/main/LinuxDesktopEntry.ts
index 9891ac409..7d9e740ab 100644
--- a/fluxer_desktop/src/main/LinuxDesktopEntry.ts
+++ b/fluxer_desktop/src/main/LinuxDesktopEntry.ts
@@ -13,7 +13,7 @@ import {
LINUX_ICON_NAME,
} from '@electron/common/DesktopIdentity';
import {createChildLogger} from '@electron/common/Logger';
-import {TASK_ARG_PREFIX} from '@electron/main/JumpList';
+import {isDirectMessagesAvailable, onDirectMessagesAvailabilityChange, TASK_ARG_PREFIX} from '@electron/main/JumpList';
import {getStableLinuxLaunchPath} from '@electron/main/LinuxLaunchPath';
import {isFlatpakRuntime} from '@electron/main/LinuxSandbox';
import {getNativeLocale, t} from '@electron/main/MainI18n';
@@ -118,8 +118,9 @@ function buildDesktopActionExecLine(execPath: string, taskId: (typeof DESKTOP_AC
}
function buildDesktopActionEntries(execPath: string): Array<string> {
- const entries = [`Actions=${DESKTOP_ACTIONS.map((action) => action.id).join(';')};`];
- for (const action of DESKTOP_ACTIONS) {
+ const actions = DESKTOP_ACTIONS.filter((action) => action.id !== 'new-dm' || isDirectMessagesAvailable());
+ const entries = [`Actions=${actions.map((action) => action.id).join(';')};`];
+ for (const action of actions) {
entries.push(
'',
`[Desktop Action ${action.id}]`,
@@ -168,7 +169,7 @@ function digestDesktopFileBody(body: string): string {
return crypto.createHash('sha256').update(body, 'utf8').digest('hex');
}
-export function buildDesktopFileContents(execPath: string, hidden: boolean): string {
+function buildDesktopFileContents(execPath: string, hidden: boolean): string {
const body = buildDesktopFileBody(execPath, hidden);
return body.replace(
`${GENERATED_MARKER}\n`,
@@ -333,6 +334,16 @@ function syncUserDesktopEntry(): boolean {
return true;
}
+function refreshDesktopEntryActions(): void {
+ try {
+ if (syncUserDesktopEntry()) runUpdateDesktopDatabase(getUserApplicationsDir());
+ } catch (error) {
+ logger.warn('Failed to rewrite the Linux .desktop entry actions', {filePath: getDesktopFilePath(), error});
+ }
+}
+
+let actionRefreshSubscribed = false;
+
function desktopEntryResolves(): boolean {
return findSystemDesktopEntry() !== null || readExistingDesktopFile(getDesktopFilePath()) !== null;
}
@@ -363,6 +374,10 @@ export function ensureLinuxDesktopEntry(): boolean {
});
}
if (changed) runUpdateDesktopDatabase(getUserApplicationsDir());
+ if (!actionRefreshSubscribed) {
+ actionRefreshSubscribed = true;
+ onDirectMessagesAvailabilityChange(refreshDesktopEntryActions);
+ }
const resolves = desktopEntryResolves();
if (resolves) registerProtocolClient();
return resolves;
diff --git a/fluxer_desktop/src/main/MainI18n.ts b/fluxer_desktop/src/main/MainI18n.ts
index ae0e3ff41..526351260 100644
--- a/fluxer_desktop/src/main/MainI18n.ts
+++ b/fluxer_desktop/src/main/MainI18n.ts
@@ -98,6 +98,13 @@ const FALLBACK_STRINGS: Readonly<Record<string, string>> = Object.freeze({
'desktop.jumpList.openSettingsDescription': 'Open {appName} settings',
'desktop.jumpList.newDirectMessage': 'New direct message',
'desktop.jumpList.newDirectMessageDescription': 'Compose a new direct message',
+ 'desktop.jumpList.chooseAccount': 'Choose an account',
+ 'desktop.jumpList.chooseAccountDescription': 'Switch to another signed-in account',
+ 'desktop.tray.accounts': 'Accounts',
+ 'desktop.tray.chooseAccount': 'Choose an account…',
+ 'desktop.tray.accountWithHost': '{name} ({host})',
+ 'desktop.tray.accountWithMentions': '{label} · {count}',
+ 'desktop.tray.accountNumbered': 'Account {number}',
'desktop.notifications.open': 'Open',
'desktop.themes.addLocalFiles': 'Add local files',
'desktop.themes.importFolder': 'Import folder',
diff --git a/fluxer_desktop/src/main/NotificationTargets.ts b/fluxer_desktop/src/main/NotificationTargets.ts
new file mode 100644
index 000000000..1b5c306f5
--- /dev/null
+++ b/fluxer_desktop/src/main/NotificationTargets.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+export interface NotificationTarget {
+ readonly accountKey: string | null;
+ readonly url: string | null;
+}
+
+const MAX_NOTIFICATION_TARGETS = 1000;
+
+export class NotificationTargets {
+ private readonly targets = new Map<string, NotificationTarget>();
+ private readonly capacity: number;
+
+ constructor(capacity: number = MAX_NOTIFICATION_TARGETS) {
+ this.capacity = capacity;
+ }
+
+ remember(id: string, target: NotificationTarget): void {
+ this.targets.delete(id);
+ this.targets.set(id, target);
+ while (this.targets.size > this.capacity) {
+ const oldest = this.targets.keys().next().value;
+ if (oldest === undefined) return;
+ this.targets.delete(oldest);
+ }
+ }
+
+ take(id: string): NotificationTarget | null {
+ const target = this.targets.get(id) ?? null;
+ this.targets.delete(id);
+ return target;
+ }
+
+ forget(id: string): void {
+ this.targets.delete(id);
+ }
+}
+
+export function readNotificationAccountKey(value: unknown): string | null {
+ return typeof value === 'string' && value.length > 0 && value.length <= 2048 ? value : null;
+}
+
+export function readNotificationUrl(value: unknown): string | null {
+ return typeof value === 'string' && value.length > 0 && value.length <= 8192 ? value : null;
+}
diff --git a/fluxer_desktop/src/main/NotificationsIpc.ts b/fluxer_desktop/src/main/NotificationsIpc.ts
index 414e2140d..c7496dd75 100644
--- a/fluxer_desktop/src/main/NotificationsIpc.ts
+++ b/fluxer_desktop/src/main/NotificationsIpc.ts
@@ -2,6 +2,7 @@
import {createRequire} from 'node:module';
import {DESKTOP_APP_NAME} from '@electron/common/DesktopIdentity';
+import {errorMessage} from '@electron/common/ErrorMessage';
import {createChildLogger} from '@electron/common/Logger';
import type {NotificationOptions} from '@electron/common/Types';
import {getNativeNotificationsMode} from '@electron/main/LaunchOptions';
@@ -9,6 +10,7 @@ import {getLinuxDesktopId} from '@electron/main/LinuxSandbox';
import {t} from '@electron/main/MainI18n';
import {resolveNotificationIcon} from '@electron/main/NotificationIcon';
import {shouldPlayNotificationSound} from '@electron/main/NotificationState';
+import {NotificationTargets, readNotificationAccountKey, readNotificationUrl} from '@electron/main/NotificationTargets';
import {requirePrivilegedRendererDocumentSender} from '@electron/main/PrivilegedRendererDocuments';
import {type BrowserWindow, ipcMain, Notification, nativeImage} from 'electron';
@@ -60,7 +62,6 @@ type NativeNotificationsCtor = new (
interface NativeNotificationsModule {
FreedesktopNotifications: NativeNotificationsCtor | null;
- getServerInformation: (() => Promise<{name: string; vendor: string; version: string; specVersion: string}>) | null;
loadError: Error | null;
}
@@ -135,7 +136,7 @@ function loadLinuxNotificationsModule(): NativeNotificationsModule | null {
} catch (error) {
throw new Error(
`@fluxer/linux-notifications failed to load on Linux — this is a packaging bug, not a runtime fallback case. ` +
- `Original error: ${error instanceof Error ? error.message : String(error)}`,
+ `Original error: ${errorMessage(error)}`,
);
}
assertLinuxNotificationsModule(mod);
@@ -169,7 +170,17 @@ let linuxNativeClient: NativeNotificationClient | null = null;
let linuxNativeWindowGetter: (() => BrowserWindow | null) | null = null;
const linuxNativeIdToString = new Map<number, string>();
-const linuxNativeStringToOptions = new Map<string, NotificationOptions>();
+const notificationTargets = new NotificationTargets();
+
+function sendNotificationClick(getMainWindow: () => BrowserWindow | null, id: string): void {
+ const target = notificationTargets.take(id);
+ const mainWindow = getMainWindow();
+ if (!mainWindow) return;
+ if (mainWindow.isMinimized()) mainWindow.restore();
+ mainWindow.show();
+ mainWindow.focus();
+ mainWindow.webContents.send('notification-click', id, target?.url ?? null, target?.accountKey ?? null);
+}
function getNotificationId(options: NotificationOptions): string {
return options.id && options.id.length > 0 ? options.id : `notification-${++notificationIdCounter}`;
@@ -199,14 +210,7 @@ function ensureLinuxNativeClient(getMainWindow: () => BrowserWindow | null): Nat
const stringId = linuxNativeIdToString.get(event.id);
if (event.kind === 'actionInvoked') {
if (!stringId) return;
- const options = linuxNativeStringToOptions.get(stringId);
- const mainWindow = linuxNativeWindowGetter ? linuxNativeWindowGetter() : null;
- if (mainWindow) {
- if (mainWindow.isMinimized()) mainWindow.restore();
- mainWindow.show();
- mainWindow.focus();
- mainWindow.webContents.send('notification-click', stringId, options?.url);
- }
+ sendNotificationClick(linuxNativeWindowGetter ?? (() => null), stringId);
cleanupLinuxNativeNotification(stringId, event.id);
} else if (event.kind === 'closed') {
if (stringId) cleanupLinuxNativeNotification(stringId, event.id);
@@ -227,7 +231,7 @@ function cleanupLinuxNativeNotification(stringId: string, nativeId: number): voi
const handle = activeNotifications.get(stringId);
if (handle?.type === 'linux-native' && handle.nativeId === nativeId) {
activeNotifications.delete(stringId);
- linuxNativeStringToOptions.delete(stringId);
+ notificationTargets.forget(stringId);
}
linuxNativeIdToString.delete(nativeId);
}
@@ -301,7 +305,6 @@ async function showLinuxNativeNotification(
linuxNativeIdToString.delete(replacesId);
}
linuxNativeIdToString.set(nativeId, id);
- linuxNativeStringToOptions.set(id, options);
activeNotifications.set(id, {type: 'linux-native', nativeId});
} catch (error) {
throw new Error(
@@ -329,15 +332,21 @@ export function registerNotificationIpcHandlers(getMainWindow: () => BrowserWind
}> => {
requirePrivilegedRendererDocumentSender(event, 'show-notification');
const id = getNotificationId(options);
+ notificationTargets.remember(id, {
+ accountKey: readNotificationAccountKey(options.accountKey),
+ url: readNotificationUrl(options.url),
+ });
if (process.platform === 'linux') {
await showLinuxNativeNotification(id, options, getMainWindow);
return {id};
}
const previousHandle = activeNotifications.get(id);
if (previousHandle) {
- closeNotificationHandle(id, previousHandle);
+ deleteActiveNotification(id, previousHandle);
+ if (previousHandle.type === 'electron') previousHandle.notification.close();
}
if (!Notification.isSupported()) {
+ notificationTargets.forget(id);
return {id};
}
const notificationOpts: Electron.NotificationConstructorOptions = {
@@ -360,19 +369,14 @@ export function registerNotificationIpcHandlers(getMainWindow: () => BrowserWind
const handle: NotificationHandle = {type: 'electron', notification};
activeNotifications.set(id, handle);
notification.on('click', () => {
- const mainWindow = getMainWindow();
- if (mainWindow) {
- if (mainWindow.isMinimized()) {
- mainWindow.restore();
- }
- mainWindow.show();
- mainWindow.focus();
- mainWindow.webContents.send('notification-click', id, options.url);
- }
+ if (activeNotifications.get(id) !== handle) return;
deleteActiveNotification(id, handle);
+ sendNotificationClick(getMainWindow, id);
});
notification.on('close', () => {
+ if (activeNotifications.get(id) !== handle) return;
deleteActiveNotification(id, handle);
+ notificationTargets.forget(id);
});
notification.show();
return {id};
@@ -393,8 +397,9 @@ export function registerNotificationIpcHandlers(getMainWindow: () => BrowserWind
function closeNotificationHandle(id: string, handle: ActiveNotificationHandle): void {
if (handle.type === 'electron') {
- handle.notification.close();
deleteActiveNotification(id, handle);
+ notificationTargets.forget(id);
+ handle.notification.close();
return;
}
if (linuxNativeClient) {
diff --git a/packages/desktop_ipc/src/DesktopBridgeTypes.ts b/packages/desktop_ipc/src/DesktopBridgeTypes.ts
index 0adab8795..785b6d947 100644
--- a/packages/desktop_ipc/src/DesktopBridgeTypes.ts
+++ b/packages/desktop_ipc/src/DesktopBridgeTypes.ts
@@ -297,6 +297,7 @@ export interface TrayRuntimeStatePayload {
selfDeaf: boolean;
presenceStatus: TrayPresenceStatus | null;
buildInfo: string | null;
+ hidePersonalInformation: boolean;
}
export type GlobalShortcutsBackend = 'portal' | 'x11' | 'evdev' | 'windows' | 'macos' | 'none';
diff --git a/packages/desktop_ipc/src/DirectMessagesContract.ts b/packages/desktop_ipc/src/DirectMessagesContract.ts
new file mode 100644
index 000000000..6ffee657e
--- /dev/null
+++ b/packages/desktop_ipc/src/DirectMessagesContract.ts
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+export const DESKTOP_DIRECT_MESSAGES_AVAILABLE_CHANNEL = 'direct-messages-availability-set';