super-productivity/electron/main-window.ts
Johannes Millan 01e30b9c7e
Feat/to me it looks like there are lots of 60dd04 (#7280)
* fix(issue): prevent crash from orphan issueProviderId (#7135)

The Jira image-headers effect in task-detail-panel subscribed to
selectIssueProviderById without an error handler, so a task with an
issueProviderId pointing at a deleted provider (e.g. after sync
convergence where taskIdsToUnlink didn't cover all local tasks)
propagated the selector throw to Zone.js as a crash dialog. Wrap the
inner selector observable in catchError that logs and falls back to
of(null); the downstream jiraCfg?.isEnabled guard handles the fallback.

Also drop IssueLog.log(issueProviderKey, issueProvider) from the
throwing variant of the selector: providers may carry credentials
(host, token, apiKey) and IssueLog history is exportable.

* fix(focus-mode): sync tray countdown with in-app timer during breaks

Tray title was rebuilt from a cached currentFocusSessionTime that only
refreshed when CURRENT_TASK_UPDATED fired. addTimeSpent is gated on an
active current task, so during focus-mode breaks or task-less focus
sessions the cache froze while the in-app timer kept ticking.

Add the tick action to taskChangeElectron$ so the cache refreshes every
second whenever the focus timer is running.

Fixes #7278

* fix(ci): restore GitHub Actions SHA pins undone by 0e9218bd68

Commit 0e9218bd68 silently reverted PR #7212 (github-actions-minor group
bump) along with its stated sync/client-id work. This restores the 15
workflow files to their pre-revert state.

Actions restored to newer pinned SHAs:
- actions/upload-artifact v7.0.0 -> v7.0.1
- step-security/harden-runner v2.16.1 -> v2.17.0
- softprops/action-gh-release v2.6.1 -> v3.0.0
- signpath/github-action-submit-signing-request v2.0 -> v2.1
- anthropics/claude-code-action v1.0.89 -> v1.0.93
- docker/build-push-action v7.0.0 -> v7.1.0
- easingthemes/ssh-deploy v5.1.1 -> v6.0.3

* fix: restore i18n, UI, and docs work undone by 0e9218bd68

Commit 0e9218bd68 silently reverted the following work alongside its stated
sync/client-id changes. Files where later master commits (fec7b25f23, etc.)
already re-applied the reverted work are intentionally left untouched.

Restored:
- #7232 docs/long-term-plans/location-based-reminders.md (513 lines)
- #7199 Romanian i18n phase 3 (ro.json + ro-md.json, ~1168 lines)
- #7049 Polish translation improvements
- #7143 planner component styling (4 scss files)
- #7211 add-task-bar preserve time estimate when typing title
- #7208 task.reducer roll-up estimates for added subtasks
- #6767 focus-mode pomodoro reset button
- #7205 plugin-dev github-issue-provider TOKEN description
- #7231 mobile-bottom-nav FAB fix
- a4fe03272 iOS keyboard accessory bar (global-theme + dialog-fullscreen-markdown)
- 309670db3 ShortSyntaxEffects undefined guard
- 667a7986f Dropbox PKCE auth comment/behavior

* fix(electron): restore electron + e2e work undone by 0e9218bd68

Commit 0e9218bd68 silently reverted the following electron/e2e work.
Files already re-fixed by later master commits are left as-is:
- e2e/tests/sync/supersync-archive-conflict.spec.ts (de33234976 + 191d129ff3)

Restored:
- e8a3e156eb fix(electron): Linux autostart IDB backing-store recovery
  (re-adds electron/clear-stale-idb-locks.ts + start-app.ts wiring)
- 5ce78a5b63 fix(electron): macOS Cmd+Q / Dock > Quit hang
  (setIsQuiting + before-quit delegate to close-handler)
- 46e0fa2d01 fix(sync): FILE_SYNC_LIST_FILES IPC contract
  (electronAPI.d.ts + local-file-sync + preload + ipc-events)
- ea1ef16307 fix(android): session-only SAF permissions on OEM devices
- 8865dc0a50 test(e2e): supersync parallel-worker stampede guard
  (SUPERSYNC_SERVER_HEALTHY env-var fallback + goto retry loop)
- af7c7687e2 test(e2e): block WS-triggered downloads in non-WS specs
- 265b44db5d test(e2e): premature waitForURL on daily-summary
  (this is literally the fix the bad commit's message claimed to add)

Conflict resolutions:
- e2e/utils/supersync-helpers.ts: kept the refined getDoneTaskElement
  checks from d64014d086 (later than c558bcab5e) while restoring the
  goto retry loop from 8865dc0a50.
- electron/start-app.ts: unioned imports (setIsQuiting +
  clearStaleLevelDbLocks from theirs, fs from ours).

* fix(sync): restore sync-core work undone by 0e9218bd68

Commit 0e9218bd68 silently reverted parts of several sync fixes. Most
sync-core reverts have already been re-addressed differently on master
by later commits (1f5184f6e7, 05cd875dd6, 09f5ced2c9, 7df43358ab,
d9158d6adb, 32dbc95ed9, 8c3b08e016, f89fe1ebc3) — those files are
intentionally left untouched to avoid reverting master's newer work.

This PR restores only the pieces that are genuinely still missing:

- e8a3e156eb fix(electron): IDB backing-store autoreload (in-app piece)
  operation-log-hydrator.service.ts + .spec.ts (the electron/clear-
  stale-idb-locks.ts piece was restored in the prior commit)

Plus three low-risk documentation/cleanup restorations:
- operation-sync.util.ts — add "Nextcloud" to isFileBasedProvider JSDoc
- dropbox.ts — restore improved _getRedirectUri JSDoc (667a7986fb)
- dialog-get-and-enter-auth-code.component.ts — restore isNativePlatform
  comment explaining why manual code entry flow is used (667a7986fb)
- file-adapter.interface.ts — remove stray "// NEW" comment (46e0fa2d01)

Intentionally NOT restored (master's newer work covers or supersedes):
- sync-trigger.service.ts / sync.effects.ts (05cd875dd6)
- sync-wrapper.service.ts (1f5184f6e7)
- sync-errors.ts (1f5184f6e7 re-added LegacySyncFormatDetectedError)
- file-based-sync-adapter.service.ts + spec (1f5184f6e7 + d9158d6adb)
- file-based-sync.types.ts (1f5184f6e7)
- operation-log.const.ts (32dbc95ed9 bumped IDB_OPEN_RETRIES to 5)
- dialog-sync-initial-cfg.component.ts (f89fe1ebc3)
2026-04-20 12:04:38 +02:00

561 lines
17 KiB
TypeScript

import windowStateKeeper from 'electron-window-state';
import {
App,
BrowserWindow,
BrowserWindowConstructorOptions,
ipcMain,
Menu,
MenuItemConstructorOptions,
nativeTheme,
shell,
} from 'electron';
import { errorHandlerWithFrontendInform } from './error-handler-with-frontend-inform';
import * as path from 'path';
import { join, normalize } from 'path';
import { IPC } from './shared-with-frontend/ipc-events.const';
import { readFileSync, stat } from 'fs';
import { error, log } from 'electron-log/main';
import { IS_MAC, IS_GNOME_DESKTOP } from './common.const';
import {
destroyTaskWidget,
getIsTaskWidgetAlwaysShow,
hideTaskWidget,
showTaskWidget,
} from './task-widget/task-widget';
import { ensureIndicator } from './indicator';
import { getIsMinimizeToTray, getIsQuiting, setIsQuiting } from './shared-state';
import { loadSimpleStoreAll } from './simple-store';
import { SimpleStoreKey } from './shared-with-frontend/simple-store.const';
let mainWin: BrowserWindow;
/**
* Returns theme-aware background color for titlebar overlay.
* Semi-transparent to ensure window controls are always visible.
*/
const getTitleBarColor = (isDark: boolean): string => {
// Dark: matches --bg (#131314) with 0% opacity (fully transparent)
// Light: matches --bg (#f8f8f7) with 0% opacity (fully transparent)
return isDark ? 'rgba(19, 19, 20, 0)' : 'rgba(248, 248, 247, 0)';
};
const mainWinModule: {
win?: BrowserWindow;
isAppReady: boolean;
} = {
win: undefined,
isAppReady: false,
};
export const getWin = (): BrowserWindow => {
if (!mainWinModule.win) {
throw new Error('No main window');
}
return mainWinModule.win;
};
export const getIsAppReady = (): boolean => {
return mainWinModule.isAppReady;
};
export const createWindow = async ({
IS_DEV,
ICONS_FOLDER,
quitApp,
app,
customUrl,
}: {
IS_DEV: boolean;
ICONS_FOLDER: string;
quitApp: () => void;
app: App;
customUrl?: string;
}): Promise<BrowserWindow> => {
// make sure the main window isn't already created
if (mainWin) {
errorHandlerWithFrontendInform('Main window already exists');
return mainWin;
}
// workaround for https://github.com/electron/electron/issues/16521
if (!IS_MAC) {
Menu.setApplicationMenu(null);
}
const mainWindowState = windowStateKeeper({
defaultWidth: 800,
defaultHeight: 800,
});
const simpleStore = await loadSimpleStoreAll();
const persistedIsUseCustomWindowTitleBar =
simpleStore[SimpleStoreKey.IS_USE_CUSTOM_WINDOW_TITLE_BAR];
const legacyIsUseObsidianStyleHeader =
simpleStore[SimpleStoreKey.LEGACY_IS_USE_OBSIDIAN_STYLE_HEADER];
const userPrefersCustomWindowTitleBar =
persistedIsUseCustomWindowTitleBar ??
legacyIsUseObsidianStyleHeader ??
!IS_GNOME_DESKTOP;
// GNOME + Wayland combinations can miss native controls when titleBarStyle is hidden.
// Force native decorations on GNOME to keep window controls available.
const isUseCustomWindowTitleBar = IS_GNOME_DESKTOP
? false
: userPrefersCustomWindowTitleBar;
const titleBarStyle: BrowserWindowConstructorOptions['titleBarStyle'] =
isUseCustomWindowTitleBar || IS_MAC ? 'hidden' : 'default';
// Determine initial symbol color based on system theme preference
const initialSymbolColor = nativeTheme.shouldUseDarkColors ? '#fff' : '#000';
const titleBarOverlay: BrowserWindowConstructorOptions['titleBarOverlay'] =
isUseCustomWindowTitleBar && !IS_MAC
? {
color: getTitleBarColor(nativeTheme.shouldUseDarkColors),
symbolColor: initialSymbolColor,
height: 44,
}
: undefined;
mainWin = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
minHeight: 240,
minWidth: 300,
title: IS_DEV ? 'Super Productivity D' : 'Super Productivity',
titleBarStyle,
titleBarOverlay,
show: false,
webPreferences: {
scrollBounce: true,
backgroundThrottling: false,
// CORS is handled at the session level via onBeforeSendHeaders (strips Origin)
// and onHeadersReceived (injects Access-Control-Allow-* headers)
webSecurity: true,
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
// make remote module work with those two settings
contextIsolation: true,
// Additional settings for better Linux/Wayland compatibility
enableBlinkFeatures: 'OverlayScrollbar',
// Disable spell checker to prevent connections to Google services (#5314)
// This maintains our "offline-first with zero data collection" promise
spellcheck: false,
},
icon: ICONS_FOLDER + '/icon_256x256.png',
// Wayland compatibility: disable transparent/frameless features that can cause issues
transparent: false,
// frame: true,
});
// see: https://pratikpc.medium.com/bypassing-cors-with-electron-ab7eaf331605
mainWin.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
const { requestHeaders } = details;
removeKeyInAnyCase(requestHeaders, 'Origin');
removeKeyInAnyCase(requestHeaders, 'Referer');
removeKeyInAnyCase(requestHeaders, 'Cookie');
removeKeyInAnyCase(requestHeaders, 'sec-ch-ua');
removeKeyInAnyCase(requestHeaders, 'sec-ch-ua-mobile');
removeKeyInAnyCase(requestHeaders, 'sec-ch-ua-platform');
removeKeyInAnyCase(requestHeaders, 'sec-fetch-dest');
removeKeyInAnyCase(requestHeaders, 'sec-fetch-mode');
removeKeyInAnyCase(requestHeaders, 'sec-fetch-site');
removeKeyInAnyCase(requestHeaders, 'accept-encoding');
removeKeyInAnyCase(requestHeaders, 'accept-language');
removeKeyInAnyCase(requestHeaders, 'priority');
removeKeyInAnyCase(requestHeaders, 'accept');
// NOTE this is needed for GitHub api requests to work :(
// office365 needs a User-Agent as well (#4677)
if (
['github.com', 'office365.com', 'outlook.live.com'].includes(
new URL(details.url).hostname,
)
) {
removeKeyInAnyCase(requestHeaders, 'User-Agent');
}
callback({ requestHeaders });
});
mainWin.webContents.session.webRequest.onHeadersReceived((details, callback) => {
const { responseHeaders } = details;
upsertKeyValue(responseHeaders, 'Access-Control-Allow-Origin', ['*']);
upsertKeyValue(responseHeaders, 'Access-Control-Allow-Headers', ['*']);
upsertKeyValue(responseHeaders, 'Access-Control-Allow-Methods', ['*']);
// CORS preflight must return 2xx to pass the browser check. Stripping
// the Origin header (above) can cause some servers to respond with a
// non-200 status for OPTIONS, which the browser rejects even with the
// injected CORS headers.
const statusLine =
details.method === 'OPTIONS' && details.statusCode >= 300
? 'HTTP/1.1 200 OK'
: undefined;
callback({
responseHeaders,
statusLine,
});
});
// Deny unnecessary permissions (webcam, microphone, geolocation, etc.)
// The app only needs notifications for desktop reminders
const allowedPermissions = ['notifications'];
mainWin.webContents.session.setPermissionRequestHandler(
(_webContents, permission, callback) => {
callback(allowedPermissions.includes(permission));
},
);
mainWin.webContents.session.setPermissionCheckHandler((_webContents, permission) => {
return allowedPermissions.includes(permission);
});
mainWindowState.manage(mainWin);
const url = customUrl
? customUrl
: IS_DEV
? 'http://localhost:4200'
: `file://${normalize(join(__dirname, '../.tmp/angular-dist/browser/index.html'))}`;
mainWin.loadURL(url).then(() => {
// Set window title for dev mode
if (IS_DEV) {
mainWin.setTitle('Super Productivity D');
}
// load custom stylesheet if any
const CSS_FILE_PATH = app.getPath('userData') + '/styles.css';
stat(app.getPath('userData') + '/styles.css', (err) => {
if (err) {
log('No custom styles detected at ' + CSS_FILE_PATH);
} else {
log('Loading custom styles from ' + CSS_FILE_PATH);
const styles = readFileSync(CSS_FILE_PATH, { encoding: 'utf8' });
try {
mainWin.webContents.insertCSS(styles);
log('Custom styles loaded successfully');
} catch (cssError) {
error('Failed to load custom styles:', cssError);
}
}
});
});
// show gracefully
mainWin.once('ready-to-show', () => {
mainWin.show();
// Workaround for Windows phantom focus bug (electron#20464):
// show() can silently fail to acquire keyboard focus after reboot.
// blur() is not supported on Wayland and limited on macOS, so only
// apply the blur+focus cycle on Windows.
const IS_WINDOWS = process.platform === 'win32';
setTimeout(() => {
if (mainWin.isDestroyed()) return;
if (IS_WINDOWS) {
mainWin.blur();
}
mainWin.focus();
if (!mainWin.webContents.isDestroyed()) {
mainWin.webContents.focus();
}
}, 60);
});
initWinEventListeners(app);
if (IS_MAC) {
createMenu(quitApp);
} else {
mainWin.setMenu(null);
mainWin.setMenuBarVisibility(false);
}
// update prop
mainWinModule.win = mainWin;
// listen for app ready
ipcMain.on(IPC.APP_READY, () => {
mainWinModule.isAppReady = true;
});
// Register F11 key handler for fullscreen toggle
mainWin.webContents.on('before-input-event', (event, input) => {
if (input.type === 'keyDown' && input.key === 'F11') {
event.preventDefault();
mainWin.setFullScreen(!mainWin.isFullScreen());
}
});
// Notify renderer of fullscreen state changes (used for app border visibility)
mainWin.on('enter-full-screen', () => {
mainWin.webContents.send(IPC.ENTER_FULL_SCREEN);
});
mainWin.on('leave-full-screen', () => {
mainWin.webContents.send(IPC.LEAVE_FULL_SCREEN);
});
mainWin.webContents.on('did-finish-load', () => {
if (mainWin.isFullScreen()) {
mainWin.webContents.send(IPC.ENTER_FULL_SCREEN);
}
});
// Listen for theme changes to update title bar overlay color and symbol
if (isUseCustomWindowTitleBar && !IS_MAC) {
ipcMain.on(IPC.UPDATE_TITLE_BAR_DARK_MODE, (ev, isDarkMode: boolean) => {
try {
const symbolColor = isDarkMode ? '#fff' : '#000';
mainWin.setTitleBarOverlay({
color: getTitleBarColor(isDarkMode),
symbolColor,
height: 44,
});
} catch (e) {
// setTitleBarOverlay may not be available on all platforms
log('Failed to update title bar overlay:', e);
}
});
}
return mainWin;
};
// isMaximized() can return an incorrect value after hide() — this is a known issue on certain platforms/configurations (electron#27838).
// to ensure maximized window state is restored reliably across all platforms, we manually track maximized state before hiding
let wasMaximizedBeforeHide: boolean = false;
export const getWasMaximizedBeforeHide = (): boolean => wasMaximizedBeforeHide;
export const setWasMaximizedBeforeHide = (value: boolean): void => {
wasMaximizedBeforeHide = value;
};
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
function initWinEventListeners(app: Electron.App): void {
const openUrlInBrowser = (url: string): void => {
// needed for mac; especially for jira urls we might have a host like this www.host.de//
const urlObj = new URL(url);
urlObj.pathname = urlObj.pathname.replace('//', '/');
const wellFormedUrl = urlObj.toString();
// shell.openExternal returns Promise<void>; surface the failure reason instead
// of silently swallowing it (e.g. when xdg-open / Flatpak portal rejects the URI).
shell.openExternal(wellFormedUrl).catch((err) => {
error('Failed to open external URL via shell.openExternal:', err);
});
};
// open new window links in browser
mainWin.webContents.on('will-navigate', (ev, url) => {
if (!url.includes('localhost')) {
ev.preventDefault();
openUrlInBrowser(url);
}
});
mainWin.webContents.setWindowOpenHandler((details) => {
openUrlInBrowser(details.url);
return { action: 'deny' };
});
// TODO refactor quitting mess
appCloseHandler(app);
appMinimizeHandler(app);
// Handle restore and show events to hide task widget
mainWin.on('restore', () => {
if (!getIsTaskWidgetAlwaysShow()) {
hideTaskWidget();
}
});
mainWin.on('show', () => {
if (!getIsTaskWidgetAlwaysShow()) {
hideTaskWidget();
}
});
mainWin.on('focus', () => {
if (mainWin.isVisible() && !mainWin.isMinimized() && !getIsTaskWidgetAlwaysShow()) {
hideTaskWidget();
}
});
// Handle hide event to show task widget
mainWin.on('hide', () => {
showTaskWidget();
});
// Handle maximize and unmaximize events to change wasMaximizedBeforeHide flag accordingly
mainWin.on('maximize', () => {
setWasMaximizedBeforeHide(true);
});
mainWin.on('unmaximize', () => {
setWasMaximizedBeforeHide(false);
});
}
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
function createMenu(quitApp: () => void): void {
// Create application menu to enable copy & pasting on MacOS
const menuTpl: MenuItemConstructorOptions[] = [
{
label: 'Application',
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{
label: 'Quit',
accelerator: 'CmdOrCtrl+Q',
click: quitApp,
},
],
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'selectAll' },
],
},
];
// we need to set a menu to get copy & paste working for mac os x
Menu.setApplicationMenu(Menu.buildFromTemplate(menuTpl));
}
// TODO this is ugly as f+ck
const appCloseHandler = (app: App): void => {
let ids: string[] = [];
const _quitApp = (): void => {
setIsQuiting(true);
// Destroy task widget before closing main window to ensure window-all-closed fires
destroyTaskWidget();
mainWin.close();
};
ipcMain.on(IPC.REGISTER_BEFORE_CLOSE, (ev, { id }) => {
ids.push(id);
});
ipcMain.on(IPC.UNREGISTER_BEFORE_CLOSE, (ev, { id }) => {
ids = ids.filter((idIn) => idIn !== id);
});
ipcMain.on(IPC.BEFORE_CLOSE_DONE, (ev, { id }) => {
ids = ids.filter((idIn) => idIn !== id);
log(IPC.BEFORE_CLOSE_DONE, id, ids);
if (ids.length === 0) {
// Destroy task widget before closing main window
destroyTaskWidget();
mainWin.close();
}
});
mainWin.on('close', (event) => {
// NOTE: this might not work if we run a second instance of the app
log('close event: isQuiting=', getIsQuiting(), 'pendingBeforeCloseIds=', ids);
if (!getIsQuiting()) {
if (getIsMinimizeToTray()) {
const indicator = ensureIndicator();
if (indicator) {
event.preventDefault();
setWasMaximizedBeforeHide(mainWin.isMaximized());
mainWin.hide();
showTaskWidget();
return;
}
}
event.preventDefault();
if (ids.length > 0) {
log('Actions to wait for ', ids);
mainWin.webContents.send(IPC.NOTIFY_ON_CLOSE, ids);
} else {
_quitApp();
}
}
});
mainWin.on('closed', () => {
// Dereference the window object
mainWin = null;
mainWinModule.win = null;
});
mainWin.webContents.on('render-process-gone', (event, detailed) => {
log('!crashed, reason: ' + detailed.reason + ', exitCode = ' + detailed.exitCode);
if (detailed.reason == 'crashed') {
process.exit(detailed.exitCode);
// relaunch app
// app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) });
// app.exit(0);
}
});
};
const appMinimizeHandler = (app: App): void => {
if (!getIsQuiting()) {
// TODO find reason for the typing error
// @ts-ignore
mainWin.on('minimize', (event: Event) => {
if (getIsMinimizeToTray()) {
const indicator = ensureIndicator();
if (!indicator) {
return;
}
event.preventDefault();
setWasMaximizedBeforeHide(mainWin.isMaximized());
mainWin.hide();
showTaskWidget();
} else {
// For regular minimize (not to tray), also show task widget
showTaskWidget();
if (IS_MAC) {
app.dock?.show();
}
}
});
}
};
const upsertKeyValue = <T extends Record<string, any> | undefined>(
obj: T,
keyToChange: string,
value: string[],
): T => {
if (!obj) return obj;
const keyToChangeLower = keyToChange.toLowerCase();
for (const key of Object.keys(obj)) {
if (key.toLowerCase() === keyToChangeLower) {
// Reassign old key
(obj as any)[key] = value;
// Done
return obj;
}
}
// Insert at end instead
(obj as any)[keyToChange] = value;
return obj;
};
const removeKeyInAnyCase = <T extends Record<string, any> | undefined>(
obj: T,
keyToRemove: string,
): T => {
if (!obj) return obj;
const keyToRemoveLower = keyToRemove.toLowerCase();
for (const key of Object.keys(obj)) {
if (key.toLowerCase() === keyToRemoveLower) {
delete (obj as any)[key];
return obj;
}
}
return obj;
};