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::Web | PlatformKind::Headless => ProtocolManifestEntry::new(
98                platform,
99                "Web navigator.registerProtocolHandler".to_string(),
100                format!("navigator.registerProtocolHandler(\"web+{scheme}\", \"/?uri=%s\")"),
101            ),
102        }
103    }
104}
105
106/// URI parser for `DeepLinkEvent`.
107impl DeepLinkEvent {
108    /// Parses a raw custom-scheme or universal link URL into a structured `DeepLinkEvent`.
109    ///
110    /// # Arguments
111    ///
112    /// - `&str` - Raw incoming URI string (e.g. `"euv://workspace/render?mode=metal"`).
113    ///
114    /// # Returns
115    ///
116    /// - `Result<Self, PlatformError>` - Structured deep link event or validation error.
117    pub fn parse(raw_url: &str) -> Result<Self, PlatformError> {
118        let trimmed: &str = raw_url.trim();
119        let Some((scheme_raw, rest)) = trimmed.split_once("://") else {
120            return Err(PlatformError::Unsupported(
121                "Invalid deep link URI: missing '://' separator".to_string(),
122            ));
123        };
124        let scheme: String = scheme_raw.to_ascii_lowercase();
125        if scheme.is_empty() {
126            return Err(PlatformError::Unsupported(
127                "Invalid deep link URI: empty scheme".to_string(),
128            ));
129        }
130        let (authority_and_path, query_raw): (&str, &str) = match rest.split_once('?') {
131            Some((left, right)) => (left, right),
132            None => (rest, ""),
133        };
134        let (host, path): (String, String) = match authority_and_path.split_once('/') {
135            Some((h, p)) => (h.to_string(), format!("/{p}")),
136            None => (authority_and_path.to_string(), "/".to_string()),
137        };
138        let mut query: HashMap<String, String> = HashMap::new();
139        if !query_raw.is_empty() {
140            for pair in query_raw.split('&') {
141                if pair.is_empty() {
142                    continue;
143                }
144                match pair.split_once('=') {
145                    Some((k, v)) => {
146                        let _: Option<String> = query.insert(k.to_string(), v.to_string());
147                    }
148                    None => {
149                        let _: Option<String> = query.insert(pair.to_string(), String::new());
150                    }
151                }
152            }
153        }
154        Ok(Self::new(trimmed.to_string(), scheme, host, path, query))
155    }
156}
157
158/// Registration and incoming link queuing for `ProtocolRegistry`.
159impl ProtocolRegistry {
160    /// Validates and registers `registration` for `platform`, returning its OS manifest descriptor.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - Mutable protocol registry.
165    /// - `ProtocolRegistration` - Custom protocol specification.
166    /// - `PlatformKind` - Active platform kind.
167    ///
168    /// # Returns
169    ///
170    /// - `Result<ProtocolManifestEntry, PlatformError>` - Generated platform registration descriptor.
171    pub fn register(
172        &mut self,
173        registration: ProtocolRegistration,
174        platform: PlatformKind,
175    ) -> Result<ProtocolManifestEntry, PlatformError> {
176        if !registration.is_valid_scheme() {
177            return Err(PlatformError::Unsupported(format!(
178                "Invalid or reserved custom URL scheme: {}",
179                registration.get_scheme()
180            )));
181        }
182        let entry: ProtocolManifestEntry = registration.platform_descriptor(platform);
183        let scheme_lower: String = registration.get_scheme().to_ascii_lowercase();
184        self.get_mut_registrations()
185            .retain(|existing: &ProtocolRegistration| {
186                existing.get_scheme().to_ascii_lowercase() != scheme_lower
187            });
188        self.get_mut_registrations().push(registration);
189        Ok(entry)
190    }
191
192    /// Returns `true` if `scheme` has been registered.
193    ///
194    /// # Arguments
195    ///
196    /// - `&Self` - Protocol registry reference.
197    /// - `&str` - Scheme name to check.
198    ///
199    /// # Returns
200    ///
201    /// - `bool` - Registration status.
202    #[must_use]
203    pub fn is_registered(&self, scheme: &str) -> bool {
204        let target: String = scheme.to_ascii_lowercase();
205        self.get_registrations()
206            .iter()
207            .any(|reg: &ProtocolRegistration| reg.get_scheme().to_ascii_lowercase() == target)
208    }
209
210    /// Parses and queues a raw incoming deep link URI.
211    ///
212    /// # Arguments
213    ///
214    /// - `&Self` - Mutable protocol registry.
215    /// - `&str` - Raw incoming URI string.
216    ///
217    /// # Returns
218    ///
219    /// - `Result<DeepLinkEvent, PlatformError>` - Parsed deep link event.
220    pub fn push_raw_url(&mut self, raw_url: &str) -> Result<DeepLinkEvent, PlatformError> {
221        let parsed: DeepLinkEvent = DeepLinkEvent::parse(raw_url)?;
222        self.get_mut_pending_links().push(parsed.clone());
223        Ok(parsed)
224    }
225
226    /// Drains all queued deep link events.
227    ///
228    /// # Arguments
229    ///
230    /// - `&Self` - Mutable protocol registry.
231    ///
232    /// # Returns
233    ///
234    /// - `Vec<DeepLinkEvent>` - Drained deep links in arrival order.
235    pub fn drain_links(&mut self) -> Vec<DeepLinkEvent> {
236        take(self.get_mut_pending_links())
237    }
238}