diff --git a/src-tauri/src/preferences.rs b/src-tauri/src/preferences.rs index 55341c0..13965f1 100644 --- a/src-tauri/src/preferences.rs +++ b/src-tauri/src/preferences.rs @@ -2,7 +2,8 @@ //! //! The file holds a `schema` number, a `revision` number, and one value for each section. //! The host does not interpret the section values. The frontend normalizes them. -//! Every write replaces the complete file atomically and sends `settings-changed` to all windows. +//! A write that changes a section replaces the complete file atomically and sends `settings-changed` to all windows. +//! A write of the value that a section already holds changes nothing and sends no event. //! Plugin settings stay in the app data folder (see `plugins.rs`). use std::io; @@ -178,6 +179,19 @@ impl Store { Ok(Change { section: section.into(), revision: next, value }) } + /// Like `write`, but when the file already holds `value` in this section, the file stays as it is. + /// The change then has the current revision, and `false` tells the caller to send no event. + /// The compare ignores the key order of objects. Without this check, windows that save the same value + /// can start each other again without end, and each write replaces the file. + pub fn write_if_changed(&mut self, section: &str, value: Value) -> Result<(Change, bool)> { + check_section(section)?; + let loaded = self.load()?; + if loaded.exists && *loaded.document.get(section).unwrap_or(&Value::Null) == value { + return Ok((Change { section: section.into(), revision: revision(&loaded.document), value }, false)); + } + Ok((self.write(section, value)?, true)) + } + /// Write the first file from the migrated values. When a file exists, keep it and return it unchanged. pub fn migrate(&mut self, sections: Map) -> Result { for name in sections.keys() { check_section(name)?; } @@ -229,9 +243,9 @@ pub async fn settings_read(app: AppHandle) -> Result { #[tauri::command] pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result { - let change = with_store(&app, move |store| store.write(§ion, value)).await?; + let (change, saved) = with_store(&app, move |store| store.write_if_changed(§ion, value)).await?; // Every window shows the same preferences, so the change goes to all of them. - let _ = app.emit(CHANGED_EVENT, &change); + if saved { let _ = app.emit(CHANGED_EVENT, &change); } Ok(change) } @@ -292,6 +306,35 @@ mod tests { fs::remove_dir_all(dir).unwrap(); } + #[test] + fn a_write_of_the_stored_value_keeps_the_file_and_the_revision() { + let (dir, path) = fixture("unchanged"); + let mut store = Store::new(path.clone()); + // A missing file gets created, also for a value that matches the empty default. + let (created, saved) = store.write_if_changed("language", Value::Null).unwrap(); + assert!(saved); + assert_eq!(created.revision, 1); + let (first, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "dark", "transparency": { "enabled": true, "amount": 18 } })).unwrap(); + assert!(saved); + assert_eq!(first.revision, 2); + let before = fs::read(&path).unwrap(); + // The same value in a different key order changes nothing. + let (again, saved) = store.write_if_changed("appearance", json!({ "transparency": { "amount": 18, "enabled": true }, "mode": "dark", "theme": "harvest-moon" })).unwrap(); + assert!(!saved, "No save and no event"); + assert_eq!(again.revision, 2); + assert_eq!(fs::read(&path).unwrap(), before, "The file stays as it is"); + // A missing section and `null` are the same. + assert!(!store.write_if_changed("terminal", Value::Null).unwrap().1); + // A different value saves as usual. + let (changed, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "light" })).unwrap(); + assert!(saved); + assert_eq!(changed.revision, 3); + assert_eq!(on_disk(&path)["appearance"], json!({ "mode": "light", "theme": "harvest-moon" })); + assert!(store.write_if_changed("plugins", json!({})).is_err(), "Unknown sections stay refused"); + assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain"); + fs::remove_dir_all(dir).unwrap(); + } + #[test] fn writes_reject_unknown_sections_and_values_above_the_limit() { let (dir, path) = fixture("limits"); diff --git a/src/lib/settings/store.ts b/src/lib/settings/store.ts index 4846e14..7a51218 100644 --- a/src/lib/settings/store.ts +++ b/src/lib/settings/store.ts @@ -56,6 +56,23 @@ function encode(section: SettingsSection, value: unknown): string { return section === 'language' && typeof value === 'string' ? value : JSON.stringify(value); } +// The same value with the object keys in alphabetical order, at every depth. +function sortKeys(value: unknown): unknown { + if (Array.isArray(value)) return value.map(sortKeys); + if (!value || typeof value !== 'object') return value; + const source = value as Record; + return Object.fromEntries(Object.keys(source).sort().map(key => [key, sortKeys(source[key])])); +} + +/** + * True when two section values hold the same data. The key order of objects does not matter. + * The desktop host stores the keys in alphabetical order, so a value that comes back from the host + * can have a different key order than the value that a window saved. + */ +export function sameSettingsValue(a: unknown, b: unknown): boolean { + return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b)); +} + function notify(section: SettingsSection) { for (const callback of [...subscribers.get(section) ?? []]) { try { callback(); } catch (reason) { console.error(`A ${section} settings subscriber failed.`, reason); } diff --git a/src/lib/theme/ThemeSync.svelte b/src/lib/theme/ThemeSync.svelte index 02a113e..2ef22a5 100644 --- a/src/lib/theme/ThemeSync.svelte +++ b/src/lib/theme/ThemeSync.svelte @@ -3,7 +3,7 @@ import { syncTableFormulas } from '$lib/formulas'; import { syncFileTitle } from '$lib/editor/fileTitle'; import { onMount } from 'svelte'; - import { onSettingsChange, readSection, writeSection } from '$lib/settings/store'; + import { onSettingsChange, readSection, sameSettingsValue, writeSection } from '$lib/settings/store'; import { applyAppearance, readAppearance } from './appearance'; onMount(() => { const stopLocale = syncLocale(); @@ -14,7 +14,8 @@ const stored = readSection('appearance'); const appearance = readAppearance(); // Save the normalized value, for example a new ID for a renamed theme. - if (stored !== undefined && JSON.stringify(stored) !== JSON.stringify(appearance)) { + // Ignore the key order: the host sorts the keys, so a text compare saves again in each window without end. + if (stored !== undefined && !sameSettingsValue(stored, appearance)) { writeSection('appearance', appearance).catch(() => { /* The normalized value applies until the next save. */ }); } applyAppearance(appearance); diff --git a/tests/unit/settings/store.spec.ts b/tests/unit/settings/store.spec.ts index 69d6be4..3ad0831 100644 --- a/tests/unit/settings/store.spec.ts +++ b/tests/unit/settings/store.spec.ts @@ -116,3 +116,17 @@ test('A failed write reaches the caller', async () => { handlers.set('settings_write', () => { throw 'Disk full'; }); await assert.rejects(store.writeSection('customThemes', []), /Disk full/); }); + +test('The same data in a different key order is the same settings value', () => { + const saved = { theme: 'harvest-moon', mode: 'dark', transparency: { enabled: true, amount: 18 }, targets: ['app', 'pm-all'] }; + // The host sends the keys back in alphabetical order. + const fromHost = { mode: 'dark', targets: ['app', 'pm-all'], theme: 'harvest-moon', transparency: { amount: 18, enabled: true } }; + assert.notEqual(JSON.stringify(saved), JSON.stringify(fromHost)); + assert.ok(store.sameSettingsValue(saved, fromHost)); + assert.ok(!store.sameSettingsValue(saved, { ...fromHost, mode: 'light' })); + assert.ok(!store.sameSettingsValue(saved, { ...fromHost, targets: ['pm-all', 'app'] }), 'The order of an array counts'); + assert.ok(!store.sameSettingsValue(saved, { ...fromHost, extra: 1 })); + assert.ok(store.sameSettingsValue('en', 'en')); + assert.ok(store.sameSettingsValue(null, null)); + assert.ok(!store.sameSettingsValue(null, {})); +}); diff --git a/tests/unit/theme/appearance.spec.ts b/tests/unit/theme/appearance.spec.ts index 10b57cd..00be050 100644 --- a/tests/unit/theme/appearance.spec.ts +++ b/tests/unit/theme/appearance.spec.ts @@ -3,6 +3,7 @@ import { test } from 'node:test'; import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts'; import { SYNTAX_ROLES } from '../../../src/lib/theme/roles.ts'; import { parseAppearance, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, THEMES, themeModes } from '../../../src/lib/theme/appearance.ts'; +import { sameSettingsValue } from '../../../src/lib/settings/store.ts'; test('Removed palettes preserve the saved mode with the default palette', () => { for (const theme of ['gpt', 'terminal', 'unknown', 'renamon', 'asuka-school']) { @@ -84,3 +85,19 @@ test('Background image references clamp the overlay and discard obsolete colors' assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: NaN } }).newTabBackground, { imageId, overlay: 0, ...layout }); assert.equal(normalizeAppearance({ newTabBackground: { imageId: 'invalid' } }).newTabBackground, undefined); }); + +test('A valid appearance from the host needs no new save, although the host sorted its keys', () => { + // ThemeSync saves the normalized appearance only when it differs from the stored value. + // A key-order difference made two windows save the same value to each other without end. + const imageId = 'd10adda6-a2ec-4d73-a0a6-2cb1ed43bebc'; + const fromHost = [ + { mode: 'dark', theme: 'harvest-moon', transparency: { amount: 18, enabled: true } }, + { mode: 'light', newTabBackground: { imageId, overlay: 0.2, position: 'center', size: 'cover' }, theme: 'default' }, + ]; + for (const stored of fromHost) { + const normalized = normalizeAppearance(stored); + assert.notEqual(JSON.stringify(normalized), JSON.stringify(stored), 'The fixture has a different key order'); + assert.ok(sameSettingsValue(stored, normalized), JSON.stringify(stored)); + } + assert.ok(!sameSettingsValue({ mode: 'dark', theme: 'holo' }, normalizeAppearance({ mode: 'dark', theme: 'holo' })), 'A renamed theme still gets saved'); +});