11import AppKit
22
3+ @ MainActor
34final class AppDelegate : NSObject , NSApplicationDelegate {
45
56 /// Singleton-ish handle so the Services provider can reach the running app.
67 static private( set) var shared : AppDelegate ?
78
89 private var statusItem : NSStatusItem !
910 private let serviceProvider = ServiceProvider ( )
11+ private let player = AudioPlayer ( )
1012 private var lastSelection : String = " "
13+ private var speakTask : Task < Void , Never > ?
1114
12- // Active backend. M1 just logs through it; later milestones swap in
13- // ElevenLabsBackend / Qwen3MLXBackend behind this same protocol.
14- private let backend : TTSBackend = StubBackend ( )
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 : " " )
1522
1623 func applicationDidFinishLaunching ( _ notification : Notification ) {
1724 AppDelegate . shared = self
1825
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+
1932 setUpStatusItem ( )
2033 registerServices ( )
34+ player . onFinish = { [ weak self ] in self ? . setIcon ( . idle ) }
2135
22- Log . app . info ( " SelectedTextTTS launched. Active backend : \( self . backend . identity , privacy : . public ) " )
36+ Log . app . info ( " Codebasic TTS launched. Backend : \( self . backend . identity , privacy : . public ) " )
2337 }
2438
2539 // MARK: - Menu bar
2640
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 }
45+
2746 private func setUpStatusItem ( ) {
2847 statusItem = NSStatusBar . system . statusItem ( withLength : NSStatusItem . variableLength )
29- statusItem . button ? . title = " 🔊 "
48+ setIcon ( . idle )
3049
3150 let menu = NSMenu ( )
3251 menu . addItem ( withTitle : " Codebasic TTS " , action : nil , keyEquivalent : " " )
@@ -37,46 +56,65 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
3756 lastItem . isEnabled = false
3857 menu . addItem ( lastItem )
3958
59+ menu . addItem ( withTitle : " Stop " , action : #selector( stopSpeaking ) , keyEquivalent : " . " )
4060 menu . addItem ( . separator ( ) )
4161 menu . addItem ( withTitle : " Quit " , action : #selector( NSApplication . terminate ( _ : ) ) , keyEquivalent : " q " )
4262
4363 statusItem . menu = menu
4464 }
4565
46- private enum MenuTag : Int {
47- case lastSelection = 100
66+ @ objc private func stopSpeaking ( ) {
67+ speakTask ? . cancel ( )
68+ player . stop ( )
69+ setIcon ( . idle )
4870 }
4971
5072 // MARK: - Services
5173
5274 private func registerServices ( ) {
53- // Wire the provider so the runtime can dispatch the Services menu item.
5475 NSApp . servicesProvider = serviceProvider
55- // Force a refresh of the dynamic services so the menu item shows up
56- // without requiring a logout/login on the very first run.
5776 NSUpdateDynamicServices ( )
5877 }
5978
6079 // MARK: - Entry point from the Services menu
6180
62- /// Called by ServiceProvider when the user picks "Read with SelectedTextTTS".
63- /// M1: log + reflect in the menu bar. M2+: hand to Segmenter → Cache → Player .
81+ /// Called by ServiceProvider when the user picks "Codebasic TTS": synthesize
82+ /// the selected text and play it .
6483 func handleSelectedText ( _ text : String ) {
65- lastSelection = text
66- let preview = text . replacingOccurrences ( of : " \n " , with : " " ) . prefix ( 60 )
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+ }
6796
68- DispatchQueue . main . async { [ weak self ] in
97+ private func speak ( _ text : String ) {
98+ speakTask ? . cancel ( )
99+ player . stop ( )
100+ setIcon ( . working )
101+
102+ speakTask = Task { [ weak self ] in
69103 guard let self else { return }
70- if let item = self . statusItem . menu ? . item ( withTag : MenuTag . lastSelection . rawValue ) {
71- item . title = " Last selection: \( preview ) \( text . count > 60 ? " … " : " " ) "
72- }
73- // Brief visual confirmation that the service fired.
74- self . statusItem . button ? . title = " 🔈 "
75- DispatchQueue . main . asyncAfter ( deadline : . now ( ) + 0.6 ) {
76- self . statusItem . button ? . title = " 🔊 "
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 )
77117 }
78118 }
79-
80- Log . app . info ( " handleSelectedText: \( text . count ) chars — \" \( preview , privacy : . public ) \" " )
81119 }
82120}
0 commit comments