wew 0.1.0

Cross-platform WebView rendering library for rust.
Documentation
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Network request related, including implementing custom request interception.
//!
//! ## Register global custom URL Scheme protocol
//!
//! ```no_run
//! use wew::{
//!     MainThreadMessageLoop, NativeWindowWebView,
//!     request::{
//!         CustomRequestHandlerFactory, CustomSchemeAttributes, RequestHandlerWithLocalDisk,
//!     },
//!     runtime::RuntimeAttributesBuilder,
//! };
//!
//! fn main() {
//!     let runtime_attributes =
//!         RuntimeAttributesBuilder::<MainThreadMessageLoop, NativeWindowWebView>::default()
//!             .register_scheme_handler(CustomSchemeAttributes::new(
//!                 "webview",
//!                 "localhost",
//!                 CustomRequestHandlerFactory::new(RequestHandlerWithLocalDisk::new("/assets")),
//!             ))
//!             .build();
//! }
//! ```
//!
//! This example uses the disk mapping implementation provided by the module to
//! provide the runtime configuration, and registers `webview://localhost` as a
//! custom scheme. When requesting the `webview://localhost/xxx` URL, it will
//! automatically map to the local disk.
//!
//! Of course, you can also implement your own request handler.
//!
//! ---
//!
//! In addition to registering custom scheme protocols globally, you can also
//! use **`request_handler_factory`** in `WebView` to implement custom request
//! handling.

use std::{
    ffi::{CStr, CString, c_void},
    fs::File,
    io::{Read, Seek, SeekFrom},
    path::{Path, PathBuf},
    ptr::null_mut,
    sync::Arc,
};

use url::Url;

use crate::{
    sys,
    utils::{GetSharedRef, ThreadSafePointer},
};

struct LocalDiskRequestHandler {
    file: Option<File>,
    path: PathBuf,
}

impl LocalDiskRequestHandler {
    fn new(path: PathBuf) -> Self {
        Self { file: None, path }
    }
}

impl RequestHandler for LocalDiskRequestHandler {
    fn open(&mut self) -> bool {
        if let Ok(file) = File::open(&self.path) {
            self.file.replace(file);

            true
        } else {
            false
        }
    }

    fn get_response(&mut self) -> Option<Response> {
        Some(Response {
            status_code: 200,
            mime_type: get_mime_type(self.path.as_path())?,
            content_length: self.file.as_ref()?.metadata().ok()?.len(),
        })
    }

    fn skip(&mut self, size: usize) -> Option<usize> {
        Some(
            self.file
                .as_mut()?
                .seek(SeekFrom::Start(size as u64))
                .ok()? as usize,
        )
    }

    fn read(&mut self, buffer: &mut [u8]) -> Option<usize> {
        self.file.as_mut()?.read(buffer).ok()
    }

    fn cancel(&mut self) {
        drop(self.file.take());
    }
}

/// This request handler is used to quickly map to the local file system.
///
/// Used to quickly map to the local file system when you need to quickly map
/// static resource files.
///
/// ## Example
///
/// If your scheme is `webview://localhost`, and the local directory you map is
/// `/assets`, then the redirect examples are as follows:
///
/// ```text
/// webview://localhost -> /assets/index.html
/// webview://localhost/index.html -> /assets/index.html
/// webview://localhost/index.css -> /assets/index.css
/// webview://localhost/images/a.jpg -> /assets/images/a.jpg
/// ```
///
/// Besides using it for custom schemes, you can also use it for `WebView`
/// request interception in the **`request_handler_factory`** of `WebView`.
///
/// Because this request handler will always remove the request protocol header
/// and host, it can be used in different scenarios. For example,
/// `http://localhost/hello/hello.html` actually uses `hello/hello.html`
/// internally.
pub struct RequestHandlerWithLocalDisk {
    root_dir: PathBuf,
}

impl RequestHandlerWithLocalDisk {
    /// Create a request handler
    ///
    /// This method is used to create a request handler. You need to
    /// provide a root directory, and files under this root directory will be
    /// mapped to the request.
    pub fn new(root_dir: &str) -> Self {
        Self {
            root_dir: PathBuf::from(root_dir),
        }
    }
}

impl RequestHandlerFactory for RequestHandlerWithLocalDisk {
    fn request(&self, request: &Request) -> Option<Box<dyn RequestHandler>> {
        let url = if request.url.is_empty() {
            "http://localhost/index.html"
        } else {
            request.url
        };

        let mut path = Url::parse(url).ok()?.path().to_string();
        if path.starts_with("/") {
            path = path[1..].to_string();
        }

        Some(Box::new(LocalDiskRequestHandler::new(
            self.root_dir.join(path),
        )))
    }
}

/// Request information
#[derive(Debug)]
pub struct Request<'a> {
    /// Request URL
    pub url: &'a str,
    /// Request method
    pub method: &'a str,
    /// Request referrer
    pub referrer: &'a str,
}

impl<'a> Request<'a> {
    fn from_raw_ptr(request: *mut sys::Request) -> Option<Self> {
        let request = unsafe { &*request };

        Some(Self {
            url: unsafe { CStr::from_ptr(request.url).to_str().ok()? },
            method: unsafe { CStr::from_ptr(request.method).to_str().ok()? },
            referrer: unsafe { CStr::from_ptr(request.referrer).to_str().ok()? },
        })
    }
}

/// Response information
#[repr(C)]
#[derive(Debug)]
pub struct Response {
    /// Response status code
    pub status_code: u32,
    /// Response content length
    pub content_length: u64,
    /// Response MIME type
    pub mime_type: String,
}

/// Request handler
///
/// This is mainly used to handle requests. You can implement custom request
/// handling through this interface.
pub trait RequestHandler: Send + Sync {
    /// Open request
    ///
    /// This method is used to open a request. You can open files, network
    /// resources, etc. in this method.
    ///
    /// If opening fails, return `false`, otherwise return `true`.
    ///
    /// This method is generally called first.
    fn open(&mut self) -> bool;

    /// Get response
    ///
    /// This method is used to get the response. You can return response
    /// content, status code, etc. in this method.
    ///
    /// If getting fails, return `None`, otherwise return `Some(Response)`.
    ///
    /// This method is generally called after the `open` method.
    fn get_response(&mut self) -> Option<Response>;

    /// Skip content
    ///
    /// This method is used to skip response content. You can skip response
    /// content in this method.
    ///
    /// If skipping fails, return `None`, otherwise return `Some(usize)`, and
    /// the returned length is the skipped length.
    ///
    /// This method is generally called after the `open` method.
    fn skip(&mut self, size: usize) -> Option<usize>;

    /// Read response
    ///
    /// This method is used to read the response. You can read response content
    /// in this method.
    ///
    /// If reading fails, return `None`, otherwise return `Some(usize)`, and the
    /// returned length is the read length.
    ///
    /// This method is generally called after the `open` method.
    fn read(&mut self, buffer: &mut [u8]) -> Option<usize>;

    /// Cancel request
    ///
    /// This method is used to cancel the request. You can cancel the request in
    /// this method. When the request ends, this method will be called.
    fn cancel(&mut self);
}

/// Implement request handling for dynamic types
impl RequestHandler for Box<dyn RequestHandler> {
    fn open(&mut self) -> bool {
        self.as_mut().open()
    }

    fn get_response(&mut self) -> Option<Response> {
        self.as_mut().get_response()
    }

    fn skip(&mut self, size: usize) -> Option<usize> {
        self.as_mut().skip(size)
    }

    fn read(&mut self, buffer: &mut [u8]) -> Option<usize> {
        self.as_mut().read(buffer)
    }

    fn cancel(&mut self) {
        self.as_mut().cancel()
    }
}

/// Custom Scheme handler factory
///
/// This interface is used to handle custom Scheme requests.
pub trait RequestHandlerFactory: Send + Sync {
    /// Handle request
    ///
    /// This method is used to handle requests. You can return request handling
    /// in this method.
    ///
    /// If you don't handle this request, return `None`, otherwise return a
    /// request handler.
    fn request(&self, request: &Request) -> Option<Box<dyn RequestHandler>>;
}

/// Custom Scheme attributes
pub struct CustomSchemeAttributes {
    pub(crate) name: CString,
    pub(crate) domain: CString,
    pub(crate) handler: CustomRequestHandlerFactory,
}

impl<'a> CustomSchemeAttributes {
    /// Create custom Scheme attributes
    ///
    /// This method is used to create custom Scheme attributes. You need to
    /// provide the Scheme name, domain, and handler.
    ///
    /// The name is the Scheme name, the domain is the Scheme domain, and the
    /// handler is the program used to handle requests.
    pub fn new(name: &'a str, domain: &'a str, handler: CustomRequestHandlerFactory) -> Self {
        Self {
            domain: CString::new(domain).unwrap(),
            name: CString::new(name).unwrap(),
            handler,
        }
    }
}

pub(crate) struct ICustomRequestHandlerFactory {
    raw: ThreadSafePointer<Box<dyn RequestHandlerFactory>>,
    raw_handler: ThreadSafePointer<sys::RequestHandlerFactory>,
}

impl Drop for ICustomRequestHandlerFactory {
    fn drop(&mut self) {
        drop(unsafe { Box::from_raw(self.raw.as_ptr()) });
    }
}

/// Custom Scheme handler
///
/// This struct is used to handle custom Scheme requests.
#[derive(Clone)]
pub struct CustomRequestHandlerFactory(Arc<ICustomRequestHandlerFactory>);

impl CustomRequestHandlerFactory {
    pub fn new<T>(handler: T) -> Self
    where
        T: RequestHandlerFactory + 'static,
    {
        let raw: *mut Box<dyn RequestHandlerFactory> = Box::into_raw(Box::new(Box::new(handler)));
        let raw_handler = Box::into_raw(Box::new(sys::RequestHandlerFactory {
            request: Some(on_create_request_handler),
            destroy_request_handler: Some(on_destroy_request_handler),
            context: raw as _,
        }));

        Self(Arc::new(ICustomRequestHandlerFactory {
            raw: ThreadSafePointer::new(raw),
            raw_handler: ThreadSafePointer::new(raw_handler),
        }))
    }

    pub(crate) fn as_raw(&self) -> &ThreadSafePointer<sys::RequestHandlerFactory> {
        &self.0.raw_handler
    }
}

impl GetSharedRef for CustomRequestHandlerFactory {
    type Ref = Arc<ICustomRequestHandlerFactory>;

    fn get_shared_ref(&self) -> Self::Ref {
        self.0.clone()
    }
}

/// Used to get the MIME type of a file
fn get_mime_type(path: &Path) -> Option<String> {
    Some(
        mime_guess::from_ext(path.extension()?.to_str()?)
            .first()?
            .to_string(),
    )
}

extern "C" fn on_create_request_handler(
    request: *mut sys::Request,
    context: *mut c_void,
) -> *mut sys::RequestHandler {
    if request.is_null() {
        return null_mut();
    }

    if let Some(request) = Request::from_raw_ptr(request) {
        if let Some(handler) =
            unsafe { &*(context as *mut Box<dyn RequestHandlerFactory>) }.request(&request)
        {
            return Box::into_raw(Box::new(sys::RequestHandler {
                open: Some(on_open),
                skip: Some(on_skip),
                read: Some(on_read),
                cancel: Some(on_cancel),
                destroy: Some(on_destroy),
                get_response: Some(on_get_response),
                context: Box::into_raw(Box::new(handler)) as _,
            })) as _;
        }
    }

    null_mut()
}

// This is to destroy `RequestHandler`, not to destroy `SchemeHandlerFactory`.
extern "C" fn on_destroy_request_handler(handler: *mut sys::RequestHandler) {
    drop(unsafe { Box::from_raw(handler) });
}

extern "C" fn on_open(context: *mut c_void) -> bool {
    unsafe { &mut *(context as *mut Box<dyn RequestHandler>) }.open()
}

extern "C" fn on_get_response(response: *mut sys::Response, context: *mut c_void) {
    let response = unsafe { &mut *response };

    // Default return 404 response.
    let res = unsafe { &mut *(context as *mut Box<dyn RequestHandler>) }
        .get_response()
        .unwrap_or_else(|| Response {
            status_code: 404,
            content_length: 0,
            mime_type: "text/plain".to_string(),
        });

    {
        let mime_type_bytes = res.mime_type.as_bytes();
        let mime_type_len = mime_type_bytes.len().min(254);

        unsafe {
            std::ptr::copy_nonoverlapping(
                mime_type_bytes.as_ptr(),
                response.mime_type as *mut u8,
                mime_type_len,
            );

            *(response.mime_type.add(mime_type_len) as *mut u8) = 0;
        }
    }

    response.status_code = res.status_code as i32;
    response.content_length = res.content_length;
}

extern "C" fn on_skip(size: usize, skip_bytes: *mut i32, context: *mut c_void) -> bool {
    let skip_bytes = unsafe { &mut *skip_bytes };

    if let Some(len) = unsafe { &mut *(context as *mut Box<dyn RequestHandler>) }.skip(size) {
        *skip_bytes = len as i32;

        true
    } else {
        // If skipping fails, set |skip_bytes| to -2 and return false.
        *skip_bytes = -2;

        false
    }
}

extern "C" fn on_read(
    buffer: *mut u8,
    size: usize,
    read_bytes: *mut i32,
    context: *mut c_void,
) -> bool {
    let read_bytes = unsafe { &mut *read_bytes };

    if let Some(len) = unsafe { &mut *(context as *mut Box<dyn RequestHandler>) }
        .read(unsafe { std::slice::from_raw_parts_mut(buffer, size) })
    {
        *read_bytes = len as i32;

        // If the end of the response is reached, return false.
        len > 0
    } else {
        // If reading fails, set |read_bytes| to -2 and return false.
        *read_bytes = -2;

        false
    }
}

extern "C" fn on_cancel(context: *mut c_void) {
    unsafe { &mut *(context as *mut Box<dyn RequestHandler>) }.cancel();
}

// Destroy `RequestHandler`
extern "C" fn on_destroy(context: *mut c_void) {
    drop(unsafe { Box::from_raw(context as *mut Box<dyn RequestHandler>) });
}