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).
This commit is contained in:
parent
f064c93197
commit
7b1210b5d1
41 changed files with 1565 additions and 1143 deletions
|
|
@ -1,6 +1,6 @@
|
|||
// src/main/bootstrap.ts — 초기화 시퀀스
|
||||
|
||||
import { app, dialog, globalShortcut, ipcMain as ipcMainRef } from 'electron'
|
||||
import { app, dialog, globalShortcut, ipcMain as ipcMainRef, nativeTheme } from 'electron'
|
||||
import { uIOhook, type UiohookKeyboardEvent } from 'uiohook-napi'
|
||||
import { VK } from '@d3ro/core/keybinding'
|
||||
import { initLoggerService, getLogger } from './services/LoggerService'
|
||||
|
|
@ -21,7 +21,7 @@ import { getTextInsertService } from './services/TextInsertService'
|
|||
import { getCustomInstructionService } from './services/CustomInstructionService'
|
||||
import { getVoiceCommandService } from './services/VoiceCommandService'
|
||||
import { getInputTelemetryService } from './services/InputTelemetryService'
|
||||
import { getSuggestionService } from './services/SuggestionService'
|
||||
import { getSuggestionService, hasInputContextConsent } from './services/SuggestionService'
|
||||
import { getSoundEffectService } from './services/SoundEffectService'
|
||||
import { getAutoLaunchService } from './services/AutoLaunchService'
|
||||
import { getAudioCaptureService } from './services/AudioCaptureService'
|
||||
|
|
@ -161,6 +161,8 @@ async function initConfigEffects(): Promise<void> {
|
|||
effects.register('autoLaunch', (value) => getAutoLaunchService().setEnabled(value === true))
|
||||
// 미리 로드된 팝업(녹음 팁·기록·명령·제안·자막)의 테마 CSS
|
||||
effects.register('theme', () => reapplyThemeToAllPopups())
|
||||
// 팝업 문서 lang 도 같은 재주입에서 맞춘다
|
||||
effects.register('language', () => reapplyThemeToAllPopups())
|
||||
effects.start()
|
||||
getShutdownRegistry().register({ name: 'config-effects', dispose: () => effects.dispose() })
|
||||
}
|
||||
|
|
@ -260,11 +262,12 @@ async function initInputIntelligence(): Promise<void> {
|
|||
|
||||
// 제안이 켜져 있으면 켜진 시점부터 모델을 미리 올려 둔다 — 토글 시에만 워밍업하면
|
||||
// 앱을 새로 켤 때마다 첫 제안이 콜드 로딩으로 타임아웃된다.
|
||||
if (configGet('suggestionEnabled')) void suggestion.warmUp()
|
||||
// 입력 수집 동의가 없으면 입력 맥락이 오지 않아 제안이 뜰 수 없다 — 모델을 데우지 않는다.
|
||||
if (configGet('suggestionEnabled') && hasInputContextConsent()) void suggestion.warmUp()
|
||||
|
||||
// Ollama 서버가 나중에 뜨는 경우(느린 부팅 등) 가용해지는 시점에도 워밍업한다.
|
||||
getLocalLLMService().on('availability-changed', ({ available }) => {
|
||||
if (available && configGet('suggestionEnabled')) void suggestion.warmUp()
|
||||
if (available && configGet('suggestionEnabled') && hasInputContextConsent()) void suggestion.warmUp()
|
||||
})
|
||||
|
||||
telemetry.start()
|
||||
|
|
@ -311,6 +314,19 @@ async function initAutoUpdate(): Promise<void> {
|
|||
async function initPopupWindows(): Promise<void> {
|
||||
preloadPopupWindows()
|
||||
|
||||
// 시스템 테마를 따르는 설정이면 OS 다크/라이트 전환 때 팝업도 다시 칠한다(언어가 바뀌면 lang 도 함께)
|
||||
const onNativeThemeUpdated = (): void => {
|
||||
const theme = configGet('theme')
|
||||
if (theme === 'auto') reapplyThemeToAllPopups()
|
||||
}
|
||||
nativeTheme.on('updated', onNativeThemeUpdated)
|
||||
getShutdownRegistry().register({
|
||||
name: 'popup-native-theme',
|
||||
dispose: () => {
|
||||
nativeTheme.removeListener('updated', onNativeThemeUpdated)
|
||||
},
|
||||
})
|
||||
|
||||
// 오디오 디바이스 미리 캐싱 (Settings 열 때 즉시 반환)
|
||||
getAudioCaptureService().getDevices().catch(() => { /* 실패해도 무시 */ })
|
||||
|
||||
|
|
@ -395,22 +411,35 @@ async function initVoiceMode(): Promise<void> {
|
|||
voiceMode.on('partial-transcript', ({ text }) => tip.onPartialTranscript(text))
|
||||
voiceMode.on('insert-failed', ({ text }) => tip.onInsertFailed(text))
|
||||
|
||||
// 수정자 없는 Esc 로 진행 중인 받아쓰기(녹음·처리)를 취소한다. 녹음 팁은 포커스를 받지 않는 창이라
|
||||
// 전역 keydown 을 직접 듣는다(제안 오버레이의 Esc 와 같은 방식). 세션이 없으면 아무 일도 하지 않는다.
|
||||
// uiohook 은 수동 감청이라 Esc 는 앞에 있는 앱에도 그대로 전달된다.
|
||||
const releaseEscapeHook = acquireGlobalInputHook()
|
||||
getShutdownRegistry().register({ name: 'voice-escape-hook', dispose: () => releaseEscapeHook() })
|
||||
uIOhook.on('keydown', (event: UiohookKeyboardEvent) => {
|
||||
if (uiohookCodeToVk(event.keycode) !== VK.Escape) return
|
||||
if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return
|
||||
voiceMode.requestEscape()
|
||||
})
|
||||
|
||||
// 효과음 연동
|
||||
voiceMode.on('session-started', () => {
|
||||
tip.onSessionStarted()
|
||||
soundEffect.play('recording-start')
|
||||
})
|
||||
|
||||
voiceMode.on('session-completed', ({ session, finalText }) => {
|
||||
tip.onSessionEnded()
|
||||
voiceMode.on('session-completed', ({ session, finalText, audioPath }) => {
|
||||
tip.onSessionCompleted()
|
||||
soundEffect.play('recording-stop')
|
||||
|
||||
// 녹음은 완료 이벤트 전에 저장됐다 — 실제 저장 경로(없으면 null)만 히스토리에 남긴다.
|
||||
persistCompletedVoiceSessionSafe(
|
||||
(error) => {
|
||||
voiceMode.emit('error', { error, session })
|
||||
},
|
||||
session,
|
||||
finalText,
|
||||
audioPath,
|
||||
)
|
||||
|
||||
notifyRenderer(IPC_CHANNELS.APP.DATA_CHANGED, { type: 'session-completed' })
|
||||
|
|
@ -426,7 +455,8 @@ async function initVoiceMode(): Promise<void> {
|
|||
voiceMode.on('error', ({ error, severity }) => {
|
||||
// 'warning'(예: Ollama 미가용 → 원문 삽입)은 세션을 막지 않는 알림이다 — 에러음·에러 팁 없음
|
||||
if (severity !== 'warning') soundEffect.play('error')
|
||||
tip.onError(error.message, severity)
|
||||
// 코드를 넘겨야 팁이 사용자 언어 문구를 고른다 — 빠져 있어 영문 로그 문구가 그대로 보였다(2026-09-28)
|
||||
tip.onError(error.message, severity, error.code)
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,10 +16,8 @@
|
|||
|
||||
import { EventEmitter } from 'events'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { writeFile, mkdir } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { app } from 'electron'
|
||||
import { getLogger } from './LoggerService'
|
||||
import { createFsRecordingStore, type RecordingStore } from './recording/recording-store'
|
||||
import { getAudioCaptureService } from './AudioCaptureService'
|
||||
import { getSTTManager } from './stt/STTManager'
|
||||
import type { TranscriptionResult } from './stt/types'
|
||||
|
|
@ -85,7 +83,8 @@ export interface VoiceModeEvents {
|
|||
current: AudioState
|
||||
}) => void
|
||||
'transcription-update': (payload: { text: string; isFinal: boolean }) => void
|
||||
'session-completed': (payload: { session: VoiceSession; finalText: string }) => void
|
||||
/** audioPath: 저장된 녹음 WAV 경로(완료 이벤트 전에 저장됨). 오디오가 없거나 저장 실패면 null */
|
||||
'session-completed': (payload: { session: VoiceSession; finalText: string; audioPath: string | null }) => void
|
||||
'session-cancelled': (payload: {
|
||||
session: VoiceSession
|
||||
reason: 'user' | 'timeout' | 'too-short'
|
||||
|
|
@ -196,6 +195,11 @@ const NOTHING_PENDING: StopOutcome = { finished: Promise.resolve() }
|
|||
// ============================================================
|
||||
|
||||
class VoiceModeService extends EventEmitter {
|
||||
/** 녹음 저장 포트 — 경로·fs·WAV 인코딩은 어댑터가 맡는다 (DIP) */
|
||||
constructor(private readonly _recordings: RecordingStore = createFsRecordingStore()) {
|
||||
super()
|
||||
}
|
||||
|
||||
private _session: VoiceSession | null = null
|
||||
private _run: SessionRun | null = null
|
||||
private _recognitionState = RecognitionState.IDLE
|
||||
|
|
@ -472,6 +476,22 @@ class VoiceModeService extends EventEmitter {
|
|||
this._cancelSession('user')
|
||||
}
|
||||
|
||||
/**
|
||||
* 수정자 없는 Esc — 녹음·처리 중인 세션을 취소한다(2026-09-28: 녹음 팁의 "Esc 취소").
|
||||
* 액션 큐로 넣어 누름/뗌과 순서를 지킨다. 진행 중인 세션이 없으면 아무것도 하지 않고 false.
|
||||
*/
|
||||
requestEscape(): boolean {
|
||||
if (!this.isActive) return false
|
||||
this._enqueueAction({
|
||||
type: 'escape',
|
||||
timestamp: Date.now(),
|
||||
mode: 'dictation',
|
||||
actionId: 'dictation',
|
||||
holdMode: false,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// ── 상태 머신 ──────────────────────────────────────────
|
||||
|
||||
private _isInTerminalState(): boolean {
|
||||
|
|
@ -916,7 +936,7 @@ class VoiceModeService extends EventEmitter {
|
|||
severity: 'warning',
|
||||
})
|
||||
}
|
||||
void this._completeSession(run, effectiveText)
|
||||
await this._completeSession(run, effectiveText)
|
||||
} else {
|
||||
await this._processWithLLM(run, effectiveText, route)
|
||||
}
|
||||
|
|
@ -985,7 +1005,7 @@ class VoiceModeService extends EventEmitter {
|
|||
const chainResult = await getChainService().execute(route.chainId, userText)
|
||||
if (!this._isCurrent(run)) return
|
||||
if (this._session) this._session.processedText = chainResult.finalText
|
||||
void this._completeSession(run, chainResult.finalText)
|
||||
await this._completeSession(run, chainResult.finalText)
|
||||
} catch (error) {
|
||||
if (!this._isCurrent(run)) return
|
||||
logger.warn(`Chain execution failed: ${describe(error)}`)
|
||||
|
|
@ -1010,7 +1030,7 @@ class VoiceModeService extends EventEmitter {
|
|||
this._session.processedText = processedText
|
||||
}
|
||||
|
||||
void this._completeSession(run, processedText)
|
||||
await this._completeSession(run, processedText)
|
||||
} catch (error) {
|
||||
if (!this._isCurrent(run)) return
|
||||
this._handleError(
|
||||
|
|
@ -1066,71 +1086,48 @@ class VoiceModeService extends EventEmitter {
|
|||
|
||||
// ── 세션 완료/취소 ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 세션 완료 — 녹음을 먼저 저장하고(실제 경로를 이벤트에 싣는다) 완료를 알린 뒤, 삽입은 따로 돈다.
|
||||
*
|
||||
* 예전엔 완료 이벤트(히스토리 생성 + history_audio 동기화 예약)가 먼저 나가고 WAV 는 텍스트 삽입이
|
||||
* 끝난 뒤에 써졌다 — 그사이 flush 가 돌면 "파일 없음"을 성공으로 처리해 녹음이 영영 올라가지 않았다.
|
||||
*/
|
||||
private async _completeSession(run: SessionRun, finalText: string): Promise<void> {
|
||||
if (!this._isCurrent(run) || !this._session) return
|
||||
|
||||
const audioPath = await this._recordings.save(this._session.id, run.lastAudio)
|
||||
// 저장하는 사이 취소·새 세션이 시작됐으면 완료를 알리지 않는다.
|
||||
if (!this._isCurrent(run) || !this._session) return
|
||||
|
||||
const session = { ...this._session }
|
||||
const lastAudio = run.lastAudio
|
||||
const selectionCapture = run.selectionCapture
|
||||
logger.info(`Session completed: "${finalText.substring(0, 50)}${finalText.length > 50 ? '...' : ''}"`)
|
||||
|
||||
// Speakly 패턴: 먼저 IDLE 복귀 (다음 핫키 즉시 사용 가능). 표시 계층이 완료 이벤트로 팁을 숨긴다.
|
||||
this._setRecognitionState(RecognitionState.COMPLETED)
|
||||
this._setAudioState(AudioState.STOPPED)
|
||||
this.emit('session-completed', { session, finalText })
|
||||
this.emit('session-completed', { session, finalText, audioPath })
|
||||
this._endRun(run)
|
||||
|
||||
// 텍스트 삽입은 세션과 무관하게 비동기 실행 (세션 블로킹 방지)
|
||||
if (configGet('autoInsert') && finalText.length > 0) {
|
||||
try {
|
||||
// 선택 텍스트 캡처가 클립보드를 쓰는 중이면 끝날 때까지 기다린다 (클립보드 경합 방지)
|
||||
if (selectionCapture) await selectionCapture
|
||||
const insertMethod = configGet('insertMethod')
|
||||
await getTextInsertService().insertText(finalText, insertMethod)
|
||||
} catch (error) {
|
||||
logger.warn(`Text insert failed: ${describe(error)}`)
|
||||
// 삽입 실패 시 표시 계층이 ResultPopup에 텍스트를 보여 준다
|
||||
this.emit('insert-failed', { text: finalText, sessionId: session.id })
|
||||
}
|
||||
}
|
||||
|
||||
// 녹음 오디오 WAV 파일 저장 (비동기, 실패해도 무시)
|
||||
void this._saveAudioFile(session.id, lastAudio)
|
||||
void this._insertCompletedText(session.id, finalText, selectionCapture)
|
||||
}
|
||||
|
||||
/** PCM 버퍼를 WAV 파일로 저장 */
|
||||
private async _saveAudioFile(sessionId: string, pcmData: Buffer | null): Promise<void> {
|
||||
if (!pcmData || pcmData.length === 0) return
|
||||
|
||||
private async _insertCompletedText(
|
||||
sessionId: string,
|
||||
finalText: string,
|
||||
selectionCapture: Promise<unknown> | null,
|
||||
): Promise<void> {
|
||||
if (!configGet('autoInsert') || finalText.length === 0) return
|
||||
try {
|
||||
const recordingsDir = join(app.getPath('userData'), 'recordings')
|
||||
await mkdir(recordingsDir, { recursive: true })
|
||||
|
||||
const wavPath = join(recordingsDir, `${sessionId}.wav`)
|
||||
|
||||
// WAV 헤더 생성 (16kHz, 16bit, mono)
|
||||
const header = Buffer.alloc(44)
|
||||
const dataSize = pcmData.length
|
||||
const fileSize = dataSize + 36
|
||||
|
||||
header.write('RIFF', 0)
|
||||
header.writeUInt32LE(fileSize, 4)
|
||||
header.write('WAVE', 8)
|
||||
header.write('fmt ', 12)
|
||||
header.writeUInt32LE(16, 16) // fmt chunk size
|
||||
header.writeUInt16LE(1, 20) // PCM format
|
||||
header.writeUInt16LE(1, 22) // mono
|
||||
header.writeUInt32LE(16000, 24) // sample rate
|
||||
header.writeUInt32LE(32000, 28) // byte rate (16000 * 2)
|
||||
header.writeUInt16LE(2, 32) // block align
|
||||
header.writeUInt16LE(16, 34) // bits per sample
|
||||
header.write('data', 36)
|
||||
header.writeUInt32LE(dataSize, 40)
|
||||
|
||||
await writeFile(wavPath, Buffer.concat([header, pcmData]))
|
||||
logger.info(`Audio saved: ${wavPath} (${Math.round(dataSize / 1024)}KB)`)
|
||||
// 선택 텍스트 캡처가 클립보드를 쓰는 중이면 끝날 때까지 기다린다 (클립보드 경합 방지)
|
||||
if (selectionCapture) await selectionCapture
|
||||
const insertMethod = configGet('insertMethod')
|
||||
await getTextInsertService().insertText(finalText, insertMethod)
|
||||
} catch (error) {
|
||||
logger.warn(`Audio save failed: ${describe(error)}`)
|
||||
logger.warn(`Text insert failed: ${describe(error)}`)
|
||||
// 삽입 실패 시 표시 계층이 ResultPopup에 텍스트를 보여 준다
|
||||
this.emit('insert-failed', { text: finalText, sessionId })
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1353,6 +1350,13 @@ export function getVoiceModeService(): VoiceModeService {
|
|||
return instance
|
||||
}
|
||||
|
||||
/** 테스트 전용: 가짜 녹음 저장소를 주입한 싱글톤을 만든다. */
|
||||
export function createVoiceModeServiceForTests(recordings: RecordingStore): VoiceModeService {
|
||||
resetVoiceModeServiceForTests()
|
||||
instance = new VoiceModeService(recordings)
|
||||
return instance
|
||||
}
|
||||
|
||||
export function resetVoiceModeServiceForTests(): void {
|
||||
if (instance) {
|
||||
instance.removeAllListeners()
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import {
|
|||
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 {
|
||||
|
|
@ -36,6 +37,7 @@ import {
|
|||
sendToPopupWindow
|
||||
} from './popup-window-factory'
|
||||
import { createElectronScreenGeometry } from './screen-geometry'
|
||||
import { installApplicationMenu } from './app-menu'
|
||||
import {
|
||||
SUGGESTION_OVERLAY_MAX_HEIGHT,
|
||||
SUGGESTION_OVERLAY_WIDTH,
|
||||
|
|
@ -48,30 +50,42 @@ const logger = getLogger('WindowManager')
|
|||
/**
|
||||
* 팝업에 주입할 i18n 문자열 맵을 반환.
|
||||
*/
|
||||
function getPopupI18nStrings(): Record<string, string> {
|
||||
/** 현재 설정 언어의 번역 함수 — 팝업(Vanilla JS)에 넘길 문구를 main 에서 만들 때 쓴다 */
|
||||
export function getPopupTranslator(): ReturnType<typeof getI18n>['t'] {
|
||||
const locale = (configGet('language') as string) || 'ko'
|
||||
const { t } = getI18n(locale as 'ko' | 'en' | 'ja' | 'zh' | 'zh-TW' | 'es' | 'fr' | 'de' | 'pt' | 'ru' | 'vi' | 'th')
|
||||
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 {
|
||||
// command-popup
|
||||
commandSelect: t('popup.commandSelect'),
|
||||
hintsSelect: t('popup.hints.select'),
|
||||
hintsApply: t('popup.hints.apply'),
|
||||
hintsClear: t('popup.hints.clear'),
|
||||
hintsClose: t('popup.hints.close'),
|
||||
noCommands: t('popup.noCommands'),
|
||||
noCommand: t('popup.noCommand'),
|
||||
// history-popup
|
||||
hintsSelectEn: t('popup.hints.selectEn'),
|
||||
hintsPaste: t('popup.hints.paste'),
|
||||
noHistory: t('popup.noHistory'),
|
||||
// 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'),
|
||||
|
|
@ -83,6 +97,8 @@ function getPopupI18nStrings(): Record<string, string> {
|
|||
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'),
|
||||
|
|
@ -259,9 +275,10 @@ export function createMainWindow(): BrowserWindow {
|
|||
mainWindowCreated = true
|
||||
mainWindow.setSkipTaskbar(false)
|
||||
|
||||
// Alt 키로 메뉴 활성화 방지: 메뉴 완전 제거
|
||||
// Win/Linux: Alt 키로 메뉴 활성화 방지(메뉴 완전 제거). macOS: 편집 단축키(Cmd+C/V/X/A/Z)와
|
||||
// Cmd+Q 는 애플리케이션 메뉴의 role 항목으로만 동작하므로 최소 메뉴를 유지한다.
|
||||
mainWindow.setMenu(null)
|
||||
Menu.setApplicationMenu(null)
|
||||
installApplicationMenu(Menu, process.platform)
|
||||
|
||||
mainWindow.on('ready-to-show', () => {
|
||||
mainWindow?.show()
|
||||
|
|
@ -368,6 +385,20 @@ export function showRecordingTip(
|
|||
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()
|
||||
|
|
@ -537,7 +568,7 @@ export function showHistoryPopup(entries: Array<Record<string, unknown>>): void
|
|||
const win = getHistoryPopupWindow()
|
||||
|
||||
// 커서 위치에 즉시 배치+표시 (2-phase 제거 — 숨겨진 윈도우 렌더러 비활성 문제 방지)
|
||||
placePopupNearCursor(win, { width: 380, height: Math.min(60 + entries.length * 44, 500) })
|
||||
placePopupNearCursor(win, historyPopupSize(entries.length))
|
||||
|
||||
sendToPopupWindow(win, IPC_CHANNELS.POPUP_HISTORY.SHOW_ITEMS, { entries, _i18n: getPopupI18nStrings() })
|
||||
|
||||
|
|
@ -572,7 +603,7 @@ export function isHistoryPopupVisible(): boolean {
|
|||
function createCommandPopupWindow(): BrowserWindow {
|
||||
return createPopupWindow({
|
||||
name: 'command-popup',
|
||||
bounds: { width: 340, height: 300 },
|
||||
bounds: commandPopupSize(0),
|
||||
onClosed: () => {
|
||||
commandPopupWindow = null
|
||||
}
|
||||
|
|
@ -588,7 +619,7 @@ export function getCommandPopupWindow(): BrowserWindow {
|
|||
|
||||
export function showCommandPopup(commands: Array<Record<string, unknown>>, activeId: string | null): void {
|
||||
const win = getCommandPopupWindow()
|
||||
placePopupNearCursor(win, { width: 340, height: Math.min(80 + commands.length * 48, 400) })
|
||||
placePopupNearCursor(win, commandPopupSize(commands.length))
|
||||
sendToPopupWindow(win, IPC_CHANNELS.POPUP_COMMAND.SHOW_ITEMS, { commands, activeId, _i18n: getPopupI18nStrings() })
|
||||
|
||||
presentPopup(win)
|
||||
|
|
|
|||
34
apps/desktop/src/main/windows/popup-list-geometry.ts
Normal file
34
apps/desktop/src/main/windows/popup-list-geometry.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// src/main/windows/popup-list-geometry.ts
|
||||
// 기록·명령 팝업(목록형) 창 크기 — CSS 치수와 같은 상수로 계산한다(순수 함수).
|
||||
//
|
||||
// 이전 공식(기록 60+44n, 명령 80+48n)은 CSS 와 따로 놀아 빈 상태에서 창이 내용보다 작아 잘렸고
|
||||
// (기록 60px ← 필요 약 116px), 항목이 많으면 남는 투명 영역이 클릭을 삼켰다(2026-09-28 감사).
|
||||
// 아래 값은 popups/_shared/popup-base.css · history-popup/style.css · command-popup/style.css 와 짝이다 —
|
||||
// 한쪽을 바꾸면 다른 쪽도 바꾼다.
|
||||
|
||||
/** 목록 한 줄 높이(px) — .d3-list-item height */
|
||||
export const POPUP_LIST_ROW = 40
|
||||
/** 제목 줄(34) + 힌트 줄(30) + 판 위아래 패딩(6+6) + 테두리(1+1) */
|
||||
export const POPUP_LIST_CHROME = 34 + 30 + 12 + 2
|
||||
/** 빈 상태 한 줄 높이 */
|
||||
export const POPUP_LIST_EMPTY = 56
|
||||
export const HISTORY_POPUP_WIDTH = 380
|
||||
export const HISTORY_POPUP_MAX_HEIGHT = 500
|
||||
export const COMMAND_POPUP_WIDTH = 340
|
||||
export const COMMAND_POPUP_MAX_HEIGHT = 420
|
||||
|
||||
export interface PopupSize {
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export function historyPopupSize(entryCount: number): PopupSize {
|
||||
const body = entryCount === 0 ? POPUP_LIST_EMPTY : entryCount * POPUP_LIST_ROW
|
||||
return { width: HISTORY_POPUP_WIDTH, height: Math.min(POPUP_LIST_CHROME + body, HISTORY_POPUP_MAX_HEIGHT) }
|
||||
}
|
||||
|
||||
/** 명령 팝업은 맨 위에 "명령 없이 원문 넣기" 줄이 항상 있다 */
|
||||
export function commandPopupSize(commandCount: number): PopupSize {
|
||||
const body = POPUP_LIST_ROW + (commandCount === 0 ? POPUP_LIST_EMPTY : commandCount * POPUP_LIST_ROW)
|
||||
return { width: COMMAND_POPUP_WIDTH, height: Math.min(POPUP_LIST_CHROME + body, COMMAND_POPUP_MAX_HEIGHT) }
|
||||
}
|
||||
|
|
@ -45,6 +45,8 @@ export const POPUP_NAV_KEYS: ReadonlyArray<{ accel: string; key: string }> = [
|
|||
{ accel: '1', key: '1' }, { accel: '2', key: '2' }, { accel: '3', key: '3' },
|
||||
{ accel: '4', key: '4' }, { accel: '5', key: '5' }, { accel: '6', key: '6' },
|
||||
{ accel: '7', key: '7' }, { accel: '8', key: '8' }, { accel: '9', key: '9' },
|
||||
// 0 = 명령 팝업의 "명령 없이 원문 넣기"(힌트만 있고 등록이 빠져 있었다 — 2026-09-28). 기록 팝업은 무시한다.
|
||||
{ accel: '0', key: '0' },
|
||||
]
|
||||
|
||||
/** 히스토리 팝업이 사라진 뒤 삽입까지 기다리는 시간(포커스 복귀 대기) */
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
// 처리를 각자 복붙하던 시절 옵션이 조용히 갈라졌다 — ResultPopup 에만 backgroundThrottling
|
||||
// 이 빠져 숨김 상태에서 2-phase 측정이 멈췄다. 창 종류는 이제 PopupWindowSpec 선언만 다르다.
|
||||
|
||||
import { BrowserWindow } from 'electron'
|
||||
import { BrowserWindow, nativeTheme } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import { buildPopupThemeCss } from '@d3ro/ui/theme-vars'
|
||||
|
|
@ -87,12 +87,16 @@ export function createPopupWindow(spec: PopupWindowSpec): BrowserWindow {
|
|||
*/
|
||||
export function injectPopupTheme(win: BrowserWindow): void {
|
||||
const theme = configGet('theme') as string
|
||||
// 'system'은 'dark'로 폴백 (팝업은 시스템 다크모드 감지 불가)
|
||||
const resolvedTheme = theme === 'system' ? 'dark' : theme
|
||||
const css = buildPopupThemeCss(resolvedTheme)
|
||||
// 시스템/자동 테마는 main 이 아는 OS 다크 모드로 푼다(이전: 늘 dark — 라이트 OS 에서 팝업만 어두웠다)
|
||||
const css = buildPopupThemeCss(theme, nativeTheme.shouldUseDarkColors)
|
||||
win.webContents.insertCSS(css).catch((err: unknown) => {
|
||||
logger.warn('팝업 테마 CSS 주입 실패', err)
|
||||
})
|
||||
// 팝업 HTML 은 lang="ko" 로 고정돼 있다 — 앱 언어로 맞춰야 중·일·태국어 글리프 선택과 줄바꿈이 맞다
|
||||
const locale = (configGet('language') as string) || 'ko'
|
||||
win.webContents
|
||||
.executeJavaScript(`document.documentElement.lang = ${JSON.stringify(locale)}`)
|
||||
.catch((err: unknown) => logger.warn('팝업 lang 설정 실패', err))
|
||||
}
|
||||
|
||||
// ── 수명주기 · 로드 전 IPC 보류 ─────────────────────────────
|
||||
|
|
|
|||
35
apps/desktop/src/main/windows/recording-tip-error-message.ts
Normal file
35
apps/desktop/src/main/windows/recording-tip-error-message.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// src/main/windows/recording-tip-error-message.ts
|
||||
// RecordingTip 에 그릴 오류 문구 정책 — 코드별 i18n 문자열로 매핑한다(순수 함수).
|
||||
//
|
||||
// VoiceModeService 의 D3ROError.message 는 로그용 영문 문구("STT model not installed: ...")라
|
||||
// 그대로 팁에 그리면 사용자 언어와 무관한 개발자 문구가 보인다. 코드 분류는 @d3ro/core 의
|
||||
// classifyVoiceError 한 곳이 정하고(렌더러 알림도 같은 분류를 쓴다), 여기서는 번역 키만 고른다.
|
||||
// 분류되지 않는 코드는 기존 동작대로 원문을 그린다.
|
||||
|
||||
import { classifyVoiceError, type VoiceErrorMessageId } from '@d3ro/core/voice-error-message'
|
||||
import type { TranslationKey } from '@d3ro/i18n'
|
||||
|
||||
export type RecordingTipTranslate = (key: TranslationKey, params?: Record<string, string | number>) => string
|
||||
|
||||
const MESSAGE_KEY: Record<Exclude<VoiceErrorMessageId, 'quota'>, TranslationKey> = {
|
||||
modelMissing: 'voice.error.modelMissing',
|
||||
engine: 'voice.error.engine',
|
||||
micOpen: 'voice.error.micOpen',
|
||||
micLost: 'voice.error.micLost',
|
||||
noSpeech: 'voice.error.noSpeech',
|
||||
tooShort: 'voice.error.tooShort',
|
||||
transcription: 'voice.error.transcription',
|
||||
captionActive: 'voice.error.captionActive',
|
||||
llmFailed: 'voice.error.llmFailed',
|
||||
}
|
||||
|
||||
export function resolveRecordingTipErrorMessage(
|
||||
code: number | undefined,
|
||||
fallbackMessage: string,
|
||||
t: RecordingTipTranslate,
|
||||
): string {
|
||||
const id = classifyVoiceError(code)
|
||||
if (id === null) return fallbackMessage
|
||||
if (id === 'quota') return t('license.quotaExceeded.title', { feature: t('license.feature.dictation') })
|
||||
return t(MESSAGE_KEY[id])
|
||||
}
|
||||
|
|
@ -9,19 +9,29 @@
|
|||
|
||||
import {
|
||||
showRecordingTip,
|
||||
showRecordingTipError,
|
||||
hideRecordingTip,
|
||||
updateRecordingTipState,
|
||||
sendAudioLevelToTip,
|
||||
sendPartialTranscriptToTip,
|
||||
showResultPopup,
|
||||
getPopupTranslator,
|
||||
} from './WindowManager'
|
||||
import { resolveRecordingTipErrorMessage } from './recording-tip-error-message'
|
||||
|
||||
/** 프레젠터가 그리는 대상(창) 포트 — 테스트에서는 가짜로 바꾼다 */
|
||||
export interface RecordingTipView {
|
||||
showRecording(): void
|
||||
hide(): void
|
||||
showThinking(): void
|
||||
showError(message: string): void
|
||||
/** 받아쓴 글을 넣었다 — 짧게 확인 표시를 보인다 */
|
||||
showDone(): void
|
||||
/**
|
||||
* 오류를 그리고 팁을 띄운다. 쿼터·자막 사용 중·모델 미설치처럼 'recording' phase 전에 끝난
|
||||
* 세션의 오류도 보여야 하므로, 숨겨진 팁이면 창을 띄워야 한다(상태 IPC 만으로는 부족).
|
||||
* code 가 있으면 사용자 언어 문구로 바꿔 그린다.
|
||||
*/
|
||||
showError(message: string, code?: number): void
|
||||
sendAudioLevel(level: number): void
|
||||
sendPartialTranscript(text: string): void
|
||||
showResult(text: string, durationMs: number): void
|
||||
|
|
@ -37,6 +47,8 @@ export interface RecordingTipPresenterOptions {
|
|||
errorHideMs?: number
|
||||
/** 자동 삽입 실패 시 결과 팝업 표시 시간(ms). 기본 10000 */
|
||||
resultPopupMs?: number
|
||||
/** 완료 확인 표시 후 팁을 숨기기까지(ms). 기본 700 */
|
||||
doneHideMs?: number
|
||||
timers?: RecordingTipTimers
|
||||
}
|
||||
|
||||
|
|
@ -47,6 +59,7 @@ export class RecordingTipPresenter {
|
|||
private _hideTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readonly _errorHideMs: number
|
||||
private readonly _resultPopupMs: number
|
||||
private readonly _doneHideMs: number
|
||||
private readonly _timers: RecordingTipTimers
|
||||
|
||||
constructor(
|
||||
|
|
@ -55,6 +68,7 @@ export class RecordingTipPresenter {
|
|||
) {
|
||||
this._errorHideMs = options.errorHideMs ?? 3000
|
||||
this._resultPopupMs = options.resultPopupMs ?? 10000
|
||||
this._doneHideMs = options.doneHideMs ?? 700
|
||||
this._timers = options.timers ?? {
|
||||
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
||||
clearTimeout: (handle) => clearTimeout(handle),
|
||||
|
|
@ -86,10 +100,11 @@ export class RecordingTipPresenter {
|
|||
/**
|
||||
* 에러 표시 후 한 번만 숨김을 예약한다(이전 예약은 교체).
|
||||
* 'warning' 은 세션을 막지 않는 알림이므로 팁을 건드리지 않는다.
|
||||
* phase 와 무관하게 표시된다 — 녹음 팁이 뜨기 전에 난 오류도 보여야 한다.
|
||||
*/
|
||||
onError(message: string, severity: RecordingTipSeverity = 'error'): void {
|
||||
onError(message: string, severity: RecordingTipSeverity = 'error', code?: number): void {
|
||||
if (severity === 'warning') return
|
||||
this._view.showError(message)
|
||||
this._view.showError(message, code)
|
||||
this._cancelHide()
|
||||
this._hideTimer = this._timers.setTimeout(() => {
|
||||
this._hideTimer = null
|
||||
|
|
@ -97,12 +112,25 @@ export class RecordingTipPresenter {
|
|||
}, this._errorHideMs)
|
||||
}
|
||||
|
||||
/** 세션 완료/취소 — 팁을 즉시 숨긴다 */
|
||||
/** 세션 취소 — 팁을 즉시 숨긴다 */
|
||||
onSessionEnded(): void {
|
||||
this._cancelHide()
|
||||
this._view.hide()
|
||||
}
|
||||
|
||||
/**
|
||||
* 세션 완료 — "입력함"을 잠깐 보이고 숨긴다. 이전에는 즉시 사라져 성공했는지 알 수 없었다(2026-09-28).
|
||||
* 숨김 예약은 오류와 같은 핸들 하나 — 곧바로 새 세션이 시작되면 onSessionStarted 가 취소한다.
|
||||
*/
|
||||
onSessionCompleted(): void {
|
||||
this._cancelHide()
|
||||
this._view.showDone()
|
||||
this._hideTimer = this._timers.setTimeout(() => {
|
||||
this._hideTimer = null
|
||||
this._view.hide()
|
||||
}, this._doneHideMs)
|
||||
}
|
||||
|
||||
onInsertFailed(text: string): void {
|
||||
this._view.showResult(text, this._resultPopupMs)
|
||||
}
|
||||
|
|
@ -125,7 +153,9 @@ export function createWindowRecordingTipView(): RecordingTipView {
|
|||
showRecording: () => showRecordingTip('recording'),
|
||||
hide: () => hideRecordingTip(),
|
||||
showThinking: () => updateRecordingTipState('thinking'),
|
||||
showError: (message) => updateRecordingTipState('error', { errorMessage: message }),
|
||||
showDone: () => updateRecordingTipState('done'),
|
||||
showError: (message, code) =>
|
||||
showRecordingTipError(resolveRecordingTipErrorMessage(code, message, getPopupTranslator())),
|
||||
sendAudioLevel: (level) => sendAudioLevelToTip(level),
|
||||
sendPartialTranscript: (text) => sendPartialTranscriptToTip(text),
|
||||
showResult: (text, durationMs) => showResultPopup(text, durationMs),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue