import React, { useCallback, useEffect, useRef, useState, useMemo } from "react"; import { AlertCircle, Import, Minus, Palette, Pencil, Plus, Trash2 } from "lucide-react"; import type { CursorShape, TerminalEmulationType, TerminalSettings, } from "../../../domain/models"; import { useI18n } from "../../../application/i18n/I18nProvider"; import { MAX_FONT_SIZE, MIN_FONT_SIZE, type TerminalFont } from "../../../infrastructure/config/fonts"; import { TERMINAL_THEMES } from "../../../infrastructure/config/terminalThemes"; import { customThemeStore, useCustomThemes } from "../../../application/state/customThemeStore"; import { parseItermcolors } from "../../../infrastructure/parsers/itermcolorsParser"; import { cn } from "../../../lib/utils"; import { useDiscoveredShells } from "../../../lib/useDiscoveredShells"; import { parseShellArgs, formatShellArgs } from "../../../domain/shellArgs"; import { Button } from "../../ui/button"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "../../ui/dialog"; import { Input } from "../../ui/input"; import { Select as ShadcnSelect, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../ui/select"; import { SectionHeader, Select, SettingsTabContent, SettingRow, Toggle } from "../settings-ui"; import { ThemeSelectModal } from "../ThemeSelectModal"; import { TerminalFontSelect } from "../TerminalFontSelect"; import { TerminalCjkFontSelect } from "../TerminalCjkFontSelect"; import { CustomThemeModal } from "../../terminal/CustomThemeModal"; import type { TerminalTheme } from "../../../domain/models"; import { resolveFollowedTerminalThemeId, TERMINAL_THEME_AUTO } from "../../../domain/terminalAppearance"; import { KeywordHighlightRulesEditor, ThemePreviewButton } from "./SettingsTerminalTabControls"; import { TerminalBehaviorSettings } from "./TerminalBehaviorSettings"; function SettingsTerminalTab(props: { terminalThemeId: string; setTerminalThemeId: (id: string) => void; followAppTerminalTheme: boolean; setFollowAppTerminalTheme: (value: boolean) => void; terminalThemeDarkId: string; setTerminalThemeDarkId: (id: string) => void; terminalThemeLightId: string; setTerminalThemeLightId: (id: string) => void; lightUiThemeId: string; darkUiThemeId: string; terminalFontFamilyId: string; setTerminalFontFamilyId: (id: string) => void; terminalFontSize: number; setTerminalFontSize: (size: number) => void; terminalSettings: TerminalSettings; updateTerminalSetting: ( key: K, value: TerminalSettings[K], ) => void; availableFonts: TerminalFont[]; workspaceFocusStyle: 'dim' | 'border'; setWorkspaceFocusStyle: (style: 'dim' | 'border') => void; }) { const { terminalThemeId, setTerminalThemeId, followAppTerminalTheme, setFollowAppTerminalTheme, terminalThemeDarkId, setTerminalThemeDarkId, terminalThemeLightId, setTerminalThemeLightId, lightUiThemeId, darkUiThemeId, terminalFontFamilyId, setTerminalFontFamilyId, terminalFontSize, setTerminalFontSize, terminalSettings, updateTerminalSetting, availableFonts, workspaceFocusStyle, setWorkspaceFocusStyle, } = props; const { t } = useI18n(); // Local shell settings state const [defaultShell, setDefaultShell] = useState(""); const [shellValidation, setShellValidation] = useState<{ valid: boolean; message?: string } | null>(null); const [dirValidation, setDirValidation] = useState<{ valid: boolean; message?: string } | null>(null); const discoveredShells = useDiscoveredShells(); const [showCustomShellInput, setShowCustomShellInput] = useState(() => { if (!terminalSettings.localShell) return false; return !discoveredShells.some(s => s.id === terminalSettings.localShell); }); const [customShellModalOpen, setCustomShellModalOpen] = useState(false); const [customShellDraft, setCustomShellDraft] = useState(""); const [customArgsDraft, setCustomArgsDraft] = useState(""); // Update showCustomShellInput once discovered shells load useEffect(() => { if (!terminalSettings.localShell) return; setShowCustomShellInput(!discoveredShells.some(s => s.id === terminalSettings.localShell)); }, [discoveredShells, terminalSettings.localShell]); // Seed the drafts from current settings and open the custom-shell editor. // Used both when picking "Custom…" and when re-editing an existing custom shell. const openCustomShellModal = useCallback(() => { setCustomShellDraft(terminalSettings.localShell || ""); setCustomArgsDraft(formatShellArgs(terminalSettings.localShellArgs ?? [])); setCustomShellModalOpen(true); }, [terminalSettings.localShell, terminalSettings.localShellArgs]); const [themeModalOpen, setThemeModalOpen] = useState(false); const [themeModalSlot, setThemeModalSlot] = useState<'dark' | 'light' | null>(null); // Subscribe to custom theme changes so editing in-place triggers re-render const customThemes = useCustomThemes(); // Get current selected theme const currentTheme = useMemo(() => { return TERMINAL_THEMES.find(t => t.id === terminalThemeId) || customThemes.find(t => t.id === terminalThemeId) || TERMINAL_THEMES[0]; }, [terminalThemeId, customThemes]); // Preview themes for the follow-app per-mode pickers. resolvedTheme is // forced per slot so each preview reflects exactly that mode's selection. const darkPreviewTheme = useMemo(() => { const id = resolveFollowedTerminalThemeId({ resolvedTheme: 'dark', terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, fallbackThemeId: terminalThemeId, }); return TERMINAL_THEMES.find(t => t.id === id) || customThemes.find(t => t.id === id) // Mirror the runtime fallback in useSettingsState.currentTerminalTheme: // a deleted per-mode override falls back to the manual theme, not [0]. || TERMINAL_THEMES.find(t => t.id === terminalThemeId) || customThemes.find(t => t.id === terminalThemeId) || TERMINAL_THEMES[0]; }, [terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, terminalThemeId, customThemes]); const lightPreviewTheme = useMemo(() => { const id = resolveFollowedTerminalThemeId({ resolvedTheme: 'light', terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, fallbackThemeId: terminalThemeId, }); return TERMINAL_THEMES.find(t => t.id === id) || customThemes.find(t => t.id === id) // Mirror the runtime fallback in useSettingsState.currentTerminalTheme: // a deleted per-mode override falls back to the manual theme, not [0]. || TERMINAL_THEMES.find(t => t.id === terminalThemeId) || customThemes.find(t => t.id === terminalThemeId) || TERMINAL_THEMES[0]; }, [terminalThemeDarkId, terminalThemeLightId, lightUiThemeId, darkUiThemeId, terminalThemeId, customThemes]); const handleAutocompleteGhostTextChange = useCallback((enabled: boolean) => { updateTerminalSetting("autocompleteGhostText", enabled); if (enabled) { updateTerminalSetting("autocompletePopupMenu", false); } }, [updateTerminalSetting]); const handleAutocompletePopupMenuChange = useCallback((enabled: boolean) => { updateTerminalSetting("autocompletePopupMenu", enabled); if (enabled) { updateTerminalSetting("autocompleteGhostText", false); } }, [updateTerminalSetting]); // Import .itermcolors file const importFileRef = useRef(null); const handleImportItermcolors = useCallback((e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) { return; } const name = file.name.replace(/\.(itermcolors|xml)$/i, ''); const reader = new FileReader(); reader.onload = () => { const xml = reader.result as string; const parsed = parseItermcolors(xml, name); if (parsed) { customThemeStore.addTheme(parsed); setTerminalThemeId(parsed.id); } else { console.error('[Settings] Failed to parse .itermcolors file:', file.name); window.alert(t('terminal.customTheme.importError') || 'Failed to parse the selected file. Please ensure it is a valid .itermcolors XML file.'); } }; reader.onerror = () => { console.error('[Settings] Failed to read file:', file.name, reader.error); }; reader.readAsText(file); e.target.value = ''; }, [setTerminalThemeId, t]); // New custom theme modal const [customThemeModalOpen, setCustomThemeModalOpen] = useState(false); const [customThemeData, setCustomThemeData] = useState(null); const [isEditingTheme, setIsEditingTheme] = useState(false); // Check if current theme is a custom theme const isCustomTheme = useMemo(() => { return currentTheme?.isCustom === true; }, [currentTheme]); const handleNewCustomTheme = useCallback(() => { const base = TERMINAL_THEMES.find(t => t.id === terminalThemeId) || customThemeStore.getThemeById(terminalThemeId) || TERMINAL_THEMES[0]; const newTheme: TerminalTheme = { ...base, id: `custom-${Date.now()}`, name: `${base.name} (Custom)`, isCustom: true, colors: { ...base.colors }, }; setCustomThemeData(newTheme); setIsEditingTheme(false); setCustomThemeModalOpen(true); }, [terminalThemeId]); const handleEditCustomTheme = useCallback(() => { if (!currentTheme?.isCustom) return; setCustomThemeData({ ...currentTheme, colors: { ...currentTheme.colors } }); setIsEditingTheme(true); setCustomThemeModalOpen(true); }, [currentTheme]); const handleDeleteCustomTheme = useCallback(() => { if (!currentTheme?.isCustom) return; customThemeStore.deleteTheme(currentTheme.id); setTerminalThemeId(TERMINAL_THEMES[0].id); }, [currentTheme, setTerminalThemeId]); // Fetch default shell on mount useEffect(() => { const bridge = (window as unknown as { netcatty?: NetcattyBridge }).netcatty; if (bridge?.getDefaultShell) { bridge.getDefaultShell().then((shell) => { setDefaultShell(shell); }).catch(() => { // Ignore errors - might not be in Electron }); } }, []); // Validate shell path when it changes (only for custom paths, not discovered shell ids) useEffect(() => { const bridge = (window as unknown as { netcatty?: NetcattyBridge }).netcatty; const shellPath = terminalSettings.localShell; if (!shellPath) { setShellValidation(null); return; } // Skip validation for discovered shell ids — only validate custom paths if (discoveredShells.some(s => s.id === shellPath)) { setShellValidation(null); return; } if (!bridge?.validatePath) { setShellValidation(null); return; } const timeoutId = setTimeout(() => { bridge.validatePath(shellPath, 'file').then((result) => { if (result.exists && result.isFile) { setShellValidation({ valid: true }); } else if (result.exists && result.isDirectory) { setShellValidation({ valid: false, message: t("settings.terminal.localShell.shell.isDirectory") }); } else { setShellValidation({ valid: false, message: t("settings.terminal.localShell.shell.notFound") }); } }).catch(() => { setShellValidation(null); }); }, 300); return () => clearTimeout(timeoutId); }, [terminalSettings.localShell, discoveredShells, t]); // Validate directory path when it changes useEffect(() => { const bridge = (window as unknown as { netcatty?: NetcattyBridge }).netcatty; const dirPath = terminalSettings.localStartDir; if (!dirPath) { setDirValidation(null); return; } if (!bridge?.validatePath) { setDirValidation(null); return; } const timeoutId = setTimeout(() => { bridge.validatePath(dirPath, 'directory').then((result) => { if (result.exists && result.isDirectory) { setDirValidation({ valid: true }); } else if (result.exists && result.isFile) { setDirValidation({ valid: false, message: t("settings.terminal.localShell.startDir.isFile") }); } else { setDirValidation({ valid: false, message: t("settings.terminal.localShell.startDir.notFound") }); } }).catch(() => { setDirValidation(null); }); }, 300); return () => clearTimeout(timeoutId); }, [terminalSettings.localStartDir, t]); const clampFontSize = useCallback((next: number) => { const safe = Math.max(MIN_FONT_SIZE, Math.min(MAX_FONT_SIZE, next)); setTerminalFontSize(safe); }, [setTerminalFontSize]); return (
{followAppTerminalTheme ? (
{t("settings.terminal.theme.darkTheme")}
setThemeModalSlot('dark')} buttonLabel={terminalThemeDarkId === TERMINAL_THEME_AUTO ? t("settings.terminal.theme.auto") : t("settings.terminal.theme.selectButton")} />
{t("settings.terminal.theme.lightTheme")}
setThemeModalSlot('light')} buttonLabel={terminalThemeLightId === TERMINAL_THEME_AUTO ? t("settings.terminal.theme.auto") : t("settings.terminal.theme.selectButton")} />
) : ( setThemeModalOpen(true)} buttonLabel={t("settings.terminal.theme.selectButton")} /> )} setThemeModalOpen(false)} selectedThemeId={terminalThemeId} onSelect={setTerminalThemeId} /> setThemeModalSlot(null)} selectedThemeId={themeModalSlot === 'dark' ? terminalThemeDarkId : terminalThemeLightId} onSelect={(id) => { if (themeModalSlot === 'dark') setTerminalThemeDarkId(id); else if (themeModalSlot === 'light') setTerminalThemeLightId(id); }} filterType={themeModalSlot === 'light' ? 'light' : 'dark'} showAutoOption /> {/* Theme action buttons */}
{isCustomTheme && ( <> )}
{/* Custom Theme Modal */} {customThemeData && ( { if (isEditingTheme) { customThemeStore.updateTheme(theme.id, theme); } else { customThemeStore.addTheme(theme); } setTerminalThemeId(theme.id); setCustomThemeModalOpen(false); setCustomThemeData(null); }} onDelete={isEditingTheme ? (themeId) => { customThemeStore.deleteTheme(themeId); setTerminalThemeId(TERMINAL_THEMES[0].id); setCustomThemeModalOpen(false); setCustomThemeData(null); } : undefined} onCancel={() => { setCustomThemeModalOpen(false); setCustomThemeData(null); }} /> )}
setTerminalFontFamilyId(id)} className="w-48" /> updateTerminalSetting("fallbackFont", next)} className="w-48" />
{terminalFontSize}px
updateTerminalSetting("fontWeightBold", parseInt(v))} className="w-40" />
updateTerminalSetting("linePadding", parseInt(e.target.value))} className="w-24 accent-primary" /> {terminalSettings.linePadding}
updateTerminalSetting("cursorShape", v as CursorShape)} className="w-32" /> updateTerminalSetting("cursorBlink", v)} />
updateTerminalSetting("altAsMeta", v)} /> updateTerminalSetting("optionArrowWordJump", v)} />
updateTerminalSetting("minimumContrastRatio", parseInt(e.target.value)) } className="w-24 accent-primary" /> {terminalSettings.minimumContrastRatio}
{t("settings.terminal.keywordHighlight.title")} updateTerminalSetting("keywordHighlightEnabled", v)} />
{terminalSettings.keywordHighlightEnabled && ( updateTerminalSetting("keywordHighlightRules", rules)} /> )}
{ if (value === "__custom__") { openCustomShellModal(); } else if (value === "__default__") { setShowCustomShellInput(false); updateTerminalSetting("localShell", ""); // Custom args only apply to a custom path; clear them so a stale // value can't leak into a discovered/default shell launch (#1221). updateTerminalSetting("localShellArgs", []); } else { setShowCustomShellInput(false); updateTerminalSetting("localShell", value); updateTerminalSetting("localShellArgs", []); } }} > {t("settings.terminal.localShell.shell.default")} {defaultShell ? ` (${defaultShell.split(/[/\\]/).pop()})` : ""} {discoveredShells.map((shell) => ( {shell.name} ))} {t("settings.terminal.localShell.shell.custom")} {showCustomShellInput && ( )} {!showCustomShellInput && defaultShell && !terminalSettings.localShell && ( {t("settings.terminal.localShell.shell.detected")}: {defaultShell} )}
updateTerminalSetting("localStartDir", e.target.value)} className={cn( "w-48", dirValidation && !dirValidation.valid && "border-destructive focus-visible:ring-destructive" )} /> {dirValidation && !dirValidation.valid && dirValidation.message && ( {dirValidation.message} )}
{ const val = parseInt(e.target.value) || 0; if (val >= 0 && val <= 3600) { updateTerminalSetting("keepaliveInterval", val); } }} className="w-24" /> { const val = parseInt(e.target.value) || 1; if (val >= 1 && val <= 100) { updateTerminalSetting("keepaliveCountMax", val); } }} className="w-24" /> updateTerminalSetting("x11Display", e.target.value)} placeholder={t("settings.terminal.connection.x11Display.placeholder")} className="w-48" />
updateTerminalSetting("showServerStats", v)} /> {terminalSettings.showServerStats && (
{ const val = parseInt(e.target.value) || 5; if (val >= 5 && val <= 300) { updateTerminalSetting("serverStatsRefreshInterval", val); } }} className="w-20" /> {t("settings.terminal.serverStats.seconds")}
)}
{ const val = parseInt(e.target.value, 10) || 3; if (val >= 2 && val <= 60) { updateTerminalSetting("systemManagerProcessRefreshInterval", val); } }} className="w-20" /> {t("settings.terminal.serverStats.seconds")}
{ const val = parseInt(e.target.value, 10) || 3; if (val >= 2 && val <= 60) { updateTerminalSetting("systemManagerTmuxRefreshInterval", val); } }} className="w-20" /> {t("settings.terminal.serverStats.seconds")}
{ const val = parseInt(e.target.value, 10) || 5; if (val >= 3 && val <= 120) { updateTerminalSetting("systemManagerDockerListRefreshInterval", val); } }} className="w-20" /> {t("settings.terminal.serverStats.seconds")}
{ const val = parseInt(e.target.value, 10) || 3; if (val >= 2 && val <= 60) { updateTerminalSetting("systemManagerDockerStatsRefreshInterval", val); } }} className="w-20" /> {t("settings.terminal.serverStats.seconds")}
setWorkspaceFocusStyle(v as 'dim' | 'border')} options={[ { value: 'dim', label: t("settings.terminal.workspaceFocus.dim") }, { value: 'border', label: t("settings.terminal.workspaceFocus.border") }, ]} className="w-40" />
updateTerminalSetting("autocompleteEnabled", v)} />
{/* Custom Shell Modal */} {t("settings.terminal.localShell.shell.custom")}
setCustomShellDraft(e.target.value)} className="w-full" autoFocus /> {shellValidation && !shellValidation.valid && shellValidation.message && ( {shellValidation.message} )} {shellValidation?.valid && ( ✓ {t("settings.terminal.localShell.shell.pathValid")} )}
setCustomArgsDraft(e.target.value)} className="w-full" /> {t("settings.terminal.localShell.shell.customArgs.desc")}
{["/bin/bash", "/bin/zsh", "/usr/bin/fish", "/bin/sh", "powershell.exe", "pwsh.exe", "cmd.exe"].map((p) => ( ))}
); } export default React.memo(SettingsTerminalTab);