Skip to content

Commit

Permalink
Add mimetype to return type of custom protocol (#296)
Browse files Browse the repository at this point in the history
* Add mimetype to return type of custom protocol

* Fix macOS
  • Loading branch information
Ngo Iok Ui (Wu Yu Wei) authored Jun 13, 2021
1 parent 761b2b5 commit cc9fc4b
Show file tree
Hide file tree
Showing 9 changed files with 35 additions and 147 deletions.
5 changes: 5 additions & 0 deletions .changes/mime.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wry": minor
---

Update signature of custom protocol closure. It should return a mime type string now.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ serde = { version = "1.0", features = [ "derive" ] }
serde_json = "1.0"
thiserror = "1.0"
url = "2.2"
infer = "0.4"
tao = { version = "0.2.6", default-features = false, features = [ "serde" ] }

[dev-dependencies]
Expand Down
6 changes: 3 additions & 3 deletions examples/custom_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ fn main() -> wry::Result<()> {

match requested_asset_path.as_str() {
// if our path match /hello.html
"/hello.html" => Ok(hello_html.as_bytes().into()),
"/hello.html" => Ok((hello_html.as_bytes().into(), "text/html".into())),
// if our path match /hello.js
"/hello.js" => Ok(hello_js.as_bytes().into()),
"/hello.js" => Ok((hello_js.as_bytes().into(), "text/javascript".into())),
// other paths should resolve index
// more logic can be applied here
_ => Ok(index_html.as_bytes().into()),
_ => Ok((index_html.as_bytes().into(), "text/html".into())),
}
})
// tell the webview to load the custom protocol
Expand Down
122 changes: 0 additions & 122 deletions src/webview/mimetype.rs

This file was deleted.

20 changes: 15 additions & 5 deletions src/webview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

//! [`WebView`] struct and associated types.
mod mimetype;
mod web_context;

pub use web_context::WebContext;
Expand Down Expand Up @@ -47,8 +46,15 @@ pub struct WebViewAttributes {
/// initialization code will be executed. It is guaranteed that code is executed before
/// `window.onload`.
pub initialization_scripts: Vec<String>,
/// Register custom file loading protocol
pub custom_protocols: Vec<(String, Box<dyn Fn(&Window, &str) -> Result<Vec<u8>>>)>,
/// Register custom file loading protocols with pairs of scheme uri string and a handling
/// closure.
///
/// The closure takes the `Window` and a url string slice as parameters, and returns a tuple of a
/// vector of bytes which is the content and a mimetype string of the conten.
pub custom_protocols: Vec<(
String,
Box<dyn Fn(&Window, &str) -> Result<(Vec<u8>, String)>>,
)>,
/// Set the RPC handler to Communicate between the host Rust code and Javascript on webview.
///
/// The communication is done via [JSON-RPC](https://www.jsonrpc.org). Users can use this to register an incoming
Expand Down Expand Up @@ -129,11 +135,15 @@ impl WebViewBuilder {
self
}

/// Register custom file loading protocol
/// Register custom file loading protocols with pairs of scheme uri string and a handling
/// closure.
///
/// The closure takes the `Window` and a url string slice as parameters, and returns a tuple of a
/// vector of bytes which is the content and a mimetype string of the conten.
#[cfg(feature = "protocol")]
pub fn with_custom_protocol<F>(mut self, name: String, handler: F) -> Self
where
F: Fn(&Window, &str) -> Result<Vec<u8>> + 'static,
F: Fn(&Window, &str) -> Result<(Vec<u8>, String)> + 'static,
{
self
.webview
Expand Down
4 changes: 1 addition & 3 deletions src/webview/webkitgtk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ use webkit2gtk_sys::{
use crate::{
application::{platform::unix::*, window::Window},
webview::{
mimetype::MimeType,
web_context::{unix::WebContextExt, WebContext},
WebViewAttributes,
},
Expand Down Expand Up @@ -175,8 +174,7 @@ impl InnerWebView {
let uri = uri.as_str();

match handler(&w, uri) {
Ok(buffer) => {
let mime = MimeType::parse(&buffer, uri);
Ok((buffer, mime)) => {
let input = gio::MemoryInputStream::from_bytes(&Bytes::from(&buffer));
request.finish(&input, buffer.len() as i64, Some(&mime))
}
Expand Down
5 changes: 2 additions & 3 deletions src/webview/webview2/win32/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
mod file_drop;

use crate::{
webview::{mimetype::MimeType, WebContext, WebViewAttributes},
webview::{WebContext, WebViewAttributes},
Result,
};

Expand Down Expand Up @@ -148,8 +148,7 @@ impl InnerWebView {
);

match function(&window_, path) {
Ok(content) => {
let mime = MimeType::parse(&content, &uri);
Ok((content, mime)) => {
let stream = webview2::Stream::from_bytes(&content);
let response = env_clone.create_web_resource_response(
stream,
Expand Down
5 changes: 2 additions & 3 deletions src/webview/webview2/winrt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use windows_webview2::{
};

use crate::{
webview::{mimetype::MimeType, FileDropEvent, RpcRequest, RpcResponse},
webview::{FileDropEvent, RpcRequest, RpcResponse},
Result,
};

Expand Down Expand Up @@ -166,8 +166,7 @@ impl InnerWebView {
&format!("{}://", name),
);

if let Ok(content) = function(&window_, &path) {
let mime = MimeType::parse(&content, &uri);
if let Ok((content, mime)) = function(&window_, &path) {
let stream = InMemoryRandomAccessStream::new()?;
let writer = DataWriter::CreateDataWriter(stream.clone())?;
writer.WriteBytes(&content)?;
Expand Down
14 changes: 7 additions & 7 deletions src/webview/wkwebview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ use crate::application::platform::ios::WindowExtIOS;

use crate::{
application::window::Window,
webview::{
mimetype::MimeType, FileDropEvent, RpcRequest, RpcResponse, WebContext, WebViewAttributes,
},
webview::{FileDropEvent, RpcRequest, RpcResponse, WebContext, WebViewAttributes},
Result,
};

Expand All @@ -54,7 +52,10 @@ pub struct InnerWebView {
),
#[cfg(target_os = "macos")]
file_drop_ptr: *mut (Box<dyn Fn(&Window, FileDropEvent) -> bool>, Rc<Window>),
protocol_ptrs: Vec<*mut (Box<dyn Fn(&Window, &str) -> Result<Vec<u8>>>, Rc<Window>)>,
protocol_ptrs: Vec<*mut (
Box<dyn Fn(&Window, &str) -> Result<(Vec<u8>, String)>>,
Rc<Window>,
)>,
}

impl InnerWebView {
Expand Down Expand Up @@ -99,7 +100,7 @@ impl InnerWebView {
let function = this.get_ivar::<*mut c_void>("function");
let function = &mut *(*function
as *mut (
Box<dyn for<'r, 's> Fn(&'r Window, &'s str) -> Result<Vec<u8>>>,
Box<dyn for<'r, 's> Fn(&'r Window, &'s str) -> Result<(Vec<u8>, String)>>,
Rc<Window>,
));

Expand All @@ -113,8 +114,7 @@ impl InnerWebView {
let uri = nsstring.to_str();

// Send response
if let Ok(content) = function.0(&function.1, uri) {
let mime = MimeType::parse(&content, uri);
if let Ok((content, mime)) = function.0(&function.1, uri) {
let dictionary: id = msg_send![class!(NSMutableDictionary), alloc];
let headers: id = msg_send![dictionary, initWithCapacity:1];
let () = msg_send![headers, setObject:NSString::new(&mime) forKey: NSString::new("content-type")];
Expand Down

0 comments on commit cc9fc4b

Please sign in to comment.