-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
3293 lines (3070 loc) · 126 KB
/
Copy pathmod.rs
File metadata and controls
3293 lines (3070 loc) · 126 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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use iced::widget::{button, container, row, scrollable, space, text};
use iced::{Element, Length, Point, Subscription, Task, Theme};
use crate::audio::effects::EffectSlot;
use crate::audio::{AudioCommand, AudioEvent, AudioHandle, PlayMode};
use crate::shortcuts::ShortcutsStatus;
use crate::state::config::{Density, OverlapMode};
use crate::state::{AppConfig, SlotMap, SoundEntry, SoundMeta, SoundMetaStore};
use crate::tray::{TrayEvent, TrayHandle};
use crate::ui::effects_panel::{self, EffectsUiState, PresetId};
use crate::ui::effects_panel_view;
use crate::ui::side_panel::{PanelAnim, PanelFlourish};
use crate::ui::sound_grid;
use crate::ui::theme::{self, Hh};
use crate::ui::{now_playing, search_bar, slot_manager};
use notices::{Notice, NoticeId, NoticeQueue};
/// Play-dispatch coordination (`request_play` / `handle_decoded` /
/// `start_playback`), extracted to keep this file from growing (#151).
mod macros;
#[cfg(test)]
mod notice_tests;
pub(crate) mod notices;
/// Panel animation state transitions extracted from the Iced update loop (#144).
mod panels;
mod playback;
mod recording;
/// Virtual category name used for the Favorites filtered tab.
pub const FAVORITES_TAB: &str = "\u{2605} Favorites";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ViewMode {
#[default]
Main,
SlotManager,
Settings,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum SettingsSection {
#[default]
Audio,
Library,
Hotkeys,
Appearance,
About,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Message {
ToggleVisibility,
Quit,
TrayEvent(TrayEvent),
TrayPoll,
AudioEvent(AudioEvent),
RaiseNotice(Notice),
DismissNotice(NoticeId),
NoticeTick(Instant),
PlaySound(String),
StopAll,
StartRecording,
StopRecording,
/// Fire macro by id (slots call this in #169).
PlayMacro(String),
/// A scheduled macro step's timer elapsed; dispatch it if its run is current.
MacroStepDue {
run_id: u64,
step: usize,
},
/// A cold macro step's off-thread decode finished.
MacroStepDecoded {
run_id: u64,
voice_id: u64,
sound_id: String,
gain: f32,
effects: crate::audio::effects::EffectSettings,
result: Result<crate::audio::CachedPcm, String>,
},
SelectCategory(Option<String>),
SearchChanged(String),
EscapePressed,
VolumeChanged(f32),
VolumeSaveRequested,
// Shortcut lifecycle
ShortcutsReady,
ShortcutsUnavailable(String),
DismissShortcutsWarning,
// Shortcut activation
ShortcutActivated(u8),
ShortcutBindingsUpdated(Vec<(u8, String)>),
// Duration scanning
DurationsLoaded(std::collections::HashMap<String, u64>),
// Slot assignment
AssignSlot(u8, std::path::PathBuf),
ClearSlot(u8),
// Context menu
OpenContextMenu(String), // sound_id
CloseContextMenu,
// Window / cursor
CursorMoved(Point),
WindowResized(f32, f32),
/// Per-frame redraw tick (vsync-paced via `window::frames()`), carrying the
/// frame time. Only subscribed while a sound plays. Drives playhead interpolation.
Frame(Instant),
// Navigation
ShowSlots,
ShowMain,
SelectSlot(u8),
// Settings navigation
ShowSettings,
ShowSettingsSection(SettingsSection),
// Library management
RescanLibrary,
AddSoundDirectory,
SoundDirectoryPickResult(Option<std::path::PathBuf>),
RemoveSoundDirectory(std::path::PathBuf),
// Appearance
ThemeChanged(theme::Theme),
DensityChanged(Density),
PanelAnimationsChanged(bool),
RendererChanged(crate::state::Renderer),
// Audio
MicPassthroughChanged(bool),
MicPassthroughLevelChanged(f32),
OverlapModeChanged(OverlapMode),
MonitorDeviceChanged(Option<String>),
InputDeviceChanged(Option<String>),
// Voice effects
SelectEffectPreset(PresetId),
SetEffectBypassUi(bool),
SetWetDryMix(f32),
SetEffectParamUi {
slot: EffectSlot,
param: &'static str,
value: f32,
},
/// Toggle the effects side panel open/closed (pull tab).
ToggleEffectsPanel,
/// Close the effects side panel (scrim / ✕ / Escape).
CloseEffectsPanel,
/// Carries the command sender from the portal stream.
/// Two `ShortcutHandle` messages are never meaningfully equal — treated as always-unequal.
ShortcutHandle(crate::shortcuts::PortalCmdSender),
/// Opens the DE's native shortcut configuration dialog for this session.
OpenShortcutConfig,
/// Whether `configure_shortcuts()` (portal v2) is available on this DE/backend.
ShortcutsConfigureAvailable(bool),
// Per-sound metadata
ToggleFavorite(String),
OpenSoundEditor(String),
CloseSoundEditor,
SoundEditorNameChanged(String),
SoundEditorVolumeChanged(String, f32),
SaveSoundMeta(String),
/// A background decode completed for play generation `generation`. Applied
/// only if still the current generation (#149/#151).
Decoded {
generation: u64,
voice_id: u64,
id: String,
result: Result<crate::audio::CachedPcm, String>,
gain: f32,
effects: crate::audio::effects::EffectSettings,
mode: PlayMode,
},
}
impl Message {
pub fn from_tray_event(event: TrayEvent) -> Self {
match event {
TrayEvent::ToggleVisibility => Message::ToggleVisibility,
TrayEvent::Quit => Message::Quit,
}
}
}
/// Smallest window dimension treated as a real, usable size. Resize events
/// below it (some compositors emit 0-size on minimize) are not recorded, and
/// restored sizes are floored to it so a bad config cannot launch an
/// invisible window.
pub const MIN_WINDOW_DIMENSION: f32 = 200.0;
pub struct HonkHonk {
visible: bool,
exit: bool,
tray_rx: Arc<Mutex<Receiver<TrayEvent>>>,
_tray: Option<TrayHandle>,
audio: Option<AudioHandle>,
pub(crate) sounds: Vec<SoundEntry>,
playing: Option<String>,
active_category: Option<String>,
pub(crate) config: AppConfig,
search_query: String,
// True after SearchChanged fires; first Escape consumes it as a blur,
// second Escape clears the query. Resets when SearchChanged fires again.
search_had_focus: bool,
progress: f32,
slots: SlotMap,
pub(crate) slot_triggers: [Option<String>; 20],
pub(crate) shortcuts_status: ShortcutsStatus,
context_menu: Option<String>,
context_menu_pos: Option<Point>,
cursor_pos: Point,
window_size: (f32, f32),
shortcuts_warning_dismissed: bool,
durations_loaded: bool,
duration_scan_pairs: std::sync::Arc<Vec<(String, std::path::PathBuf)>>,
view_mode: ViewMode,
selected_slot: Option<u8>,
pub(crate) settings_section: SettingsSection,
pub monitor_devices: Vec<(String, String)>,
pub input_devices: Vec<(String, String)>,
shortcut_config: crate::shortcuts::config_ui::ShortcutConfigService,
/// User-visible in-window notices raised from app/audio events.
notices: NoticeQueue,
/// Per-sound metadata: favorites, per-sound volume, display names.
pub(crate) sound_meta: SoundMetaStore,
/// Master persistence switch. When `false`, every disk write —
/// `config.save()`, `slots.save()`, `sound_meta.save()` — is skipped. Test
/// fixtures (`new_for_test`) set this `false` so `cargo test` never
/// overwrites the developer's real XDG config dir (config.json, slots.json,
/// meta.json).
persist: bool,
/// Set when startup could not load the on-disk config (I/O or parse
/// error): the in-memory state is then bare defaults, and a quit-time
/// save would overwrite the user's repairable file with them.
config_load_failed: bool,
/// Sound ID currently open in the per-sound editor overlay.
editor_sound_id: Option<String>,
/// Draft display name held while the editor is open.
editor_draft_name: String,
/// Draft per-sound volume held while the editor is open.
editor_draft_volume: f32,
/// User-facing voice-effects state (preset, bypass, wet/dry, params).
effects_ui: EffectsUiState,
/// Open/close animation state for the effects side panel (#143). Logic lives
/// in `ui::side_panel`.
effects_panel: PanelAnim,
/// Reusable panel open/close feather burst overlay (#144).
panel_flourish: PanelFlourish,
/// Eased panel progress (0=closed..1=open) fed to the view; refreshed each
/// frame by `effects_panel.tick`.
panel_progress: f32,
/// Persistent now-playing playback UI owner (#142): playhead lifecycle,
/// display progress, waveform cache key, and per-sound envelopes.
now_playing: crate::ui::now_playing::NowPlaying,
/// Monotonic counter bumped on every play dispatch. Stamped onto the `Play`
/// command and echoed back on `PlaybackFinished` to tell a genuine end from
/// the stale `Finished` of a re-pressed voice (#149), and onto each
/// off-thread decode so the latest same-id cold repeat can claim ownership
/// when the shared decode lands (#151/#152).
play_generation: u64,
/// Hot-path decoded-PCM cache (#151).
audio_store: crate::audio::AudioStore,
pending_play_ids: HashSet<u64>,
pending_decodes: HashMap<String, playback::PendingDecode>,
/// Persisted macro collection (#165).
macros: crate::state::MacroStore,
/// Active live macro capture, if recording is enabled (#167).
recording: Option<recording::Recording>,
/// Unsaved macro draft produced by `StopRecording`, ready for #168's editor
/// buffer to adopt.
macro_editor_draft: Option<crate::state::Macro>,
/// Session-local counter used for draft names/ids. Unsaved drafts are not
/// inserted into `MacroStore`; #168 owns keep/discard persistence.
macro_draft_seq: u64,
/// The single in-flight macro run, if any — `Some` enforces one macro at a
/// time (#166). `None` when idle.
macro_playback: Option<macros::MacroPlayback>,
/// Monotonic run counter; a `MacroStepDue`/`MacroStepDecoded` for a run that
/// is no longer current is ignored (re-fire / Stop All cancellation).
macro_run_id: u64,
/// Per-voice counter for macro steps. Combined with a top-bit flag into a
/// voice-id space disjoint from the tile `play_generation`, so a macro firing
/// mid-tile-press never advances (and corrupts) the tile's now-playing UI
/// ownership (#166).
macro_voice_seq: u64,
}
fn shortcuts_stream_sub(
window_id: Option<ashpd::WindowIdentifier>,
) -> impl iced::futures::Stream<Item = Message> {
use iced::futures::SinkExt;
use iced::futures::StreamExt;
iced::stream::channel(16, async move |mut tx| {
use crate::shortcuts::{ShortcutEvent, portal};
let stream = portal::shortcut_stream(window_id);
let mut stream = std::pin::pin!(stream);
while let Some(ev) = stream.next().await {
let msg = match ev {
ShortcutEvent::Ready => Message::ShortcutsReady,
ShortcutEvent::Handle(sender) => {
Message::ShortcutHandle(crate::shortcuts::PortalCmdSender(sender))
}
ShortcutEvent::ConfigureAvailable(v) => Message::ShortcutsConfigureAvailable(v),
ShortcutEvent::Activated(i) => Message::ShortcutActivated(i),
ShortcutEvent::Bindings(b) => Message::ShortcutBindingsUpdated(b),
ShortcutEvent::Changed(b) => Message::ShortcutBindingsUpdated(b),
ShortcutEvent::Failed(r) => Message::ShortcutsUnavailable(r),
};
if tx.send(msg).await.is_err() {
break;
}
}
// Stream ended unexpectedly (portal crashed mid-session). Notify the UI
// so the unavailability banner appears, then park to keep the subscription alive.
let _ = tx
.send(Message::ShortcutsUnavailable(
"portal connection lost".into(),
))
.await;
iced::futures::future::pending::<()>().await;
})
}
/// Zero-arg wrapper for `Subscription::run` (which requires a fn pointer, not a closure).
fn shortcuts_stream_sub_none() -> impl iced::futures::Stream<Item = Message> {
shortcuts_stream_sub(None)
}
/// Builder for the one-shot duration scan subscription.
///
/// Returns a `BoxStream` (concrete type) so it can be used as `fn(&D) -> S`
/// with `Subscription::run_with`, which requires a concrete `S: Stream`.
fn duration_scan_builder(
pairs: &std::sync::Arc<Vec<(String, std::path::PathBuf)>>,
) -> iced::futures::stream::BoxStream<'static, Message> {
let pairs = std::sync::Arc::clone(pairs);
Box::pin(iced::stream::channel(1, async move |mut tx| {
use iced::futures::SinkExt;
let owned = (*pairs).clone();
let map =
tokio::task::spawn_blocking(move || crate::state::library::probe_durations(owned))
.await
.unwrap_or_default();
let _ = tx.send(Message::DurationsLoaded(map)).await;
iced::futures::future::pending::<()>().await;
}))
}
async fn pick_directory() -> anyhow::Result<Option<std::path::PathBuf>> {
use anyhow::Context;
use ashpd::desktop::file_chooser::SelectedFiles;
let request = SelectedFiles::open_file()
.title("Select Sound Folder")
.directory(true)
.send()
.await
.map_err(|e| anyhow::anyhow!(e))
.context("file chooser portal send failed")?;
let files = match request.response() {
Ok(f) => f,
Err(ashpd::Error::Response(_)) => return Ok(None), // user cancelled
Err(e) => return Err(anyhow::anyhow!(e).context("file chooser response failed")),
};
let uri = match files.uris().first() {
Some(u) => u.clone(),
None => return Ok(None),
};
let url = url::Url::parse(uri.as_str()).with_context(|| format!("parsing file URI: {uri}"))?;
url.to_file_path()
.map(Some)
.map_err(|_| anyhow::anyhow!("URI is not a file:// path: {uri}"))
}
/// First-run notice text for the persistent virtual mic (issue #49). When the
/// per-user conf.d was written the device persists across restarts; otherwise
/// it only lasts the session (until reboot) via the lingering node.
fn source_first_run_notice(confd_written: bool) -> String {
if confd_written {
"Created HonkHonk Mic virtual device. It will persist after restart. \
Select 'HonkHonk Mic' as your input in Discord/OBS."
.to_string()
} else {
"HonkHonk Mic created for this session. \
Select 'HonkHonk Mic' as your input in Discord/OBS."
.to_string()
}
}
impl HonkHonk {
#[allow(
clippy::too_many_lines,
reason = "constructor lists every app state field explicitly to avoid hidden defaults during app split"
)]
pub fn new(
mut tray: TrayHandle,
audio: AudioHandle,
sounds: Vec<SoundEntry>,
config: AppConfig,
slots: SlotMap,
) -> Self {
let rx = tray.take_rx();
let duration_scan_pairs = std::sync::Arc::new(
sounds
.iter()
.map(|s| (s.id.clone(), s.path.clone()))
.collect::<Vec<_>>(),
);
Self {
visible: true,
exit: false,
tray_rx: Arc::new(Mutex::new(rx)),
_tray: Some(tray),
audio: Some(audio),
sounds,
playing: None,
active_category: None,
config,
search_query: String::new(),
search_had_focus: false,
progress: 0.0,
slots,
slot_triggers: std::array::from_fn(|_| None),
shortcuts_status: ShortcutsStatus::Initializing,
context_menu: None,
context_menu_pos: None,
cursor_pos: Point::ORIGIN,
window_size: (1280.0, 800.0),
shortcuts_warning_dismissed: false,
durations_loaded: false,
duration_scan_pairs,
view_mode: ViewMode::default(),
selected_slot: None,
settings_section: SettingsSection::default(),
monitor_devices: Vec::new(),
input_devices: Vec::new(),
shortcut_config: crate::shortcuts::config_ui::ShortcutConfigService::new(),
notices: NoticeQueue::new(),
sound_meta: SoundMetaStore::load(),
persist: true,
config_load_failed: false,
editor_sound_id: None,
editor_draft_name: String::new(),
editor_draft_volume: 1.0,
effects_ui: EffectsUiState::default(),
effects_panel: PanelAnim::default(),
panel_flourish: PanelFlourish::default(),
panel_progress: 0.0,
now_playing: crate::ui::now_playing::NowPlaying::default(),
play_generation: 0,
audio_store: crate::audio::AudioStore::new(crate::audio::DEFAULT_PCM_CAP_BYTES),
pending_play_ids: HashSet::new(),
pending_decodes: HashMap::new(),
macros: crate::state::MacroStore::load(),
recording: None,
macro_editor_draft: None,
macro_draft_seq: 0,
macro_playback: None,
macro_run_id: 0,
macro_voice_seq: 0,
}
}
#[allow(
clippy::too_many_lines,
reason = "test constructor mirrors app state fields explicitly so tests do not depend on hidden defaults"
)]
pub fn new_for_test() -> Self {
let (_tx, rx) = std::sync::mpsc::channel();
let config = AppConfig::default();
Self {
visible: true,
exit: false,
tray_rx: Arc::new(Mutex::new(rx)),
_tray: None,
audio: None,
sounds: Vec::new(),
playing: None,
active_category: None,
config,
search_query: String::new(),
search_had_focus: false,
progress: 0.0,
slots: SlotMap::default(),
slot_triggers: std::array::from_fn(|_| None),
shortcuts_status: ShortcutsStatus::Initializing,
context_menu: None,
context_menu_pos: None,
cursor_pos: Point::ORIGIN,
window_size: (1280.0, 800.0),
shortcuts_warning_dismissed: false,
durations_loaded: false,
duration_scan_pairs: std::sync::Arc::new(Vec::new()),
view_mode: ViewMode::default(),
selected_slot: None,
settings_section: SettingsSection::default(),
monitor_devices: Vec::new(),
input_devices: Vec::new(),
shortcut_config: crate::shortcuts::config_ui::ShortcutConfigService::new(),
notices: NoticeQueue::new(),
sound_meta: SoundMetaStore::default(),
persist: false,
config_load_failed: false,
editor_sound_id: None,
editor_draft_name: String::new(),
editor_draft_volume: 1.0,
effects_ui: EffectsUiState::default(),
effects_panel: PanelAnim::default(),
panel_flourish: PanelFlourish::default(),
panel_progress: 0.0,
now_playing: crate::ui::now_playing::NowPlaying::default(),
play_generation: 0,
audio_store: crate::audio::AudioStore::new(crate::audio::DEFAULT_PCM_CAP_BYTES),
pending_play_ids: HashSet::new(),
pending_decodes: HashMap::new(),
macros: crate::state::MacroStore::default(),
recording: None,
macro_editor_draft: None,
macro_draft_seq: 0,
macro_playback: None,
macro_run_id: 0,
macro_voice_seq: 0,
}
}
pub fn should_exit(&self) -> bool {
self.exit
}
/// Marks the on-disk config as having failed to load at startup, which
/// disables the quit-time config save for the session: the in-memory
/// defaults must not clobber the user's repairable file.
pub fn mark_config_load_failed(&mut self) {
self.config_load_failed = true;
}
/// The quit save is gated on a live audio engine so unit-test fixtures
/// (`audio: None`) never write the user's real config file, and on the
/// config having loaded cleanly at startup. The `persist` master switch
/// applies on top, inside `persist_config`.
fn should_persist_config_on_quit(&self) -> bool {
self.audio.is_some() && !self.config_load_failed
}
pub fn is_visible(&self) -> bool {
self.visible
}
pub fn playing(&self) -> Option<&str> {
self.playing.as_deref()
}
pub fn active_category(&self) -> Option<&str> {
self.active_category.as_deref()
}
/// Route effects commands to the audio thread, no-op when no engine is up.
fn send_audio_commands(&self, cmds: impl IntoIterator<Item = AudioCommand>) {
if let Some(ref audio) = self.audio {
for cmd in cmds {
audio.send(cmd);
}
}
}
#[cfg(test)]
pub(crate) fn effects_ui_preset(&self) -> PresetId {
self.effects_ui.preset
}
#[cfg(test)]
pub(crate) fn effects_ui_wet_dry(&self) -> f32 {
self.effects_ui.wet_dry
}
#[cfg(test)]
pub(crate) fn effects_ui_chain_bypass(&self) -> bool {
self.effects_ui.chain_bypass
}
pub fn search_query(&self) -> &str {
&self.search_query
}
pub fn progress(&self) -> f32 {
self.progress
}
pub fn shortcuts_status(&self) -> &ShortcutsStatus {
&self.shortcuts_status
}
pub fn slots(&self) -> &SlotMap {
&self.slots
}
pub fn slot_triggers(&self) -> &[Option<String>; 20] {
&self.slot_triggers
}
pub fn context_menu(&self) -> Option<&str> {
self.context_menu.as_deref()
}
pub fn view_mode(&self) -> ViewMode {
self.view_mode
}
pub fn selected_slot(&self) -> Option<u8> {
self.selected_slot
}
pub fn shortcuts_warning_dismissed(&self) -> bool {
self.shortcuts_warning_dismissed
}
pub(crate) fn notices(&self) -> &NoticeQueue {
&self.notices
}
pub fn sound_meta(&self) -> &SoundMetaStore {
&self.sound_meta
}
pub fn editor_sound_id(&self) -> Option<&str> {
self.editor_sound_id.as_deref()
}
pub fn filtered_sounds(&self) -> Vec<&SoundEntry> {
let query = self.search_query.to_lowercase();
self.sounds
.iter()
.filter(|s| match self.active_category.as_deref() {
Some(cat) if cat == FAVORITES_TAB => self.sound_meta.is_favorite(&s.id),
Some(cat) => s.category == cat,
None => true,
})
.filter(|s| {
if query.is_empty() {
return true;
}
// Also match against the display-name override so sounds
// renamed by the user remain discoverable by their visible label.
let display_name_matches = self
.sound_meta
.get_ref(&s.id)
.and_then(|m| m.display_name.as_deref())
.is_some_and(|name| name.to_lowercase().contains(&query));
s.name.to_lowercase().contains(&query) || display_name_matches
})
.collect()
}
#[allow(
clippy::cognitive_complexity,
clippy::too_many_lines,
reason = "legacy Elm update dispatcher is being split under #142; keep message routing visible until then"
)]
pub fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::ToggleVisibility => {
self.visible = !self.visible;
if !self.visible {
self.panel_flourish.clear();
}
Task::none()
}
Message::Quit => {
if let Some(ref audio) = self.audio {
audio.shutdown();
}
// Persist the latest window size (recorded in-memory on
// resize) and any other config on a real quit.
if self.should_persist_config_on_quit() {
self.persist_config();
}
self.exit = true;
iced::exit()
}
Message::TrayEvent(event) => {
let msg = Message::from_tray_event(event);
self.update(msg)
}
Message::TrayPoll => {
let event = self.tray_rx.lock().ok().and_then(|rx| rx.try_recv().ok());
if let Some(e) = event {
let msg = Message::from_tray_event(e);
return self.update(msg);
}
self.drain_audio_events()
}
Message::AudioEvent(event) => {
match event {
AudioEvent::Ready => {
tracing::info!("audio engine ready");
if let Some(ref audio) = self.audio {
audio.send(AudioCommand::SetVolume(self.config.volume));
}
}
AudioEvent::PlaybackStarted {
sound_id,
generation,
} => {
// Warm plays and successful cold decodes claim
// `playing` before the engine's Started event. When the
// UI is idle, only the current generation may claim it:
// a late superseded concurrent voice (older generation)
// finishing after a newer short sound already ended
// would otherwise re-highlight its tile and then leave
// it stuck when the stale Finished is ignored
// (#149/#152/#164).
let confirms_current = self.playing.as_deref() == Some(sound_id.as_str());
let claims_idle =
self.playing.is_none() && generation == self.play_generation;
if confirms_current || claims_idle {
self.playing = Some(sound_id);
}
}
AudioEvent::PlaybackFinished {
voice_id,
sound_id,
generation,
} => {
// Clear only when this Finished is for the sound we are
// showing AND belongs to the current play. The sound_id
// check keeps a Finished for an already-replaced sound
// from blanking a newer press (#111); the generation
// check additionally ignores the stale Finished emitted
// for a same-sound voice that was superseded by an
// immediate re-press, so its fresh playhead survives
// (#149).
if self.playing.as_deref() == Some(sound_id.as_str())
&& generation == self.play_generation
{
self.clear_playback_state();
}
// A macro voice ending advances its run's completion
// bookkeeping; a non-macro voice is ignored (#166).
self.note_macro_voice_finished(voice_id);
}
AudioEvent::Progress(p) => {
// Raw 10 Hz anchor, retained for diagnostics/tests. The
// smooth playhead is wall-clock driven (`Message::Frame`),
// NOT this sample: re-anchoring a sample measured ~100 ms
// ago to the current instant snapped the line backward
// every drain (left/right jitter, #138).
self.progress = p;
}
AudioEvent::Error(e) => {
tracing::error!(error = %e, "audio error");
self.notices
.push(Notice::error("Audio error", e.to_string()), Instant::now());
}
AudioEvent::SourceFirstRun { confd_written } => {
let body = source_first_run_notice(confd_written);
tracing::info!(notice = %body, "source first-run notice");
self.notices
.push(Notice::info("HonkHonk Mic created", body), Instant::now());
}
AudioEvent::OutputDevicesChanged(devices) => {
if let Some(ref target) = self.config.monitor_device.clone() {
let was_visible = self.monitor_devices.iter().any(|(n, _)| n == target);
let still_visible = devices.iter().any(|(n, _)| n == target);
if was_visible && !still_visible {
let config = AppConfig {
monitor_device: None,
..self.config.clone()
};
self.config = config;
self.persist_config();
if let Some(ref audio) = self.audio {
audio.send(AudioCommand::SetMonitorDevice(None));
}
}
}
self.monitor_devices = devices;
}
AudioEvent::InputDevicesChanged(devices) => {
if let Some(ref target) = self.config.input_device.clone() {
let was_visible = self.input_devices.iter().any(|(n, _)| n == target);
let still_visible = devices.iter().any(|(n, _)| n == target);
if was_visible && !still_visible {
let config = AppConfig {
input_device: None,
..self.config.clone()
};
self.config = config;
self.persist_config();
if let Some(ref audio) = self.audio {
audio.send(AudioCommand::SetInputDevice(None));
}
}
}
self.input_devices = devices;
}
AudioEvent::EffectsLatencyChanged(_latency) => {
// Reserved for Phase 4B: update UI latency indicator.
}
}
Task::none()
}
Message::RaiseNotice(notice) => {
self.notices.push(notice, Instant::now());
Task::none()
}
Message::DismissNotice(id) => {
self.notices.dismiss(id);
Task::none()
}
Message::NoticeTick(now) => {
self.notices.expire(now);
Task::none()
}
Message::PlaySound(sound_id) => {
if let Some(sound) = self.sounds.iter().find(|s| s.id == sound_id).cloned() {
self.request_play(&sound, false)
} else {
Task::none()
}
}
Message::StopAll => {
if let Some(ref audio) = self.audio {
audio.send(AudioCommand::Stop);
}
// `clear_playback_state` sets `playing = None`; `handle_decoded`
// gates on `playing == Some(id)`, so any decode still in flight
// for the stopped sound is dropped on arrival rather than
// resurrecting it (#151).
self.pending_play_ids.clear();
self.pending_decodes.clear();
self.clear_playback_state();
self.cancel_macro();
Task::none()
}
Message::StartRecording => {
self.start_recording_at(Instant::now());
Task::none()
}
Message::StopRecording => {
self.stop_recording();
Task::none()
}
Message::PlayMacro(id) => self.play_macro(&id),
Message::MacroStepDue { run_id, step } => self.on_macro_step_due(run_id, step),
Message::MacroStepDecoded {
run_id,
voice_id,
sound_id,
gain,
effects,
result,
} => self.on_macro_step_decoded(
run_id,
macros::MacroVoice {
voice_id,
sound_id,
gain,
effects,
},
result,
),
Message::SelectCategory(cat) => {
self.active_category = cat;
Task::none()
}
Message::EscapePressed => {
if self.context_menu.is_some() {
// Context menu takes priority — close it, leave search state intact.
self.context_menu = None;
self.context_menu_pos = None;
} else if self.editor_sound_id.is_some() {
// Editor overlay takes next priority — discard draft and close.
self.editor_sound_id = None;
self.editor_draft_name = String::new();
self.editor_draft_volume = 1.0;
} else if self.effects_panel.is_visible() {
// Drawer absorbs Escape whenever it is on screen — including
// mid-close — so a second Escape never falls through to clear
// the search query. `close` is a no-op if already closing.
self.close_effects_panel_from_escape(Instant::now());
} else if self.search_had_focus {
// First Esc: treat as blur — Iced already handled unfocus.
self.search_had_focus = false;
} else if !self.search_query.is_empty() {
// Second Esc (or Esc when unfocused): clear query.
self.search_query = String::new();
}
Task::none()
}
Message::SearchChanged(query) => {
self.search_had_focus = true;
self.search_query = query;
Task::none()
}
Message::VolumeChanged(v) => {
self.config.volume = v.clamp(0.0, 1.0);
if let Some(ref audio) = self.audio {
audio.send(AudioCommand::SetVolume(self.config.volume));
}
Task::none()
}
Message::VolumeSaveRequested => {
self.persist_config();
Task::none()
}
Message::ShortcutsReady => {
self.shortcuts_status = ShortcutsStatus::Active;
Task::none()
}
Message::ShortcutsUnavailable(reason) => {
self.shortcuts_status = ShortcutsStatus::Unavailable(reason);
Task::none()
}
Message::DismissShortcutsWarning => {
self.shortcuts_warning_dismissed = true;
Task::none()
}
Message::ShortcutActivated(idx) => {
if let Some(path) = self.slots.get(idx).cloned() {
if let Some(sound) = self.sounds.iter().find(|s| s.path == path).cloned() {
return self.request_play(&sound, true);
} else {
// Path no longer in library (file deleted/moved) — clear stale slot
tracing::warn!(
slot = idx + 1,
?path,
"slot points to missing file; clearing stale slot"
);
self.slots.clear(idx);
self.persist_slots();
}
}
Task::none()
}
Message::ShortcutBindingsUpdated(bindings) => {
for (idx, trigger) in bindings {
if let Some(slot) = self.slot_triggers.get_mut(idx as usize) {
*slot = Some(trigger);
}
}
Task::none()
}
Message::DurationsLoaded(map) => {
self.sounds =
crate::state::library::apply_durations(std::mem::take(&mut self.sounds), &map);
self.durations_loaded = true;
Task::none()
}
Message::AssignSlot(idx, path) => {
self.slots.set(idx, path);
self.persist_slots();
Task::none()
}
Message::ClearSlot(idx) => {
self.slots.clear(idx);
self.persist_slots();
Task::none()
}
Message::OpenContextMenu(sound_id) => {
self.context_menu = Some(sound_id);
self.context_menu_pos = Some(self.cursor_pos);
Task::none()
}
Message::CloseContextMenu => {
self.context_menu = None;
self.context_menu_pos = None;
Task::none()
}
Message::CursorMoved(pos) => {
self.cursor_pos = pos;
Task::none()
}
Message::WindowResized(w, h) => {
self.window_size = (w, h);
// Record into config (in-memory only — no disk write per resize
// event); persisted on quit and by any other settings save.
// Degenerate events must not clobber the last real size; NaN
// also fails these comparisons and is skipped.
if w >= MIN_WINDOW_DIMENSION && h >= MIN_WINDOW_DIMENSION {
self.config.window_width = w.round() as u32;
self.config.window_height = h.round() as u32;
}
Task::none()
}
Message::Frame(now) => {
self.tick_frame(now);
Task::none()
}
Message::ShowSlots => {
self.view_mode = ViewMode::SlotManager;
self.selected_slot = None;
Task::none()
}
Message::ShowMain => {
self.view_mode = ViewMode::Main;
self.selected_slot = None;
Task::none()