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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,25 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- **The favourite drawing tools bar can be moved.** Drag it by the grip on its left end to anywhere
on the charts; it stays there after a restart and keeps inside the charts when the window shrinks.

### Changed

- **Sync looks after itself and stays quiet.** Problems you cannot act on are retried by themselves
instead of stopping sync until you press Try again. The status bar shows a small cloud icon that
no longer flickers to "Syncing" on every check; words appear only when sync needs you, such as
confirming large deletions or reconnecting GitHub.

### Fixed

- The drawing rail's cursor, magnet, Stay in Drawing Mode, Lock and Hide settings are kept between
launches instead of resetting each time the app opens.
- The main window reopens at the size and position it was closed at, maximised or full screen if it
was. A window last left on a monitor that is no longer connected opens on the main screen.

## [1.1.0] - 2026-11-06

### Added
Expand Down
11 changes: 9 additions & 2 deletions electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { loadAccounts, secretCipher } from './accounts';
import { SessionPool } from './session-pool';
import { handleTradingView } from './tradingview';
import { AppZoom } from './app-zoom';
import { WindowBounds } from './window-bounds';
import { isZoomStep } from '../shared/zoom';
import { AutomationHost } from './automation-host';
import type { AutomationEvent, AutomationMethod } from '../shared/automation';
Expand Down Expand Up @@ -199,6 +200,8 @@ async function applySettings(): Promise<void> {
}

const zoom = new AppZoom(path.join(app.getPath('userData'), 'zoom.json'), (factor) => send('zoom', factor));
const windowBounds = new WindowBounds(path.join(app.getPath('userData'), 'window.json'));
const minimumSize = { width: 960, height: 600 };

// Charts popped out of the layout: windows the renderer opens on about:blank and draws into itself.
const popoutPrefix = 'openterm-pip-';
Expand Down Expand Up @@ -226,11 +229,13 @@ function closePopouts(): void {

function createWindow(): void {
isSyncFlushed = false;
const workAreas = [screen.getPrimaryDisplay(), ...screen.getAllDisplays()].map((display) => display.workArea);
window = new BrowserWindow({
width: 1440,
height: 900,
minWidth: 960,
minHeight: 600,
...windowBounds.options(workAreas, minimumSize),
minWidth: minimumSize.width,
minHeight: minimumSize.height,
title: 'OpenTerm5',
show: false,
// macOS takes the icon from the app bundle; Linux and Windows need it on the window.
Expand All @@ -245,6 +250,7 @@ function createWindow(): void {
nodeIntegration: false,
},
});
windowBounds.track(window);
window.once('ready-to-show', () => window?.show());
window.on('focus', () => sync?.setFocused(true));
window.on('blur', () => sync?.setFocused(false));
Expand Down Expand Up @@ -628,6 +634,7 @@ if (!app.requestSingleInstanceLock()) {
installMenu();
settings = await loadSettings();
await zoom.load();
await windowBounds.load();
await device.load();
try { accounts = await loadAccounts(() => sync?.noteLocalChange()); }
catch { journal('Saved accounts could not be loaded. Log in manually.', 'Accounts'); }
Expand Down
23 changes: 23 additions & 0 deletions electron/sync-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,29 @@ test('being offline retries later instead of stopping', async () => {
assert.equal(first.view().status, 'idle');
});

test('an unexpected failure retries quietly, is journalled once and clears on its own', async () => {
const github = fakeGitHub();
const chart = new MemorySource('chart');
const { first } = await setUpFirst(github, null, [chart]);
const snapshot = chart.snapshot.bind(chart);
let failures = 2;
chart.snapshot = async () => {
if (failures-- > 0) throw new Error('disk busy');
return snapshot();
};
await first.service.handle('sync.syncNow', {});
await first.tick();
assert.equal(first.view().status, 'retrying');
assert.equal(first.view().attention, null);
assert.ok(first.view().nextRunAt);
await first.tick(30_000);
assert.equal(first.view().status, 'retrying');
assert.equal(first.journal.filter((line) => line.includes('disk busy')).length, 1);
await first.tick(60_000);
assert.equal(first.view().status, 'idle');
assert.equal(first.view().error, null);
});

test('an altered manifest stops sync and says why', async () => {
const github = fakeGitHub();
const { first } = await setUpFirst(github);
Expand Down
15 changes: 12 additions & 3 deletions electron/sync-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ export class SyncService {
}

private failed(error: Error): RunResult {
if (error instanceof SyncIntegrityError) return this.attend(error.reason, error.message);
if (error instanceof SyncIntegrityError) return error.reason === 'tooNew' ? this.retryQuietly(error.message) : this.attend(error.reason, error.message);
if (error instanceof SyncSourceUnavailableError) {
[this.status, this.error] = ['loading', error.message];
return { kind: 'retry' };
Expand All @@ -834,7 +834,16 @@ export class SyncService {
[this.status, this.error] = ['offline', error.message];
return { kind: 'retry' };
}
if (error instanceof SyncSetupError || error instanceof SyncFileDamagedError) return this.attend('failed', error.message);
return this.attend('failed', `Sync stopped: ${error.message}`);
return this.retryQuietly(error.message);
}

// Anything that is not a choice for the user, a lost sign-in or a sign of tampering is tried
// again on the scheduler's back-off: most clear up on their own (a sync file another computer is
// writing, an update that adds a newer format), and "Try again" was all the user could do.
// Each new problem is journalled once, not on every retry.
private retryQuietly(message: string): RunResult {
if (message !== this.error) this.deps.journal(`Sync will try again: ${message}`);
[this.status, this.error] = ['retrying', message];
return { kind: 'retry' };
}
}
62 changes: 62 additions & 0 deletions electron/window-bounds.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import assert from 'node:assert/strict';
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { test } from 'node:test';
import type { BrowserWindow } from 'electron';
import { parsePlacement, restoredBounds, WindowBounds } from './window-bounds';

const minimum = { width: 960, height: 600 };
const laptop = { x: 0, y: 25, width: 1440, height: 875 };
const monitor = { x: 1440, y: 0, width: 2560, height: 1440 };

test('a window comes back where it was left while that place is on a display', () => {
assert.deepEqual(restoredBounds({ x: 1600, y: 100, width: 1800, height: 1100 }, [laptop, monitor], minimum), { x: 1600, y: 100, width: 1800, height: 1100 });
});

test('a window left on a display that is gone opens centred on the primary one, shrunk to fit', () => {
assert.deepEqual(restoredBounds({ x: 1600, y: 100, width: 1800, height: 1100 }, [laptop], minimum), { width: 1440, height: 875 });
});

test('saved bounds never go below the minimum size', () => {
assert.deepEqual(restoredBounds({ x: 10, y: 40, width: 200, height: 100 }, [laptop], minimum), { x: 10, y: 40, width: 960, height: 600 });
});

test('an unreadable placement is ignored', () => {
assert.equal(parsePlacement({ bounds: { x: 0, y: 0, width: 'wide' } }), null);
assert.equal(parsePlacement(null), null);
assert.deepEqual(parsePlacement({ bounds: { x: 1, y: 2, width: 3, height: 4 }, isMaximized: true }), { bounds: { x: 1, y: 2, width: 3, height: 4 }, isMaximized: true, isFullScreen: false });
});

test('without a saved placement the window keeps its default size', async () => {
const bounds = new WindowBounds(path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'openterm-window-')), 'window.json'));
await bounds.load();
assert.deepEqual(bounds.options([laptop], minimum), {});
});

test('the size a window is closed at is the size it opens at next time, maximised included', async () => {
const file = path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'openterm-window-')), 'window.json');
const handlers = new Map<string, () => void>();
const window = {
isDestroyed: () => false, isMinimized: () => false, isMaximized: () => true, isFullScreen: () => false,
getNormalBounds: () => ({ x: 100, y: 80, width: 1200, height: 800 }),
on(name: string, handler: () => void) { handlers.set(name, handler); return this; },
once(name: string, handler: () => void) { handlers.set(name, handler); return this; },
};
const first = new WindowBounds(file);
await first.load();
first.track(window as unknown as BrowserWindow);
handlers.get('close')!();
const deadline = Date.now() + 10_000;
while (!await fs.stat(file).then(() => true, () => false)) {
if (Date.now() > deadline) throw new Error('window.json was never written');
await new Promise((resolve) => setTimeout(resolve, 10));
}
const next = new WindowBounds(file);
await next.load();
assert.deepEqual(next.options([laptop], minimum), { x: 100, y: 80, width: 1200, height: 800 });
let isMaximized = false;
next.track({ ...window, maximize: () => { isMaximized = true; } } as unknown as BrowserWindow);
handlers.get('ready-to-show')!();
assert.equal(isMaximized, true);
});
90 changes: 90 additions & 0 deletions electron/window-bounds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import type { BrowserWindow, Rectangle } from 'electron';
import { JsonStore } from './json-store';

export interface WindowPlacement {
readonly bounds: Rectangle;
readonly isMaximized: boolean;
readonly isFullScreen: boolean;
}

interface Size {
readonly width: number;
readonly height: number;
}

const SAVE_DELAY_MS = 500;

// A window must keep this much of its title bar on a display to come back where it was left.
const VISIBLE_PX = 100;

// Windows reports a window snapped to the top edge a few pixels above the work area.
const EDGE_PX = 8;

const isRectangle = (value: unknown): value is Rectangle => !!value && typeof value === 'object'
&& ['x', 'y', 'width', 'height'].every((key) => Number.isFinite((value as Record<string, unknown>)[key]));

export function parsePlacement(value: unknown): WindowPlacement | null {
const saved = value as Partial<Record<keyof WindowPlacement, unknown>> | null;
if (!saved || !isRectangle(saved.bounds)) return null;
return { bounds: saved.bounds, isMaximized: saved.isMaximized === true, isFullScreen: saved.isFullScreen === true };
}

// The saved bounds, fitted to the displays there are now: a window last left on a monitor that is
// gone opens centred on the primary display at its saved size, shrunk to fit.
export function restoredBounds(saved: Rectangle, workAreas: readonly Rectangle[], minimum: Size): Partial<Rectangle> {
const isOnScreen = workAreas.some((area) => saved.x + saved.width - VISIBLE_PX >= area.x && saved.x + VISIBLE_PX <= area.x + area.width
&& saved.y >= area.y - EDGE_PX && saved.y + VISIBLE_PX / 2 <= area.y + area.height);
const [primary] = workAreas;
const fit = (size: number, room: number, least: number) => Math.round(Math.max(least, Math.min(size, room)));
if (isOnScreen) return { x: Math.round(saved.x), y: Math.round(saved.y), width: fit(saved.width, Infinity, minimum.width), height: fit(saved.height, Infinity, minimum.height) };
if (!primary) return { width: fit(saved.width, Infinity, minimum.width), height: fit(saved.height, Infinity, minimum.height) };
return { width: fit(saved.width, primary.width, minimum.width), height: fit(saved.height, primary.height, minimum.height) };
}

// Remembers the main window's size, place and maximised or full-screen state in `window.json`.
// Bounds are the normal ones, so a maximised window still restores to the size it had before.
export class WindowBounds {
private placement: WindowPlacement | null = null;
private readonly store: JsonStore<WindowPlacement | null>;

constructor(file: string) {
this.store = new JsonStore(file, parsePlacement, () => null);
}

async load(): Promise<void> {
try { this.placement = await this.store.load(); }
catch { this.placement = null; }
}

options(workAreas: readonly Rectangle[], minimum: Size): Partial<Rectangle> {
return this.placement ? restoredBounds(this.placement.bounds, workAreas, minimum) : {};
}

// Call before the window's own ready-to-show listener: maximising shows the window on Windows.
track(window: BrowserWindow): void {
const restored = this.placement;
window.once('ready-to-show', () => {
if (restored?.isFullScreen) window.setFullScreen(true);
else if (restored?.isMaximized) window.maximize();
});
let timer: ReturnType<typeof setTimeout> | undefined;
const save = () => {
clearTimeout(timer);
timer = undefined;
if (window.isDestroyed() || window.isMinimized()) return;
this.placement = { bounds: window.getNormalBounds(), isMaximized: window.isMaximized(), isFullScreen: window.isFullScreen() };
void this.store.save(this.placement).catch(() => undefined);
};
const later = () => {
clearTimeout(timer);
timer = setTimeout(save, SAVE_DELAY_MS);
};
window.on('resize', later);
window.on('move', later);
window.on('maximize', later);
window.on('unmaximize', later);
window.on('enter-full-screen', later);
window.on('leave-full-screen', later);
window.on('close', save);
}
}
6 changes: 5 additions & 1 deletion packages/meridian-charts/src/ui/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ const css = `
.mc-star.is-on { color: #f7a600; }
.mc-star:hover { color: #f7a600; }

.mc-favorites { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); z-index: 5; display: flex; gap: 2px; padding: 2px; border-radius: 6px; background: var(--mc-surface); border: 1px solid var(--mc-border); box-shadow: 0 2px 8px rgb(0 0 0 / 0.25); }
.mc-favorites { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); z-index: 5; display: flex; align-items: center; gap: 2px; padding: 2px 2px 2px 0; border-radius: 6px; background: var(--mc-surface); border: 1px solid var(--mc-border); box-shadow: 0 2px 8px rgb(0 0 0 / 0.25); }
.mc-favorites-list { display: flex; gap: 2px; }
.mc-favorites .mc-btn { width: 32px; height: 32px; }
.mc-favorites-handle { display: flex; align-items: center; justify-content: center; width: 14px; height: 32px; color: var(--mc-muted); cursor: grab; touch-action: none; }
.mc-favorites-handle:active { cursor: grabbing; }
.mc-favorites-handle svg { width: 24px; height: 24px; margin: 0 -5px; }

.mc-legend { position: absolute; left: 8px; z-index: 3; display: flex; flex-direction: column; gap: 2px; max-width: calc(100% - 90px); pointer-events: none; }
.mc-legend-row { display: flex; align-items: center; gap: 6px; height: 20px; padding: 0 4px; border-radius: 4px; white-space: nowrap; pointer-events: auto; font-size: 12px; }
Expand Down
Loading
Loading