Skip to content

Commit 7a8610c

Browse files
Lee Seongjooclaude
andcommitted
UI: SwiftUI management window (connection / history / generate / settings)
Add a four-tab management window (SwiftUI hosted in an NSWindow, opened from the menu bar) and a cache/history layer: - AppState (@mainactor ObservableObject): single source of truth — backend, key, voice/model, voice settings, cache toggle, history; runs cache-first synthesis + playback; persists settings to Application Support. - CacheStore: history + audio cache (sha256 key of text+voice+model+settings), JSON index + audio files; replay from disk instead of re-calling the API. - ElevenLabsBackend: accept voice_settings; ElevenLabs.voices() listing + the Korean-capable model list. - Views: Generate (text → synth/play/stop), History (replay/delete/clear), Settings (backend/voice/model + stability/similarity/style/speaker-boost + cache), Connection (status, API key entry, voice refresh, local sidecar URL). - AppDelegate routes both the Services action and the window through AppState; menu-bar icon reflects ⏳/🔈/⚠️ via a Combine subscription; adds "open window". - build.sh links SwiftUI + AVFoundation. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 2094563 commit 7a8610c

11 files changed

Lines changed: 635 additions & 84 deletions

‎Sources/App/AppDelegate.swift‎

Lines changed: 35 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import AppKit
2+
import Combine
23

34
@MainActor
45
final class AppDelegate: NSObject, NSApplicationDelegate {
@@ -8,113 +9,71 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
89

910
private var statusItem: NSStatusItem!
1011
private let serviceProvider = ServiceProvider()
11-
private let player = AudioPlayer()
12-
private var lastSelection: String = ""
13-
private var speakTask: Task<Void, Never>?
14-
15-
// Active backend: ElevenLabs (cloud) when a key is present, else a no-op stub.
16-
private var backend: TTSBackend = StubBackend()
17-
18-
// The user's cloned ElevenLabs voice (성주) + the low-latency model.
19-
private let voice = VoiceConfig(voiceId: "Yp1WZJMrN7OSdP8PG9sm",
20-
modelId: "eleven_flash_v2_5",
21-
settingsHash: "")
12+
let appState = AppState()
13+
private lazy var mainWindow = MainWindow(appState: appState)
14+
private var cancellables = Set<AnyCancellable>()
2215

2316
func applicationDidFinishLaunching(_ notification: Notification) {
2417
AppDelegate.shared = self
2518

26-
if let key = Secrets.elevenLabsKey {
27-
backend = ElevenLabsBackend(apiKey: key)
28-
} else {
29-
Log.app.error("No ElevenLabs key at \(Secrets.appSupportDir)/eleven_key — speech disabled")
30-
}
31-
3219
setUpStatusItem()
3320
registerServices()
34-
player.onFinish = { [weak self] in self?.setIcon(.idle) }
21+
observeState()
22+
if appState.keyPresent { appState.refreshVoices() }
3523

36-
Log.app.info("Codebasic TTS launched. Backend: \(self.backend.identity, privacy: .public)")
24+
Log.app.info("Codebasic TTS launched. Backend: \(self.appState.backendIdentity, privacy: .public)")
3725
}
3826

3927
// MARK: - Menu bar
4028

41-
private enum Icon: String { case idle = "🔊", working = "⏳", speaking = "🔈", error = "⚠️" }
42-
private enum MenuTag: Int { case lastSelection = 100 }
43-
44-
private func setIcon(_ icon: Icon) { statusItem.button?.title = icon.rawValue }
29+
private func setIcon(_ s: String) { statusItem.button?.title = s }
4530

4631
private func setUpStatusItem() {
4732
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
48-
setIcon(.idle)
33+
setIcon("🔊")
4934

5035
let menu = NSMenu()
51-
menu.addItem(withTitle: "Codebasic TTS", action: nil, keyEquivalent: "")
36+
let open = NSMenuItem(title: "Codebasic TTS 열기…", action: #selector(openWindow), keyEquivalent: "o")
37+
open.target = self
38+
menu.addItem(open)
5239
menu.addItem(.separator())
53-
54-
let lastItem = NSMenuItem(title: "Last selection: —", action: nil, keyEquivalent: "")
55-
lastItem.tag = MenuTag.lastSelection.rawValue
56-
lastItem.isEnabled = false
57-
menu.addItem(lastItem)
58-
59-
menu.addItem(withTitle: "Stop", action: #selector(stopSpeaking), keyEquivalent: ".")
40+
let stop = NSMenuItem(title: "중지", action: #selector(stopSpeaking), keyEquivalent: ".")
41+
stop.target = self
42+
menu.addItem(stop)
6043
menu.addItem(.separator())
61-
menu.addItem(withTitle: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
62-
44+
menu.addItem(withTitle: "종료", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
6345
statusItem.menu = menu
6446
}
6547

66-
@objc private func stopSpeaking() {
67-
speakTask?.cancel()
68-
player.stop()
69-
setIcon(.idle)
48+
/// Reflect synthesis/playback state in the menu-bar icon.
49+
private func observeState() {
50+
appState.$isWorking.combineLatest(appState.$statusText)
51+
.receive(on: RunLoop.main)
52+
.sink { [weak self] working, status in
53+
guard let self else { return }
54+
if status.hasPrefix("오류") { self.setIcon("⚠️") }
55+
else if status.contains("합성") { self.setIcon("⏳") }
56+
else if working { self.setIcon("🔈") }
57+
else { self.setIcon("🔊") }
58+
}
59+
.store(in: &cancellables)
7060
}
7161

62+
@objc private func openWindow() { mainWindow.show() }
63+
@objc private func stopSpeaking() { appState.stop() }
64+
7265
// MARK: - Services
7366

7467
private func registerServices() {
7568
NSApp.servicesProvider = serviceProvider
7669
NSUpdateDynamicServices()
7770
}
7871

79-
// MARK: - Entry point from the Services menu
80-
8172
/// Called by ServiceProvider when the user picks "Codebasic TTS": synthesize
82-
/// the selected text and play it.
73+
/// the selected text (cache-first) and play it.
8374
func handleSelectedText(_ text: String) {
84-
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
85-
guard !trimmed.isEmpty else { return }
86-
lastSelection = trimmed
87-
88-
let preview = trimmed.replacingOccurrences(of: "\n", with: " ").prefix(60)
89-
if let item = statusItem.menu?.item(withTag: MenuTag.lastSelection.rawValue) {
90-
item.title = "Last selection: \(preview)\(trimmed.count > 60 ? "…" : "")"
91-
}
92-
Log.app.info("handleSelectedText: \(trimmed.count) chars — \"\(preview, privacy: .public)\"")
93-
94-
speak(trimmed)
95-
}
96-
97-
private func speak(_ text: String) {
98-
speakTask?.cancel()
99-
player.stop()
100-
setIcon(.working)
101-
102-
speakTask = Task { [weak self] in
103-
guard let self else { return }
104-
do {
105-
for try await chunk in self.backend.stream(segment: text, voice: self.voice) {
106-
try Task.checkCancellation()
107-
self.setIcon(.speaking)
108-
try self.player.play(chunk)
109-
}
110-
} catch is CancellationError {
111-
// user pressed Stop / new selection
112-
} catch {
113-
Log.app.error("speak failed: \(error.localizedDescription)")
114-
self.setIcon(.error)
115-
try? await Task.sleep(nanoseconds: 1_500_000_000)
116-
self.setIcon(.idle)
117-
}
118-
}
75+
let preview = text.replacingOccurrences(of: "\n", with: " ").prefix(60)
76+
Log.app.info("handleSelectedText: \(text.count) chars — \"\(preview, privacy: .public)\"")
77+
appState.synthesize(text)
11978
}
12079
}

‎Sources/App/AppState.swift‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
import Foundation
2+
import Combine
3+
4+
/// Single source of truth for the UI and the speak path. Holds connection,
5+
/// settings, history, and runs synthesis (cache-first) + playback.
6+
@MainActor
7+
final class AppState: ObservableObject {
8+
9+
enum BackendKind: String, CaseIterable, Identifiable {
10+
case elevenlabs, local
11+
var id: String { rawValue }
12+
var label: String { self == .elevenlabs ? "ElevenLabs (클라우드)" : "로컬 (sidecar)" }
13+
}
14+
15+
// Connection
16+
@Published var keyPresent: Bool = Secrets.elevenLabsKey != nil
17+
@Published var backendKind: BackendKind = .elevenlabs
18+
@Published var voices: [ElevenVoice] = []
19+
@Published var connectionStatus = ""
20+
21+
// Settings
22+
@Published var voiceId = "Yp1WZJMrN7OSdP8PG9sm" // 성주 (cloned)
23+
@Published var voiceName = "성주"
24+
@Published var modelId = "eleven_flash_v2_5"
25+
@Published var voiceSettings = ElevenVoiceSettings()
26+
@Published var useCache = true
27+
@Published var localBaseURL = "http://127.0.0.1:8765"
28+
29+
// Runtime
30+
@Published var isWorking = false
31+
@Published var statusText = ""
32+
@Published private(set) var history: [HistoryEntry] = []
33+
34+
private let cache = CacheStore()
35+
private let player = AudioPlayer()
36+
private var task: Task<Void, Never>?
37+
38+
init() {
39+
loadSettings()
40+
history = cache.entries
41+
player.onFinish = { [weak self] in self?.finish() }
42+
}
43+
44+
private func finish() { isWorking = false; statusText = "" }
45+
46+
var backendIdentity: String { backendKind == .elevenlabs ? "elevenlabs" : "qwen3-local" }
47+
var settingsHash: String { backendKind == .elevenlabs ? voiceSettings.hash : "" }
48+
var audioExt: String { backendKind == .elevenlabs ? "mp3" : "wav" }
49+
50+
private func makeBackend() -> TTSBackend? {
51+
switch backendKind {
52+
case .elevenlabs:
53+
guard let key = Secrets.elevenLabsKey else { return nil }
54+
return ElevenLabsBackend(apiKey: key, settings: voiceSettings)
55+
case .local:
56+
return Qwen3MLXBackend(identity: backendIdentity,
57+
baseURL: URL(string: localBaseURL) ?? URL(string: "http://127.0.0.1:8765")!)
58+
}
59+
}
60+
61+
// MARK: - Synthesize (cache-first)
62+
63+
func synthesize(_ text: String) {
64+
let t = text.trimmingCharacters(in: .whitespacesAndNewlines)
65+
guard !t.isEmpty else { return }
66+
task?.cancel(); player.stop()
67+
68+
let key = CacheStore.key(text: t, backend: backendIdentity,
69+
voiceId: voiceId, modelId: modelId, settingsHash: settingsHash)
70+
if useCache, let data = cache.data(forKey: key) {
71+
cache.touch(key); history = cache.entries
72+
isWorking = true; statusText = "캐시에서 재생"
73+
try? player.play(data)
74+
return
75+
}
76+
guard let backend = makeBackend() else { statusText = "키/백엔드 미설정"; return }
77+
isWorking = true; statusText = "합성 중…"
78+
let voice = VoiceConfig(voiceId: voiceId, modelId: modelId, settingsHash: settingsHash)
79+
let vName = voiceName, ident = backendIdentity, ext = audioExt
80+
task = Task { [weak self] in
81+
guard let self else { return }
82+
do {
83+
var data = Data()
84+
for try await chunk in backend.stream(segment: t, voice: voice) {
85+
try Task.checkCancellation(); data.append(chunk)
86+
}
87+
if self.useCache {
88+
self.cache.save(key: key, text: t, backend: ident, voiceId: self.voiceId,
89+
voiceName: vName, modelId: self.modelId, ext: ext, data: data)
90+
self.history = self.cache.entries
91+
}
92+
self.statusText = "재생 중…"
93+
try self.player.play(data)
94+
} catch is CancellationError {
95+
self.finish()
96+
} catch {
97+
self.isWorking = false
98+
self.statusText = "오류: \(error.localizedDescription)"
99+
}
100+
}
101+
}
102+
103+
func replay(_ e: HistoryEntry) {
104+
task?.cancel(); player.stop()
105+
guard let data = cache.data(forKey: e.id) else { statusText = "오디오 파일 없음"; return }
106+
cache.touch(e.id); history = cache.entries
107+
isWorking = true; statusText = "캐시에서 재생"
108+
try? player.play(data)
109+
}
110+
111+
func stop() { task?.cancel(); player.stop(); finish() }
112+
113+
func deleteHistory(_ id: String) { cache.delete(id); history = cache.entries }
114+
func clearHistory() { cache.clear(); history = cache.entries }
115+
116+
// MARK: - Connection
117+
118+
func saveKey(_ key: String) {
119+
let k = key.trimmingCharacters(in: .whitespacesAndNewlines)
120+
try? FileManager.default.createDirectory(atPath: Secrets.appSupportDir,
121+
withIntermediateDirectories: true)
122+
let path = (Secrets.appSupportDir as NSString).appendingPathComponent("eleven_key")
123+
try? k.write(toFile: path, atomically: true, encoding: .utf8)
124+
keyPresent = !k.isEmpty
125+
connectionStatus = k.isEmpty ? "키 삭제됨" : "키 저장됨"
126+
if !k.isEmpty { refreshVoices() }
127+
}
128+
129+
func refreshVoices() {
130+
guard let key = Secrets.elevenLabsKey else { connectionStatus = "키 없음"; return }
131+
connectionStatus = "연결 확인 중…"
132+
Task { [weak self] in
133+
do {
134+
let vs = try await ElevenLabs.voices(apiKey: key)
135+
guard let self else { return }
136+
self.voices = vs
137+
self.connectionStatus = "연결됨 · 보이스 \(vs.count)개"
138+
if let v = vs.first(where: { $0.id == self.voiceId }) { self.voiceName = v.name }
139+
} catch {
140+
self?.connectionStatus = "연결 실패: \(error.localizedDescription)"
141+
}
142+
}
143+
}
144+
145+
// MARK: - Settings persistence
146+
147+
private var settingsURL: URL {
148+
URL(fileURLWithPath: (Secrets.appSupportDir as NSString).appendingPathComponent("settings.json"))
149+
}
150+
151+
func saveSettings() {
152+
let dict: [String: Any] = [
153+
"voiceId": voiceId, "voiceName": voiceName, "modelId": modelId,
154+
"backend": backendKind.rawValue, "useCache": useCache, "localBaseURL": localBaseURL,
155+
"stability": voiceSettings.stability, "similarity": voiceSettings.similarityBoost,
156+
"style": voiceSettings.style, "speakerBoost": voiceSettings.useSpeakerBoost,
157+
]
158+
if let d = try? JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted]) {
159+
try? d.write(to: settingsURL)
160+
}
161+
}
162+
163+
private func loadSettings() {
164+
guard let d = try? Data(contentsOf: settingsURL),
165+
let o = try? JSONSerialization.jsonObject(with: d) as? [String: Any] else { return }
166+
voiceId = o["voiceId"] as? String ?? voiceId
167+
voiceName = o["voiceName"] as? String ?? voiceName
168+
modelId = o["modelId"] as? String ?? modelId
169+
backendKind = BackendKind(rawValue: o["backend"] as? String ?? "") ?? backendKind
170+
useCache = o["useCache"] as? Bool ?? useCache
171+
localBaseURL = o["localBaseURL"] as? String ?? localBaseURL
172+
voiceSettings.stability = o["stability"] as? Double ?? voiceSettings.stability
173+
voiceSettings.similarityBoost = o["similarity"] as? Double ?? voiceSettings.similarityBoost
174+
voiceSettings.style = o["style"] as? Double ?? voiceSettings.style
175+
voiceSettings.useSpeakerBoost = o["speakerBoost"] as? Bool ?? voiceSettings.useSpeakerBoost
176+
}
177+
}

0 commit comments

Comments
 (0)