Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): opening a script opens its project, in an editor already installed

esengine07e4173ce8c0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c1f5a4ebd..6311692f1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,8 +26,17 @@ published separately; it ships inside the editor.
### Added
-- **Settings → External Tools.** Name the script editor, the image editor and the
- browser once, and the editor hands files to them. A slot is registered rather
+- **Settings → External Tools.** The script editor, the image editor and the
+ browser. The script row is not a blank field: the editors actually installed are
+ detected and offered, and leaving it alone means *automatic* — which names the
+ one it would pick, so the row answers "what happens if I do nothing?".
+ A code editor is handed the PROJECT and then the file, because a `.ts` opened by
+ itself has no tsconfig: the SDK types staged into the project resolve to nothing
+ and correct code gets red squiggles. Which arguments a program wants is derived
+ from what it IS — its executable's name — so a VS Code browsed to by hand, in a
+ directory nobody would guess, still opens the project. Anything the catalogue
+ does not recognise gets the file alone: a paint program handed a directory would
+ open the project folder as an image. A slot is registered rather
than hard-coded — an asset type declares which kind of program opens it, the way
it already declares its icon — so a plugin's type can say "open me the way
scripts are opened", or bring a slot of its own, and the settings page grows a
diff --git a/desktop/electron/editorCatalog.ts b/desktop/electron/editorCatalog.ts
new file mode 100644
index 000000000..f59d599ea
--- /dev/null
+++ b/desktop/electron/editorCatalog.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file editorCatalog.ts
+ * @brief The programs the editor knows how to hand a file to, and where they
+ * usually live. Two things come out of this: a list to offer instead of a
+ * blank field, and — the part that actually matters — the ARGUMENTS each
+ * one wants.
+ *
+ * A code editor opened on a lone file has no project. For this engine
+ * that is not a nicety: the SDK's types are staged into the project's
+ * `.esengine/sdk` and resolved through its tsconfig, so a `.ts` opened by
+ * itself gets no completion, no `esengine` types, and red squiggles under
+ * correct code. Every known editor is therefore handed the PROJECT ROOT
+ * and then the file.
+ *
+ * A program is identified by what it IS — its executable's name — not by
+ * which row of the settings UI selected it. So a VS Code the user browsed
+ * to by hand, in a directory nobody would guess, still opens the project.
+ */
+import { access, constants } from 'node:fs/promises';
+import path from 'node:path';
+import { homedir } from 'node:os';
+
+export interface KnownEditor {
+ id: string;
+ label: string;
+ /** Lower-case executable / bundle names that identify it, however it was found. */
+ matches: readonly string[];
+ /** Where it installs, per platform. `~` is expanded. */
+ candidates: Partial<Record<string, readonly string[]>>;
+}
+
+/**
+ * Ordered by what a 2D TypeScript game project is most likely to want, because the
+ * first one detected is what "auto" resolves to.
+ */
+export const KNOWN_EDITORS: readonly KnownEditor[] = [
+ {
+ id: 'vscode',
+ label: 'Visual Studio Code',
+ matches: ['code', 'code.exe', 'code - insiders', 'visual studio code.app'],
+ candidates: {
+ darwin: ['/Applications/Visual Studio Code.app', '~/Applications/Visual Studio Code.app'],
+ win32: [
+ '~/AppData/Local/Programs/Microsoft VS Code/Code.exe',
+ 'C:/Program Files/Microsoft VS Code/Code.exe',
+ 'C:/Program Files (x86)/Microsoft VS Code/Code.exe',
+ ],
+ linux: ['/usr/share/code/code', '/usr/bin/code', '/snap/bin/code'],
+ },
+ },
+ {
+ id: 'cursor',
+ label: 'Cursor',
+ matches: ['cursor', 'cursor.exe', 'cursor.app'],
+ candidates: {
+ darwin: ['/Applications/Cursor.app', '~/Applications/Cursor.app'],
+ win32: ['~/AppData/Local/Programs/cursor/Cursor.exe'],
+ linux: ['/usr/bin/cursor'],
+ },
+ },
+ {
+ id: 'webstorm',
+ label: 'WebStorm',
+ matches: ['webstorm', 'webstorm.exe', 'webstorm.app'],
+ candidates: {
+ darwin: ['/Applications/WebStorm.app', '~/Applications/WebStorm.app'],
+ win32: ['C:/Program Files/JetBrains/WebStorm/bin/webstorm64.exe'],
+ linux: ['/usr/bin/webstorm', '/snap/bin/webstorm'],
+ },
+ },
+ {
+ id: 'sublime',
+ label: 'Sublime Text',
+ matches: ['sublime text.app', 'sublime_text', 'sublime_text.exe', 'subl'],
+ candidates: {
+ darwin: ['/Applications/Sublime Text.app'],
+ win32: ['C:/Program Files/Sublime Text/sublime_text.exe'],
+ linux: ['/usr/bin/subl', '/opt/sublime_text/sublime_text'],
+ },
+ },
+ {
+ id: 'zed',
+ label: 'Zed',
+ matches: ['zed', 'zed.app', 'zed.exe'],
+ candidates: {
+ darwin: ['/Applications/Zed.app', '~/Applications/Zed.app'],
+ win32: ['~/AppData/Local/Programs/Zed/Zed.exe'],
+ linux: ['/usr/bin/zed', '~/.local/bin/zed'],
+ },
+ },
+];
+
+const expand = (p: string): string => (p.startsWith('~/') ? path.join(homedir(), p.slice(2)) : p);
+
+/** The catalog entry a program path is, or null when it is something else. */
+export function identify(program: string): KnownEditor | null {
+ const name = path.basename(program).toLowerCase();
+ return KNOWN_EDITORS.find((e) => e.matches.includes(name)) ?? null;
+}
+
+export interface DetectedEditor {
+ id: string;
+ label: string;
+ path: string;
+}
+
+/** Every known editor actually installed, in catalog order. */
+export async function detectEditors(platform: string = process.platform): Promise<DetectedEditor[]> {
+ const found: DetectedEditor[] = [];
+ for (const editor of KNOWN_EDITORS) {
+ for (const candidate of editor.candidates[platform] ?? []) {
+ const abs = expand(candidate);
+ try {
+ await access(abs, constants.F_OK);
+ found.push({ id: editor.id, label: editor.label, path: abs });
+ break; // first hit wins; a second install of the same editor is not a choice
+ } catch {
+ // Not here. Try the next location.
+ }
+ }
+ }
+ return found;
+}
+
+/**
+ * What to pass a program after its own path.
+ *
+ * A known editor gets the project and then the file, which is what opens the file
+ * IN its project rather than alone. Anything else gets only the file: an unknown
+ * program handed a directory it did not ask for is at best confused, and a paint
+ * program would open the project folder as an image.
+ */
+export function argsFor(program: string, projectRoot: string, file: string): string[] {
+ return identify(program) ? [projectRoot, file] : [file];
+}
diff --git a/desktop/electron/externalProgram.ts b/desktop/electron/externalProgram.ts
index fc1d7285c..173128209 100644
--- a/desktop/electron/externalProgram.ts
+++ b/desktop/electron/externalProgram.ts
@@ -22,6 +22,7 @@ import { spawn } from 'node:child_process';
import { access, constants } from 'node:fs/promises';
import type { BrowserWindow } from 'electron';
import { showOpenDialog } from './shotDialogs';
+import { argsFor } from './editorCatalog';
/** Why a launch did not happen, or `null` when it did. */
export type LaunchError = 'missing' | 'failed';
@@ -31,18 +32,27 @@ export type LaunchError = 'missing' | 'failed';
* caller can turn into a message — a program the user configured months ago and
* has since uninstalled is the common case, and it deserves better than a stack
* trace in the console.
+ *
+ * `projectRoot` is passed ahead of the file to editors that understand a project
+ * (see editorCatalog.ts) — the difference between a `.ts` with completion and a
+ * `.ts` with red squiggles under correct code.
*/
-export async function launchProgram(program: string, filePath: string): Promise<LaunchError | null> {
+export async function launchProgram(
+ program: string,
+ filePath: string,
+ projectRoot: string,
+): Promise<LaunchError | null> {
try {
await access(program, constants.F_OK);
} catch {
return 'missing';
}
+ const argv = argsFor(program, projectRoot, filePath);
const [cmd, args] =
process.platform === 'darwin' && program.endsWith('.app')
- ? ['/usr/bin/open', ['-a', program, filePath]]
- : [program, [filePath]];
+ ? ['/usr/bin/open', ['-a', program, ...argv]]
+ : [program, argv];
try {
const child = spawn(cmd, args, { detached: true, stdio: 'ignore', shell: false });
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 1140bf2c9..6b945d6a3 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -56,6 +56,7 @@ import {
} from './pluginPackage';
import { findUpdate, downloadUpdate, installUpdate } from './autoUpdate';
import { pickProgram, launchProgram, type LaunchError } from './externalProgram';
+import { detectEditors } from './editorCatalog';
import {
listPlatforms, loadProjectPlatform, createProjectPlatform, setPlatformTrustGate,
listPlayableNetworks, loadPlayableProfile,
@@ -811,13 +812,21 @@ ipcMain.on('external:browser', (_e, exe: unknown) => {
* stale preference should not be able to swallow it.
*/
async function openUrl(url: string): Promise<void> {
- if (preferredBrowser && !(await launchProgram(preferredBrowser, url))) return;
+ if (preferredBrowser && !(await launchProgram(preferredBrowser, url, ''))) return;
await shell.openExternal(url);
}
-ipcMain.handle('external:launch', async (_e, program: string, relPath: string): Promise<LaunchError | null> => {
- const abs = resolveInRoot(requireRoot(), relPath);
- if (!program) return (await shell.openPath(abs)) ? 'failed' : null;
- return launchProgram(program, abs);
+ipcMain.handle('external:detect', () => detectEditors());
+ipcMain.handle('external:launch', async (_e, slot: string, program: string, relPath: string): Promise<LaunchError | null> => {
+ const root = requireRoot();
+ const abs = resolveInRoot(root, relPath);
+ // Unset means AUTO, and auto is resolved here rather than in the settings UI:
+ // the common case is a user who never opened that page at all, and a fresh
+ // install that opens scripts in the editor they already have beats one that
+ // does nothing until configured. Only source has a catalog to detect from —
+ // for anything else the OS default is the honest answer.
+ const chosen = program || (slot === 'script' ? (await detectEditors())[0]?.path : '') || '';
+ if (!chosen) return (await shell.openPath(abs)) ? 'failed' : null;
+ return launchProgram(chosen, abs, root);
});
ipcMain.handle('workspace:save', (_e, ws: WorkspaceState) => saveWorkspace(requireRoot(), ws));
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index e3accf2fe..3c545e9e6 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -13,6 +13,7 @@ import type {
import type { PlayRealmResult } from './buildPlayRealm';
import type { AvailableUpdate, DownloadProgress } from './autoUpdate';
import type { LaunchError } from './externalProgram';
+import type { DetectedEditor } from './editorCatalog';
import type { DiscoveredPlugin, CompiledPlugin } from './pluginHost';
import type { ScaffoldPluginOptions, ScaffoldPluginResult } from './pluginScaffold';
import type { PluginPackageInfo, InstallPluginResult } from './pluginPackage';
@@ -215,9 +216,11 @@ const api = {
pickProgram: (title: string): Promise<string | null> => ipcRenderer.invoke('external:pick', title),
/** Mirror the chosen browser to main, which opens urls without a call site. */
setBrowser: (program: string): void => ipcRenderer.send('external:browser', program),
- /** Open a project-relative file with `program`; null on success, else why not. */
- launchProgram: (program: string, relPath: string): Promise<LaunchError | null> =>
- ipcRenderer.invoke('external:launch', program, relPath),
+ /** Known code editors actually installed, in preference order. */
+ detectEditors: (): Promise<DetectedEditor[]> => ipcRenderer.invoke('external:detect'),
+ /** Open a project-relative file for `slot`; empty `program` = auto/OS default. */
+ launchProgram: (slot: string, program: string, relPath: string): Promise<LaunchError | null> =>
+ ipcRenderer.invoke('external:launch', slot, program, relPath),
},
workspace: {
save: (ws: WorkspaceState): Promise<void> => ipcRenderer.invoke('workspace:save', ws),
diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsx
index 32dd45cf3..627b3b6dc 100644
--- a/desktop/src/components/SettingsDialog.tsx
+++ b/desktop/src/components/SettingsDialog.tsx
@@ -155,19 +155,44 @@ function KeybindCapture({ setting }: { setting: KeybindingSetting }) {
function PathControl({ setting }: { setting: PathSetting }) {
const setValue = useSettings((s) => s.setValue);
const value = useSettings((s) => s.getValue<string>(setting.id) ?? '');
+ const [found, setFound] = useState<{ id: string; label: string; path: string }[]>([]);
+ // Detection is an fs walk in main; do it when the page is looked at, not at boot.
+ useEffect(() => {
+ if (!setting.detect) return;
+ void window.estella?.shell?.detectEditors?.().then((list) => setFound(list ?? []));
+ }, [setting.detect]);
+
const browse = async () => {
const picked = await window.estella?.shell?.pickProgram?.(setting.pickTitle ?? setting.label);
if (picked) setValue(setting.id, picked);
};
+
+ // '' is AUTO, not "nothing": it names what the editor would actually do, so the
+ // row answers "what happens if I leave this alone?" without the user guessing.
+ const auto = found[0]
+ ? t('set.externalTools.autoNamed', { program: found[0].label })
+ : t('set.externalTools.placeholder');
+ const options = [
+ { value: '', label: auto },
+ ...found.map((f) => ({ value: f.path, label: f.label })),
+ // A path the user browsed to is not in the catalog; keep it selectable so the
+ // dropdown never silently drops the very thing that is in effect.
+ ...(value && !found.some((f) => f.path === value) ? [{ value, label: basename(value) }] : []),
+ ];
+
return (
<div className="set-path">
- <input
- className="set-str"
- value={value}
- placeholder={setting.placeholder ?? ''}
- spellCheck={false}
- onChange={(e) => setValue(setting.id, e.target.value)}
- />
+ {setting.detect ? (
+ <Select value={value} options={options} onChange={(v) => setValue(setting.id, v)} />
+ ) : (
+ <input
+ className="set-str"
+ value={value}
+ placeholder={setting.placeholder ?? ''}
+ spellCheck={false}
+ onChange={(e) => setValue(setting.id, e.target.value)}
+ />
+ )}
{value && (
<IconButton title={t('ui.clear')} ariaLabel={t('ui.clear')} onClick={() => setValue(setting.id, '')}>
<X size={13} />
@@ -180,6 +205,8 @@ function PathControl({ setting }: { setting: PathSetting }) {
);
}
+const basename = (p: string): string => p.split(/[\\/]/).pop() || p;
+
function StringListControl({ setting }: { setting: StringListSetting }) {
const setValue = useSettings((s) => s.setValue);
const value = useSettings(useShallow((s) => s.getValue<string[]>(setting.id) ?? (EMPTY_LIST as string[])));
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 184d8f7f7..67be7d7d4 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -44,11 +44,12 @@ export const settingsMessages = defineMessages({
},
'toast.programFailed': { en: 'Could not start {program}', zh: '无法启动 {program}' },
'toast.openFailed': { en: 'No program is set up to open this file', zh: '没有可打开该文件的程序' },
- 'set.externalTools.placeholder': { en: 'Unset — use the system default', zh: '未填写时使用系统默认程序' },
+ 'set.externalTools.placeholder': { en: 'Automatic — the system default', zh: '自动 — 使用系统默认程序' },
+ 'set.externalTools.autoNamed': { en: 'Automatic ({program})', zh: '自动({program})' },
'set.externalTools.script': { en: 'Script editor', zh: '默认脚本编辑器' },
'set.externalTools.script.desc': {
- en: 'Opens .ts, .js and .esshader files.',
- zh: '用于打开 .ts、.js 和 .esshader 文件。',
+ en: 'Opens .ts, .js and .esshader files, with the project alongside so types resolve.',
+ zh: '用于打开 .ts、.js 和 .esshader 文件;会连同项目一起打开,类型才能解析。',
},
'set.externalTools.image': { en: 'Image editor', zh: '默认图片编辑器' },
'set.externalTools.image.desc': {
diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.ts
index 652962b5c..fa01ab0d8 100644
--- a/desktop/src/project/assetOpen.ts
+++ b/desktop/src/project/assetOpen.ts
@@ -55,11 +55,12 @@ export function openAssetOfType(type: AssetType, path: string, name: string): bo
* end of a table that only knew about editors this editor ships.
*/
async function openOutside(type: AssetType, path: string): Promise<void> {
- const slot = assetTypeDef(type).externalProgram;
- // Empty = the OS default, which is the right answer for a kind with no slot and
- // for a slot the user has deliberately left unset.
+ const slot = assetTypeDef(type).externalProgram ?? '';
+ // Empty program = "decide for me", which main answers with the editor it can
+ // detect for this slot, or the OS default. Deliberately NOT resolved here: the
+ // common case is a user who has never opened the settings page.
const program = slot ? externalPrograms.pathFor(slot) : '';
- const failure = await window.estella?.shell?.launchProgram?.(program, path);
+ const failure = await window.estella?.shell?.launchProgram?.(slot, program, path);
if (!failure) return;
if (!program) {
Toasts.push(t('toast.openFailed'), 'error');
diff --git a/desktop/src/project/externalPrograms.ts b/desktop/src/project/externalPrograms.ts
index e48ae22ad..dca505304 100644
--- a/desktop/src/project/externalPrograms.ts
+++ b/desktop/src/project/externalPrograms.ts
@@ -28,6 +28,8 @@ export interface ExternalProgram {
id: string;
label: string;
description?: string;
+ /** Offer detected code editors for this slot (only source has a catalog). */
+ detect?: boolean;
/** Push the value somewhere on change + on hydrate (see the browser slot). */
effect?: (program: string) => void;
}
@@ -52,6 +54,7 @@ class ExternalProgramRegistry {
default: '',
placeholder: t('set.externalTools.placeholder'),
pickTitle: program.label,
+ detect: program.detect,
effect: program.effect,
},
owner,
@@ -87,6 +90,7 @@ externalPrograms.register({
id: 'script',
label: t('set.externalTools.script'),
description: t('set.externalTools.script.desc'),
+ detect: true,
});
externalPrograms.register({
id: 'image',
diff --git a/desktop/src/settings/types.ts b/desktop/src/settings/types.ts
index 913a8c5c9..b25ae5db0 100644
--- a/desktop/src/settings/types.ts
+++ b/desktop/src/settings/types.ts
@@ -80,6 +80,8 @@ export interface PathSetting extends BaseSetting<string> {
placeholder?: string;
/** Title of the picker dialog. */
pickTitle?: string;
+ /** Offer the code editors found installed, so the row is a choice, not a blank. */
+ detect?: boolean;
}
export interface ColorSetting extends BaseSetting<string> {
diff --git a/desktop/tests/editor-catalog.test.ts b/desktop/tests/editor-catalog.test.ts
new file mode 100644
index 000000000..37dd00a46
--- /dev/null
+++ b/desktop/tests/editor-catalog.test.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// A `.ts` opened on its own has no tsconfig, so the SDK types staged into the
+// project resolve to nothing and correct code gets red squiggles. The fix is one
+// argument — the project, ahead of the file — and these pin down who gets it.
+import { describe, it, expect } from 'vitest';
+import { identify, argsFor, detectEditors, KNOWN_EDITORS } from '../electron/editorCatalog';
+
+const ROOT = '/proj';
+const FILE = '/proj/src/main.ts';
+
+describe('identify', () => {
+ it('recognises an editor by its executable, wherever it was installed', () => {
+ // The point of matching on the name: a VS Code the user browsed to by hand,
+ // in a directory nobody would guess, is still VS Code.
+ expect(identify('/Applications/Visual Studio Code.app')?.id).toBe('vscode');
+ expect(identify('C:/Program Files/Microsoft VS Code/Code.exe')?.id).toBe('vscode');
+ expect(identify('/opt/weird/place/code')?.id).toBe('vscode');
+ expect(identify('/Applications/Cursor.app')?.id).toBe('cursor');
+ });
+
+ it('is case-insensitive, because two of the three platforms are', () => {
+ expect(identify('/x/CODE.EXE')?.id).toBe('vscode');
+ expect(identify('/Applications/Sublime Text.app')?.id).toBe('sublime');
+ });
+
+ it('does not recognise something it has never heard of', () => {
+ expect(identify('/Applications/Aseprite.app')).toBeNull();
+ expect(identify('/usr/bin/vim')).toBeNull();
+ });
+});
+
+describe('argsFor', () => {
+ it('hands a code editor the project, then the file', () => {
+ expect(argsFor('/Applications/Visual Studio Code.app', ROOT, FILE)).toEqual([ROOT, FILE]);
+ });
+
+ it('hands everything else the file alone', () => {
+ // A paint program given a directory it did not ask for would try to open the
+ // project folder as an image — so an unknown program gets only what it can use.
+ expect(argsFor('/Applications/Aseprite.app', ROOT, FILE)).toEqual([FILE]);
+ });
+});
+
+describe('detectEditors', () => {
+ it('finds nothing on a platform nothing is catalogued for', async () => {
+ // Not an error: an unrecognised platform means "no suggestions", and the OS
+ // default still opens the file.
+ expect(await detectEditors('sunos')).toEqual([]);
+ });
+
+ it('offers each editor at most once', async () => {
+ const found = await detectEditors();
+ expect(new Set(found.map((f) => f.id)).size).toBe(found.length);
+ });
+
+ it('catalogues every editor for every platform it can be installed on', () => {
+ for (const editor of KNOWN_EDITORS) {
+ for (const platform of ['darwin', 'win32', 'linux']) {
+ expect(editor.candidates[platform]?.length, `${editor.id} has no ${platform} location`).toBeGreaterThan(0);
+ }
+ // An entry nothing can match is a row that can never be selected.
+ expect(editor.matches.length).toBeGreaterThan(0);
+ expect(editor.matches.every((m) => m === m.toLowerCase())).toBe(true);
+ }
+ });
+});