The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Desktop: the menu bar and the update dialogs speak Studio's language (#128)
riverisbuilding25a84b723286
diff --git a/.changeset/menu-bar-languages.md b/.changeset/menu-bar-languages.mdnew file mode 100644index 0000000..bf2415e--- /dev/null+++ b/.changeset/menu-bar-languages.md@@ -0,0 +1,5 @@+---+"@openfilm/desktop": patch+---++Desktop: the menu bar speaks Studio's language, in each of its five, every item in it, and changes when Studio's does. So do the dialogs of Check for Updates. Before Studio is up, the menu takes the system's language.diff --git a/apps/desktop/src/i18n/language.mjs b/apps/desktop/src/i18n/language.mjsnew file mode 100644index 0000000..64364cc--- /dev/null+++ b/apps/desktop/src/i18n/language.mjs@@ -0,0 +1,22 @@+/** Studio's languages: the app's own words (the menu bar, its dialogs, the install window) come in each of them. */+export const LANGUAGES = ['en', 'zh-CN', 'ja', 'ko', 'es'];++/**+ * The language the app speaks: the one Studio's page is in (or was last shown in), else the system's as Studio picks+ * it (its i18n `languageFor`): `zh-Hans-CN` and `zh` are Simplified Chinese, `es-MX` is Spanish.+ * @param {string | null | undefined} saved+ * @param {readonly string[]} [system] the system's preferred languages, most preferred first+ */+export function appLanguage(saved, system = []) {+ if (saved && LANGUAGES.includes(saved)) return saved;+ for (const tag of system) {+ const lower = String(tag).toLowerCase();+ if (lower.startsWith('zh')) {+ if (/^zh-(hant|tw|hk|mo)\b/.test(lower)) continue;+ return 'zh-CN';+ }+ const base = lower.split('-')[0];+ if (LANGUAGES.includes(base)) return base;+ }+ return 'en';+}diff --git a/apps/desktop/src/i18n/menu.mjs b/apps/desktop/src/i18n/menu.mjsnew file mode 100644index 0000000..764b412--- /dev/null+++ b/apps/desktop/src/i18n/menu.mjs@@ -0,0 +1,71 @@+/**+ * The menu bar's words (menu.mjs), in each of Studio's languages. Electron's own items (Undo, Hide, Quit…) are named+ * here too: Electron names them in English whatever the system's language.+ */+export const MENU_WORDS = {+ en: {+ about: 'About {name}', checkForUpdates: 'Check for Updates…', betaUpdates: 'Beta Updates', settings: 'Settings…', services: 'Services',+ hide: 'Hide {name}', hideOthers: 'Hide Others', showAll: 'Show All', quit: 'Quit {name}',+ file: 'File', newTab: 'New Tab', openProject: 'Open Project…', closeTab: 'Close Tab', reopenClosedTab: 'Reopen Closed Tab',+ edit: 'Edit', undo: 'Undo', redo: 'Redo', cut: 'Cut', copy: 'Copy', paste: 'Paste', pasteAndMatchStyle: 'Paste and Match Style',+ delete: 'Delete', selectAll: 'Select All', substitutions: 'Substitutions', showSubstitutions: 'Show Substitutions',+ smartQuotes: 'Smart Quotes', smartDashes: 'Smart Dashes', textReplacement: 'Text Replacement', speech: 'Speech',+ startSpeaking: 'Start Speaking', stopSpeaking: 'Stop Speaking',+ view: 'View', showChat: 'Show Chat', actualSize: 'Actual Size', zoomIn: 'Zoom In', zoomOut: 'Zoom Out',+ toggleFullScreen: 'Toggle Full Screen', reload: 'Reload', developerTools: 'Developer Tools',+ window: 'Window', minimize: 'Minimize', zoom: 'Zoom', showNextTab: 'Show Next Tab', showPreviousTab: 'Show Previous Tab',+ bringAllToFront: 'Bring All to Front', help: 'Help',+ },+ 'zh-CN': {+ about: '关于 {name}', checkForUpdates: '检查更新…', betaUpdates: 'Beta 版更新', settings: '设置…', services: '服务',+ hide: '隐藏 {name}', hideOthers: '隐藏其他', showAll: '全部显示', quit: '退出 {name}',+ file: '文件', newTab: '新建标签页', openProject: '打开项目…', closeTab: '关闭标签页', reopenClosedTab: '重新打开关闭的标签页',+ edit: '编辑', undo: '撤销', redo: '重做', cut: '剪切', copy: '拷贝', paste: '粘贴', pasteAndMatchStyle: '粘贴并匹配样式',+ delete: '删除', selectAll: '全选', substitutions: '替换', showSubstitutions: '显示替换',+ smartQuotes: '智能引号', smartDashes: '智能破折号', textReplacement: '文本替换', speech: '语音',+ startSpeaking: '开始朗读', stopSpeaking: '停止朗读',+ view: '显示', showChat: '显示对话', actualSize: '实际大小', zoomIn: '放大', zoomOut: '缩小',+ toggleFullScreen: '切换全屏', reload: '重新载入', developerTools: '开发者工具',+ window: '窗口', minimize: '最小化', zoom: '缩放', showNextTab: '显示下一个标签页', showPreviousTab: '显示上一个标签页',+ bringAllToFront: '前置全部窗口', help: '帮助',+ },+ ja: {+ about: '{name}について', checkForUpdates: 'アップデートを確認…', betaUpdates: 'ベータ版のアップデート', settings: '設定…', services: 'サービス',+ hide: '{name}を非表示', hideOthers: 'ほかを非表示', showAll: 'すべてを表示', quit: '{name}を終了',+ file: 'ファイル', newTab: '新規タブ', openProject: 'プロジェクトを開く…', closeTab: 'タブを閉じる', reopenClosedTab: '閉じたタブを開き直す',+ edit: '編集', undo: '取り消す', redo: 'やり直す', cut: 'カット', copy: 'コピー', paste: 'ペースト', pasteAndMatchStyle: 'ペーストしてスタイルを合わせる',+ delete: '削除', selectAll: 'すべてを選択', substitutions: '自動置換', showSubstitutions: '自動置換を表示',+ smartQuotes: 'スマート引用符', smartDashes: 'スマートダッシュ', textReplacement: 'テキストの置換', speech: '音声読み上げ',+ startSpeaking: '読み上げを開始', stopSpeaking: '読み上げを停止',+ view: '表示', showChat: 'チャットを表示', actualSize: '実際のサイズ', zoomIn: '拡大', zoomOut: '縮小',+ toggleFullScreen: 'フルスクリーンを切り替える', reload: '再読み込み', developerTools: '開発者ツール',+ window: 'ウインドウ', minimize: 'しまう', zoom: '拡大/縮小', showNextTab: '次のタブを表示', showPreviousTab: '前のタブを表示',+ bringAllToFront: 'すべてを手前に移動', help: 'ヘルプ',+ },+ ko: {+ about: '{name}에 관하여', checkForUpdates: '업데이트 확인…', betaUpdates: '베타 업데이트', settings: '설정…', services: '서비스',+ hide: '{name} 가리기', hideOthers: '기타 가리기', showAll: '모두 보기', quit: '{name} 종료',+ file: '파일', newTab: '새로운 탭', openProject: '프로젝트 열기…', closeTab: '탭 닫기', reopenClosedTab: '닫은 탭 다시 열기',+ edit: '편집', undo: '실행 취소', redo: '실행 복귀', cut: '오려두기', copy: '복사하기', paste: '붙여넣기', pasteAndMatchStyle: '붙여넣고 스타일 일치시키기',+ delete: '삭제', selectAll: '전체 선택', substitutions: '대치', showSubstitutions: '대치 보기',+ smartQuotes: '스마트 인용', smartDashes: '스마트 대시', textReplacement: '텍스트 대치', speech: '말하기',+ startSpeaking: '말하기 시작', stopSpeaking: '말하기 멈추기',+ view: '보기', showChat: '채팅 보기', actualSize: '실제 크기', zoomIn: '확대', zoomOut: '축소',+ toggleFullScreen: '전체 화면 전환', reload: '새로 고침', developerTools: '개발자 도구',+ window: '윈도우', minimize: '최소화', zoom: '확대/축소', showNextTab: '다음 탭 보기', showPreviousTab: '이전 탭 보기',+ bringAllToFront: '모두 앞으로 가져오기', help: '도움말',+ },+ es: {+ about: 'Acerca de {name}', checkForUpdates: 'Buscar actualizaciones…', betaUpdates: 'Actualizaciones beta', settings: 'Ajustes…', services: 'Servicios',+ hide: 'Ocultar {name}', hideOthers: 'Ocultar otros', showAll: 'Mostrar todo', quit: 'Salir de {name}',+ file: 'Archivo', newTab: 'Nueva pestaña', openProject: 'Abrir proyecto…', closeTab: 'Cerrar pestaña', reopenClosedTab: 'Volver a abrir la pestaña cerrada',+ edit: 'Edición', undo: 'Deshacer', redo: 'Rehacer', cut: 'Cortar', copy: 'Copiar', paste: 'Pegar', pasteAndMatchStyle: 'Pegar con el mismo estilo',+ delete: 'Eliminar', selectAll: 'Seleccionar todo', substitutions: 'Sustituciones', showSubstitutions: 'Mostrar sustituciones',+ smartQuotes: 'Comillas tipográficas', smartDashes: 'Guiones inteligentes', textReplacement: 'Sustitución de texto', speech: 'Voz',+ startSpeaking: 'Iniciar locución', stopSpeaking: 'Detener locución',+ view: 'Visualización', showChat: 'Mostrar chat', actualSize: 'Tamaño real', zoomIn: 'Ampliar', zoomOut: 'Reducir',+ toggleFullScreen: 'Pantalla completa', reload: 'Volver a cargar', developerTools: 'Herramientas para desarrolladores',+ window: 'Ventana', minimize: 'Minimizar', zoom: 'Zoom', showNextTab: 'Mostrar pestaña siguiente', showPreviousTab: 'Mostrar pestaña anterior',+ bringAllToFront: 'Traer todo al frente', help: 'Ayuda',+ },+};diff --git a/apps/desktop/src/i18n/update-dialogs.mjs b/apps/desktop/src/i18n/update-dialogs.mjsnew file mode 100644index 0000000..09d11b2--- /dev/null+++ b/apps/desktop/src/i18n/update-dialogs.mjs@@ -0,0 +1,86 @@+/**+ * What the dialogs of "Check for Updates…" say (update-menu.mjs), in each of Studio's languages. `errors` has one+ * line for each code of the update controller's `error`; Studio's top bar has its own words (its i18n, `update`).+ */+export const UPDATE_DIALOG_WORDS = {+ en: {+ title: 'Check for Updates', ok: 'OK', restart: 'Restart', later: 'Later',+ upToDate: '{name} is up to date', version: 'Version {version}', betaVersion: 'Version {version} (beta)',+ ready: '{name} {version} is ready', readyDetail: 'Restart now to update, or it installs when you quit and opens as the new version next time.',+ notRestarting: 'Not restarting yet',+ downloading: 'Downloading {name} {version}', downloadingDetail: 'It downloads in the background: keep working. A Restart button appears at the top left when it is ready.',+ failed: 'Could not check for updates', failedDetail: '{error} {name} also tries again by itself.',+ errors: {+ offline: 'Could not reach the update service. Check your connection and try again.',+ unavailable: 'Updates are unavailable right now. Please try again later.',+ failed: 'Could not complete the update. Please try again later.',+ 'agent-busy': 'An agent is still working. Restart when it has finished.',+ exporting: 'An export is running. Restart when it has finished.',+ 'install-failed': 'Could not install the update. Quit {name} and open it again to install it.',+ },+ },+ 'zh-CN': {+ title: '检查更新', ok: '好', restart: '重启', later: '稍后',+ upToDate: '{name} 已是最新版本', version: '版本 {version}', betaVersion: '版本 {version}(Beta)',+ ready: '{name} {version} 已准备好', readyDetail: '现在重启即可更新;或者退出时自动安装,下次打开就是新版本。',+ notRestarting: '暂时不能重启',+ downloading: '正在下载 {name} {version}', downloadingDetail: '更新在后台下载,可以继续工作。下载好后,左上角会出现“重启”按钮。',+ failed: '无法检查更新', failedDetail: '{error}{name} 之后也会自动再试。',+ errors: {+ offline: '无法连接更新服务。请检查网络后再试。',+ unavailable: '现在无法更新,请稍后再试。',+ failed: '更新没有完成,请稍后再试。',+ 'agent-busy': '智能体还在工作,等它完成后再重启。',+ exporting: '正在导出,导出完成后再重启。',+ 'install-failed': '无法安装更新。退出 {name} 后重新打开即可安装。',+ },+ },+ ja: {+ title: 'アップデートを確認', ok: 'OK', restart: '再起動', later: 'あとで',+ upToDate: '{name} は最新です', version: 'バージョン {version}', betaVersion: 'バージョン {version}(ベータ)',+ ready: '{name} {version} の準備ができました', readyDetail: '今すぐ再起動して更新するか、終了時に自動でインストールされ、次に開くと新しいバージョンになります。',+ notRestarting: 'まだ再起動できません',+ downloading: '{name} {version} をダウンロードしています', downloadingDetail: 'バックグラウンドでダウンロードしています。作業を続けてください。準備ができると左上に「再起動」ボタンが表示されます。',+ failed: 'アップデートを確認できませんでした', failedDetail: '{error}{name} はあとで自動的にもう一度試します。',+ errors: {+ offline: 'アップデートサービスに接続できませんでした。接続を確認してもう一度お試しください。',+ unavailable: '現在アップデートを利用できません。しばらくしてからもう一度お試しください。',+ failed: 'アップデートを完了できませんでした。しばらくしてからもう一度お試しください。',+ 'agent-busy': 'エージェントがまだ作業中です。終わってから再起動してください。',+ exporting: '書き出し中です。終わってから再起動してください。',+ 'install-failed': 'アップデートをインストールできませんでした。{name} を終了してもう一度開くとインストールされます。',+ },+ },+ ko: {+ title: '업데이트 확인', ok: '확인', restart: '재시작', later: '나중에',+ upToDate: '{name}이(가) 최신 버전입니다', version: '버전 {version}', betaVersion: '버전 {version} (베타)',+ ready: '{name} {version} 준비가 끝났습니다', readyDetail: '지금 재시작해 업데이트하거나, 종료할 때 자동으로 설치되어 다음에 열면 새 버전이 됩니다.',+ notRestarting: '아직 재시작할 수 없습니다',+ downloading: '{name} {version} 다운로드 중', downloadingDetail: '백그라운드에서 다운로드하고 있으니 계속 작업하세요. 준비가 끝나면 왼쪽 위에 재시작 버튼이 나타납니다.',+ failed: '업데이트를 확인하지 못했습니다', failedDetail: '{error} {name}이(가) 나중에 자동으로 다시 시도합니다.',+ errors: {+ offline: '업데이트 서비스에 연결하지 못했습니다. 연결을 확인하고 다시 시도하세요.',+ unavailable: '지금은 업데이트를 사용할 수 없습니다. 잠시 후 다시 시도하세요.',+ failed: '업데이트를 완료하지 못했습니다. 잠시 후 다시 시도하세요.',+ 'agent-busy': '에이전트가 아직 작업 중입니다. 끝난 뒤 재시작하세요.',+ exporting: '내보내는 중입니다. 끝난 뒤 재시작하세요.',+ 'install-failed': '업데이트를 설치하지 못했습니다. {name}을(를) 종료했다가 다시 열면 설치됩니다.',+ },+ },+ es: {+ title: 'Buscar actualizaciones', ok: 'Aceptar', restart: 'Reiniciar', later: 'Más tarde',+ upToDate: '{name} está actualizado', version: 'Versión {version}', betaVersion: 'Versión {version} (beta)',+ ready: '{name} {version} está listo', readyDetail: 'Reinicia para actualizar ahora, o se instalará al salir y la próxima vez se abrirá la nueva versión.',+ notRestarting: 'Todavía no se reinicia',+ downloading: 'Descargando {name} {version}', downloadingDetail: 'Se descarga en segundo plano: sigue trabajando. Cuando esté listo, aparecerá un botón Reiniciar arriba a la izquierda.',+ failed: 'No se pudo buscar actualizaciones', failedDetail: '{error} {name} también lo volverá a intentar por sí solo.',+ errors: {+ offline: 'No se pudo conectar con el servicio de actualizaciones. Revisa tu conexión y vuelve a intentarlo.',+ unavailable: 'Las actualizaciones no están disponibles ahora. Vuelve a intentarlo más tarde.',+ failed: 'No se pudo completar la actualización. Vuelve a intentarlo más tarde.',+ 'agent-busy': 'Un agente sigue trabajando. Reinicia cuando termine.',+ exporting: 'Hay una exportación en curso. Reinicia cuando termine.',+ 'install-failed': 'No se pudo instalar la actualización. Sal de {name} y vuelve a abrirlo para instalarlo.',+ },+ },+};diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjsindex feec43c..0af7f64 100644--- a/apps/desktop/src/main.mjs+++ b/apps/desktop/src/main.mjs@@ -21,6 +21,7 @@ import { startWindowStudio } from './studio.mjs';import { CHAT_MIN, STUDIO_MIN, WINDOW_MIN, placeOnDisplays, readWindowState, writeWindowState } from './window-state.mjs';import { createPagePresentation, preparePage, revealPage } from './page-presentation.mjs';import { closeTabOrWindow, keepWindowOnClose, quitAfterStudio } from './window-lifecycle.mjs';+import { appLanguage } from './i18n/language.mjs';import { applicationMenuTemplate } from './menu.mjs';import { registerLocalAgentIpc } from './local-agents-ipc.mjs';import { readPreferences, registerChatIpc } from './chat-ipc.mjs';@@ -473,11 +474,14 @@ async function start() {win.on('closed', () => { win = null; views.clear(); pagePresentation = null; app.quit(); });ipcMain.on('desktop:theme', (event, next) => { if (fromPage(event)) setTheme(next); });- /* the page's language, kept for what the app shows before a page is up (the update installed at launch) */+ /* the page's language, kept for what the app shows before a page is up (the update installed at launch), and+ the menu bar's (showMenu) */+ let menuLanguage = null;ipcMain.on('desktop:language', (event, next) => {if (!fromPage(event) || typeof next !== 'string' || next === state.language) return;state = { ...state, language: next.slice(0, 20) };try { writeWindowState(DATA, state); } catch { /* kept until next time */ }+ showMenu();});ipcMain.handle('desktop:hello', (event) => {if (!fromPage(event)) throw new Error('not the window\'s page');@@ -637,32 +641,40 @@ async function start() {ipcMain.handle('desktop:update-state', (event) => (fromPage(event) ? updates?.snapshot() ?? null : null));ipcMain.handle('desktop:update-check', (event) => (fromPage(event) ? updates?.check() ?? null : null));- Menu.setApplicationMenu(Menu.buildFromTemplate(applicationMenuTemplate({- productName: PRODUCT_NAME,- packaged: app.isPackaged,- toggleChat: () => activeView()?.webContents.send('desktop:toggle-chat'),- openProject: () => void openProjectFolder(),- openSettings: () => { focusWindow(); activeView()?.webContents.send('desktop:open-settings'); },- reload: () => activeView()?.webContents.reload(),- devTools: () => activeView()?.webContents.toggleDevTools(),- tabs: {- /* the projects window, in the page in front, to pick the project a new tab shows */- open: () => activeView()?.webContents.send('desktop:tabs:pick') ?? views.get(HOME)?.webContents.focus(),- close: () => closeTabOrWindow(win, { mac, activeId: tabs?.activeId(), closeTab }),- reopen: () => { const tab = tabs?.reopen(); if (tab) showTab(tab.id); },- step: (by) => {- const list = tabs?.list() ?? [];- const i = list.findIndex((t) => t.active);- if (list.length > 1) showTab(list[(i + by + list.length) % list.length].id);+ /* the menu bar speaks the page's language (the system's until the page says), built again when it changes */+ function showMenu() {+ const language = appLanguage(state.language, app.getPreferredSystemLanguages());+ if (language === menuLanguage) return;+ menuLanguage = language;+ Menu.setApplicationMenu(Menu.buildFromTemplate(applicationMenuTemplate({+ language,+ productName: PRODUCT_NAME,+ packaged: app.isPackaged,+ toggleChat: () => activeView()?.webContents.send('desktop:toggle-chat'),+ openProject: () => void openProjectFolder(),+ openSettings: () => { focusWindow(); activeView()?.webContents.send('desktop:open-settings'); },+ reload: () => activeView()?.webContents.reload(),+ devTools: () => activeView()?.webContents.toggleDevTools(),+ tabs: {+ /* the projects window, in the page in front, to pick the project a new tab shows */+ open: () => activeView()?.webContents.send('desktop:tabs:pick') ?? views.get(HOME)?.webContents.focus(),+ close: () => closeTabOrWindow(win, { mac, activeId: tabs?.activeId(), closeTab }),+ reopen: () => { const tab = tabs?.reopen(); if (tab) showTab(tab.id); },+ step: (by) => {+ const list = tabs?.list() ?? [];+ const i = list.findIndex((t) => t.active);+ if (list.length > 1) showTab(list[(i + by + list.length) % list.length].id);+ },+ pick: (n) => { const list = tabs?.list() ?? []; const tab = n === 9 ? list.at(-1) : list[n - 1]; if (tab) showTab(tab.id); },},- pick: (n) => { const list = tabs?.list() ?? []; const tab = n === 9 ? list.at(-1) : list[n - 1]; if (tab) showTab(tab.id); },- },- updates: updates.packaged ? {- check: () => updates.manualCheck(),- beta: updates.channel() === 'beta',- setBeta: (on) => updates.setChannel(on ? 'beta' : 'stable'),- } : null,- })));+ updates: updates.packaged ? {+ check: () => updates.manualCheck(menuLanguage),+ beta: updates.channel() === 'beta',+ setBeta: (on) => updates.setChannel(on ? 'beta' : 'stable'),+ } : null,+ })));+ }+ showMenu();win.show();if (needFfmpeg) {diff --git a/apps/desktop/src/menu.mjs b/apps/desktop/src/menu.mjsindex e794359..ec06ef8 100644--- a/apps/desktop/src/menu.mjs+++ b/apps/desktop/src/menu.mjs@@ -1,93 +1,139 @@-/** Pure native menu template, built by Electron in main.mjs. Studio's editing shortcuts stay in its page. */+/**+ * Pure native menu template, built by Electron in main.mjs, in Studio's language. Studio's editing shortcuts stay in+ * its page.+ */+import { MENU_WORDS } from './i18n/menu.mjs';/**+ * `language`: one of Studio's (i18n/language.mjs `appLanguage`). Every item is named in it, Electron's role items too:+ * Electron names those in English whatever the system's language.* `updates`: the packaged app's (updates.mjs), for "Check for Updates…" (the app menu on macOS, Help on Windows) and* "Beta Updates" (builds before they go to everyone); null from source, which has none.* `tabs`: a new tab (its launcher), the one in front closed, the one closed last opened again, the next or previous,* the nth (9: the last).- * @param {{ productName: string, packaged: boolean, toggleChat: () => void, openProject: () => void, reload: () => void,- * devTools: () => void, openSettings: () => void,+ * @param {{ productName: string, packaged: boolean, language?: string, toggleChat: () => void, openProject: () => void,+ * reload: () => void, devTools: () => void, openSettings: () => void,* tabs: { open: () => void, close: () => void, reopen: () => void, step: (by: number) => void, pick: (n: number) => void },* updates?: { check: () => Promise<void>, beta: boolean, setBeta: (on: boolean) => void } | null }} actions+ * @returns {Electron.MenuItemConstructorOptions[]}*/-export function applicationMenuTemplate({ productName, packaged, toggleChat, openProject, reload, devTools, openSettings, tabs, updates = null }, platform = process.platform) {+export function applicationMenuTemplate({ productName, packaged, language = 'en', toggleChat, openProject, reload, devTools, openSettings, tabs, updates = null }, platform = process.platform) {const mac = platform === 'darwin';+ const words = MENU_WORDS[language] ?? MENU_WORDS.en;+ /** @param {keyof typeof MENU_WORDS.en} key */+ const say = (key) => words[key].replaceAll('{name}', productName);/** @type {Electron.MenuItemConstructorOptions} */- const settings = { label: 'Settings…', accelerator: 'CmdOrCtrl+,', click: openSettings };+ const settings = { label: say('settings'), accelerator: 'CmdOrCtrl+,', click: openSettings };/** @type {Electron.MenuItemConstructorOptions[]} */const updateItems = updates ? [{- label: 'Check for Updates…',+ label: say('checkForUpdates'),/* off while its dialog is up, so a second click does not queue another */click: async (item) => {item.enabled = false;try { await updates.check(); } finally { item.enabled = true; }},},- { label: 'Beta Updates', type: 'checkbox', checked: updates.beta, click: (item) => updates.setBeta(item.checked) },+ { label: say('betaUpdates'), type: 'checkbox', checked: updates.beta, click: (item) => updates.setBeta(item.checked) },] : [];/** @type {Electron.MenuItemConstructorOptions[]} */+ const editItems = [+ { role: 'undo', label: say('undo') },+ { role: 'redo', label: say('redo') },+ { type: 'separator' },+ { role: 'cut', label: say('cut') },+ { role: 'copy', label: say('copy') },+ { role: 'paste', label: say('paste') },+ ...(mac ? /** @type {Electron.MenuItemConstructorOptions[]} */ ([+ { role: 'pasteAndMatchStyle', label: say('pasteAndMatchStyle') },+ { role: 'delete', label: say('delete') },+ { role: 'selectAll', label: say('selectAll') },+ { type: 'separator' },+ {+ label: say('substitutions'),+ submenu: [+ { role: 'showSubstitutions', label: say('showSubstitutions') },+ { type: 'separator' },+ { role: 'toggleSmartQuotes', label: say('smartQuotes') },+ { role: 'toggleSmartDashes', label: say('smartDashes') },+ { role: 'toggleTextReplacement', label: say('textReplacement') },+ ],+ },+ {+ label: say('speech'),+ submenu: [+ { role: 'startSpeaking', label: say('startSpeaking') },+ { role: 'stopSpeaking', label: say('stopSpeaking') },+ ],+ },+ ]) : [+ { role: 'delete', label: say('delete') },+ { type: 'separator' },+ { role: 'selectAll', label: say('selectAll') },+ ]),+ ];+ /** @type {Electron.MenuItemConstructorOptions[]} */const template = [...(mac ? [{label: productName,submenu: [- { role: 'about' },+ { role: 'about', label: say('about') },...updateItems,{ type: 'separator' },settings,{ type: 'separator' },- { role: 'services' },+ { role: 'services', label: say('services') },{ type: 'separator' },- { role: 'hide' },- { role: 'hideOthers' },- { role: 'unhide' },+ { role: 'hide', label: say('hide') },+ { role: 'hideOthers', label: say('hideOthers') },+ { role: 'unhide', label: say('showAll') },{ type: 'separator' },- { role: 'quit' },+ { role: 'quit', label: say('quit') },],}] : []),{- label: 'File',+ label: say('file'),submenu: [- { label: 'New Tab', accelerator: 'CmdOrCtrl+T', click: () => tabs.open() },- { label: 'Open Project…', accelerator: 'CmdOrCtrl+O', click: openProject },+ { label: say('newTab'), accelerator: 'CmdOrCtrl+T', click: () => tabs.open() },+ { label: say('openProject'), accelerator: 'CmdOrCtrl+O', click: openProject },...(!mac ? [{ type: 'separator' }, settings] : []),{ type: 'separator' },- { label: 'Close Tab', accelerator: 'CmdOrCtrl+W', click: () => tabs.close() },- { label: 'Reopen Closed Tab', accelerator: 'CmdOrCtrl+Shift+T', click: () => tabs.reopen() },+ { label: say('closeTab'), accelerator: 'CmdOrCtrl+W', click: () => tabs.close() },+ { label: say('reopenClosedTab'), accelerator: 'CmdOrCtrl+Shift+T', click: () => tabs.reopen() },],},- { role: 'editMenu' },+ { label: say('edit'), submenu: editItems },{- label: 'View',+ label: say('view'),submenu: [- { label: 'Show Chat', type: 'normal', accelerator: 'CmdOrCtrl+Shift+L', click: toggleChat },+ { label: say('showChat'), type: 'normal', accelerator: 'CmdOrCtrl+Shift+L', click: toggleChat },{ type: 'separator' },- { role: 'resetZoom' },- { role: 'zoomIn' },- { role: 'zoomOut' },+ { role: 'resetZoom', label: say('actualSize') },+ { role: 'zoomIn', label: say('zoomIn') },+ { role: 'zoomOut', label: say('zoomOut') },{ type: 'separator' },- { role: 'togglefullscreen' },+ { role: 'togglefullscreen', label: say('toggleFullScreen') },...(packaged ? [] : [{ type: 'separator' },- { label: 'Reload', accelerator: 'CmdOrCtrl+Shift+R', click: reload },- { label: 'Developer Tools', accelerator: 'Alt+CmdOrCtrl+I', click: () => devTools() },+ { label: say('reload'), accelerator: 'CmdOrCtrl+Shift+R', click: reload },+ { label: say('developerTools'), accelerator: 'Alt+CmdOrCtrl+I', click: () => devTools() },]),],},{- label: 'Window',+ label: say('window'),submenu: [- { role: 'minimize' },- { role: 'zoom' },+ { role: 'minimize', label: say('minimize') },+ { role: 'zoom', label: say('zoom') },{ type: 'separator' },- { label: 'Show Next Tab', accelerator: 'Control+Tab', click: () => tabs.step(1) },- { label: 'Show Previous Tab', accelerator: 'Control+Shift+Tab', click: () => tabs.step(-1) },- /* ⌘1–⌘9, as in a browser: each a tab, 9 the last */+ { label: say('showNextTab'), accelerator: 'Control+Tab', click: () => tabs.step(1) },+ { label: say('showPreviousTab'), accelerator: 'Control+Shift+Tab', click: () => tabs.step(-1) },+ /* ⌘1–⌘9, as in a browser: each a tab, 9 the last (hidden, so never read) */...Array.from({ length: 9 }, (_, i) => ({ label: `Tab ${i + 1}`, accelerator: `CmdOrCtrl+${i + 1}`, visible: false, acceleratorWorksWhenHidden: true, click: () => tabs.pick(i + 1) })),- ...(mac ? [{ type: 'separator' }, { role: 'front' }] : []),+ ...(mac ? [{ type: 'separator' }, { role: 'front', label: say('bringAllToFront') }] : []),],},- ...(!mac && updateItems.length ? [{ role: 'help', submenu: updateItems }] : []),+ ...(!mac && updateItems.length ? [{ role: 'help', label: say('help'), submenu: updateItems }] : []),];return template;}diff --git a/apps/desktop/src/menu.test.mjs b/apps/desktop/src/menu.test.mjsindex 7e675e2..4ee6752 100644--- a/apps/desktop/src/menu.test.mjs+++ b/apps/desktop/src/menu.test.mjs@@ -1,6 +1,10 @@import { test } from 'node:test';import assert from 'node:assert/strict';+import { LANGUAGES, appLanguage } from './i18n/language.mjs';+import { MENU_WORDS } from './i18n/menu.mjs';+import { UPDATE_DIALOG_WORDS } from './i18n/update-dialogs.mjs';import { applicationMenuTemplate } from './menu.mjs';+import { createManualUpdateCheck } from './update-menu.mjs';function fixture(platform, packaged = true, updates = null) {let opened = 0;@@ -48,3 +52,86 @@ for (const updates of [null, { check: async () => {}, beta: false, setBeta: () =}});}++const noop = () => {};+const build = (language, platform, { packaged = false, updates = true } = {}) => applicationMenuTemplate({+ productName: 'OpenFilm', packaged, language, toggleChat: noop, openProject: noop, reload: noop, devTools: noop, openSettings: noop,+ tabs: { open: noop, close: noop, reopen: noop, step: noop, pick: noop },+ updates: updates ? { check: async () => {}, beta: false, setBeta: noop } : null,+}, platform);+/** every item the menu bar shows, submenus included (separators and the hidden ⌘1–⌘9 left out) */+const shown = (items) => items.flatMap((item) => (item.type === 'separator' || item.visible === false ? []+ : [item, ...(Array.isArray(item.submenu) ? shown(item.submenu) : [])]));++test('the menu speaks the page\'s language, else the system\'s as Studio picks it', () => {+ assert.equal(appLanguage('zh-CN', ['en-US']), 'zh-CN');+ assert.equal(appLanguage(null, ['en-US', 'zh-Hans-US']), 'en');+ assert.equal(appLanguage(null, ['zh-Hans-CN', 'en-US']), 'zh-CN');+ assert.equal(appLanguage(null, ['zh-Hant-TW', 'ja-JP']), 'ja');+ assert.equal(appLanguage('fr', ['ko-KR']), 'ko');+ assert.equal(appLanguage(undefined, ['es-MX']), 'es');+ assert.equal(appLanguage(null, ['de-DE']), 'en');+ assert.equal(appLanguage(null), 'en');+ const [app, file] = build('zh-CN', 'darwin');+ assert.equal(app.label, 'OpenFilm');+ assert.equal(file.label, '文件');+ assert.deepEqual(shown(app.submenu).map((item) => item.label), ['关于 OpenFilm', '检查更新…', 'Beta 版更新', '设置…', '服务', '隐藏 OpenFilm', '隐藏其他', '全部显示', '退出 OpenFilm']);+ assert.equal(build('xx', 'darwin')[1].label, 'File');+});++test('every language names every item, Electron\'s role items too, on macOS and elsewhere', () => {+ const keys = Object.keys(MENU_WORDS.en).sort();+ assert.deepEqual(Object.keys(MENU_WORDS).sort(), [...LANGUAGES].sort());+ const used = new Set();+ for (const language of LANGUAGES) {+ const words = MENU_WORDS[language];+ assert.deepEqual(Object.keys(words).sort(), keys, language);+ for (const key of keys) assert.ok(words[key].trim(), `${language} ${key}`);+ const named = new Map(Object.entries(words).map(([key, text]) => [text.replaceAll('{name}', 'OpenFilm'), key]));+ for (const platform of ['darwin', 'win32']) {+ const template = build(language, platform);+ if (platform === 'darwin') assert.equal(template[0].label, 'OpenFilm');+ for (const item of shown(platform === 'darwin' ? template.slice(1) : template).concat(platform === 'darwin' ? shown(template[0].submenu) : [])) {+ assert.ok(named.has(item.label), `${language} ${platform}: "${item.label}" (${item.role ?? 'item'}) is not in its words`);+ used.add(named.get(item.label));+ }+ }+ }+ assert.deepEqual([...used].sort(), keys, 'every word is used');+});++test('Check for Updates is in the app menu on macOS, in Help elsewhere, and only in a packaged app\'s menu', () => {+ const labels = (template) => shown(template).map((item) => item.label);+ assert.ok(labels(build('ja', 'darwin')[0].submenu).includes('アップデートを確認…'));+ assert.deepEqual(labels([build('ko', 'win32').at(-1)]), ['도움말', '업데이트 확인…', '베타 업데이트']);+ assert.ok(!labels(build('en', 'darwin', { updates: false })).includes('Check for Updates…'));+ assert.ok(!labels(build('en', 'win32', { updates: false })).includes('Help'));+ assert.ok(!labels(build('es', 'darwin', { packaged: true })).includes('Herramientas para desarrolladores'));+});++test('the update dialogs have every line in every language', async () => {+ const keys = Object.keys(UPDATE_DIALOG_WORDS.en).sort();+ const errors = Object.keys(UPDATE_DIALOG_WORDS.en.errors).sort();+ assert.deepEqual(Object.keys(UPDATE_DIALOG_WORDS).sort(), [...LANGUAGES].sort());+ for (const language of LANGUAGES) {+ const words = UPDATE_DIALOG_WORDS[language];+ assert.deepEqual(Object.keys(words).sort(), keys, language);+ assert.deepEqual(Object.keys(words.errors).sort(), errors, language);+ }+ const messages = [];+ const check = (state) => createManualUpdateCheck({+ controller: { check: async () => state, restart: async () => ({ ok: false, error: 'agent-busy' }) },+ showMessage: async (m) => { messages.push(m); return { response: 0 }; }, focusWindow: noop,+ });+ await check({ status: 'current', version: '0.2.3', channel: 'beta' })('zh-CN');+ await check({ status: 'downloading' })('ja');+ await check({ status: 'ready', availableVersion: '0.2.4' })('ko');+ await check({ status: 'error', error: 'offline' })('es');+ assert.deepEqual(messages.map((m) => [m.title, m.message, m.detail, m.buttons]), [+ ['检查更新', 'OpenFilm 已是最新版本', '版本 0.2.3(Beta)', ['好']],+ ['アップデートを確認', 'OpenFilm をダウンロードしています', UPDATE_DIALOG_WORDS.ja.downloadingDetail, ['OK']],+ ['업데이트 확인', 'OpenFilm 0.2.4 준비가 끝났습니다', UPDATE_DIALOG_WORDS.ko.readyDetail, ['재시작', '나중에']],+ ['업데이트 확인', '아직 재시작할 수 없습니다', UPDATE_DIALOG_WORDS.ko.errors['agent-busy'], ['확인']],+ ['Buscar actualizaciones', 'No se pudo buscar actualizaciones', `${UPDATE_DIALOG_WORDS.es.errors.offline} OpenFilm también lo volverá a intentar por sí solo.`, ['Aceptar']],+ ]);+});diff --git a/apps/desktop/src/update-controller.mjs b/apps/desktop/src/update-controller.mjsindex 56fc8be..0af5d7c 100644--- a/apps/desktop/src/update-controller.mjs+++ b/apps/desktop/src/update-controller.mjs@@ -10,16 +10,6 @@* agent-busy | exporting | install-failed Restart was refused or did not work (the update stays ready)*/-/** What the menu's dialogs say for each code; Studio's top bar has its own words (its i18n, `update`). */-export const UPDATE_ERRORS = {- offline: 'Could not reach the update service. Check your connection and try again.',- unavailable: 'Updates are unavailable right now. Please try again later.',- failed: 'Could not complete the update. Please try again later.',- 'agent-busy': 'An agent is still working. Restart when it has finished.',- exporting: 'An export is running. Restart when it has finished.',- 'install-failed': 'Could not install the update. Quit OpenFilm and open it again to install it.',-};-const NETWORK_CODES = ['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'ERR_INTERNET_DISCONNECTED', 'ERR_NETWORK_CHANGED'];/** Which kind of failure an updater error is: the feed missing or the host busy, the network, or anything else. */diff --git a/apps/desktop/src/update-launch.mjs b/apps/desktop/src/update-launch.mjsindex f432051..59ca233 100644--- a/apps/desktop/src/update-launch.mjs+++ b/apps/desktop/src/update-launch.mjs@@ -104,23 +104,8 @@ export function readyToInstall({ controller, subscribe, ms = LAUNCH_INSTALL_MS }}-/**- * The install window's language: the one Studio was last shown in, else the system's as Studio picks it (its i18n- * `languageFor`): `zh-Hans-CN` and `zh` are Simplified Chinese, `es-MX` is Spanish.- */-export function installLanguage(saved, system = []) {- if (saved && saved in WORDS) return saved;- for (const tag of system) {- const lower = String(tag).toLowerCase();- if (lower.startsWith('zh')) {- if (/^zh-(hant|tw|hk|mo)\b/.test(lower)) continue;- return 'zh-CN';- }- const base = lower.split('-')[0];- if (base in WORDS) return base;- }- return 'en';-}+/** The install window's language: the app's (i18n/language.mjs). */+export { appLanguage as installLanguage } from './i18n/language.mjs';export function installWords(language, { name, version }) {const fill = (text) => text.replaceAll('{name}', name).replaceAll('{version}', version);diff --git a/apps/desktop/src/update-menu.mjs b/apps/desktop/src/update-menu.mjsindex f1f7031..d61ada0 100644--- a/apps/desktop/src/update-menu.mjs+++ b/apps/desktop/src/update-menu.mjs@@ -1,10 +1,12 @@/*** "Check for Updates…" in the menu: the one place a check answers with a dialog (background checks are silent, and the- * chat only shows an update once it is ready). The dialogs never show the updater's own errors, only UPDATE_ERRORS.+ * chat only shows an update once it is ready). The dialogs never show the updater's own errors, only+ * their words for its codes (i18n/update-dialogs.mjs), in the menu's language.*/-import { UPDATE_ERRORS } from './update-controller.mjs';+import { UPDATE_DIALOG_WORDS } from './i18n/update-dialogs.mjs';/**+ * The check takes the menu's language (one of Studio's, i18n/language.mjs `appLanguage`).* @param {{ controller: { check: () => Promise<any>, restart: () => Promise<{ ok: boolean, error?: string }> },* showMessage: (options: Electron.MessageBoxOptions) => Promise<{ response: number }>, focusWindow: () => void,* productName?: string }} options@@ -12,36 +14,34 @@ import { UPDATE_ERRORS } from './update-controller.mjs';export function createManualUpdateCheck({ controller, showMessage, focusWindow, productName = 'OpenFilm' }) {/** one check, one dialog: the menu clicked again while it is open waits on the same one */let pending = null;- const say = (options) => showMessage({ title: 'Check for Updates', buttons: ['OK'], defaultId: 0, cancelId: 0, ...options });- return function manualCheck() {+ return function manualCheck(language = 'en') {pending ??= (async () => {+ const words = UPDATE_DIALOG_WORDS[language] ?? UPDATE_DIALOG_WORDS.en;+ /* a version not known yet leaves no gap ("Downloading OpenFilm") */+ const fill = (text, values = {}) => Object.entries({ name: productName, ...values })+ .reduce((out, [key, value]) => out.replaceAll(`{${key}}`, value), text).replace(/ {2,}/g, ' ').trim();+ const error = (code) => fill(words.errors[code] ?? words.errors.failed);+ const say = (options) => showMessage({ title: words.title, buttons: [words.ok], defaultId: 0, cancelId: 0, ...options });const state = await controller.check();- const next = state.availableVersion ?? '';+ const version = state.availableVersion ?? '';if (state.status === 'installing') return;if (state.status === 'current') {- await say({ type: 'info', message: `${productName} is up to date`, detail: `Version ${state.version}${state.channel === 'beta' ? ' (beta)' : ''}` });+ await say({ type: 'info', message: fill(words.upToDate), detail: fill(state.channel === 'beta' ? words.betaVersion : words.version, { version: state.version }) });} else if (state.status === 'ready') {focusWindow();const { response } = await say({- type: 'info', message: `${productName} ${next} is ready`,- detail: 'Restart now to update, or it installs when you quit and opens as the new version next time.',- buttons: ['Restart', 'Later'], defaultId: 0, cancelId: 1,+ type: 'info', message: fill(words.ready, { version }), detail: words.readyDetail,+ buttons: [words.restart, words.later], defaultId: 0, cancelId: 1,});if (response !== 0) return;const result = await controller.restart();- if (!result.ok && UPDATE_ERRORS[result.error]) await say({ type: 'warning', message: 'Not restarting yet', detail: UPDATE_ERRORS[result.error] });+ if (!result.ok && words.errors[result.error]) await say({ type: 'warning', message: words.notRestarting, detail: error(result.error) });} else if (['checking', 'available', 'downloading', 'staging'].includes(state.status)) {const progress = state.status === 'downloading' && state.progress ? ` (${Math.round(state.progress)}%)` : '';- await say({- type: 'info', message: `${['Downloading', productName, next].filter(Boolean).join(' ')}${progress}`,- detail: 'It downloads in the background: keep working. A Restart button appears at the top left when it is ready.',- });+ await say({ type: 'info', message: `${fill(words.downloading, { version })}${progress}`, detail: words.downloadingDetail });} else {- await say({- type: 'warning', message: 'Could not check for updates',- detail: `${UPDATE_ERRORS[state.error] ?? UPDATE_ERRORS.failed} ${productName} also tries again by itself.`,- });+ await say({ type: 'warning', message: words.failed, detail: fill(words.failedDetail, { error: error(state.error) }) });}})().finally(() => { pending = null; });return pending;