BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / speech / system / mod.rs

mod.rs

mod.rs 2.4 KiB Download Raw
1//! The platform's own speech recognizer.
2
3use std::{cell::OnceCell, rc::Rc};
4
5use gpui::{App, SharedString};
6
7use super::{AudioFormat, RecognitionSession, SpeechError, SpeechRecognizer, SpeechSink};
8
9#[cfg(target_os = "macos")]
10pub(super) mod macos;
11#[cfg(target_os = "macos")]
12use macos as platform;
13
14#[cfg(target_os = "windows")]
15mod winrt;
16#[cfg(target_os = "windows")]
17use winrt as platform;
18
19#[cfg(not(any(target_os = "macos", target_os = "windows")))]
20mod unsupported;
21#[cfg(not(any(target_os = "macos", target_os = "windows")))]
22use unsupported as platform;
23
24/// The operating system's speech recognizer.
25///
26/// - **macOS**: `SFSpeechRecognizer`, recognizing on the device only. A
27/// language the device cannot recognize offline is not available, so audio
28/// never leaves the machine.
29/// - **Windows**: `Windows.Media.SpeechRecognition`. Dictation needs the
30/// language's speech pack and the "Online speech recognition" privacy
31/// setting, and runs through Microsoft's online service.
32/// - **Other platforms**: never available.
33///
34/// A [`SpeechState`](super::SpeechState) without its own recognizer uses this
35/// one; create it directly to choose the language.
36pub struct SystemRecognizer {
37 locale: Option<SharedString>,
38 platform: OnceCell<Rc<platform::PlatformRecognizer>>,
39}
40
41impl SystemRecognizer {
42 /// A recognizer for the system's current language.
43 pub fn new() -> Self {
44 Self {
45 locale: None,
46 platform: OnceCell::new(),
47 }
48 }
49
50 /// Recognize `locale`, a BCP 47 language tag such as `en-US` or `zh-CN`,
51 /// instead of the system's language.
52 pub fn locale(mut self, locale: impl Into<SharedString>) -> Self {
53 self.locale = Some(locale.into());
54 self.platform = OnceCell::new();
55 self
56 }
57
58 fn platform(&self) -> &Rc<platform::PlatformRecognizer> {
59 self.platform
60 .get_or_init(|| Rc::new(platform::PlatformRecognizer::new(self.locale.clone())))
61 }
62}
63
64impl Default for SystemRecognizer {
65 fn default() -> Self {
66 Self::new()
67 }
68}
69
70impl SpeechRecognizer for SystemRecognizer {
71 fn audio_format(&self) -> AudioFormat {
72 self.platform().audio_format()
73 }
74
75 fn is_available(&self, cx: &App) -> bool {
76 self.platform().is_available(cx)
77 }
78
79 fn start(
80 &self,
81 sink: SpeechSink,
82 cx: &mut App,
83 ) -> Result<Box<dyn RecognitionSession>, SpeechError> {
84 self.platform().start(sink, cx)
85 }
86}