Skip to main content

euv_core/system/protocol/
impl.rs

1use super::*;
2
3/// Validation and platform manifest generation for `ProtocolRegistration`.
4impl ProtocolRegistration {
5    /// Validates that `scheme` conforms to RFC 3986 and excludes dangerous reserved schemes.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Protocol registration reference.
10    ///
11    /// # Returns
12    ///
13    /// - `bool` - `true` when the custom scheme is valid and safe to register.
14    #[must_use]
15    pub fn is_valid_scheme(&self) -> bool {
16        let lower: String = self.get_scheme().to_ascii_lowercase();
17        let mut chars: Chars<'_> = lower.chars();
18        let Some(first) = chars.next() else {
19            return false;
20        };
21        if !first.is_ascii_alphabetic() {
22            return false;
23        }
24        if !chars.all(|c: char| {
25            c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '-' | '.')
26        }) {
27            return false;
28        }
29        !matches!(
30            lower.as_str(),
31            "http" | "https" | "file" | "javascript" | "data" | "vbscript" | "about"
32        )
33    }
34
35    /// Generates the native OS protocol registration descriptor for `platform`.
36    ///
37    /// # Arguments
38    ///
39    /// - `&Self` - Protocol registration definition.
40    /// - `PlatformKind` - Target platform.
41    ///
42    /// # Returns
43    ///
44    /// - `ProtocolManifestEntry` - Native registration descriptor.
45    #[must_use]
46    pub fn platform_descriptor(&self, platform: PlatformKind) -> ProtocolManifestEntry {
47        let scheme: String = self.get_scheme().to_ascii_lowercase();
48        let bundle: &str = self.get_bundle_id().as_str();
49        let name: &str = self.get_display_name().as_str();
50        let exe: &str = if self.get_executable_path().is_empty() {
51            "%EXE%"
52        } else {
53            self.get_executable_path().as_str()
54        };
55        match platform {
56            PlatformKind::MacOs => ProtocolManifestEntry::new(
57                platform,
58                "LaunchServices / Info.plist CFBundleURLTypes".to_string(),
59                format!(
60                    "CFBundleURLName={bundle}; CFBundleURLSchemes=[{scheme}]; LSSetDefaultHandlerForURLScheme({scheme}, {bundle})"
61                ),
62            ),
63            PlatformKind::Ios | PlatformKind::IpadOs => {
64                let domains: String = self
65                    .get_universal_domains()
66                    .iter()
67                    .map(|d: &String| format!("applinks:{d}"))
68                    .collect::<Vec<String>>()
69                    .join(",");
70                ProtocolManifestEntry::new(
71                    platform,
72                    "UIKit CFBundleURLTypes + Associated Domains".to_string(),
73                    format!("CFBundleURLSchemes=[{scheme}]; AssociatedDomains=[{domains}]"),
74                )
75            }
76            PlatformKind::Windows => ProtocolManifestEntry::new(
77                platform,
78                "Win32 HKCU\\Software\\Classes URL Protocol".to_string(),
79                format!(
80                    "HKCU\\Software\\Classes\\{scheme}\\shell\\open\\command = \"{exe}\" \"%1\" (URL Protocol=\"\", Name=\"{name}\")"
81                ),
82            ),
83            PlatformKind::Linux => ProtocolManifestEntry::new(
84                platform,
85                "XDG Desktop Entry x-scheme-handler".to_string(),
86                format!(
87                    "[Desktop Entry]\nName={name}\nExec={exe} %u\nType=Application\nMimeType=x-scheme-handler/{scheme};"
88                ),
89            ),
90            PlatformKind::Android => ProtocolManifestEntry::new(
91                platform,
92                "AndroidManifest intent-filter VIEW/BROWSABLE".to_string(),
93                format!(
94                    "<intent-filter><action android:name=\"android.intent.action.VIEW\"/><category android:name=\"android.intent.category.DEFAULT\"/><category android:name=\"android.intent.category.BROWSABLE\"/><data android:scheme=\"{scheme}\"/></intent-filter>"
95                ),
96            ),
97            PlatformKind::HarmonyOs => ProtocolManifestEntry::new(
98                platform,
99                PROTO_API_HARMONY.to_string(),
100                format!(
101                    "{{\"skills\":[{{\"actions\":[\"ohos.want.action.viewData\"],\"uris\":[{{\"scheme\":\"{scheme}\",\"host\":\"{bundle}\"}}]}}]}}"
102                ),
103            ),
104            PlatformKind::Wearable => ProtocolManifestEntry::new(
105                platform,
106                PROTO_API_WEARABLE.to_string(),
107                format!("wearable-deeplink://{scheme}/{bundle}"),
108            ),
109            PlatformKind::MiniApp => ProtocolManifestEntry::new(
110                platform,
111                PROTO_API_MINIAPP.to_string(),
112                format!("miniapp://{bundle}?scheme={scheme}"),
113            ),
114            PlatformKind::QuickApp => ProtocolManifestEntry::new(
115                platform,
116                PROTO_API_QUICKAPP.to_string(),
117                format!("hap://app/{bundle}/?scheme={scheme}"),
118            ),
119            PlatformKind::Terminal | PlatformKind::TerminalCli => ProtocolManifestEntry::new(
120                platform,
121                PROTO_API_TERMINAL.to_string(),
122                format!("{exe} --uri {scheme}://"),
123            ),
124            PlatformKind::Web | PlatformKind::Headless => ProtocolManifestEntry::new(
125                platform,
126                "Web navigator.registerProtocolHandler".to_string(),
127                format!("navigator.registerProtocolHandler(\"web+{scheme}\", \"/?uri=%s\")"),
128            ),
129        }
130    }
131}
132
133/// URI parser for `DeepLinkEvent`.
134impl DeepLinkEvent {
135    /// Parses a raw custom-scheme or universal link URL into a structured `DeepLinkEvent`.
136    ///
137    /// # Arguments
138    ///
139    /// - `&str` - Raw incoming URI string (e.g. `"euv://workspace/render?mode=metal"`).
140    ///
141    /// # Returns
142    ///
143    /// - `Result<Self, PlatformError>` - Structured deep link event or validation error.
144    pub fn parse(raw_url: &str) -> Result<Self, PlatformError> {
145        let trimmed: &str = raw_url.trim();
146        let Some((scheme_raw, rest)) = trimmed.split_once("://") else {
147            return Err(PlatformError::Unsupported(
148                "Invalid deep link URI: missing '://' separator".to_string(),
149            ));
150        };
151        let scheme: String = scheme_raw.to_ascii_lowercase();
152        if scheme.is_empty() {
153            return Err(PlatformError::Unsupported(
154                "Invalid deep link URI: empty scheme".to_string(),
155            ));
156        }
157        let (authority_and_path, query_raw): (&str, &str) = match rest.split_once('?') {
158            Some((left, right)) => (left, right),
159            None => (rest, ""),
160        };
161        let (host, path): (String, String) = match authority_and_path.split_once('/') {
162            Some((h, p)) => (h.to_string(), format!("/{p}")),
163            None => (authority_and_path.to_string(), "/".to_string()),
164        };
165        let mut query: HashMap<String, String> = HashMap::new();
166        if !query_raw.is_empty() {
167            for pair in query_raw.split('&') {
168                if pair.is_empty() {
169                    continue;
170                }
171                match pair.split_once('=') {
172                    Some((k, v)) => {
173                        let _: Option<String> = query.insert(k.to_string(), v.to_string());
174                    }
175                    None => {
176                        let _: Option<String> = query.insert(pair.to_string(), String::new());
177                    }
178                }
179            }
180        }
181        Ok(Self::new(trimmed.to_string(), scheme, host, path, query))
182    }
183}
184
185/// Registration and incoming link queuing for `ProtocolRegistry`.
186impl ProtocolRegistry {
187    /// Validates and registers `registration` for `platform`, returning its OS manifest descriptor.
188    ///
189    /// # Arguments
190    ///
191    /// - `&Self` - Mutable protocol registry.
192    /// - `ProtocolRegistration` - Custom protocol specification.
193    /// - `PlatformKind` - Active platform kind.
194    ///
195    /// # Returns
196    ///
197    /// - `Result<ProtocolManifestEntry, PlatformError>` - Generated platform registration descriptor.
198    pub fn register(
199        &mut self,
200        registration: ProtocolRegistration,
201        platform: PlatformKind,
202    ) -> Result<ProtocolManifestEntry, PlatformError> {
203        if !registration.is_valid_scheme() {
204            return Err(PlatformError::Unsupported(format!(
205                "Invalid or reserved custom URL scheme: {}",
206                registration.get_scheme()
207            )));
208        }
209        let entry: ProtocolManifestEntry = registration.platform_descriptor(platform);
210        let scheme_lower: String = registration.get_scheme().to_ascii_lowercase();
211        self.get_mut_registrations()
212            .retain(|existing: &ProtocolRegistration| {
213                existing.get_scheme().to_ascii_lowercase() != scheme_lower
214            });
215        self.get_mut_registrations().push(registration);
216        Ok(entry)
217    }
218
219    /// Returns `true` if `scheme` has been registered.
220    ///
221    /// # Arguments
222    ///
223    /// - `&Self` - Protocol registry reference.
224    /// - `&str` - Scheme name to check.
225    ///
226    /// # Returns
227    ///
228    /// - `bool` - Registration status.
229    #[must_use]
230    pub fn is_registered(&self, scheme: &str) -> bool {
231        let target: String = scheme.to_ascii_lowercase();
232        self.get_registrations()
233            .iter()
234            .any(|reg: &ProtocolRegistration| reg.get_scheme().to_ascii_lowercase() == target)
235    }
236
237    /// Parses and queues a raw incoming deep link URI.
238    ///
239    /// # Arguments
240    ///
241    /// - `&Self` - Mutable protocol registry.
242    /// - `&str` - Raw incoming URI string.
243    ///
244    /// # Returns
245    ///
246    /// - `Result<DeepLinkEvent, PlatformError>` - Parsed deep link event.
247    pub fn push_raw_url(&mut self, raw_url: &str) -> Result<DeepLinkEvent, PlatformError> {
248        let parsed: DeepLinkEvent = DeepLinkEvent::parse(raw_url)?;
249        self.get_mut_pending_links().push(parsed.clone());
250        Ok(parsed)
251    }
252
253    /// Drains all queued deep link events.
254    ///
255    /// # Arguments
256    ///
257    /// - `&Self` - Mutable protocol registry.
258    ///
259    /// # Returns
260    ///
261    /// - `Vec<DeepLinkEvent>` - Drained deep links in arrival order.
262    pub fn drain_links(&mut self) -> Vec<DeepLinkEvent> {
263        take(self.get_mut_pending_links())
264    }
265}