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