d3ro-voice/apps/desktop/src/main/windows/WindowManager.ts
Yun Chan 7b1210b5d1 feat(desktop): honest, unified dictation popups with Esc to cancel
Wave 3 of the 2026-09-28 design overhaul.

- Esc (no modifiers) cancels an in-progress dictation, recording or
  processing: VoiceModeService.requestEscape() queues the dead 'escape'
  action. Clicking the capsule cancels only while recording, so a stray
  click during processing no longer throws the text away.
- Errors show in the user's language: bootstrap now passes error.code to
  the tip (the translated branch never ran), and one core classifier
  (voice-error-message) feeds both the tip and the main-window alert.
- Capsule: bars stay flat without input (no fake "alive" wobble before the
  mic opens), an indeterminate bar replaces the made-up percentage, the
  partial transcript stays visible while processing, an Esc hint, and a
  brief "Inserted" state so success is visible.
- All six popups share popups/_shared (Pretendard, one panel radius,
  selection, kbd hints, reduced motion). History/command popups get
  titles, listbox roles and window sizes from popup-list-geometry (empty
  states were clipped); the command popup's "0" key is registered;
  result popup explains why it appeared and can be closed; captions keep
  a theme-independent dark backing on purpose.
- Popup themes follow the OS when set to system and the document lang
  follows the app language.
- Site hero demo mirrors the new capsule (done state, indeterminate bar,
  Esc hint; 10 locales).
2026-09-28 20:46:24 +09:00

1004 lines
37 KiB
TypeScript

// src/main/windows/WindowManager.ts
// 설계서 01 WindowManagerService: 메인 윈도우 + 팝업 프리로딩 + 2-phase 리사이즈
import { app, BrowserWindow, screen, ipcMain, Menu, clipboard } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import { WINDOW_SIZE } from '@d3ro/core/constants'
import type { AnchorKind, PhysicalRect } from '@d3ro/core/input-intelligence'
import {
fitAnchoredPanel,
placeAnchoredPanel,
placeNearCursor,
type AnchoredPanelPlacement,
type DipPoint,
type ScreenGeometryPort,
type UiRect,
type UiSize
} from '@d3ro/core/popup-placement'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import {
formatBindingSegments,
joinBindingSegments,
type BindingPlatform,
type KeyBinding,
type KeyBindingActionId
} from '@d3ro/core/keybinding'
import { getLogger } from '../services/LoggerService'
import { getIsQuitting, setIsQuitting } from '../lifecycle'
import { hardenWebContents } from './web-contents-hardening'
import { commandPopupSize, historyPopupSize } from './popup-list-geometry'
import { configGet, configSet } from '../services/ConfigService'
import { getI18n } from '@d3ro/i18n'
import {
createPopupWindow,
injectPopupTheme,
presentPopup,
sendToPopupWindow
} from './popup-window-factory'
import { createElectronScreenGeometry } from './screen-geometry'
import { installApplicationMenu } from './app-menu'
import {
SUGGESTION_OVERLAY_MAX_HEIGHT,
SUGGESTION_OVERLAY_WIDTH,
suggestionPanelHeight
} from './suggestion-overlay-geometry'
const logger = getLogger('WindowManager')
// ── 팝업 i18n 문자열 가져오기 ─────────────────────────────
/**
* 팝업에 주입할 i18n 문자열 맵을 반환.
*/
/** 현재 설정 언어의 번역 함수 — 팝업(Vanilla JS)에 넘길 문구를 main 에서 만들 때 쓴다 */
export function getPopupTranslator(): ReturnType<typeof getI18n>['t'] {
const locale = (configGet('language') as string) || 'ko'
return getI18n(locale as 'ko' | 'en' | 'ja' | 'zh' | 'zh-TW' | 'es' | 'fr' | 'de' | 'pt' | 'ru' | 'vi' | 'th').t
}
function getPopupI18nStrings(): Record<string, string> {
const t = getPopupTranslator()
return {
// history-popup 상대 시간
timeJustNow: t('popup.time.justNow'),
timeMinutesAgo: t('popup.time.minutesAgo'),
timeHoursAgo: t('popup.time.hoursAgo'),
timeDaysAgo: t('popup.time.daysAgo'),
// result-popup
copy: t('popup.copy'),
copied: t('popup.copied'),
resultTitle: t('popup.result.title'),
// 목록 팝업 공통 (v4: 키는 kbd 칩, 설명은 동사)
hintMove: t('popup.hints.move'),
hintPaste: t('popup.hints.paste2'),
hintApply: t('popup.hints.apply2'),
hintClose: t('popup.hints.close2'),
hintPick: t('popup.hints.pick'),
historyTitle: t('popup.history.title'),
historyEmpty: t('popup.history.empty'),
commandTitle: t('popup.command.title'),
commandEmpty: t('popup.command.empty'),
commandNone: t('popup.command.none'),
// recording-tip
errorDefault: t('popup.error.default'),
tipProcessing: t('popup.tip.processing'),
tipInserted: t('popup.tip.inserted'),
tipCancelHint: t('popup.tip.cancelHint'),
tipRecording: t('popup.tip.recordingLabel'),
close: t('popup.close'),
// caption-overlay
captionLoading: t('popup.caption.loading'),
captionWaiting: t('popup.caption.waiting'),
captionDragHint: t('popup.caption.dragHint'),
// suggestion-overlay
suggestionHintAccept: t('popup.suggestion.hintAccept'),
suggestionHintNext: t('popup.suggestion.hintNext'),
suggestionHintDismiss: t('popup.suggestion.hintDismiss'),
suggestionWarming: t('popup.suggestion.warming'),
suggestionHintGenerating: t('popup.suggestion.hintGenerating'),
suggestionLoading: t('popup.suggestion.loading'),
// 경과 초가 붙는 "생성 중 {{s}}초" — 빠져 있어 script.js 가 loading 으로 떨어졌다(2026-09-28)
suggestionGenerating: t('popup.suggestion.generating'),
suggestionSourceModel: t('popup.suggestion.sourceModel'),
suggestionSourceMemory: t('popup.suggestion.sourceMemory'),
suggestionContinuations: t('popup.suggestion.continuations'),
suggestionRelated: t('popup.suggestion.related'),
suggestionPhrases: t('popup.suggestion.phrases'),
suggestionAppPhrases: t('popup.suggestion.appPhrases'),
// 키 힌트 줄 (동작 낱말 — 실제 키는 사용자 바인딩에서 매번 계산해 붙인다)
suggestionHintMoveLabel: t('popup.suggestion.hintMove'),
suggestionHintAcceptLabel: t('popup.suggestion.hintAccept'),
suggestionHintCloseLabel: t('popup.suggestion.hintDismiss'),
suggestionHintGeneratingMore: t('popup.suggestion.hintGeneratingMore'),
}
}
/** win32/darwin 외 플랫폼은 linux 로 간주한다(키캡 표기 정본 — BindingPlatform). */
function resolveBindingPlatform(): BindingPlatform {
if (process.platform === 'darwin') return 'darwin'
if (process.platform === 'win32') return 'win32'
return 'linux'
}
interface SplitBinding {
modifiers: string[]
key: string
}
function splitBinding(binding: KeyBinding, platform: BindingPlatform): SplitBinding {
const labels = formatBindingSegments(binding, platform).map((segment) => segment.label)
return { modifiers: labels.slice(0, -1), key: labels[labels.length - 1] ?? '' }
}
function sameModifiers(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((mod, index) => mod === b[index])
}
export interface SuggestionKeyHints {
/** 이동·수락이 모두 같은 수정자를 쓰면 그 수정자(예: "Ctrl+Alt") — 한 번만 보여준다 */
shared: string | null
move: string | null
accept: string | null
close: string
}
/**
* 제안 오버레이 키 힌트 — 사용자가 실제로 설정한 바인딩에서 매번 다시 계산한다.
*
* 라벨은 키바인딩 SSOT(formatBindingSegments/joinBindingSegments) 로만 만든다.
* 수정자가 모두 같으면 앞에 한 번만 두고 각 힌트는 키만 보여준다 — 같은 "Ctrl+Alt+" 를
* 네 번 반복하면 한 줄에 들어가지 않고 읽기도 어렵다. 바인딩 없는 액션은 생략한다.
* 닫기는 오버레이 전용 Esc 로 고정한다(보조 바인딩은 설정 화면에서 보인다).
*/
function buildSuggestionKeyHints(): SuggestionKeyHints {
const bindings = configGet('keyBindings')
const platform = resolveBindingPlatform()
const splitOf = (actionId: KeyBindingActionId): SplitBinding | null => {
const binding = bindings[actionId]?.[0]
return binding ? splitBinding(binding, platform) : null
}
const prev = splitOf('suggestion-prev')
const next = splitOf('suggestion-next')
const accept = splitOf('suggestion-accept')
const present = [prev, next, accept].filter((b): b is SplitBinding => b !== null)
const common = present[0]?.modifiers ?? []
const shareAll =
present.length > 0 && common.length > 0 && present.every((b) => sameModifiers(b.modifiers, common))
const label = (b: SplitBinding): string =>
shareAll ? b.key : joinBindingSegments([...b.modifiers, b.key], platform)
const pair = (a: SplitBinding | null, b: SplitBinding | null): string | null => {
if (!a && !b) return null
if (a && b) return shareAll ? `${a.key}${b.key}` : `${label(a)} / ${label(b)}`
return label((a ?? b) as SplitBinding)
}
return {
shared: shareAll ? joinBindingSegments(common, platform) : null,
move: pair(prev, next),
accept: accept ? label(accept) : null,
close: 'Esc'
}
}
// ── 화면 기하 (DIP) ───────────────────────────────────
// 팝업 창 생성·수명주기·표시는 popup-window-factory, 배치 정책은 core popup-placement 가 정본이다.
let screenGeometry: ScreenGeometryPort | null = null
/** Electron screen 은 app ready 뒤에만 쓸 수 있다 — 처음 배치할 때 만든다. */
function getScreenGeometry(): ScreenGeometryPort {
if (!screenGeometry) screenGeometry = createElectronScreenGeometry(screen)
return screenGeometry
}
/** 커서 기준 배치 (녹음 팁 · 결과 · 기록 · 명령 팝업 공통) — 커서와 작업 영역 모두 DIP. */
function placePopupNearCursor(
win: BrowserWindow,
size: UiSize,
cursor: DipPoint = getScreenGeometry().cursor()
): void {
const position = placeNearCursor(cursor, size, getScreenGeometry().workAreaNear(cursor))
win.setBounds({ x: position.x, y: position.y, width: size.width, height: size.height })
}
// ── 윈도우 참조 ───────────────────────────────────────
let mainWindow: BrowserWindow | null = null
let recordingTipWindow: BrowserWindow | null = null
let resultPopupWindow: BrowserWindow | null = null
let historyPopupWindow: BrowserWindow | null = null
let commandPopupWindow: BrowserWindow | null = null
let captionOverlayWindow: BrowserWindow | null = null
let suggestionOverlayWindow: BrowserWindow | null = null
// ── 메인 윈도우 ───────────────────────────────────────
export function getMainWindow(): BrowserWindow | null {
return mainWindow
}
/** 부트스트랩이 메인 창을 한 번이라도 만들었는지 — 그 전에는 다시 만들지 않는다(중복 창 방지). */
let mainWindowCreated = false
/**
* 메인 창을 앞으로 가져온다. 이미 한 번 만들어진 뒤 닫혀 없으면 다시 만든다(트레이 '표시'·두 번째 실행).
* 부트스트랩 전이면 null.
*/
export function showMainWindow(): BrowserWindow | null {
let win = mainWindow && !mainWindow.isDestroyed() ? mainWindow : null
if (!win) {
if (!mainWindowCreated) return null
win = createMainWindow()
}
if (win.isMinimized()) win.restore()
win.show()
win.focus()
return win
}
export function createMainWindow(): BrowserWindow {
const primaryDisplay = screen.getPrimaryDisplay()
const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
const initWidth = Math.min(WINDOW_SIZE.MAIN.width, screenWidth)
const initHeight = Math.min(WINDOW_SIZE.MAIN.height, screenHeight)
mainWindow = new BrowserWindow({
title: 'D3RO Voice',
width: initWidth,
height: initHeight,
x: Math.max(0, Math.round((screenWidth - initWidth) / 2)),
y: Math.max(0, Math.round((screenHeight - initHeight) / 2)),
minWidth: 800,
minHeight: 600,
show: true,
autoHideMenuBar: true,
// 보더리스: 렌더러의 커스텀 TitleBar(AppLayout 최상단)가 크롬을 대체한다.
// macOS는 hiddenInset으로 네이티브 교통신호(traffic lights)를 콘텐츠 위에
// 인셋 유지 — 이 플랫폼에서는 커스텀 최대/최소/닫기 버튼을 렌더러에서 숨긴다.
...(process.platform === 'darwin'
? { titleBarStyle: 'hiddenInset' as const, trafficLightPosition: { x: 16, y: 13 } }
: { frame: false }),
roundedCorners: true,
backgroundColor: '#0a0e1c',
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
contextIsolation: true,
nodeIntegration: false
}
})
mainWindowCreated = true
mainWindow.setSkipTaskbar(false)
// Win/Linux: Alt 키로 메뉴 활성화 방지(메뉴 완전 제거). macOS: 편집 단축키(Cmd+C/V/X/A/Z)와
// Cmd+Q 는 애플리케이션 메뉴의 role 항목으로만 동작하므로 최소 메뉴를 유지한다.
mainWindow.setMenu(null)
installApplicationMenu(Menu, process.platform)
mainWindow.on('ready-to-show', () => {
mainWindow?.show()
mainWindow?.restore()
mainWindow?.focus()
mainWindow?.flashFrame(true)
if (is.dev && process.env['ELECTRON_OPEN_DEVTOOLS'] === '1') {
mainWindow?.webContents.openDevTools({ mode: 'right' })
}
logger.info('Main window shown')
})
mainWindow.on('close', (event) => {
if (getIsQuitting()) return
if (configGet('closeToTray')) {
event.preventDefault()
mainWindow?.hide()
logger.info('Main window hidden to tray')
return
}
// 트레이로 숨기지 않는 설정이면 창 닫기 = 앱 종료. 숨은 팝업이 남아 있어 window-all-closed가
// 오지 않으므로, 그대로 두면 다시 열 수 없는 창 없는 프로세스가 남는다.
setIsQuitting(true)
logger.info('Main window closed with closeToTray=false — quitting')
app.quit()
})
mainWindow.on('closed', () => {
mainWindow = null
})
mainWindow.webContents.on('console-message', (_event, level, message, line, sourceId) => {
logger.info(`[Renderer] [${level}] ${message} (${sourceId}:${line})`)
})
// 앱 밖 링크는 창 안에서 열지 않고(원격 페이지가 preload API를 얻지 못하게) 허용 scheme만 브라우저로 넘긴다.
hardenWebContents(mainWindow)
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
}
mainWindow.center()
mainWindow.restore()
mainWindow.show()
mainWindow.focus()
mainWindow.setAlwaysOnTop(true)
setTimeout(() => {
try {
mainWindow?.setAlwaysOnTop(false)
} catch {
// ignore
}
}, 1000)
logger.info('Main window created')
return mainWindow
}
// ── RecordingTip 팝업 ─────────────────────────────────
function createRecordingTipWindow(): BrowserWindow {
return createPopupWindow({
name: 'recording-tip',
bounds: { width: WINDOW_SIZE.RECORDING_TIP.width, height: WINDOW_SIZE.RECORDING_TIP.height },
onClosed: () => {
recordingTipWindow = null
}
})
}
export function getRecordingTipWindow(): BrowserWindow {
if (!recordingTipWindow || recordingTipWindow.isDestroyed()) {
recordingTipWindow = createRecordingTipWindow()
logger.info('RecordingTip window created (preloaded)')
}
return recordingTipWindow
}
/**
* RecordingTip 표시 (2-phase 리사이즈)
* Phase 1: prepare → 측정
* Phase 2: resize → show
*/
// RecordingTip 기본 크기 (고정 — 2-phase 복잡도 제거)
// v2: 실시간 부분 전사 라인 표시를 위해 상향 (280x80 → 320x110)
const TIP_WIDTH = 320
const TIP_HEIGHT = 110
export function showRecordingTip(
state: string,
params?: { text?: string; errorMessage?: string }
): void {
const win = getRecordingTipWindow()
// 커서 위치에 배치 (화면 밖 보정 포함)
placePopupNearCursor(win, { width: TIP_WIDTH, height: TIP_HEIGHT })
// 상태 전송 후 즉시 show (2-phase 제거 — 숨겨진 윈도우의 렌더러 비활성 문제 방지)
sendToPopupWindow(win, IPC_CHANNELS.WINDOW.TIP_STATE_CHANGED, { state, _i18n: getPopupI18nStrings(), ...params })
presentPopup(win, 'screen-saver')
logger.debug(`RecordingTip presented: state=${state} visible=${win.isVisible()} loading=${win.webContents.isLoading()}`)
}
/**
* 오류를 RecordingTip 에 그리고 팁을 띄운다.
* 쿼터 초과·자막 사용 중·STT 모델 미설치 오류는 'recording' phase 전에 세션을 끝내므로 팁이 숨겨진
* 상태다 — 상태 IPC 만 보내면 보이지 않는 창에 그려지고 오류음만 남는다. 이미 떠 있는 팁(녹음 도중
* 난 오류)은 자리를 옮기지 않고 상태만 바꾼다.
*/
export function showRecordingTipError(errorMessage: string): void {
if (recordingTipWindow && !recordingTipWindow.isDestroyed() && recordingTipWindow.isVisible()) {
updateRecordingTipState('error', { errorMessage })
return
}
showRecordingTip('error', { errorMessage })
}
export function hideRecordingTip(): void {
if (recordingTipWindow && !recordingTipWindow.isDestroyed()) {
recordingTipWindow.hide()
}
}
export function updateRecordingTipState(
state: string,
params?: { text?: string; errorMessage?: string }
): void {
if (recordingTipWindow && !recordingTipWindow.isDestroyed()) {
sendToPopupWindow(recordingTipWindow, IPC_CHANNELS.WINDOW.TIP_STATE_CHANGED, { state, _i18n: getPopupI18nStrings(), ...params })
}
}
export function sendAudioLevelToTip(level: number): void {
if (recordingTipWindow && !recordingTipWindow.isDestroyed()) {
sendToPopupWindow(recordingTipWindow, IPC_CHANNELS.VOICE.AUDIO_LEVEL, { level })
}
}
/** 실시간 부분 전사 텍스트를 RecordingTip에 전달 */
export function sendPartialTranscriptToTip(text: string): void {
if (recordingTipWindow && !recordingTipWindow.isDestroyed()) {
sendToPopupWindow(recordingTipWindow, IPC_CHANNELS.VOICE_PARTIAL.PARTIAL_TRANSCRIPT, { text })
}
}
// ── ResultPopup 팝업 ──────────────────────────────────
function createResultPopupWindow(): BrowserWindow {
return createPopupWindow({
name: 'result-popup',
bounds: { width: WINDOW_SIZE.RESULT_POPUP.width, height: WINDOW_SIZE.RESULT_POPUP.height },
onClosed: () => {
cancelPendingResultShow()
resultPopupWindow = null
}
})
}
export function getResultPopupWindow(): BrowserWindow {
if (!resultPopupWindow || resultPopupWindow.isDestroyed()) {
resultPopupWindow = createResultPopupWindow()
logger.info('ResultPopup window created (preloaded)')
}
return resultPopupWindow
}
/**
* 측정이 오지 않을 때 기다리는 한도.
*
* 숨긴 창에서는 렌더러의 requestAnimationFrame 이 멈출 수 있어 측정(result:measured)이 영영
* 오지 않았다 — 두 번째 삽입 실패부터 받아쓴 텍스트를 볼 방법이 없었다. 한도가 지나면 기본
* 크기로 그대로 보여준다.
*/
const RESULT_MEASURE_TIMEOUT_MS = 400
interface PendingResultShow {
autoHideMs: number
cursor: DipPoint
fallbackTimer: NodeJS.Timeout
}
let pendingResultShow: PendingResultShow | null = null
/** 마지막 표시의 커서 — 한도 뒤 늦게 도착한 측정으로 크기만 고칠 때 쓴다 */
let lastResultCursor: DipPoint | null = null
function cancelPendingResultShow(): void {
if (!pendingResultShow) return
clearTimeout(pendingResultShow.fallbackTimer)
pendingResultShow = null
}
function isMeasuredSize(data: unknown): data is UiSize {
if (data === null || typeof data !== 'object') return false
const { width, height } = data as Record<string, unknown>
return (
typeof width === 'number' &&
typeof height === 'number' &&
Number.isFinite(width) &&
Number.isFinite(height) &&
width > 0 &&
height > 0
)
}
/** Phase 2: 측정 크기(없으면 현재 크기)로 배치를 마무리하고 내용을 보인다. */
function finishResultShow(measured: UiSize | null): void {
const pending = pendingResultShow
if (!pending) return
cancelPendingResultShow()
const win = resultPopupWindow
if (!win || win.isDestroyed()) return
if (measured) placePopupNearCursor(win, measured, pending.cursor)
presentPopup(win)
sendToPopupWindow(win, IPC_CHANNELS.POPUP_RESULT.SHOW, { autoHideMs: pending.autoHideMs })
}
/**
* ResultPopup 표시 (2-phase 리사이즈)
*
* Phase 1: 기본 크기로 커서 곁에 먼저 띄운다 — 내용은 SHOW 전까지 투명하다. 창이 보여야
* 렌더러가 측정 프레임을 돈다(숨긴 창의 rAF 정지 방지).
* Phase 2: 측정이 오면(또는 한도가 지나면) 크기를 맞추고 내용을 보인다.
* 측정 응답은 모듈 단일 리스너가 받는다 — 호출마다 ipcMain.once 를 쌓지 않는다.
*/
export function showResultPopup(text: string, autoHideMs = 5000): void {
const win = getResultPopupWindow()
cancelPendingResultShow()
const cursor = getScreenGeometry().cursor()
lastResultCursor = cursor
placePopupNearCursor(
win,
{ width: WINDOW_SIZE.RESULT_POPUP.width, height: WINDOW_SIZE.RESULT_POPUP.height },
cursor
)
sendToPopupWindow(win, IPC_CHANNELS.POPUP_RESULT.PREPARE, { text, _i18n: getPopupI18nStrings() })
presentPopup(win)
const fallbackTimer = setTimeout(() => finishResultShow(null), RESULT_MEASURE_TIMEOUT_MS)
fallbackTimer.unref?.()
pendingResultShow = { autoHideMs, cursor, fallbackTimer }
}
ipcMain.on(IPC_CHANNELS.POPUP_RESULT.MEASURED, (event: Electron.IpcMainEvent, data: unknown) => {
const win = resultPopupWindow
if (!win || win.isDestroyed() || event.sender !== win.webContents) return
if (!isMeasuredSize(data)) return
if (pendingResultShow) {
finishResultShow(data)
return
}
// 한도 뒤에 늦게 도착한 측정 — 이미 보이는 팝업의 크기만 맞춘다.
if (win.isVisible() && lastResultCursor) placePopupNearCursor(win, data, lastResultCursor)
})
export function hideResultPopup(): void {
if (resultPopupWindow && !resultPopupWindow.isDestroyed()) {
resultPopupWindow.hide()
}
}
// ── HistoryPopup 팝업 ─────────────────────────────────
function createHistoryPopupWindow(): BrowserWindow {
return createPopupWindow({
name: 'history-popup',
bounds: { width: 360, height: 400 },
onClosed: () => {
historyPopupWindow = null
}
})
}
export function getHistoryPopupWindow(): BrowserWindow {
if (!historyPopupWindow || historyPopupWindow.isDestroyed()) {
historyPopupWindow = createHistoryPopupWindow()
logger.info('HistoryPopup window created')
}
return historyPopupWindow
}
export function showHistoryPopup(entries: Array<Record<string, unknown>>): void {
const win = getHistoryPopupWindow()
// 커서 위치에 즉시 배치+표시 (2-phase 제거 — 숨겨진 윈도우 렌더러 비활성 문제 방지)
placePopupNearCursor(win, historyPopupSize(entries.length))
sendToPopupWindow(win, IPC_CHANNELS.POPUP_HISTORY.SHOW_ITEMS, { entries, _i18n: getPopupI18nStrings() })
presentPopup(win)
sendToPopupWindow(win, IPC_CHANNELS.POPUP_HISTORY.SHOW, {})
}
export function hideHistoryPopup(): void {
if (historyPopupWindow && !historyPopupWindow.isDestroyed()) {
sendToPopupWindow(historyPopupWindow, IPC_CHANNELS.POPUP_HISTORY.HIDE, {})
setTimeout(() => {
if (historyPopupWindow && !historyPopupWindow.isDestroyed()) {
historyPopupWindow.hide()
}
}, 150)
}
}
export function sendKeyToHistoryPopup(key: string): void {
if (historyPopupWindow && !historyPopupWindow.isDestroyed() && historyPopupWindow.isVisible()) {
sendToPopupWindow(historyPopupWindow, IPC_CHANNELS.POPUP_HISTORY.KEY_EVENT, { key })
}
}
export function isHistoryPopupVisible(): boolean {
return !!(historyPopupWindow && !historyPopupWindow.isDestroyed() && historyPopupWindow.isVisible())
}
// ── CommandPopup 팝업 ─────────────────────────────────
function createCommandPopupWindow(): BrowserWindow {
return createPopupWindow({
name: 'command-popup',
bounds: commandPopupSize(0),
onClosed: () => {
commandPopupWindow = null
}
})
}
export function getCommandPopupWindow(): BrowserWindow {
if (!commandPopupWindow || commandPopupWindow.isDestroyed()) {
commandPopupWindow = createCommandPopupWindow()
}
return commandPopupWindow
}
export function showCommandPopup(commands: Array<Record<string, unknown>>, activeId: string | null): void {
const win = getCommandPopupWindow()
placePopupNearCursor(win, commandPopupSize(commands.length))
sendToPopupWindow(win, IPC_CHANNELS.POPUP_COMMAND.SHOW_ITEMS, { commands, activeId, _i18n: getPopupI18nStrings() })
presentPopup(win)
sendToPopupWindow(win, IPC_CHANNELS.POPUP_COMMAND.SHOW, {})
}
export function hideCommandPopup(): void {
if (commandPopupWindow && !commandPopupWindow.isDestroyed()) {
sendToPopupWindow(commandPopupWindow, IPC_CHANNELS.POPUP_COMMAND.HIDE, {})
setTimeout(() => {
if (commandPopupWindow && !commandPopupWindow.isDestroyed()) {
commandPopupWindow.hide()
}
}, 150)
}
}
export function sendKeyToCommandPopup(key: string): void {
if (commandPopupWindow && !commandPopupWindow.isDestroyed() && commandPopupWindow.isVisible()) {
sendToPopupWindow(commandPopupWindow, IPC_CHANNELS.POPUP_COMMAND.KEY_EVENT, { key })
}
}
export function isCommandPopupVisible(): boolean {
return !!(commandPopupWindow && !commandPopupWindow.isDestroyed() && commandPopupWindow.isVisible())
}
// ── CaptionOverlay 팝업 (Phase 10.1) ─────────────────
const CAPTION_OVERLAY_HEIGHT = 140
/** 기본 위치: 주 모니터 작업 영역 아래 가운데. */
function defaultCaptionOverlayBounds(): Electron.Rectangle {
const { workArea } = screen.getPrimaryDisplay()
const width = Math.round(workArea.width * 0.8)
return {
x: workArea.x + Math.round((workArea.width - width) / 2),
y: workArea.y + workArea.height - CAPTION_OVERLAY_HEIGHT - 40,
width,
height: CAPTION_OVERLAY_HEIGHT
}
}
/** 저장된 위치가 지금 연결된 어느 모니터 안에 들어오면 쓴다 (모니터를 뺐으면 기본 위치). */
function initialCaptionOverlayBounds(): Electron.Rectangle {
const fallback = defaultCaptionOverlayBounds()
const saved = configGet('captionOverlayPosition')
if (!saved) return fallback
const handle = { x: saved.x + Math.round(fallback.width / 2), y: saved.y + 20 }
const onScreen = screen.getAllDisplays().some(({ workArea }) =>
handle.x >= workArea.x && handle.x < workArea.x + workArea.width &&
handle.y >= workArea.y && handle.y < workArea.y + workArea.height
)
return onScreen ? { ...fallback, x: saved.x, y: saved.y } : fallback
}
function createCaptionOverlayWindow(): BrowserWindow {
return createPopupWindow({
name: 'caption-overlay',
bounds: initialCaptionOverlayBounds(),
// 표시 중에는 항상 보이는 창이다 — 기존 기본값(늦춤)을 유지한다.
backgroundThrottling: true,
// 클릭 통과: 마우스 이벤트를 무시하되, CSS hover 등을 위해 forward 활성화
beforeLoad: (win) => win.setIgnoreMouseEvents(true, { forward: true }),
onClosed: () => {
captionOverlayWindow = null
}
})
}
export function getCaptionOverlayWindow(): BrowserWindow {
if (!captionOverlayWindow || captionOverlayWindow.isDestroyed()) {
captionOverlayWindow = createCaptionOverlayWindow()
logger.info('CaptionOverlay window created')
}
return captionOverlayWindow
}
export function showCaptionOverlay(): void {
const win = getCaptionOverlayWindow()
presentPopup(win)
}
export function hideCaptionOverlay(): void {
endCaptionOverlayDrag()
if (captionOverlayWindow && !captionOverlayWindow.isDestroyed()) {
sendToPopupWindow(captionOverlayWindow, IPC_CHANNELS.POPUP_CAPTION.HIDE, {})
captionOverlayWindow.setIgnoreMouseEvents(true, { forward: true })
captionOverlayWindow.hide()
}
}
export function sendToCaptionOverlay(channel: string, data: unknown): void {
if (captionOverlayWindow && !captionOverlayWindow.isDestroyed()) {
// 상태 이벤트에 문구를 실어 보낸다 — 빠지면 오버레이가 영어 기본 문구로 떨어진다.
const payload =
channel === IPC_CHANNELS.CAPTION.STATE_CHANGED && data !== null && typeof data === 'object'
? { ...data, _i18n: getPopupI18nStrings() }
: data
sendToPopupWindow(captionOverlayWindow, channel, payload)
}
}
// ── 자막 창 끌어서 옮기기 ──
// 창은 기본적으로 클릭 통과다. 렌더러의 손잡이 위에 있는 동안만 마우스를 받고,
// 끄는 동안은 커서를 따라 창을 옮긴다(포커스를 받지 않는 창이라 OS 제목줄 끌기에 기대지 않는다).
let captionDragTimer: NodeJS.Timeout | null = null
let captionDragOffset: { x: number; y: number } | null = null
/** 버튼 뗌 신호가 유실돼도 창이 커서에 영원히 붙어 있지 않게 한다 */
const CAPTION_DRAG_MAX_MS = 30_000
export function setCaptionOverlayInteractive(interactive: boolean): void {
if (!captionOverlayWindow || captionOverlayWindow.isDestroyed()) return
if (!interactive && captionDragTimer) return
if (interactive) captionOverlayWindow.setIgnoreMouseEvents(false)
else captionOverlayWindow.setIgnoreMouseEvents(true, { forward: true })
}
export function startCaptionOverlayDrag(): void {
const win = captionOverlayWindow
if (!win || win.isDestroyed() || captionDragTimer) return
const cursor = screen.getCursorScreenPoint()
const [x, y] = win.getPosition()
captionDragOffset = { x: cursor.x - x, y: cursor.y - y }
const startedAt = Date.now()
captionDragTimer = setInterval(() => {
if (win.isDestroyed() || !captionDragOffset || Date.now() - startedAt > CAPTION_DRAG_MAX_MS) {
endCaptionOverlayDrag()
return
}
const point = screen.getCursorScreenPoint()
win.setPosition(point.x - captionDragOffset.x, point.y - captionDragOffset.y)
}, 16)
}
export function endCaptionOverlayDrag(): void {
if (!captionDragTimer) return
clearInterval(captionDragTimer)
captionDragTimer = null
captionDragOffset = null
const win = captionOverlayWindow
if (!win || win.isDestroyed()) return
const [x, y] = win.getPosition()
configSet('captionOverlayPosition', { x, y })
win.setIgnoreMouseEvents(true, { forward: true })
}
export function resetCaptionOverlayPosition(): void {
endCaptionOverlayDrag()
configSet('captionOverlayPosition', null)
const win = captionOverlayWindow
if (win && !win.isDestroyed()) win.setBounds(defaultCaptionOverlayBounds())
}
// ── SuggestionOverlay (입력 인텔리전스) ──────────────
/**
* 다음 문장 제안 ghost text 오버레이.
*
* IME 후보창과 같은 관례를 따른다: 캐럿/포커스 요소 바로 아래에 붙고,
* 포커스를 막지 않는다(focusable:false).
* (KeyType.Windows 의 WS_EX_TRANSPARENT|WS_EX_NOACTIVATE 오버레이와 동일한 전략)
*
* 창은 그려진 패널 높이만큼만 둔다(suggestionPanelHeight). 투명 영역도 클릭을 삼키므로,
* 고정 높이 창은 "준비 중" 한 줄만 보일 때 캐럿 아래 줄의 클릭을 가로챘다.
*/
function applySuggestionOverlayMouseMode(win: BrowserWindow): void {
const interactive = configGet('suggestionOverlayInteractive') !== false
try {
if (interactive) {
// 클릭을 받아 수락할 수 있게 한다. focusable:false 라 대상 앱 포커스는 유지된다.
win.setIgnoreMouseEvents(false)
} else {
win.setIgnoreMouseEvents(true, { forward: true })
}
} catch (err) {
logger.warn(
`SuggestionOverlay 마우스 모드 적용 실패: ${err instanceof Error ? err.message : String(err)}`
)
}
}
function createSuggestionOverlayWindow(): BrowserWindow {
return createPopupWindow({
name: 'suggestion-overlay',
bounds: { width: SUGGESTION_OVERLAY_WIDTH, height: SUGGESTION_OVERLAY_MAX_HEIGHT },
beforeLoad: applySuggestionOverlayMouseMode,
onClosed: () => {
suggestionOverlayPlacement = null
suggestionOverlayBounds = null
suggestionOverlayWindow = null
}
})
}
export function getSuggestionOverlayWindow(): BrowserWindow {
if (!suggestionOverlayWindow || suggestionOverlayWindow.isDestroyed()) {
suggestionOverlayWindow = createSuggestionOverlayWindow()
logger.info('SuggestionOverlay window created')
}
return suggestionOverlayWindow
}
interface SuggestionOverlayProvenance {
mode: 'local-model' | 'local-memory'
continuationCount: number
relatedCount: number
phraseCount: number
appPhraseCount: number
}
interface SuggestionOverlayContent {
candidates: Array<{ text: string; rank: number }>
activeIndex: number
/** 이 세션이 채우려는 후보 총량 — 페이지/진행률 표시의 분모 */
targetTotal?: number
/** 후보 도착 전(생성 중) 이거나, 후보가 있어도 채우기 루프가 더 만드는 중 */
generating?: boolean
/** 모델 적재 중 — 팝업이 "준비 중" 을 보여준다 */
warmingUp?: boolean
/** 스트리밍 중 부분 텍스트 */
partialText?: string | null
provenance?: SuggestionOverlayProvenance | null
}
/** 현재 세션의 배치(최대 높이 기준) — 내용이 바뀌면 이 자리에서 높이만 맞춘다. */
let suggestionOverlayPlacement: AnchoredPanelPlacement | null = null
let suggestionOverlayBounds: UiRect | null = null
function sameRect(a: UiRect | null, b: UiRect): boolean {
return !!a && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height
}
/**
* 내용 높이에 맞춰 창 크기를 고친다. 늘어날 때는 내용보다 먼저(잘림 방지),
* 줄어들 때는 내용 다음에(`deliver` 뒤) 적용한다.
*/
function fitSuggestionOverlay(win: BrowserWindow, content: SuggestionOverlayContent, deliver: () => void): void {
const placement = suggestionOverlayPlacement
if (!placement) {
deliver()
return
}
const bounds = fitAnchoredPanel(
placement,
suggestionPanelHeight({
candidateCount: content.candidates.length,
activeIndex: content.activeIndex,
generating: content.generating === true,
warmingUp: content.warmingUp === true,
hasPartialText: !!content.partialText
})
)
const previous = suggestionOverlayBounds
const apply = (): void => {
if (sameRect(suggestionOverlayBounds, bounds)) return
suggestionOverlayBounds = bounds
win.setBounds(bounds)
}
if (!previous || bounds.height >= previous.height) {
apply()
deliver()
} else {
deliver()
apply()
}
}
/**
* 제안 오버레이 표시 — 캐럿 → 요소 → 커서 기준 배치.
*
* anchor 는 UIA 가 준 물리 픽셀이다. 화면 기하 포트로 한 번만 DIP 로 바꾼 뒤 모니터를 고르고
* 배치한다(서비스에는 DIP 를 저장하지 않는다 — 이중 변환 방지).
*/
export function showSuggestionOverlay(
payload: SuggestionOverlayContent & {
anchor: PhysicalRect | null
anchorKind?: AnchorKind
appName: string | null
}
): void {
const win = getSuggestionOverlayWindow()
suggestionOverlayPlacement = placeAnchoredPanel(
getScreenGeometry(),
payload.anchor,
payload.anchorKind ?? null,
{ width: SUGGESTION_OVERLAY_WIDTH, height: SUGGESTION_OVERLAY_MAX_HEIGHT }
)
suggestionOverlayBounds = null
fitSuggestionOverlay(win, payload, () => sendToPopupWindow(win, IPC_CHANNELS.POPUP_SUGGESTION.SHOW, {
candidates: payload.candidates,
activeIndex: payload.activeIndex,
targetTotal: payload.targetTotal ?? payload.candidates.length,
generating: payload.generating === true,
warmingUp: payload.warmingUp === true,
partialText: payload.partialText ?? null,
appName: payload.appName,
provenance: payload.provenance ?? null,
_i18n: getPopupI18nStrings(),
_keyHints: buildSuggestionKeyHints()
}))
presentPopup(win, 'screen-saver')
}
export function updateSuggestionOverlay(payload: SuggestionOverlayContent): void {
const win = suggestionOverlayWindow
if (win && !win.isDestroyed()) {
fitSuggestionOverlay(win, payload, () =>
sendToPopupWindow(win, IPC_CHANNELS.POPUP_SUGGESTION.UPDATE, {
...payload,
targetTotal: payload.targetTotal ?? payload.candidates.length,
_keyHints: buildSuggestionKeyHints()
})
)
}
}
export function hideSuggestionOverlay(): void {
suggestionOverlayPlacement = null
suggestionOverlayBounds = null
if (suggestionOverlayWindow && !suggestionOverlayWindow.isDestroyed()) {
sendToPopupWindow(suggestionOverlayWindow, IPC_CHANNELS.POPUP_SUGGESTION.HIDE, {})
suggestionOverlayWindow.hide()
}
}
export function isSuggestionOverlayVisible(): boolean {
return !!(
suggestionOverlayWindow &&
!suggestionOverlayWindow.isDestroyed() &&
suggestionOverlayWindow.isVisible()
)
}
/** 설정(클릭 허용) 변경 시 즉시 반영. */
export function applySuggestionOverlayConfig(): void {
if (suggestionOverlayWindow && !suggestionOverlayWindow.isDestroyed()) {
applySuggestionOverlayMouseMode(suggestionOverlayWindow)
}
}
// ─ 프리로딩 ──────────────────────────────────────────
export function preloadPopupWindows(): void {
getRecordingTipWindow()
getResultPopupWindow()
getHistoryPopupWindow()
getCommandPopupWindow()
logger.info('Popup windows preloaded')
}
// ── 테마 재주입 (설정에서 테마 변경 시 호출) ───────────
/**
* 현재 살아있는 팝업 윈도우에 테마 CSS를 재주입.
* config SET_THEME 핸들러에서 호출한다.
*/
export function reapplyThemeToAllPopups(): void {
const popupWindows = [
recordingTipWindow,
resultPopupWindow,
historyPopupWindow,
commandPopupWindow,
captionOverlayWindow,
suggestionOverlayWindow,
]
for (const win of popupWindows) {
if (win && !win.isDestroyed()) {
injectPopupTheme(win)
}
}
}
// ── clipboard:copy IPC (ResultPopup에서 사용) ─────────
ipcMain.on(IPC_CHANNELS.CLIPBOARD.COPY, (_event, text: string) => {
clipboard.writeText(text)
})