webview.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! Items specific to the [`Runtime`](crate::runtime::Runtime)'s webview.
  5. use crate::runtime::Icon;
  6. use crate::{
  7. api::config::{WindowConfig, WindowUrl},
  8. runtime::window::DetachedWindow,
  9. };
  10. use serde_json::Value as JsonValue;
  11. use std::{collections::HashMap, path::PathBuf};
  12. type UriSchemeProtocol = dyn Fn(&str) -> crate::Result<Vec<u8>> + Send + Sync + 'static;
  13. /// The attributes used to create an webview.
  14. pub struct WebviewAttributes {
  15. pub(crate) url: WindowUrl,
  16. pub(crate) initialization_scripts: Vec<String>,
  17. pub(crate) data_directory: Option<PathBuf>,
  18. pub(crate) uri_scheme_protocols: HashMap<String, Box<UriSchemeProtocol>>,
  19. }
  20. impl WebviewAttributes {
  21. /// Initializes the default attributes for a webview.
  22. pub fn new(url: WindowUrl) -> Self {
  23. Self {
  24. url,
  25. initialization_scripts: Vec::new(),
  26. data_directory: None,
  27. uri_scheme_protocols: Default::default(),
  28. }
  29. }
  30. /// Sets the init script.
  31. pub fn initialization_script(mut self, script: &str) -> Self {
  32. self.initialization_scripts.push(script.to_string());
  33. self
  34. }
  35. /// Data directory for the webview.
  36. pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
  37. self.data_directory.replace(data_directory);
  38. self
  39. }
  40. /// Whether the webview URI scheme protocol is defined or not.
  41. pub fn has_uri_scheme_protocol(&self, name: &str) -> bool {
  42. self.uri_scheme_protocols.contains_key(name)
  43. }
  44. /// Registers a webview protocol handler.
  45. /// Leverages [setURLSchemeHandler](https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/2875766-seturlschemehandler) on macOS,
  46. /// [AddWebResourceRequestedFilter](https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.addwebresourcerequestedfilter?view=webview2-dotnet-1.0.774.44) on Windows
  47. /// and [webkit-web-context-register-uri-scheme](https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebContext.html#webkit-web-context-register-uri-scheme) on Linux.
  48. ///
  49. /// # Arguments
  50. ///
  51. /// * `uri_scheme` The URI scheme to register, such as `example`.
  52. /// * `protocol` the protocol associated with the given URI scheme. It's a function that takes an URL such as `example://localhost/asset.css`.
  53. pub fn register_uri_scheme_protocol<
  54. N: Into<String>,
  55. H: Fn(&str) -> crate::Result<Vec<u8>> + Send + Sync + 'static,
  56. >(
  57. mut self,
  58. uri_scheme: N,
  59. protocol: H,
  60. ) -> Self {
  61. let uri_scheme = uri_scheme.into();
  62. self
  63. .uri_scheme_protocols
  64. .insert(uri_scheme, Box::new(move |data| (protocol)(data)));
  65. self
  66. }
  67. }
  68. /// Do **NOT** implement this trait except for use in a custom [`Runtime`](crate::runtime::Runtime).
  69. ///
  70. /// This trait is separate from [`WindowBuilder`] to prevent "accidental" implementation.
  71. pub trait WindowBuilderBase: Sized {}
  72. /// A builder for all attributes related to a single webview.
  73. ///
  74. /// This trait is only meant to be implemented by a custom [`Runtime`](crate::runtime::Runtime)
  75. /// and not by applications.
  76. pub trait WindowBuilder: WindowBuilderBase {
  77. /// Initializes a new window attributes builder.
  78. fn new() -> Self;
  79. /// Initializes a new webview builder from a [`WindowConfig`]
  80. fn with_config(config: WindowConfig) -> Self;
  81. /// The initial position of the window's.
  82. fn position(self, x: f64, y: f64) -> Self;
  83. /// Window size.
  84. fn inner_size(self, min_width: f64, min_height: f64) -> Self;
  85. /// Window min inner size.
  86. fn min_inner_size(self, min_width: f64, min_height: f64) -> Self;
  87. /// Window max inner size.
  88. fn max_inner_size(self, min_width: f64, min_height: f64) -> Self;
  89. /// Whether the window is resizable or not.
  90. fn resizable(self, resizable: bool) -> Self;
  91. /// The title of the window in the title bar.
  92. fn title<S: Into<String>>(self, title: S) -> Self;
  93. /// Whether to start the window in fullscreen or not.
  94. fn fullscreen(self, fullscreen: bool) -> Self;
  95. /// Whether the window should be maximized upon creation.
  96. fn maximized(self, maximized: bool) -> Self;
  97. /// Whether the window should be immediately visible upon creation.
  98. fn visible(self, visible: bool) -> Self;
  99. /// Whether the the window should be transparent. If this is true, writing colors
  100. /// with alpha values different than `1.0` will produce a transparent window.
  101. fn transparent(self, transparent: bool) -> Self;
  102. /// Whether the window should have borders and bars.
  103. fn decorations(self, decorations: bool) -> Self;
  104. /// Whether the window should always be on top of other windows.
  105. fn always_on_top(self, always_on_top: bool) -> Self;
  106. /// Sets the window icon.
  107. fn icon(self, icon: Icon) -> crate::Result<Self>;
  108. /// Whether the icon was set or not.
  109. fn has_icon(&self) -> bool;
  110. }
  111. /// Rpc request.
  112. pub struct RpcRequest {
  113. /// RPC command.
  114. pub command: String,
  115. /// Params.
  116. pub params: Option<JsonValue>,
  117. }
  118. /// Uses a custom URI scheme handler to resolve file requests
  119. pub struct CustomProtocol {
  120. /// Handler for protocol
  121. pub protocol: Box<dyn Fn(&str) -> crate::Result<Vec<u8>> + Send + Sync>,
  122. }
  123. /// The file drop event payload.
  124. #[derive(Debug, Clone)]
  125. pub enum FileDropEvent {
  126. /// The file(s) have been dragged onto the window, but have not been dropped yet.
  127. Hovered(Vec<PathBuf>),
  128. /// The file(s) have been dropped onto the window.
  129. Dropped(Vec<PathBuf>),
  130. /// The file drop was aborted.
  131. Cancelled,
  132. }
  133. /// Rpc handler.
  134. pub(crate) type WebviewRpcHandler<M> = Box<dyn Fn(DetachedWindow<M>, RpcRequest) + Send>;
  135. /// File drop handler callback
  136. /// Return `true` in the callback to block the OS' default behavior of handling a file drop.
  137. pub(crate) type FileDropHandler<M> = Box<dyn Fn(FileDropEvent, DetachedWindow<M>) -> bool + Send>;