forked from cjpais/Handy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactions.rs
More file actions
532 lines (471 loc) · 20.1 KB
/
actions.rs
File metadata and controls
532 lines (471 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
use crate::apple_intelligence;
use crate::audio_feedback::{play_feedback_sound, play_feedback_sound_blocking, SoundType};
use crate::managers::audio::AudioRecordingManager;
use crate::managers::history::HistoryManager;
use crate::managers::transcription::TranscriptionManager;
use crate::settings::{get_settings, AppSettings, APPLE_INTELLIGENCE_PROVIDER_ID};
use crate::shortcut;
use crate::tray::{change_tray_icon, TrayIconState};
use crate::utils::{self, show_recording_overlay, show_transcribing_overlay};
use crate::ManagedToggleState;
use ferrous_opencc::{config::BuiltinConfig, OpenCC};
use log::{debug, error};
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use tauri::AppHandle;
use tauri::Manager;
// Shortcut Action Trait
pub trait ShortcutAction: Send + Sync {
fn start(&self, app: &AppHandle, binding_id: &str, shortcut_str: &str);
fn stop(&self, app: &AppHandle, binding_id: &str, shortcut_str: &str);
}
// Transcribe Action
struct TranscribeAction;
async fn maybe_post_process_transcription(
settings: &AppSettings,
transcription: &str,
) -> Option<String> {
if !settings.post_process_enabled {
return None;
}
let provider = match settings.active_post_process_provider().cloned() {
Some(provider) => provider,
None => {
debug!("Post-processing enabled but no provider is selected");
return None;
}
};
let model = settings
.post_process_models
.get(&provider.id)
.cloned()
.unwrap_or_default();
if model.trim().is_empty() {
debug!(
"Post-processing skipped because provider '{}' has no model configured",
provider.id
);
return None;
}
let selected_prompt_id = match &settings.post_process_selected_prompt_id {
Some(id) => id.clone(),
None => {
debug!("Post-processing skipped because no prompt is selected");
return None;
}
};
let prompt = match settings
.post_process_prompts
.iter()
.find(|prompt| prompt.id == selected_prompt_id)
{
Some(prompt) => prompt.prompt.clone(),
None => {
debug!(
"Post-processing skipped because prompt '{}' was not found",
selected_prompt_id
);
return None;
}
};
if prompt.trim().is_empty() {
debug!("Post-processing skipped because the selected prompt is empty");
return None;
}
debug!(
"Starting LLM post-processing with provider '{}' (model: {})",
provider.id, model
);
// Replace ${output} variable in the prompt with the actual text
let processed_prompt = prompt.replace("${output}", transcription);
debug!("Processed prompt length: {} chars", processed_prompt.len());
if provider.id == APPLE_INTELLIGENCE_PROVIDER_ID {
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
{
if !apple_intelligence::check_apple_intelligence_availability() {
debug!("Apple Intelligence selected but not currently available on this device");
return None;
}
let token_limit = model.trim().parse::<i32>().unwrap_or(0);
return match apple_intelligence::process_text(&processed_prompt, token_limit) {
Ok(result) => {
if result.trim().is_empty() {
debug!("Apple Intelligence returned an empty response");
None
} else {
debug!(
"Apple Intelligence post-processing succeeded. Output length: {} chars",
result.len()
);
Some(result)
}
}
Err(err) => {
error!("Apple Intelligence post-processing failed: {}", err);
None
}
};
}
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
{
debug!("Apple Intelligence provider selected on unsupported platform");
return None;
}
}
let api_key = settings
.post_process_api_keys
.get(&provider.id)
.cloned()
.unwrap_or_default();
// Send the chat completion request
match crate::llm_client::send_chat_completion(&provider, api_key, &model, processed_prompt)
.await
{
Ok(Some(content)) => {
debug!(
"LLM post-processing succeeded for provider '{}'. Output length: {} chars",
provider.id,
content.len()
);
Some(content)
}
Ok(None) => {
error!("LLM API response has no content");
None
}
Err(e) => {
error!(
"LLM post-processing failed for provider '{}': {}. Falling back to original transcription.",
provider.id,
e
);
None
}
}
}
async fn maybe_convert_chinese_variant(
settings: &AppSettings,
transcription: &str,
) -> Option<String> {
// Check if language is set to Simplified or Traditional Chinese
let is_simplified = settings.selected_language == "zh-Hans";
let is_traditional = settings.selected_language == "zh-Hant";
if !is_simplified && !is_traditional {
debug!("selected_language is not Simplified or Traditional Chinese; skipping translation");
return None;
}
debug!(
"Starting Chinese translation using OpenCC for language: {}",
settings.selected_language
);
// Use OpenCC to convert based on selected language
let config = if is_simplified {
// Convert Traditional Chinese to Simplified Chinese
BuiltinConfig::Tw2sp
} else {
// Convert Simplified Chinese to Traditional Chinese
BuiltinConfig::S2twp
};
match OpenCC::from_config(config) {
Ok(converter) => {
let converted = converter.convert(transcription);
debug!(
"OpenCC translation completed. Input length: {}, Output length: {}",
transcription.len(),
converted.len()
);
Some(converted)
}
Err(e) => {
error!("Failed to initialize OpenCC converter: {}. Falling back to original transcription.", e);
None
}
}
}
impl ShortcutAction for TranscribeAction {
fn start(&self, app: &AppHandle, binding_id: &str, _shortcut_str: &str) {
let start_time = Instant::now();
debug!("TranscribeAction::start called for binding: {}", binding_id);
// Load model in the background
let tm = app.state::<Arc<TranscriptionManager>>();
tm.initiate_model_load();
let binding_id = binding_id.to_string();
change_tray_icon(app, TrayIconState::Recording);
show_recording_overlay(app);
let rm = app.state::<Arc<AudioRecordingManager>>();
// Get the microphone mode to determine audio feedback timing
let settings = get_settings(app);
let is_always_on = settings.always_on_microphone;
debug!("Microphone mode - always_on: {}", is_always_on);
let mut recording_started = false;
if is_always_on {
// Always-on mode: Play audio feedback immediately, then apply mute after sound finishes
debug!("Always-on mode: Playing audio feedback immediately");
let rm_clone = Arc::clone(&rm);
let app_clone = app.clone();
// The blocking helper exits immediately if audio feedback is disabled,
// so we can always reuse this thread to ensure mute happens right after playback.
std::thread::spawn(move || {
play_feedback_sound_blocking(&app_clone, SoundType::Start);
rm_clone.apply_mute();
});
recording_started = rm.try_start_recording(&binding_id);
debug!("Recording started: {}", recording_started);
} else {
// On-demand mode: Start recording first, then play audio feedback, then apply mute
// This allows the microphone to be activated before playing the sound
debug!("On-demand mode: Starting recording first, then audio feedback");
let recording_start_time = Instant::now();
if rm.try_start_recording(&binding_id) {
recording_started = true;
debug!("Recording started in {:?}", recording_start_time.elapsed());
// Small delay to ensure microphone stream is active
let app_clone = app.clone();
let rm_clone = Arc::clone(&rm);
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(100));
debug!("Handling delayed audio feedback/mute sequence");
// Helper handles disabled audio feedback by returning early, so we reuse it
// to keep mute sequencing consistent in every mode.
play_feedback_sound_blocking(&app_clone, SoundType::Start);
rm_clone.apply_mute();
});
} else {
debug!("Failed to start recording");
}
}
if recording_started {
// Dynamically register the cancel shortcut in a separate task to avoid deadlock
shortcut::register_cancel_shortcut(app);
}
debug!(
"TranscribeAction::start completed in {:?}",
start_time.elapsed()
);
}
fn stop(&self, app: &AppHandle, binding_id: &str, _shortcut_str: &str) {
// Unregister the cancel shortcut when transcription stops
shortcut::unregister_cancel_shortcut(app);
let stop_time = Instant::now();
debug!("TranscribeAction::stop called for binding: {}", binding_id);
let ah = app.clone();
let rm = Arc::clone(&app.state::<Arc<AudioRecordingManager>>());
let tm = Arc::clone(&app.state::<Arc<TranscriptionManager>>());
let hm = Arc::clone(&app.state::<Arc<HistoryManager>>());
change_tray_icon(app, TrayIconState::Transcribing);
show_transcribing_overlay(app);
// Unmute before playing audio feedback so the stop sound is audible
rm.remove_mute();
// Play audio feedback for recording stop
play_feedback_sound(app, SoundType::Stop);
let binding_id = binding_id.to_string(); // Clone binding_id for the async task
tauri::async_runtime::spawn(async move {
let binding_id = binding_id.clone(); // Clone for the inner async task
debug!(
"Starting async transcription task for binding: {}",
binding_id
);
let stop_recording_time = Instant::now();
if let Some(samples) = rm.stop_recording(&binding_id) {
debug!(
"Recording stopped and samples retrieved in {:?}, sample count: {}",
stop_recording_time.elapsed(),
samples.len()
);
let transcription_time = Instant::now();
let samples_clone = samples.clone(); // Clone for history saving
match tm.transcribe(samples) {
Ok(transcription) => {
debug!(
"Transcription completed in {:?}: '{}'",
transcription_time.elapsed(),
transcription
);
if !transcription.is_empty() {
let settings = get_settings(&ah);
let mut final_text = transcription.clone();
let mut post_processed_text: Option<String> = None;
let mut post_process_prompt: Option<String> = None;
// First, check if Chinese variant conversion is needed
if let Some(converted_text) =
maybe_convert_chinese_variant(&settings, &transcription).await
{
final_text = converted_text.clone();
post_processed_text = Some(converted_text);
}
// Then apply regular post-processing if enabled
else if let Some(processed_text) =
maybe_post_process_transcription(&settings, &transcription).await
{
final_text = processed_text.clone();
post_processed_text = Some(processed_text);
// Get the prompt that was used
if let Some(prompt_id) = &settings.post_process_selected_prompt_id {
if let Some(prompt) = settings
.post_process_prompts
.iter()
.find(|p| &p.id == prompt_id)
{
post_process_prompt = Some(prompt.prompt.clone());
}
}
}
// Save to history with post-processed text and prompt
let hm_clone = Arc::clone(&hm);
let transcription_for_history = transcription.clone();
tauri::async_runtime::spawn(async move {
if let Err(e) = hm_clone
.save_transcription(
samples_clone,
transcription_for_history,
post_processed_text,
post_process_prompt,
)
.await
{
error!("Failed to save transcription to history: {}", e);
}
});
// Paste the final text (either processed or original)
let ah_clone = ah.clone();
let paste_time = Instant::now();
ah.run_on_main_thread(move || {
match utils::paste(final_text, ah_clone.clone()) {
Ok(()) => debug!(
"Text pasted successfully in {:?}",
paste_time.elapsed()
),
Err(e) => error!("Failed to paste transcription: {}", e),
}
// Hide the overlay after transcription is complete
utils::hide_recording_overlay(&ah_clone);
change_tray_icon(&ah_clone, TrayIconState::Idle);
})
.unwrap_or_else(|e| {
error!("Failed to run paste on main thread: {:?}", e);
utils::hide_recording_overlay(&ah);
change_tray_icon(&ah, TrayIconState::Idle);
});
} else {
utils::hide_recording_overlay(&ah);
change_tray_icon(&ah, TrayIconState::Idle);
}
}
Err(err) => {
debug!("Global Shortcut Transcription error: {}", err);
utils::hide_recording_overlay(&ah);
change_tray_icon(&ah, TrayIconState::Idle);
}
}
} else {
debug!("No samples retrieved from recording stop");
utils::hide_recording_overlay(&ah);
change_tray_icon(&ah, TrayIconState::Idle);
}
// Clear toggle state now that transcription is complete
if let Ok(mut states) = ah.state::<ManagedToggleState>().lock() {
states.active_toggles.insert(binding_id, false);
}
});
debug!(
"TranscribeAction::stop completed in {:?}",
stop_time.elapsed()
);
}
}
// Cancel Action
struct CancelAction;
impl ShortcutAction for CancelAction {
fn start(&self, app: &AppHandle, _binding_id: &str, _shortcut_str: &str) {
utils::cancel_current_operation(app);
}
fn stop(&self, _app: &AppHandle, _binding_id: &str, _shortcut_str: &str) {
// Nothing to do on stop for cancel
}
}
struct RetypeLastAction;
impl ShortcutAction for RetypeLastAction {
fn start(&self, app: &AppHandle, _binding_id: &str, _shortcut_str: &str) {
debug!("RetypeLastAction::start called");
let app_handle = app.clone();
tauri::async_runtime::spawn(async move {
let hm = app_handle.state::<Arc<HistoryManager>>();
match hm.get_latest_entry().await {
Ok(Some(entry)) => {
let text = entry
.post_processed_text
.filter(|t| !t.is_empty())
.unwrap_or(entry.transcription_text);
if text.is_empty() {
debug!("RetypeLastAction: Latest entry has empty text");
return;
}
debug!("RetypeLastAction: Retyping text: '{}'", text);
let app_for_paste = app_handle.clone();
app_handle
.run_on_main_thread(move || {
if let Err(e) = utils::paste(text, app_for_paste) {
error!("RetypeLastAction: Failed to paste text: {}", e);
}
})
.unwrap_or_else(|e| {
error!("RetypeLastAction: Failed to run on main thread: {:?}", e);
});
}
Ok(None) => {
debug!("RetypeLastAction: No history entries found");
}
Err(e) => {
error!("RetypeLastAction: Failed to get latest entry: {}", e);
}
}
});
}
fn stop(&self, _app: &AppHandle, _binding_id: &str, _shortcut_str: &str) {
// Nothing to do on stop for retype
}
}
// Test Action
struct TestAction;
impl ShortcutAction for TestAction {
fn start(&self, app: &AppHandle, binding_id: &str, shortcut_str: &str) {
log::info!(
"Shortcut ID '{}': Started - {} (App: {})", // Changed "Pressed" to "Started" for consistency
binding_id,
shortcut_str,
app.package_info().name
);
}
fn stop(&self, app: &AppHandle, binding_id: &str, shortcut_str: &str) {
log::info!(
"Shortcut ID '{}': Stopped - {} (App: {})", // Changed "Released" to "Stopped" for consistency
binding_id,
shortcut_str,
app.package_info().name
);
}
}
// Static Action Map
pub static ACTION_MAP: Lazy<HashMap<String, Arc<dyn ShortcutAction>>> = Lazy::new(|| {
let mut map = HashMap::new();
map.insert(
"transcribe".to_string(),
Arc::new(TranscribeAction) as Arc<dyn ShortcutAction>,
);
map.insert(
"cancel".to_string(),
Arc::new(CancelAction) as Arc<dyn ShortcutAction>,
);
map.insert(
"retype_last".to_string(),
Arc::new(RetypeLastAction) as Arc<dyn ShortcutAction>,
);
map.insert(
"test".to_string(),
Arc::new(TestAction) as Arc<dyn ShortcutAction>,
);
map
});