lingxia-webview 0.4.3

WebView abstraction layer for LingXia framework (Android, iOS, HarmonyOS)
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
use crate::webview::{WebTag, find_webview};
use crate::{WebResourceBody, WebResourceResponse};
use objc2::runtime::{AnyObject, NSObject, Sel};
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, rc::Retained};
use objc2_foundation::{NSData, NSMutableDictionary, NSObjectProtocol, NSString};
use objc2_web_kit::WKURLSchemeHandler;
use std::fs::File;
use std::io::Read;
#[cfg(unix)]
use std::os::fd::FromRawFd;

#[inline]
unsafe fn nsdata_bytes_ptr_unchecked(ns_data: *mut AnyObject) -> *const u8 {
    // Avoid objc2's debug-time method signature verification for `-[NSData bytes]`.
    //
    // On some Apple OS versions, the runtime type encoding for this method can
    // differ from what headers declare, causing a panic in debug builds.
    let sel: Sel = objc2::sel!(bytes);
    let func: unsafe extern "C" fn(*mut AnyObject, Sel) -> *const core::ffi::c_void =
        unsafe { core::mem::transmute(objc2::ffi::objc_msgSend as *const ()) };
    unsafe { func(ns_data, sel) }.cast()
}
// Define ivars struct first
#[derive(Debug)]
pub(super) struct LingXiaSchemeHandlerIvars {
    webtag: WebTag,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[name = "LingXiaSchemeHandler"]
    #[thread_kind = MainThreadOnly]
    #[ivars = LingXiaSchemeHandlerIvars]
    pub(super) struct LingXiaSchemeHandler;

    unsafe impl NSObjectProtocol for LingXiaSchemeHandler {}

    unsafe impl WKURLSchemeHandler for LingXiaSchemeHandler {
        #[unsafe(method(webView:startURLSchemeTask:))]
        fn start_url_scheme_task(&self, _webview: *mut AnyObject, task: *mut AnyObject) {
            if task.is_null() {
                log::error!("Task is null!");
                return;
            }

            unsafe {
                // Extract request information from the task
                let request: *mut AnyObject = msg_send![task, request];
                if request.is_null() {
                    log::error!("Request is null");
                    self.fail_task_with_error(task, "Request is null");
                    return;
                }

                // Get URL string
                let url_obj: *mut AnyObject = msg_send![request, URL];
                if url_obj.is_null() {
                    log::error!("URL object is null");
                    self.fail_task_with_error(task, "URL object is null");
                    return;
                }

                let url_string: *mut AnyObject = msg_send![url_obj, absoluteString];
                if url_string.is_null() {
                    log::error!("URL string is null");
                    self.fail_task_with_error(task, "URL string is null");
                    return;
                }

                let url_cstring: *const std::ffi::c_char = msg_send![url_string, UTF8String];
                if url_cstring.is_null() {
                    log::error!("URL C string is null");
                    self.fail_task_with_error(task, "URL C string is null");
                    return;
                }

                let url = std::ffi::CStr::from_ptr(url_cstring)
                    .to_string_lossy()
                    .to_string();

                // Get HTTP method
                let method_obj: *mut AnyObject = msg_send![request, HTTPMethod];
                let method = if method_obj.is_null() {
                    log::warn!("HTTP method is null, defaulting to GET");
                    "GET".to_string()
                } else {
                    let method_cstring: *const std::ffi::c_char = msg_send![method_obj, UTF8String];
                    if method_cstring.is_null() {
                        log::warn!("HTTP method C string is null, defaulting to GET");
                        "GET".to_string()
                    } else {
                        std::ffi::CStr::from_ptr(method_cstring)
                            .to_string_lossy()
                            .to_string()
                    }
                };

                // Extract scheme from URL
                let scheme = url.split("://").next().unwrap_or("").to_string();

                log::info!("Processing {}:// request: {} {}", scheme, method, url);

                // Get request body
                let mut body = vec![];
                let body_data: *mut AnyObject = msg_send![request, HTTPBody];
                if !body_data.is_null() {
                    let length: usize = msg_send![body_data, length];
                    if length > 0 {
                        let bytes_ptr: *const u8 = nsdata_bytes_ptr_unchecked(body_data);
                        if !bytes_ptr.is_null() {
                            body = std::slice::from_raw_parts(bytes_ptr, length).to_vec();
                        }
                    }
                }

                // Create http::Request and add headers directly (more efficient)
                let mut builder = http::Request::builder()
                    .method(method.as_str())
                    .uri(url.as_str());

                // Add headers directly to builder without intermediate storage
                let headers_dict: *mut AnyObject = msg_send![request, allHTTPHeaderFields];
                if !headers_dict.is_null() {
                    let keys_array: *mut AnyObject = msg_send![headers_dict, allKeys];
                    let values_array: *mut AnyObject = msg_send![headers_dict, allValues];

                    if !keys_array.is_null() && !values_array.is_null() {
                        let count: usize = msg_send![keys_array, count];

                        for i in 0..count {
                            let key_obj: *mut AnyObject = msg_send![keys_array, objectAtIndex: i];
                            let value_obj: *mut AnyObject =
                                msg_send![values_array, objectAtIndex: i];

                            if !key_obj.is_null() && !value_obj.is_null() {
                                let key_cstring: *const std::ffi::c_char =
                                    msg_send![key_obj, UTF8String];
                                let value_cstring: *const std::ffi::c_char =
                                    msg_send![value_obj, UTF8String];

                                if !key_cstring.is_null() && !value_cstring.is_null() {
                                    let key =
                                        std::ffi::CStr::from_ptr(key_cstring).to_string_lossy();
                                    let value =
                                        std::ffi::CStr::from_ptr(value_cstring).to_string_lossy();

                                    if let (Ok(header_name), Ok(header_value)) = (
                                        key.parse::<http::header::HeaderName>(),
                                        value.parse::<http::header::HeaderValue>(),
                                    ) {
                                        builder = builder.header(header_name, header_value);
                                    }
                                }
                            }
                        }
                    }
                }

                let http_request = match builder.body(body) {
                    Ok(req) => req,
                    Err(e) => {
                        log::error!("Failed to build HTTP request: {}", e);
                        self.fail_task_with_error(task, "Failed to build HTTP request");
                        return;
                    }
                };

                // Dispatch to closure-based scheme handler
                let webtag = &self.ivars().webtag;
                let response = if let Some(webview) = find_webview(webtag) {
                    webview.handle_scheme_request(&scheme, http_request)
                } else {
                    None
                };
                match response {
                    Some(http_response) => {
                        log::debug!(
                            "Got response from scheme handler, status: {}",
                            http_response.parts().status,
                        );
                        self.send_response_to_task(task, http_response, request);
                    }
                    None => {
                        log::warn!("Scheme handler returned None, sending 404");
                        self.send_404_response(task, request);
                    }
                }
            }
        }

        #[unsafe(method(webView:stopURLSchemeTask:))]
        fn stop_url_scheme_task(&self, _webview: *mut AnyObject, _task: *mut AnyObject) {
            log::debug!("Stopped lx:// request");
        }
    }
);

impl LingXiaSchemeHandler {
    /// Create a new LingXiaSchemeHandler bound to a specific WebView
    pub(super) fn new(webtag: WebTag) -> Option<Retained<Self>> {
        log::debug!(
            "Creating LingXiaSchemeHandler for webtag: {}",
            webtag.as_str()
        );

        let mtm = match MainThreadMarker::new() {
            Some(marker) => marker,
            None => {
                log::error!("Not on main thread when creating scheme handler");
                return None;
            }
        };

        unsafe {
            let instance = Self::alloc(mtm);
            let instance = instance.set_ivars(LingXiaSchemeHandlerIvars { webtag });
            let instance: Retained<Self> = msg_send![super(instance), init];
            log::debug!("Successfully created LingXiaSchemeHandler");
            Some(instance)
        }
    }

    /// Send a successful response to the URL scheme task
    fn send_response_to_task(
        &self,
        task: *mut AnyObject,
        response: WebResourceResponse,
        request: *mut AnyObject,
    ) {
        unsafe {
            let (parts, body) = response.into_parts();
            let status = parts.status;
            let mut headers_map = parts.headers.clone();

            let url_obj: *mut AnyObject = msg_send![request, URL];
            let status_code = status.as_u16() as i64;
            let http_version = NSString::from_str("HTTP/1.1");
            let headers = NSMutableDictionary::new();

            let content_type = headers_map
                .get("content-type")
                .and_then(|v| v.to_str().ok())
                .unwrap_or("application/octet-stream");

            let content_type_key = NSString::from_str("Content-Type");
            let content_type_with_charset = if content_type == "text/html" {
                "text/html; charset=UTF-8"
            } else {
                content_type
            };
            let content_type_value = NSString::from_str(content_type_with_charset);
            headers.insert(&*content_type_key, &*content_type_value);

            if !headers_map.contains_key("content-length") {
                let content_len = match &body {
                    WebResourceBody::Path(path) => std::fs::metadata(path).ok().map(|m| m.len()),
                    WebResourceBody::Bytes(data) => Some(data.len() as u64),
                    WebResourceBody::Pipe(_) => None,
                };
                if let Some(len) = content_len
                    && let Ok(value) = http::HeaderValue::from_str(&len.to_string())
                {
                    headers_map.insert(http::header::CONTENT_LENGTH, value);
                }
            }

            for (key, value) in headers_map.iter() {
                if let Ok(value_str) = value.to_str() {
                    let key_ns = NSString::from_str(key.as_str());
                    let value_ns = NSString::from_str(value_str);
                    headers.insert(&*key_ns, &*value_ns);
                }
            }

            let response_class: *mut AnyObject = msg_send![objc2::class!(NSHTTPURLResponse), alloc];
            let response_result: *mut AnyObject = msg_send![response_class,
            initWithURL: url_obj,
            statusCode: status_code,
            HTTPVersion: &*http_version,
            headerFields: &*headers];

            if response_result.is_null() {
                log::error!("Failed to create NSHTTPURLResponse using msg_send approach!");
                self.fail_task_with_error(task, "Failed to create HTTP response");
                return;
            }

            let _: () = msg_send![task, didReceiveResponse: response_result];

            match body {
                WebResourceBody::Path(path) => {
                    let mut reader: Box<dyn std::io::Read> = match File::open(&path) {
                        Ok(file) => Box::new(file),
                        Err(e) => {
                            log::error!("Failed to open response file {}: {}", path.display(), e);
                            self.fail_task_with_error(task, "Failed to open response file");
                            return;
                        }
                    };

                    let mut buffer = [0u8; 64 * 1024];
                    loop {
                        match reader.read(&mut buffer) {
                            Ok(0) => {
                                let _: () = msg_send![task, didFinish];
                                break;
                            }
                            Ok(read_bytes) => {
                                let chunk = NSData::from_vec(buffer[..read_bytes].to_vec());
                                let _: () = msg_send![task, didReceiveData: &*chunk];
                            }
                            Err(e) => {
                                log::error!("Failed while streaming response data: {}", e);
                                self.fail_task_with_error(task, "Failed to read response data");
                                return;
                            }
                        }
                    }
                }
                WebResourceBody::Pipe(pipe) => {
                    #[cfg(unix)]
                    {
                        let mut reader: Box<dyn std::io::Read> = {
                            let fd = pipe.into_raw_fd();
                            let file = File::from_raw_fd(fd);
                            Box::new(file)
                        };

                        let mut buffer = [0u8; 64 * 1024];
                        loop {
                            match reader.read(&mut buffer) {
                                Ok(0) => {
                                    let _: () = msg_send![task, didFinish];
                                    break;
                                }
                                Ok(read_bytes) => {
                                    let chunk = NSData::from_vec(buffer[..read_bytes].to_vec());
                                    let _: () = msg_send![task, didReceiveData: &*chunk];
                                }
                                Err(e) => {
                                    log::error!("Failed while streaming response data: {}", e);
                                    self.fail_task_with_error(task, "Failed to read response data");
                                    return;
                                }
                            }
                        }
                    }
                    #[cfg(not(unix))]
                    {
                        log::error!("Pipe bodies are not supported on this platform");
                        self.fail_task_with_error(task, "Pipe body unsupported");
                        return;
                    }
                }
                WebResourceBody::Bytes(data) => {
                    if !data.is_empty() {
                        let chunk = NSData::from_vec(data);
                        let _: () = msg_send![task, didReceiveData: &*chunk];
                    }
                    let _: () = msg_send![task, didFinish];
                }
            }
        }
    }

    /// Send a 404 response to the URL scheme task
    fn send_404_response(&self, task: *mut AnyObject, request: *mut AnyObject) {
        unsafe {
            // Get the original request URL for creating the response
            let url_obj: *mut AnyObject = msg_send![request, URL];

            // Create a 404 HTTP response with proper HTTP version using wry method
            let status_code = 404i64;
            let http_version = NSString::from_str("HTTP/1.1");

            // Create headers dictionary for 404 response like Swift version
            let headers = NSMutableDictionary::new();
            let content_type_key = NSString::from_str("Content-Type");
            let content_type_value = NSString::from_str("text/plain");
            headers.insert(&*content_type_key, &*content_type_value);

            // Create 404 response using same approach as successful response
            let response_class: *mut AnyObject = msg_send![objc2::class!(NSHTTPURLResponse), alloc];
            let response_result: *mut AnyObject = msg_send![response_class,
                initWithURL: url_obj,
                statusCode: status_code,
                HTTPVersion: &*http_version,
                headerFields: &*headers];

            let body_data = NSData::from_vec("Not Found".as_bytes().to_vec());

            if !response_result.is_null() {
                // Send response to WebView - use correct method names from wry
                let _: () = msg_send![task, didReceiveResponse: response_result];
                let _: () = msg_send![task, didReceiveData: &*body_data];
                let _: () = msg_send![task, didFinish];
            } else {
                log::error!("Failed to create 404 response");
                let _: () = msg_send![task, didFinish];
            }
        }
    }

    /// Fail the task with an error
    fn fail_task_with_error(&self, task: *mut AnyObject, error_message: &str) {
        unsafe {
            // Create a proper error response with status code
            let error_html = format!(
                "<html><body><h1>Error</h1><p>{}</p></body></html>",
                error_message
            );
            let body_data = NSData::from_vec(error_html.as_bytes().to_vec());

            // Create a 500 error response
            let response_class: *mut AnyObject = msg_send![objc2::class!(NSHTTPURLResponse), alloc];
            let http_version = NSString::from_str("HTTP/1.1");
            let headers = NSMutableDictionary::new();

            let content_type_key = NSString::from_str("Content-Type");
            let content_type_value = NSString::from_str("text/html; charset=UTF-8");
            headers.insert(&*content_type_key, &*content_type_value);

            // Get URL from the task
            let request: *mut AnyObject = msg_send![task, request];
            let url_obj: *mut AnyObject = msg_send![request, URL];

            let response_result: *mut AnyObject = msg_send![response_class,
                initWithURL: url_obj,
                statusCode: 500i64,
                HTTPVersion: &*http_version,
                headerFields: &*headers];

            if !response_result.is_null() {
                let _: () = msg_send![task, didReceiveResponse: response_result];
                let _: () = msg_send![task, didReceiveData: &*body_data];
                let _: () = msg_send![task, didFinish];
            } else {
                // Last resort - just send data and finish
                let _: () = msg_send![task, didReceiveData: &*body_data];
                let _: () = msg_send![task, didFinish];
            }

            log::error!("SchemeHandler error: {}", error_message);
        }
    }
}