/** Writing project settings, and how the editor takes a change made on disk. */ import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import type { ToolResponse } from '../answer-json.js'; import { errorMessage } from '../errors.js'; import { AddonOfAnotherRelease } from '../godot-bridge.js'; import { projectFiles } from '../project-scan.js'; import { reloadableInTheEditor, SCENE_OR_RESOURCE_EXTENSIONS } from '../rename.js'; import type { GodotServer } from '../server.js'; import { asParams, type OperationParams, readArray, readString } from '../tool-args.js'; import { editorHasOpen, settingKeysOf } from './editor-connection.js'; import { runHeadless } from './headless-ops.js'; import { checkedProject } from './project-checks.js'; /** The project_settings ops that write the bus layout rather than project.godot. */ const AUDIO_BUS_OPS: ReadonlySet = new Set([ 'add_audio_bus', 'remove_audio_bus', 'set_audio_bus_effect', 'set_audio_bus_volume', 'rename_audio_bus', 'set_audio_bus_send', ]); /** * The scenes and resources giving a node the bus [from], rewritten to give it [to], with what was * rewritten and the scripts naming [from] in a string. A player names its bus by name and plays on * Master when the layout has none of that name, so one left on a renamed bus went quiet on its own * bus with nothing saying so. Scripts are only named, since a string in code can mean anything. */ function rewriteBusNamed( projectPath: string, from: string, to: string, ): { report: Record; changed: string[] } { const quoted = (name: string): string => name.replaceAll('\\', '\\\\').replaceAll('"', '\\"'); const giving = new Set([`bus = &"${quoted(from)}"`, `bus = "${quoted(from)}"`]); const rewritten: { file: string; lines: number[] }[] = []; for (const file of projectFiles(projectPath, SCENE_OR_RESOURCE_EXTENSIONS)) { const absolute = join(projectPath, file); const lines = readFileSync(absolute, 'utf8').split('\n'); const at: number[] = []; const after = lines.map((line, index) => { const ending = line.endsWith('\r') ? '\r' : ''; if (!giving.has(line.slice(0, line.length - ending.length))) { return line; } at.push(index + 1); return `bus = &"${quoted(to)}"${ending}`; }); if (at.length > 0) { writeFileSync(absolute, after.join('\n')); rewritten.push({ file: `res://${file}`, lines: at }); } } const namedInScripts: { file: string; line: number; text: string }[] = []; for (const file of projectFiles(projectPath, ['.gd'])) { const lines = readFileSync(join(projectPath, file), 'utf8').split('\n'); for (const [index, line] of lines.entries()) { if (line.includes(`"${from}"`)) { namedInScripts.push({ file: `res://${file}`, line: index + 1, text: line.trim() }); } } } return { report: { rewritten, ...(namedInScripts.length > 0 ? { namedInScripts } : {}) }, changed: rewritten.map((one) => one.file), }; } /** * The settings whose value differs between two readings of project.godot, added and removed ones * included, or null when either reading failed and nobody can say. */ export function changedSettings( before: ReadonlyMap | null, after: ReadonlyMap | null, ): string[] | null { if (before === null || after === null) { return null; } const names = new Set([...before.keys(), ...after.keys()]); return [...names] .filter((name) => JSON.stringify(before.get(name)) !== JSON.stringify(after.get(name))) .toSorted(); } /** * The settings a project_settings write names, whatever the file held before it. * * Handed to the editor beside what the write changed, because the file is not the only copy: put * back with a checkout after an earlier set, it already held the value written, nothing changed, * the editor was not told, and it kept the earlier value to write back on its next save. */ export function settingsNamedBy(op: string, args: OperationParams): string[] { const text = (key: string): string => readString(args, key) ?? ''; switch (op) { case 'set': case 'unset': return text('setting') === '' ? [] : [text('setting')]; case 'add_autoload': case 'remove_autoload': return text('name') === '' ? [] : [`autoload/${text('name')}`]; case 'set_main_scene': return ['application/run/main_scene']; case 'add_input_action': case 'remove_input_action': return text('actionName') === '' ? [] : [`input/${text('actionName')}`]; case 'enable_plugin': case 'disable_plugin': return ['editor_plugins/enabled']; default: return []; } } /** The note on scenes the editor holds with unsaved edits and so did not read again, none when there are none. */ function unsavedScenesNote(unsavedScenes: readonly string[]): { note?: string } { if (unsavedScenes.length === 0) { return {}; } const one = unsavedScenes.length === 1; return { note: `${unsavedScenes.join(', ')} ${one ? 'is' : 'are'} open in the editor with unsaved edits, so ${one ? 'it was' : 'they were'} not read again from the file and still ${one ? 'gives' : 'give'} the old bus. Saving there writes it back.`, }; } /** What a project_settings write is working on, passed from step to step. */ interface SettingsWrite { readonly op: string; readonly args: OperationParams; readonly projectPath: string; readonly before: Parameters[0]; readonly written: ToolResponse; readonly renamed: ReturnType | null; } /** * A project_settings write: to the file through a headless engine, as ever, and then taken up by * the editor when one serves the project. * * Written to the file alone, the editor went on holding the old values, answered them when asked, * and would write them back over the new ones the next time it saved the project settings. So the * settings the write changed, read off the file before and after, are handed to the editor to take * from the file. A bus layout, which the editor holds in its audio server, is reloaded there. */ export async function handleProjectSettingsWrite( server: GodotServer, op: string, operation: string, args: OperationParams, ): Promise { const project = checkedProject(server, args); if (!project.ok) { return project.response; } const projectPath = project.value.path; const served = editorHasOpen(server, projectPath); const before = served ? settingKeysOf(projectPath) : null; const written = await runHeadless(server, operation, args); if (written.isError === true) { return written; } const renamed = op === 'rename_audio_bus' ? rewriteBusNamed(projectPath, readString(args, 'busName') ?? '', readString(args, 'newBusName') ?? '') : null; if (!served) { return renamed === null ? written : server.jsonTextResponse({ ...asParams(JSON.parse(written.content[0]?.text ?? '{}')), ...renamed.report, }); } return await settingsTakenByTheEditor(server, { op, args, projectPath, before, written, renamed }); } /** The editor told to take up what a project_settings write changed, once the file holds it. */ async function settingsTakenByTheEditor(server: GodotServer, write: SettingsWrite): Promise { const { op, written, renamed } = write; const answer = asParams(JSON.parse(written.content[0]?.text ?? '{}')); if (AUDIO_BUS_OPS.has(op)) { const adopted = await editorTakes(server, 'adopt_audio_bus_layout', {}); if (renamed === null || renamed.changed.length === 0) { return server.jsonTextResponse({ ...answer, ...renamed?.report, ...adopted }); } // The scenes rewritten under the editor are read again there, or it saves the old bus back. const told: OperationParams = {}; const changed = renamed.changed.filter(reloadableInTheEditor); const reread = await editorTakes(server, 'files_moved', { moved: [], changed }, told); const unsavedScenes = (readArray(told, 'unsavedScenes') ?? []).map(String); return server.jsonTextResponse({ ...answer, ...renamed.report, ...adopted, ...reread, editor: { reloadedScenes: (readArray(told, 'reloadedScenes') ?? []).map(String), ...(unsavedScenes.length > 0 ? { unsavedScenes } : {}), }, ...unsavedScenesNote(unsavedScenes), }); } return await adoptChangedSettings(server, write, answer); } /** The settings a write changed, handed to the editor, and what it says it took. */ async function adoptChangedSettings( server: GodotServer, write: SettingsWrite, answer: OperationParams, ): Promise { const { op, args, projectPath, before, written } = write; const diffed = changedSettings(before, settingKeysOf(projectPath)); const changed = diffed === null ? null : [...new Set([...diffed, ...settingsNamedBy(op, args)])].toSorted(); if (changed === null) { return server.jsonTextResponse({ ...answer, editorNote: 'project.godot could not be read on both sides of the write, so what it changed is unknown and the open editor was not told: it may still hold the old values and write them back the next time it saves. editor_launch restart loads the file.', }); } if (changed.length === 0) { return written; } const adopting: OperationParams = {}; const taken = await editorTakes(server, 'adopt_project_settings', { settings: changed }, adopting); if (taken['editorNote'] !== undefined) { return server.jsonTextResponse({ ...answer, ...taken }); } // What the editor says it took, not the list it was sent: the answer echoed the list, and the // addon passes over a name it cannot place in a section. const adopted = Array.isArray(adopting['adopted']) ? adopting['adopted'].map(String) : []; const passedOver = changed.filter((name) => !adopted.includes(name)); return server.jsonTextResponse({ ...answer, editorAdopted: adopted, ...(passedOver.length > 0 ? { editorPassedOver: passedOver } : {}), }); } /** * The editor asked to take up what a write changed, and what to add to the answer about it. What * the editor answered is copied into [answered]. */ export async function editorTakes( server: GodotServer, command: string, args: OperationParams, answered: OperationParams = {}, ): Promise { try { const result = await server.godotBridge.invokeTool(command, args); if (typeof result === 'object' && result !== null) { Object.assign(answered, result); } return {}; } catch (error) { const message = errorMessage(error); return { editorNote: error instanceof AddonOfAnotherRelease ? `The open editor was not asked to take the change, so it still holds the old values, answers them when asked, and writes them back over the file the next time it saves. ${message}` : `The open editor could not take the change (${message}), so it still holds the old values, answers them when asked, and writes them back over the file the next time it saves. editor_launch restart loads the file again.`, }; } }