lib.rs 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! The [`wry`] Tauri [`Runtime`].
  5. use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle};
  6. use tauri_runtime::{
  7. http::{header::CONTENT_TYPE, Request as HttpRequest, RequestParts, Response as HttpResponse},
  8. menu::{AboutMetadata, CustomMenuItem, Menu, MenuEntry, MenuHash, MenuId, MenuItem, MenuUpdate},
  9. monitor::Monitor,
  10. webview::{WebviewIpcHandler, WindowBuilder, WindowBuilderBase},
  11. window::{
  12. dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
  13. CursorIcon, DetachedWindow, FileDropEvent, JsEventListenerKey, PendingWindow, WindowEvent,
  14. },
  15. Dispatch, Error, EventLoopProxy, ExitRequestedEventAction, Icon, Result, RunEvent, RunIteration,
  16. Runtime, RuntimeHandle, UserAttentionType, UserEvent,
  17. };
  18. use tauri_runtime::window::MenuEvent;
  19. #[cfg(all(desktop, feature = "system-tray"))]
  20. use tauri_runtime::{SystemTray, SystemTrayEvent};
  21. #[cfg(windows)]
  22. use webview2_com::FocusChangedEventHandler;
  23. #[cfg(windows)]
  24. use windows::Win32::{Foundation::HWND, System::WinRT::EventRegistrationToken};
  25. #[cfg(target_os = "macos")]
  26. use wry::application::platform::macos::EventLoopWindowTargetExtMacOS;
  27. #[cfg(target_os = "macos")]
  28. use wry::application::platform::macos::WindowBuilderExtMacOS;
  29. #[cfg(target_os = "linux")]
  30. use wry::application::platform::unix::{WindowBuilderExtUnix, WindowExtUnix};
  31. #[cfg(windows)]
  32. use wry::application::platform::windows::{WindowBuilderExtWindows, WindowExtWindows};
  33. #[cfg(target_os = "macos")]
  34. use tauri_utils::TitleBarStyle;
  35. use tauri_utils::{config::WindowConfig, debug_eprintln, Theme};
  36. use uuid::Uuid;
  37. use wry::{
  38. application::{
  39. dpi::{
  40. LogicalPosition as WryLogicalPosition, LogicalSize as WryLogicalSize,
  41. PhysicalPosition as WryPhysicalPosition, PhysicalSize as WryPhysicalSize,
  42. Position as WryPosition, Size as WrySize,
  43. },
  44. event::{Event, StartCause, WindowEvent as WryWindowEvent},
  45. event_loop::{
  46. ControlFlow, EventLoop, EventLoopProxy as WryEventLoopProxy, EventLoopWindowTarget,
  47. },
  48. menu::{
  49. AboutMetadata as WryAboutMetadata, CustomMenuItem as WryCustomMenuItem, MenuBar,
  50. MenuId as WryMenuId, MenuItem as WryMenuItem, MenuItemAttributes as WryMenuItemAttributes,
  51. MenuType,
  52. },
  53. monitor::MonitorHandle,
  54. window::{
  55. CursorIcon as WryCursorIcon, Fullscreen, Icon as WryWindowIcon, Theme as WryTheme,
  56. UserAttentionType as WryUserAttentionType,
  57. },
  58. },
  59. http::{Request as WryRequest, Response as WryResponse},
  60. webview::{FileDropEvent as WryFileDropEvent, WebContext, WebView, WebViewBuilder},
  61. };
  62. pub use wry;
  63. pub use wry::application::window::{Window, WindowBuilder as WryWindowBuilder, WindowId};
  64. #[cfg(windows)]
  65. use wry::webview::WebviewExtWindows;
  66. #[cfg(target_os = "macos")]
  67. use tauri_runtime::{menu::NativeImage, ActivationPolicy};
  68. #[cfg(target_os = "macos")]
  69. pub use wry::application::platform::macos::{
  70. ActivationPolicy as WryActivationPolicy, CustomMenuItemExtMacOS, EventLoopExtMacOS,
  71. NativeImage as WryNativeImage, WindowExtMacOS,
  72. };
  73. use std::{
  74. cell::RefCell,
  75. collections::{
  76. hash_map::Entry::{Occupied, Vacant},
  77. HashMap, HashSet,
  78. },
  79. fmt,
  80. ops::Deref,
  81. path::PathBuf,
  82. sync::{
  83. mpsc::{channel, Sender},
  84. Arc, Mutex, Weak,
  85. },
  86. thread::{current as current_thread, ThreadId},
  87. };
  88. pub type WebviewId = u64;
  89. type IpcHandler = dyn Fn(&Window, String) + 'static;
  90. type FileDropHandler = dyn Fn(&Window, WryFileDropEvent) -> bool + 'static;
  91. #[cfg(all(desktop, feature = "system-tray"))]
  92. pub use tauri_runtime::TrayId;
  93. #[cfg(desktop)]
  94. mod webview;
  95. #[cfg(desktop)]
  96. pub use webview::Webview;
  97. #[cfg(all(desktop, feature = "system-tray"))]
  98. mod system_tray;
  99. #[cfg(all(desktop, feature = "system-tray"))]
  100. use system_tray::*;
  101. #[cfg(all(desktop, feature = "global-shortcut"))]
  102. mod global_shortcut;
  103. #[cfg(all(desktop, feature = "global-shortcut"))]
  104. use global_shortcut::*;
  105. #[cfg(feature = "clipboard")]
  106. mod clipboard;
  107. #[cfg(feature = "clipboard")]
  108. use clipboard::*;
  109. pub type WebContextStore = Arc<Mutex<HashMap<Option<PathBuf>, WebContext>>>;
  110. // window
  111. pub type WindowEventHandler = Box<dyn Fn(&WindowEvent) + Send>;
  112. pub type WindowEventListeners = Arc<Mutex<HashMap<Uuid, WindowEventHandler>>>;
  113. // menu
  114. pub type MenuEventHandler = Box<dyn Fn(&MenuEvent) + Send>;
  115. pub type WindowMenuEventListeners = Arc<Mutex<HashMap<Uuid, MenuEventHandler>>>;
  116. #[derive(Debug, Clone, Default)]
  117. pub struct WebviewIdStore(Arc<Mutex<HashMap<WindowId, WebviewId>>>);
  118. impl WebviewIdStore {
  119. pub fn insert(&self, w: WindowId, id: WebviewId) {
  120. self.0.lock().unwrap().insert(w, id);
  121. }
  122. fn get(&self, w: &WindowId) -> Option<WebviewId> {
  123. self.0.lock().unwrap().get(w).copied()
  124. }
  125. }
  126. #[macro_export]
  127. macro_rules! getter {
  128. ($self: ident, $rx: expr, $message: expr) => {{
  129. $crate::send_user_message(&$self.context, $message)?;
  130. $rx
  131. .recv()
  132. .map_err(|_| $crate::Error::FailedToReceiveMessage)
  133. }};
  134. }
  135. macro_rules! window_getter {
  136. ($self: ident, $message: expr) => {{
  137. let (tx, rx) = channel();
  138. getter!($self, rx, Message::Window($self.window_id, $message(tx)))
  139. }};
  140. }
  141. pub(crate) fn send_user_message<T: UserEvent>(
  142. context: &Context<T>,
  143. message: Message<T>,
  144. ) -> Result<()> {
  145. if current_thread().id() == context.main_thread_id {
  146. handle_user_message(
  147. &context.main_thread.window_target,
  148. message,
  149. UserMessageContext {
  150. webview_id_map: context.webview_id_map.clone(),
  151. #[cfg(all(desktop, feature = "global-shortcut"))]
  152. global_shortcut_manager: context.main_thread.global_shortcut_manager.clone(),
  153. #[cfg(feature = "clipboard")]
  154. clipboard_manager: context.main_thread.clipboard_manager.clone(),
  155. windows: context.main_thread.windows.clone(),
  156. #[cfg(all(desktop, feature = "system-tray"))]
  157. system_tray_manager: context.main_thread.system_tray_manager.clone(),
  158. },
  159. &context.main_thread.web_context,
  160. );
  161. Ok(())
  162. } else {
  163. context
  164. .proxy
  165. .send_event(message)
  166. .map_err(|_| Error::FailedToSendMessage)
  167. }
  168. }
  169. #[derive(Clone)]
  170. pub struct Context<T: UserEvent> {
  171. pub webview_id_map: WebviewIdStore,
  172. main_thread_id: ThreadId,
  173. pub proxy: WryEventLoopProxy<Message<T>>,
  174. main_thread: DispatcherMainThreadContext<T>,
  175. }
  176. impl<T: UserEvent> Context<T> {
  177. pub fn run_threaded<R, F>(&self, f: F) -> R
  178. where
  179. F: FnOnce(Option<&DispatcherMainThreadContext<T>>) -> R,
  180. {
  181. f(if current_thread().id() == self.main_thread_id {
  182. Some(&self.main_thread)
  183. } else {
  184. None
  185. })
  186. }
  187. }
  188. impl<T: UserEvent> Context<T> {
  189. fn create_webview(&self, pending: PendingWindow<T, Wry<T>>) -> Result<DetachedWindow<T, Wry<T>>> {
  190. let label = pending.label.clone();
  191. let menu_ids = pending.menu_ids.clone();
  192. let js_event_listeners = pending.js_event_listeners.clone();
  193. let context = self.clone();
  194. let window_id = rand::random();
  195. send_user_message(
  196. self,
  197. Message::CreateWebview(
  198. window_id,
  199. Box::new(move |event_loop, web_context| {
  200. create_webview(window_id, event_loop, web_context, context, pending)
  201. }),
  202. ),
  203. )?;
  204. let dispatcher = WryDispatcher {
  205. window_id,
  206. context: self.clone(),
  207. };
  208. Ok(DetachedWindow {
  209. label,
  210. dispatcher,
  211. menu_ids,
  212. js_event_listeners,
  213. })
  214. }
  215. }
  216. #[derive(Debug, Clone)]
  217. pub struct DispatcherMainThreadContext<T: UserEvent> {
  218. pub window_target: EventLoopWindowTarget<Message<T>>,
  219. pub web_context: WebContextStore,
  220. #[cfg(all(desktop, feature = "global-shortcut"))]
  221. pub global_shortcut_manager: Arc<Mutex<WryShortcutManager>>,
  222. #[cfg(feature = "clipboard")]
  223. pub clipboard_manager: Arc<Mutex<Clipboard>>,
  224. pub windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
  225. #[cfg(all(desktop, feature = "system-tray"))]
  226. system_tray_manager: SystemTrayManager,
  227. }
  228. // SAFETY: we ensure this type is only used on the main thread.
  229. #[allow(clippy::non_send_fields_in_send_ty)]
  230. unsafe impl<T: UserEvent> Send for DispatcherMainThreadContext<T> {}
  231. // SAFETY: we ensure this type is only used on the main thread.
  232. #[allow(clippy::non_send_fields_in_send_ty)]
  233. unsafe impl<T: UserEvent> Sync for DispatcherMainThreadContext<T> {}
  234. impl<T: UserEvent> fmt::Debug for Context<T> {
  235. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  236. f.debug_struct("Context")
  237. .field("main_thread_id", &self.main_thread_id)
  238. .field("proxy", &self.proxy)
  239. .field("main_thread", &self.main_thread)
  240. .finish()
  241. }
  242. }
  243. struct HttpRequestWrapper(HttpRequest);
  244. impl From<&WryRequest<Vec<u8>>> for HttpRequestWrapper {
  245. fn from(req: &WryRequest<Vec<u8>>) -> Self {
  246. let parts = RequestParts {
  247. uri: req.uri().to_string(),
  248. method: req.method().clone(),
  249. headers: req.headers().clone(),
  250. };
  251. Self(HttpRequest::new_internal(parts, req.body().clone()))
  252. }
  253. }
  254. // response
  255. struct HttpResponseWrapper(WryResponse<Vec<u8>>);
  256. impl From<HttpResponse> for HttpResponseWrapper {
  257. fn from(response: HttpResponse) -> Self {
  258. let (parts, body) = response.into_parts();
  259. let mut res_builder = WryResponse::builder()
  260. .status(parts.status)
  261. .version(parts.version);
  262. if let Some(mime) = parts.mimetype {
  263. res_builder = res_builder.header(CONTENT_TYPE, mime);
  264. }
  265. for (name, val) in parts.headers.iter() {
  266. res_builder = res_builder.header(name, val);
  267. }
  268. let res = res_builder.body(body).unwrap();
  269. Self(res)
  270. }
  271. }
  272. pub struct MenuItemAttributesWrapper<'a>(pub WryMenuItemAttributes<'a>);
  273. impl<'a> From<&'a CustomMenuItem> for MenuItemAttributesWrapper<'a> {
  274. fn from(item: &'a CustomMenuItem) -> Self {
  275. let mut attributes = WryMenuItemAttributes::new(&item.title)
  276. .with_enabled(item.enabled)
  277. .with_selected(item.selected)
  278. .with_id(WryMenuId(item.id));
  279. if let Some(accelerator) = item.keyboard_accelerator.as_ref() {
  280. attributes = attributes.with_accelerators(&accelerator.parse().expect("invalid accelerator"));
  281. }
  282. Self(attributes)
  283. }
  284. }
  285. pub struct AboutMetadataWrapper(pub WryAboutMetadata);
  286. impl From<AboutMetadata> for AboutMetadataWrapper {
  287. fn from(metadata: AboutMetadata) -> Self {
  288. Self(WryAboutMetadata {
  289. version: metadata.version,
  290. authors: metadata.authors,
  291. comments: metadata.comments,
  292. copyright: metadata.copyright,
  293. license: metadata.license,
  294. website: metadata.website,
  295. website_label: metadata.website_label,
  296. })
  297. }
  298. }
  299. pub struct MenuItemWrapper(pub WryMenuItem);
  300. impl From<MenuItem> for MenuItemWrapper {
  301. fn from(item: MenuItem) -> Self {
  302. match item {
  303. MenuItem::About(name, metadata) => Self(WryMenuItem::About(
  304. name,
  305. AboutMetadataWrapper::from(metadata).0,
  306. )),
  307. MenuItem::Hide => Self(WryMenuItem::Hide),
  308. MenuItem::Services => Self(WryMenuItem::Services),
  309. MenuItem::HideOthers => Self(WryMenuItem::HideOthers),
  310. MenuItem::ShowAll => Self(WryMenuItem::ShowAll),
  311. MenuItem::CloseWindow => Self(WryMenuItem::CloseWindow),
  312. MenuItem::Quit => Self(WryMenuItem::Quit),
  313. MenuItem::Copy => Self(WryMenuItem::Copy),
  314. MenuItem::Cut => Self(WryMenuItem::Cut),
  315. MenuItem::Undo => Self(WryMenuItem::Undo),
  316. MenuItem::Redo => Self(WryMenuItem::Redo),
  317. MenuItem::SelectAll => Self(WryMenuItem::SelectAll),
  318. MenuItem::Paste => Self(WryMenuItem::Paste),
  319. MenuItem::EnterFullScreen => Self(WryMenuItem::EnterFullScreen),
  320. MenuItem::Minimize => Self(WryMenuItem::Minimize),
  321. MenuItem::Zoom => Self(WryMenuItem::Zoom),
  322. MenuItem::Separator => Self(WryMenuItem::Separator),
  323. _ => unimplemented!(),
  324. }
  325. }
  326. }
  327. #[cfg(target_os = "macos")]
  328. pub struct NativeImageWrapper(pub WryNativeImage);
  329. #[cfg(target_os = "macos")]
  330. impl std::fmt::Debug for NativeImageWrapper {
  331. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  332. f.debug_struct("NativeImageWrapper").finish()
  333. }
  334. }
  335. #[cfg(target_os = "macos")]
  336. impl From<NativeImage> for NativeImageWrapper {
  337. fn from(image: NativeImage) -> NativeImageWrapper {
  338. let wry_image = match image {
  339. NativeImage::Add => WryNativeImage::Add,
  340. NativeImage::Advanced => WryNativeImage::Advanced,
  341. NativeImage::Bluetooth => WryNativeImage::Bluetooth,
  342. NativeImage::Bookmarks => WryNativeImage::Bookmarks,
  343. NativeImage::Caution => WryNativeImage::Caution,
  344. NativeImage::ColorPanel => WryNativeImage::ColorPanel,
  345. NativeImage::ColumnView => WryNativeImage::ColumnView,
  346. NativeImage::Computer => WryNativeImage::Computer,
  347. NativeImage::EnterFullScreen => WryNativeImage::EnterFullScreen,
  348. NativeImage::Everyone => WryNativeImage::Everyone,
  349. NativeImage::ExitFullScreen => WryNativeImage::ExitFullScreen,
  350. NativeImage::FlowView => WryNativeImage::FlowView,
  351. NativeImage::Folder => WryNativeImage::Folder,
  352. NativeImage::FolderBurnable => WryNativeImage::FolderBurnable,
  353. NativeImage::FolderSmart => WryNativeImage::FolderSmart,
  354. NativeImage::FollowLinkFreestanding => WryNativeImage::FollowLinkFreestanding,
  355. NativeImage::FontPanel => WryNativeImage::FontPanel,
  356. NativeImage::GoLeft => WryNativeImage::GoLeft,
  357. NativeImage::GoRight => WryNativeImage::GoRight,
  358. NativeImage::Home => WryNativeImage::Home,
  359. NativeImage::IChatTheater => WryNativeImage::IChatTheater,
  360. NativeImage::IconView => WryNativeImage::IconView,
  361. NativeImage::Info => WryNativeImage::Info,
  362. NativeImage::InvalidDataFreestanding => WryNativeImage::InvalidDataFreestanding,
  363. NativeImage::LeftFacingTriangle => WryNativeImage::LeftFacingTriangle,
  364. NativeImage::ListView => WryNativeImage::ListView,
  365. NativeImage::LockLocked => WryNativeImage::LockLocked,
  366. NativeImage::LockUnlocked => WryNativeImage::LockUnlocked,
  367. NativeImage::MenuMixedState => WryNativeImage::MenuMixedState,
  368. NativeImage::MenuOnState => WryNativeImage::MenuOnState,
  369. NativeImage::MobileMe => WryNativeImage::MobileMe,
  370. NativeImage::MultipleDocuments => WryNativeImage::MultipleDocuments,
  371. NativeImage::Network => WryNativeImage::Network,
  372. NativeImage::Path => WryNativeImage::Path,
  373. NativeImage::PreferencesGeneral => WryNativeImage::PreferencesGeneral,
  374. NativeImage::QuickLook => WryNativeImage::QuickLook,
  375. NativeImage::RefreshFreestanding => WryNativeImage::RefreshFreestanding,
  376. NativeImage::Refresh => WryNativeImage::Refresh,
  377. NativeImage::Remove => WryNativeImage::Remove,
  378. NativeImage::RevealFreestanding => WryNativeImage::RevealFreestanding,
  379. NativeImage::RightFacingTriangle => WryNativeImage::RightFacingTriangle,
  380. NativeImage::Share => WryNativeImage::Share,
  381. NativeImage::Slideshow => WryNativeImage::Slideshow,
  382. NativeImage::SmartBadge => WryNativeImage::SmartBadge,
  383. NativeImage::StatusAvailable => WryNativeImage::StatusAvailable,
  384. NativeImage::StatusNone => WryNativeImage::StatusNone,
  385. NativeImage::StatusPartiallyAvailable => WryNativeImage::StatusPartiallyAvailable,
  386. NativeImage::StatusUnavailable => WryNativeImage::StatusUnavailable,
  387. NativeImage::StopProgressFreestanding => WryNativeImage::StopProgressFreestanding,
  388. NativeImage::StopProgress => WryNativeImage::StopProgress,
  389. NativeImage::TrashEmpty => WryNativeImage::TrashEmpty,
  390. NativeImage::TrashFull => WryNativeImage::TrashFull,
  391. NativeImage::User => WryNativeImage::User,
  392. NativeImage::UserAccounts => WryNativeImage::UserAccounts,
  393. NativeImage::UserGroup => WryNativeImage::UserGroup,
  394. NativeImage::UserGuest => WryNativeImage::UserGuest,
  395. };
  396. Self(wry_image)
  397. }
  398. }
  399. /// Wrapper around a [`wry::application::window::Icon`] that can be created from an [`Icon`].
  400. pub struct WryIcon(pub WryWindowIcon);
  401. fn icon_err<E: std::error::Error + Send + Sync + 'static>(e: E) -> Error {
  402. Error::InvalidIcon(Box::new(e))
  403. }
  404. impl TryFrom<Icon> for WryIcon {
  405. type Error = Error;
  406. fn try_from(icon: Icon) -> std::result::Result<Self, Self::Error> {
  407. WryWindowIcon::from_rgba(icon.rgba, icon.width, icon.height)
  408. .map(Self)
  409. .map_err(icon_err)
  410. }
  411. }
  412. pub struct WindowEventWrapper(pub Option<WindowEvent>);
  413. impl WindowEventWrapper {
  414. fn parse(webview: &Option<WindowHandle>, event: &WryWindowEvent<'_>) -> Self {
  415. match event {
  416. // resized event from tao doesn't include a reliable size on macOS
  417. // because wry replaces the NSView
  418. WryWindowEvent::Resized(_) => {
  419. if let Some(webview) = webview {
  420. Self(Some(WindowEvent::Resized(
  421. PhysicalSizeWrapper(webview.inner_size()).into(),
  422. )))
  423. } else {
  424. Self(None)
  425. }
  426. }
  427. e => e.into(),
  428. }
  429. }
  430. }
  431. pub fn map_theme(theme: &WryTheme) -> Theme {
  432. match theme {
  433. WryTheme::Light => Theme::Light,
  434. WryTheme::Dark => Theme::Dark,
  435. _ => Theme::Light,
  436. }
  437. }
  438. impl<'a> From<&WryWindowEvent<'a>> for WindowEventWrapper {
  439. fn from(event: &WryWindowEvent<'a>) -> Self {
  440. let event = match event {
  441. WryWindowEvent::Resized(size) => WindowEvent::Resized(PhysicalSizeWrapper(*size).into()),
  442. WryWindowEvent::Moved(position) => {
  443. WindowEvent::Moved(PhysicalPositionWrapper(*position).into())
  444. }
  445. WryWindowEvent::Destroyed => WindowEvent::Destroyed,
  446. WryWindowEvent::ScaleFactorChanged {
  447. scale_factor,
  448. new_inner_size,
  449. } => WindowEvent::ScaleFactorChanged {
  450. scale_factor: *scale_factor,
  451. new_inner_size: PhysicalSizeWrapper(**new_inner_size).into(),
  452. },
  453. #[cfg(any(target_os = "linux", target_os = "macos"))]
  454. WryWindowEvent::Focused(focused) => WindowEvent::Focused(*focused),
  455. WryWindowEvent::ThemeChanged(theme) => WindowEvent::ThemeChanged(map_theme(theme)),
  456. _ => return Self(None),
  457. };
  458. Self(Some(event))
  459. }
  460. }
  461. impl From<&WebviewEvent> for WindowEventWrapper {
  462. fn from(event: &WebviewEvent) -> Self {
  463. let event = match event {
  464. WebviewEvent::Focused(focused) => WindowEvent::Focused(*focused),
  465. };
  466. Self(Some(event))
  467. }
  468. }
  469. pub struct MonitorHandleWrapper(pub MonitorHandle);
  470. impl From<MonitorHandleWrapper> for Monitor {
  471. fn from(monitor: MonitorHandleWrapper) -> Monitor {
  472. Self {
  473. name: monitor.0.name(),
  474. position: PhysicalPositionWrapper(monitor.0.position()).into(),
  475. size: PhysicalSizeWrapper(monitor.0.size()).into(),
  476. scale_factor: monitor.0.scale_factor(),
  477. }
  478. }
  479. }
  480. pub struct PhysicalPositionWrapper<T>(pub WryPhysicalPosition<T>);
  481. impl<T> From<PhysicalPositionWrapper<T>> for PhysicalPosition<T> {
  482. fn from(position: PhysicalPositionWrapper<T>) -> Self {
  483. Self {
  484. x: position.0.x,
  485. y: position.0.y,
  486. }
  487. }
  488. }
  489. impl<T> From<PhysicalPosition<T>> for PhysicalPositionWrapper<T> {
  490. fn from(position: PhysicalPosition<T>) -> Self {
  491. Self(WryPhysicalPosition {
  492. x: position.x,
  493. y: position.y,
  494. })
  495. }
  496. }
  497. struct LogicalPositionWrapper<T>(WryLogicalPosition<T>);
  498. impl<T> From<LogicalPosition<T>> for LogicalPositionWrapper<T> {
  499. fn from(position: LogicalPosition<T>) -> Self {
  500. Self(WryLogicalPosition {
  501. x: position.x,
  502. y: position.y,
  503. })
  504. }
  505. }
  506. pub struct PhysicalSizeWrapper<T>(pub WryPhysicalSize<T>);
  507. impl<T> From<PhysicalSizeWrapper<T>> for PhysicalSize<T> {
  508. fn from(size: PhysicalSizeWrapper<T>) -> Self {
  509. Self {
  510. width: size.0.width,
  511. height: size.0.height,
  512. }
  513. }
  514. }
  515. impl<T> From<PhysicalSize<T>> for PhysicalSizeWrapper<T> {
  516. fn from(size: PhysicalSize<T>) -> Self {
  517. Self(WryPhysicalSize {
  518. width: size.width,
  519. height: size.height,
  520. })
  521. }
  522. }
  523. struct LogicalSizeWrapper<T>(WryLogicalSize<T>);
  524. impl<T> From<LogicalSize<T>> for LogicalSizeWrapper<T> {
  525. fn from(size: LogicalSize<T>) -> Self {
  526. Self(WryLogicalSize {
  527. width: size.width,
  528. height: size.height,
  529. })
  530. }
  531. }
  532. pub struct SizeWrapper(pub WrySize);
  533. impl From<Size> for SizeWrapper {
  534. fn from(size: Size) -> Self {
  535. match size {
  536. Size::Logical(s) => Self(WrySize::Logical(LogicalSizeWrapper::from(s).0)),
  537. Size::Physical(s) => Self(WrySize::Physical(PhysicalSizeWrapper::from(s).0)),
  538. }
  539. }
  540. }
  541. pub struct PositionWrapper(pub WryPosition);
  542. impl From<Position> for PositionWrapper {
  543. fn from(position: Position) -> Self {
  544. match position {
  545. Position::Logical(s) => Self(WryPosition::Logical(LogicalPositionWrapper::from(s).0)),
  546. Position::Physical(s) => Self(WryPosition::Physical(PhysicalPositionWrapper::from(s).0)),
  547. }
  548. }
  549. }
  550. #[derive(Debug, Clone)]
  551. pub struct UserAttentionTypeWrapper(pub WryUserAttentionType);
  552. impl From<UserAttentionType> for UserAttentionTypeWrapper {
  553. fn from(request_type: UserAttentionType) -> Self {
  554. let o = match request_type {
  555. UserAttentionType::Critical => WryUserAttentionType::Critical,
  556. UserAttentionType::Informational => WryUserAttentionType::Informational,
  557. };
  558. Self(o)
  559. }
  560. }
  561. #[derive(Debug)]
  562. pub struct CursorIconWrapper(pub WryCursorIcon);
  563. impl From<CursorIcon> for CursorIconWrapper {
  564. fn from(icon: CursorIcon) -> Self {
  565. use CursorIcon::*;
  566. let i = match icon {
  567. Default => WryCursorIcon::Default,
  568. Crosshair => WryCursorIcon::Crosshair,
  569. Hand => WryCursorIcon::Hand,
  570. Arrow => WryCursorIcon::Arrow,
  571. Move => WryCursorIcon::Move,
  572. Text => WryCursorIcon::Text,
  573. Wait => WryCursorIcon::Wait,
  574. Help => WryCursorIcon::Help,
  575. Progress => WryCursorIcon::Progress,
  576. NotAllowed => WryCursorIcon::NotAllowed,
  577. ContextMenu => WryCursorIcon::ContextMenu,
  578. Cell => WryCursorIcon::Cell,
  579. VerticalText => WryCursorIcon::VerticalText,
  580. Alias => WryCursorIcon::Alias,
  581. Copy => WryCursorIcon::Copy,
  582. NoDrop => WryCursorIcon::NoDrop,
  583. Grab => WryCursorIcon::Grab,
  584. Grabbing => WryCursorIcon::Grabbing,
  585. AllScroll => WryCursorIcon::AllScroll,
  586. ZoomIn => WryCursorIcon::ZoomIn,
  587. ZoomOut => WryCursorIcon::ZoomOut,
  588. EResize => WryCursorIcon::EResize,
  589. NResize => WryCursorIcon::NResize,
  590. NeResize => WryCursorIcon::NeResize,
  591. NwResize => WryCursorIcon::NwResize,
  592. SResize => WryCursorIcon::SResize,
  593. SeResize => WryCursorIcon::SeResize,
  594. SwResize => WryCursorIcon::SwResize,
  595. WResize => WryCursorIcon::WResize,
  596. EwResize => WryCursorIcon::EwResize,
  597. NsResize => WryCursorIcon::NsResize,
  598. NeswResize => WryCursorIcon::NeswResize,
  599. NwseResize => WryCursorIcon::NwseResize,
  600. ColResize => WryCursorIcon::ColResize,
  601. RowResize => WryCursorIcon::RowResize,
  602. _ => WryCursorIcon::Default,
  603. };
  604. Self(i)
  605. }
  606. }
  607. #[derive(Debug, Clone, Default)]
  608. pub struct WindowBuilderWrapper {
  609. inner: WryWindowBuilder,
  610. center: bool,
  611. #[cfg(target_os = "macos")]
  612. tabbing_identifier: Option<String>,
  613. menu: Option<Menu>,
  614. }
  615. // SAFETY: this type is `Send` since `menu_items` are read only here
  616. #[allow(clippy::non_send_fields_in_send_ty)]
  617. unsafe impl Send for WindowBuilderWrapper {}
  618. impl WindowBuilderBase for WindowBuilderWrapper {}
  619. impl WindowBuilder for WindowBuilderWrapper {
  620. fn new() -> Self {
  621. Self::default().focused(true)
  622. }
  623. fn with_config(config: WindowConfig) -> Self {
  624. let mut window = WindowBuilderWrapper::new()
  625. .title(config.title.to_string())
  626. .inner_size(config.width, config.height)
  627. .visible(config.visible)
  628. .resizable(config.resizable)
  629. .fullscreen(config.fullscreen)
  630. .decorations(config.decorations)
  631. .maximized(config.maximized)
  632. .always_on_top(config.always_on_top)
  633. .content_protected(config.content_protected)
  634. .skip_taskbar(config.skip_taskbar)
  635. .theme(config.theme);
  636. #[cfg(target_os = "macos")]
  637. {
  638. window = window
  639. .hidden_title(config.hidden_title)
  640. .title_bar_style(config.title_bar_style);
  641. if let Some(identifier) = &config.tabbing_identifier {
  642. window = window.tabbing_identifier(identifier);
  643. }
  644. }
  645. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  646. {
  647. window = window.transparent(config.transparent);
  648. }
  649. #[cfg(all(
  650. target_os = "macos",
  651. not(feature = "macos-private-api"),
  652. debug_assertions
  653. ))]
  654. if config.transparent {
  655. eprintln!(
  656. "The window is set to be transparent but the `macos-private-api` is not enabled.
  657. This can be enabled via the `tauri.macOSPrivateApi` configuration property <https://tauri.app/docs/api/config#tauri.macOSPrivateApi>
  658. ");
  659. }
  660. if let (Some(min_width), Some(min_height)) = (config.min_width, config.min_height) {
  661. window = window.min_inner_size(min_width, min_height);
  662. }
  663. if let (Some(max_width), Some(max_height)) = (config.max_width, config.max_height) {
  664. window = window.max_inner_size(max_width, max_height);
  665. }
  666. if let (Some(x), Some(y)) = (config.x, config.y) {
  667. window = window.position(x, y);
  668. }
  669. if config.center {
  670. window = window.center();
  671. }
  672. window
  673. }
  674. fn menu(mut self, menu: Menu) -> Self {
  675. self.menu.replace(menu);
  676. self
  677. }
  678. fn center(mut self) -> Self {
  679. self.center = true;
  680. self
  681. }
  682. fn position(mut self, x: f64, y: f64) -> Self {
  683. self.inner = self.inner.with_position(WryLogicalPosition::new(x, y));
  684. self
  685. }
  686. fn inner_size(mut self, width: f64, height: f64) -> Self {
  687. self.inner = self
  688. .inner
  689. .with_inner_size(WryLogicalSize::new(width, height));
  690. self
  691. }
  692. fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
  693. self.inner = self
  694. .inner
  695. .with_min_inner_size(WryLogicalSize::new(min_width, min_height));
  696. self
  697. }
  698. fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
  699. self.inner = self
  700. .inner
  701. .with_max_inner_size(WryLogicalSize::new(max_width, max_height));
  702. self
  703. }
  704. fn resizable(mut self, resizable: bool) -> Self {
  705. self.inner = self.inner.with_resizable(resizable);
  706. self
  707. }
  708. fn title<S: Into<String>>(mut self, title: S) -> Self {
  709. self.inner = self.inner.with_title(title.into());
  710. self
  711. }
  712. fn fullscreen(mut self, fullscreen: bool) -> Self {
  713. self.inner = if fullscreen {
  714. self
  715. .inner
  716. .with_fullscreen(Some(Fullscreen::Borderless(None)))
  717. } else {
  718. self.inner.with_fullscreen(None)
  719. };
  720. self
  721. }
  722. fn focused(mut self, focused: bool) -> Self {
  723. self.inner = self.inner.with_focused(focused);
  724. self
  725. }
  726. fn maximized(mut self, maximized: bool) -> Self {
  727. self.inner = self.inner.with_maximized(maximized);
  728. self
  729. }
  730. fn visible(mut self, visible: bool) -> Self {
  731. self.inner = self.inner.with_visible(visible);
  732. self
  733. }
  734. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  735. fn transparent(mut self, transparent: bool) -> Self {
  736. self.inner = self.inner.with_transparent(transparent);
  737. self
  738. }
  739. fn decorations(mut self, decorations: bool) -> Self {
  740. self.inner = self.inner.with_decorations(decorations);
  741. self
  742. }
  743. fn always_on_top(mut self, always_on_top: bool) -> Self {
  744. self.inner = self.inner.with_always_on_top(always_on_top);
  745. self
  746. }
  747. fn content_protected(mut self, protected: bool) -> Self {
  748. self.inner = self.inner.with_content_protection(protected);
  749. self
  750. }
  751. #[cfg(windows)]
  752. fn parent_window(mut self, parent: HWND) -> Self {
  753. self.inner = self.inner.with_parent_window(parent);
  754. self
  755. }
  756. #[cfg(target_os = "macos")]
  757. fn parent_window(mut self, parent: *mut std::ffi::c_void) -> Self {
  758. self.inner = self.inner.with_parent_window(parent);
  759. self
  760. }
  761. #[cfg(windows)]
  762. fn owner_window(mut self, owner: HWND) -> Self {
  763. self.inner = self.inner.with_owner_window(owner);
  764. self
  765. }
  766. #[cfg(target_os = "macos")]
  767. fn title_bar_style(mut self, style: TitleBarStyle) -> Self {
  768. match style {
  769. TitleBarStyle::Visible => {
  770. self.inner = self.inner.with_titlebar_transparent(false);
  771. // Fixes rendering issue when resizing window with devtools open (https://github.com/tauri-apps/tauri/issues/3914)
  772. self.inner = self.inner.with_fullsize_content_view(true);
  773. }
  774. TitleBarStyle::Transparent => {
  775. self.inner = self.inner.with_titlebar_transparent(true);
  776. self.inner = self.inner.with_fullsize_content_view(false);
  777. }
  778. TitleBarStyle::Overlay => {
  779. self.inner = self.inner.with_titlebar_transparent(true);
  780. self.inner = self.inner.with_fullsize_content_view(true);
  781. }
  782. }
  783. self
  784. }
  785. #[cfg(target_os = "macos")]
  786. fn hidden_title(mut self, hidden: bool) -> Self {
  787. self.inner = self.inner.with_title_hidden(hidden);
  788. self
  789. }
  790. #[cfg(target_os = "macos")]
  791. fn tabbing_identifier(mut self, identifier: &str) -> Self {
  792. self.inner = self.inner.with_tabbing_identifier(identifier);
  793. self.tabbing_identifier.replace(identifier.into());
  794. self
  795. }
  796. fn icon(mut self, icon: Icon) -> Result<Self> {
  797. self.inner = self
  798. .inner
  799. .with_window_icon(Some(WryIcon::try_from(icon)?.0));
  800. Ok(self)
  801. }
  802. #[cfg(any(windows, target_os = "linux"))]
  803. fn skip_taskbar(mut self, skip: bool) -> Self {
  804. self.inner = self.inner.with_skip_taskbar(skip);
  805. self
  806. }
  807. #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))]
  808. fn skip_taskbar(self, _skip: bool) -> Self {
  809. self
  810. }
  811. #[allow(unused_variables, unused_mut)]
  812. fn theme(mut self, theme: Option<Theme>) -> Self {
  813. self.inner = self.inner.with_theme(if let Some(t) = theme {
  814. match t {
  815. Theme::Dark => Some(WryTheme::Dark),
  816. _ => Some(WryTheme::Light),
  817. }
  818. } else {
  819. None
  820. });
  821. self
  822. }
  823. fn has_icon(&self) -> bool {
  824. self.inner.window.window_icon.is_some()
  825. }
  826. fn get_menu(&self) -> Option<&Menu> {
  827. self.menu.as_ref()
  828. }
  829. }
  830. pub struct FileDropEventWrapper(WryFileDropEvent);
  831. // on Linux, the paths are percent-encoded
  832. #[cfg(any(
  833. target_os = "linux",
  834. target_os = "dragonfly",
  835. target_os = "freebsd",
  836. target_os = "netbsd",
  837. target_os = "openbsd"
  838. ))]
  839. fn decode_path(path: PathBuf) -> PathBuf {
  840. percent_encoding::percent_decode(path.display().to_string().as_bytes())
  841. .decode_utf8_lossy()
  842. .into_owned()
  843. .into()
  844. }
  845. // on Windows and macOS, we do not need to decode the path
  846. #[cfg(not(any(
  847. target_os = "linux",
  848. target_os = "dragonfly",
  849. target_os = "freebsd",
  850. target_os = "netbsd",
  851. target_os = "openbsd"
  852. )))]
  853. fn decode_path(path: PathBuf) -> PathBuf {
  854. path
  855. }
  856. impl From<FileDropEventWrapper> for FileDropEvent {
  857. fn from(event: FileDropEventWrapper) -> Self {
  858. match event.0 {
  859. WryFileDropEvent::Hovered(paths) => {
  860. FileDropEvent::Hovered(paths.into_iter().map(decode_path).collect())
  861. }
  862. WryFileDropEvent::Dropped(paths) => {
  863. FileDropEvent::Dropped(paths.into_iter().map(decode_path).collect())
  864. }
  865. // default to cancelled
  866. // FIXME(maybe): Add `FileDropEvent::Unknown` event?
  867. _ => FileDropEvent::Cancelled,
  868. }
  869. }
  870. }
  871. #[cfg(any(
  872. target_os = "linux",
  873. target_os = "dragonfly",
  874. target_os = "freebsd",
  875. target_os = "netbsd",
  876. target_os = "openbsd"
  877. ))]
  878. pub struct GtkWindow(pub gtk::ApplicationWindow);
  879. #[cfg(any(
  880. target_os = "linux",
  881. target_os = "dragonfly",
  882. target_os = "freebsd",
  883. target_os = "netbsd",
  884. target_os = "openbsd"
  885. ))]
  886. #[allow(clippy::non_send_fields_in_send_ty)]
  887. unsafe impl Send for GtkWindow {}
  888. pub struct RawWindowHandle(pub raw_window_handle::RawWindowHandle);
  889. unsafe impl Send for RawWindowHandle {}
  890. #[cfg(target_os = "macos")]
  891. #[derive(Debug, Clone)]
  892. pub enum ApplicationMessage {
  893. Show,
  894. Hide,
  895. }
  896. pub enum WindowMessage {
  897. #[cfg(desktop)]
  898. WithWebview(Box<dyn FnOnce(Webview) + Send>),
  899. AddEventListener(Uuid, Box<dyn Fn(&WindowEvent) + Send>),
  900. AddMenuEventListener(Uuid, Box<dyn Fn(&MenuEvent) + Send>),
  901. // Devtools
  902. #[cfg(any(debug_assertions, feature = "devtools"))]
  903. OpenDevTools,
  904. #[cfg(any(debug_assertions, feature = "devtools"))]
  905. CloseDevTools,
  906. #[cfg(any(debug_assertions, feature = "devtools"))]
  907. IsDevToolsOpen(Sender<bool>),
  908. // Getters
  909. ScaleFactor(Sender<f64>),
  910. InnerPosition(Sender<Result<PhysicalPosition<i32>>>),
  911. OuterPosition(Sender<Result<PhysicalPosition<i32>>>),
  912. InnerSize(Sender<PhysicalSize<u32>>),
  913. OuterSize(Sender<PhysicalSize<u32>>),
  914. IsFullscreen(Sender<bool>),
  915. IsMinimized(Sender<bool>),
  916. IsMaximized(Sender<bool>),
  917. IsDecorated(Sender<bool>),
  918. IsResizable(Sender<bool>),
  919. IsVisible(Sender<bool>),
  920. Title(Sender<String>),
  921. IsMenuVisible(Sender<bool>),
  922. CurrentMonitor(Sender<Option<MonitorHandle>>),
  923. PrimaryMonitor(Sender<Option<MonitorHandle>>),
  924. AvailableMonitors(Sender<Vec<MonitorHandle>>),
  925. #[cfg(any(
  926. target_os = "linux",
  927. target_os = "dragonfly",
  928. target_os = "freebsd",
  929. target_os = "netbsd",
  930. target_os = "openbsd"
  931. ))]
  932. GtkWindow(Sender<GtkWindow>),
  933. RawWindowHandle(Sender<RawWindowHandle>),
  934. Theme(Sender<Theme>),
  935. // Setters
  936. Center,
  937. RequestUserAttention(Option<UserAttentionTypeWrapper>),
  938. SetResizable(bool),
  939. SetTitle(String),
  940. Maximize,
  941. Unmaximize,
  942. Minimize,
  943. Unminimize,
  944. ShowMenu,
  945. HideMenu,
  946. Show,
  947. Hide,
  948. Close,
  949. SetDecorations(bool),
  950. SetAlwaysOnTop(bool),
  951. SetContentProtected(bool),
  952. SetSize(Size),
  953. SetMinSize(Option<Size>),
  954. SetMaxSize(Option<Size>),
  955. SetPosition(Position),
  956. SetFullscreen(bool),
  957. SetFocus,
  958. SetIcon(WryWindowIcon),
  959. SetSkipTaskbar(bool),
  960. SetCursorGrab(bool),
  961. SetCursorVisible(bool),
  962. SetCursorIcon(CursorIcon),
  963. SetCursorPosition(Position),
  964. SetIgnoreCursorEvents(bool),
  965. DragWindow,
  966. UpdateMenuItem(u16, MenuUpdate),
  967. RequestRedraw,
  968. }
  969. #[derive(Debug, Clone)]
  970. pub enum WebviewMessage {
  971. EvaluateScript(String),
  972. #[allow(dead_code)]
  973. WebviewEvent(WebviewEvent),
  974. Print,
  975. }
  976. #[allow(dead_code)]
  977. #[derive(Debug, Clone)]
  978. pub enum WebviewEvent {
  979. Focused(bool),
  980. }
  981. #[cfg(all(desktop, feature = "system-tray"))]
  982. #[derive(Debug, Clone)]
  983. pub enum TrayMessage {
  984. UpdateItem(u16, MenuUpdate),
  985. UpdateMenu(SystemTrayMenu),
  986. UpdateIcon(Icon),
  987. #[cfg(target_os = "macos")]
  988. UpdateIconAsTemplate(bool),
  989. #[cfg(target_os = "macos")]
  990. UpdateTitle(String),
  991. Create(SystemTray, Sender<Result<()>>),
  992. Destroy(Sender<Result<()>>),
  993. }
  994. pub type CreateWebviewClosure<T> = Box<
  995. dyn FnOnce(&EventLoopWindowTarget<Message<T>>, &WebContextStore) -> Result<WindowWrapper> + Send,
  996. >;
  997. pub enum Message<T: 'static> {
  998. Task(Box<dyn FnOnce() + Send>),
  999. #[cfg(target_os = "macos")]
  1000. Application(ApplicationMessage),
  1001. Window(WebviewId, WindowMessage),
  1002. Webview(WebviewId, WebviewMessage),
  1003. #[cfg(all(desktop, feature = "system-tray"))]
  1004. Tray(TrayId, TrayMessage),
  1005. CreateWebview(WebviewId, CreateWebviewClosure<T>),
  1006. CreateWindow(
  1007. WebviewId,
  1008. Box<dyn FnOnce() -> (String, WryWindowBuilder) + Send>,
  1009. Sender<Result<Weak<Window>>>,
  1010. ),
  1011. #[cfg(all(desktop, feature = "global-shortcut"))]
  1012. GlobalShortcut(GlobalShortcutMessage),
  1013. #[cfg(feature = "clipboard")]
  1014. Clipboard(ClipboardMessage),
  1015. UserEvent(T),
  1016. }
  1017. impl<T: UserEvent> Clone for Message<T> {
  1018. fn clone(&self) -> Self {
  1019. match self {
  1020. Self::Webview(i, m) => Self::Webview(*i, m.clone()),
  1021. #[cfg(all(desktop, feature = "system-tray"))]
  1022. Self::Tray(i, m) => Self::Tray(*i, m.clone()),
  1023. #[cfg(all(desktop, feature = "global-shortcut"))]
  1024. Self::GlobalShortcut(m) => Self::GlobalShortcut(m.clone()),
  1025. #[cfg(feature = "clipboard")]
  1026. Self::Clipboard(m) => Self::Clipboard(m.clone()),
  1027. Self::UserEvent(t) => Self::UserEvent(t.clone()),
  1028. _ => unimplemented!(),
  1029. }
  1030. }
  1031. }
  1032. /// The Tauri [`Dispatch`] for [`Wry`].
  1033. #[derive(Debug, Clone)]
  1034. pub struct WryDispatcher<T: UserEvent> {
  1035. window_id: WebviewId,
  1036. context: Context<T>,
  1037. }
  1038. // SAFETY: this is safe since the `Context` usage is guarded on `send_user_message`.
  1039. #[allow(clippy::non_send_fields_in_send_ty)]
  1040. unsafe impl<T: UserEvent> Sync for WryDispatcher<T> {}
  1041. impl<T: UserEvent> WryDispatcher<T> {
  1042. #[cfg(desktop)]
  1043. pub fn with_webview<F: FnOnce(Webview) + Send + 'static>(&self, f: F) -> Result<()> {
  1044. send_user_message(
  1045. &self.context,
  1046. Message::Window(self.window_id, WindowMessage::WithWebview(Box::new(f))),
  1047. )
  1048. }
  1049. }
  1050. impl<T: UserEvent> Dispatch<T> for WryDispatcher<T> {
  1051. type Runtime = Wry<T>;
  1052. type WindowBuilder = WindowBuilderWrapper;
  1053. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
  1054. send_user_message(&self.context, Message::Task(Box::new(f)))
  1055. }
  1056. fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> Uuid {
  1057. let id = Uuid::new_v4();
  1058. let _ = self.context.proxy.send_event(Message::Window(
  1059. self.window_id,
  1060. WindowMessage::AddEventListener(id, Box::new(f)),
  1061. ));
  1062. id
  1063. }
  1064. fn on_menu_event<F: Fn(&MenuEvent) + Send + 'static>(&self, f: F) -> Uuid {
  1065. let id = Uuid::new_v4();
  1066. let _ = self.context.proxy.send_event(Message::Window(
  1067. self.window_id,
  1068. WindowMessage::AddMenuEventListener(id, Box::new(f)),
  1069. ));
  1070. id
  1071. }
  1072. #[cfg(any(debug_assertions, feature = "devtools"))]
  1073. fn open_devtools(&self) {
  1074. let _ = send_user_message(
  1075. &self.context,
  1076. Message::Window(self.window_id, WindowMessage::OpenDevTools),
  1077. );
  1078. }
  1079. #[cfg(any(debug_assertions, feature = "devtools"))]
  1080. fn close_devtools(&self) {
  1081. let _ = send_user_message(
  1082. &self.context,
  1083. Message::Window(self.window_id, WindowMessage::CloseDevTools),
  1084. );
  1085. }
  1086. /// Gets the devtools window's current open state.
  1087. #[cfg(any(debug_assertions, feature = "devtools"))]
  1088. fn is_devtools_open(&self) -> Result<bool> {
  1089. window_getter!(self, WindowMessage::IsDevToolsOpen)
  1090. }
  1091. // Getters
  1092. fn scale_factor(&self) -> Result<f64> {
  1093. window_getter!(self, WindowMessage::ScaleFactor)
  1094. }
  1095. fn inner_position(&self) -> Result<PhysicalPosition<i32>> {
  1096. window_getter!(self, WindowMessage::InnerPosition)?
  1097. }
  1098. fn outer_position(&self) -> Result<PhysicalPosition<i32>> {
  1099. window_getter!(self, WindowMessage::OuterPosition)?
  1100. }
  1101. fn inner_size(&self) -> Result<PhysicalSize<u32>> {
  1102. window_getter!(self, WindowMessage::InnerSize)
  1103. }
  1104. fn outer_size(&self) -> Result<PhysicalSize<u32>> {
  1105. window_getter!(self, WindowMessage::OuterSize)
  1106. }
  1107. fn is_fullscreen(&self) -> Result<bool> {
  1108. window_getter!(self, WindowMessage::IsFullscreen)
  1109. }
  1110. fn is_minimized(&self) -> Result<bool> {
  1111. window_getter!(self, WindowMessage::IsMinimized)
  1112. }
  1113. fn is_maximized(&self) -> Result<bool> {
  1114. window_getter!(self, WindowMessage::IsMaximized)
  1115. }
  1116. /// Gets the window’s current decoration state.
  1117. fn is_decorated(&self) -> Result<bool> {
  1118. window_getter!(self, WindowMessage::IsDecorated)
  1119. }
  1120. /// Gets the window’s current resizable state.
  1121. fn is_resizable(&self) -> Result<bool> {
  1122. window_getter!(self, WindowMessage::IsResizable)
  1123. }
  1124. fn is_visible(&self) -> Result<bool> {
  1125. window_getter!(self, WindowMessage::IsVisible)
  1126. }
  1127. fn title(&self) -> Result<String> {
  1128. window_getter!(self, WindowMessage::Title)
  1129. }
  1130. fn is_menu_visible(&self) -> Result<bool> {
  1131. window_getter!(self, WindowMessage::IsMenuVisible)
  1132. }
  1133. fn current_monitor(&self) -> Result<Option<Monitor>> {
  1134. Ok(window_getter!(self, WindowMessage::CurrentMonitor)?.map(|m| MonitorHandleWrapper(m).into()))
  1135. }
  1136. fn primary_monitor(&self) -> Result<Option<Monitor>> {
  1137. Ok(window_getter!(self, WindowMessage::PrimaryMonitor)?.map(|m| MonitorHandleWrapper(m).into()))
  1138. }
  1139. fn available_monitors(&self) -> Result<Vec<Monitor>> {
  1140. Ok(
  1141. window_getter!(self, WindowMessage::AvailableMonitors)?
  1142. .into_iter()
  1143. .map(|m| MonitorHandleWrapper(m).into())
  1144. .collect(),
  1145. )
  1146. }
  1147. fn theme(&self) -> Result<Theme> {
  1148. window_getter!(self, WindowMessage::Theme)
  1149. }
  1150. /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
  1151. #[cfg(any(
  1152. target_os = "linux",
  1153. target_os = "dragonfly",
  1154. target_os = "freebsd",
  1155. target_os = "netbsd",
  1156. target_os = "openbsd"
  1157. ))]
  1158. fn gtk_window(&self) -> Result<gtk::ApplicationWindow> {
  1159. window_getter!(self, WindowMessage::GtkWindow).map(|w| w.0)
  1160. }
  1161. fn raw_window_handle(&self) -> Result<raw_window_handle::RawWindowHandle> {
  1162. window_getter!(self, WindowMessage::RawWindowHandle).map(|w| w.0)
  1163. }
  1164. // Setters
  1165. fn center(&self) -> Result<()> {
  1166. send_user_message(
  1167. &self.context,
  1168. Message::Window(self.window_id, WindowMessage::Center),
  1169. )
  1170. }
  1171. fn print(&self) -> Result<()> {
  1172. send_user_message(
  1173. &self.context,
  1174. Message::Webview(self.window_id, WebviewMessage::Print),
  1175. )
  1176. }
  1177. fn request_user_attention(&self, request_type: Option<UserAttentionType>) -> Result<()> {
  1178. send_user_message(
  1179. &self.context,
  1180. Message::Window(
  1181. self.window_id,
  1182. WindowMessage::RequestUserAttention(request_type.map(Into::into)),
  1183. ),
  1184. )
  1185. }
  1186. // Creates a window by dispatching a message to the event loop.
  1187. // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
  1188. fn create_window(
  1189. &mut self,
  1190. pending: PendingWindow<T, Self::Runtime>,
  1191. ) -> Result<DetachedWindow<T, Self::Runtime>> {
  1192. self.context.create_webview(pending)
  1193. }
  1194. fn set_resizable(&self, resizable: bool) -> Result<()> {
  1195. send_user_message(
  1196. &self.context,
  1197. Message::Window(self.window_id, WindowMessage::SetResizable(resizable)),
  1198. )
  1199. }
  1200. fn set_title<S: Into<String>>(&self, title: S) -> Result<()> {
  1201. send_user_message(
  1202. &self.context,
  1203. Message::Window(self.window_id, WindowMessage::SetTitle(title.into())),
  1204. )
  1205. }
  1206. fn maximize(&self) -> Result<()> {
  1207. send_user_message(
  1208. &self.context,
  1209. Message::Window(self.window_id, WindowMessage::Maximize),
  1210. )
  1211. }
  1212. fn unmaximize(&self) -> Result<()> {
  1213. send_user_message(
  1214. &self.context,
  1215. Message::Window(self.window_id, WindowMessage::Unmaximize),
  1216. )
  1217. }
  1218. fn minimize(&self) -> Result<()> {
  1219. send_user_message(
  1220. &self.context,
  1221. Message::Window(self.window_id, WindowMessage::Minimize),
  1222. )
  1223. }
  1224. fn unminimize(&self) -> Result<()> {
  1225. send_user_message(
  1226. &self.context,
  1227. Message::Window(self.window_id, WindowMessage::Unminimize),
  1228. )
  1229. }
  1230. fn show_menu(&self) -> Result<()> {
  1231. send_user_message(
  1232. &self.context,
  1233. Message::Window(self.window_id, WindowMessage::ShowMenu),
  1234. )
  1235. }
  1236. fn hide_menu(&self) -> Result<()> {
  1237. send_user_message(
  1238. &self.context,
  1239. Message::Window(self.window_id, WindowMessage::HideMenu),
  1240. )
  1241. }
  1242. fn show(&self) -> Result<()> {
  1243. send_user_message(
  1244. &self.context,
  1245. Message::Window(self.window_id, WindowMessage::Show),
  1246. )
  1247. }
  1248. fn hide(&self) -> Result<()> {
  1249. send_user_message(
  1250. &self.context,
  1251. Message::Window(self.window_id, WindowMessage::Hide),
  1252. )
  1253. }
  1254. fn close(&self) -> Result<()> {
  1255. // NOTE: close cannot use the `send_user_message` function because it accesses the event loop callback
  1256. self
  1257. .context
  1258. .proxy
  1259. .send_event(Message::Window(self.window_id, WindowMessage::Close))
  1260. .map_err(|_| Error::FailedToSendMessage)
  1261. }
  1262. fn set_decorations(&self, decorations: bool) -> Result<()> {
  1263. send_user_message(
  1264. &self.context,
  1265. Message::Window(self.window_id, WindowMessage::SetDecorations(decorations)),
  1266. )
  1267. }
  1268. fn set_always_on_top(&self, always_on_top: bool) -> Result<()> {
  1269. send_user_message(
  1270. &self.context,
  1271. Message::Window(self.window_id, WindowMessage::SetAlwaysOnTop(always_on_top)),
  1272. )
  1273. }
  1274. fn set_content_protected(&self, protected: bool) -> Result<()> {
  1275. send_user_message(
  1276. &self.context,
  1277. Message::Window(
  1278. self.window_id,
  1279. WindowMessage::SetContentProtected(protected),
  1280. ),
  1281. )
  1282. }
  1283. fn set_size(&self, size: Size) -> Result<()> {
  1284. send_user_message(
  1285. &self.context,
  1286. Message::Window(self.window_id, WindowMessage::SetSize(size)),
  1287. )
  1288. }
  1289. fn set_min_size(&self, size: Option<Size>) -> Result<()> {
  1290. send_user_message(
  1291. &self.context,
  1292. Message::Window(self.window_id, WindowMessage::SetMinSize(size)),
  1293. )
  1294. }
  1295. fn set_max_size(&self, size: Option<Size>) -> Result<()> {
  1296. send_user_message(
  1297. &self.context,
  1298. Message::Window(self.window_id, WindowMessage::SetMaxSize(size)),
  1299. )
  1300. }
  1301. fn set_position(&self, position: Position) -> Result<()> {
  1302. send_user_message(
  1303. &self.context,
  1304. Message::Window(self.window_id, WindowMessage::SetPosition(position)),
  1305. )
  1306. }
  1307. fn set_fullscreen(&self, fullscreen: bool) -> Result<()> {
  1308. send_user_message(
  1309. &self.context,
  1310. Message::Window(self.window_id, WindowMessage::SetFullscreen(fullscreen)),
  1311. )
  1312. }
  1313. fn set_focus(&self) -> Result<()> {
  1314. send_user_message(
  1315. &self.context,
  1316. Message::Window(self.window_id, WindowMessage::SetFocus),
  1317. )
  1318. }
  1319. fn set_icon(&self, icon: Icon) -> Result<()> {
  1320. send_user_message(
  1321. &self.context,
  1322. Message::Window(
  1323. self.window_id,
  1324. WindowMessage::SetIcon(WryIcon::try_from(icon)?.0),
  1325. ),
  1326. )
  1327. }
  1328. fn set_skip_taskbar(&self, skip: bool) -> Result<()> {
  1329. send_user_message(
  1330. &self.context,
  1331. Message::Window(self.window_id, WindowMessage::SetSkipTaskbar(skip)),
  1332. )
  1333. }
  1334. fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  1335. send_user_message(
  1336. &self.context,
  1337. Message::Window(self.window_id, WindowMessage::SetCursorGrab(grab)),
  1338. )
  1339. }
  1340. fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  1341. send_user_message(
  1342. &self.context,
  1343. Message::Window(self.window_id, WindowMessage::SetCursorVisible(visible)),
  1344. )
  1345. }
  1346. fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  1347. send_user_message(
  1348. &self.context,
  1349. Message::Window(self.window_id, WindowMessage::SetCursorIcon(icon)),
  1350. )
  1351. }
  1352. fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1353. send_user_message(
  1354. &self.context,
  1355. Message::Window(
  1356. self.window_id,
  1357. WindowMessage::SetCursorPosition(position.into()),
  1358. ),
  1359. )
  1360. }
  1361. fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
  1362. send_user_message(
  1363. &self.context,
  1364. Message::Window(self.window_id, WindowMessage::SetIgnoreCursorEvents(ignore)),
  1365. )
  1366. }
  1367. fn start_dragging(&self) -> Result<()> {
  1368. send_user_message(
  1369. &self.context,
  1370. Message::Window(self.window_id, WindowMessage::DragWindow),
  1371. )
  1372. }
  1373. fn eval_script<S: Into<String>>(&self, script: S) -> Result<()> {
  1374. send_user_message(
  1375. &self.context,
  1376. Message::Webview(
  1377. self.window_id,
  1378. WebviewMessage::EvaluateScript(script.into()),
  1379. ),
  1380. )
  1381. }
  1382. fn update_menu_item(&self, id: u16, update: MenuUpdate) -> Result<()> {
  1383. send_user_message(
  1384. &self.context,
  1385. Message::Window(self.window_id, WindowMessage::UpdateMenuItem(id, update)),
  1386. )
  1387. }
  1388. }
  1389. #[derive(Clone)]
  1390. enum WindowHandle {
  1391. Webview {
  1392. inner: Arc<WebView>,
  1393. context_store: WebContextStore,
  1394. // the key of the WebContext if it's not shared
  1395. context_key: Option<PathBuf>,
  1396. },
  1397. Window(Arc<Window>),
  1398. }
  1399. impl Drop for WindowHandle {
  1400. fn drop(&mut self) {
  1401. if let Self::Webview {
  1402. inner,
  1403. context_store,
  1404. context_key,
  1405. } = self
  1406. {
  1407. if Arc::get_mut(inner).is_some() {
  1408. context_store.lock().unwrap().remove(context_key);
  1409. }
  1410. }
  1411. }
  1412. }
  1413. impl fmt::Debug for WindowHandle {
  1414. fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1415. Ok(())
  1416. }
  1417. }
  1418. impl Deref for WindowHandle {
  1419. type Target = Window;
  1420. #[inline(always)]
  1421. fn deref(&self) -> &Window {
  1422. match self {
  1423. Self::Webview { inner, .. } => inner.window(),
  1424. Self::Window(w) => w,
  1425. }
  1426. }
  1427. }
  1428. impl WindowHandle {
  1429. fn inner_size(&self) -> WryPhysicalSize<u32> {
  1430. match self {
  1431. WindowHandle::Window(w) => w.inner_size(),
  1432. WindowHandle::Webview { inner, .. } => inner.inner_size(),
  1433. }
  1434. }
  1435. }
  1436. pub struct WindowWrapper {
  1437. label: String,
  1438. inner: Option<WindowHandle>,
  1439. menu_items: Option<HashMap<u16, WryCustomMenuItem>>,
  1440. window_event_listeners: WindowEventListeners,
  1441. menu_event_listeners: WindowMenuEventListeners,
  1442. }
  1443. impl fmt::Debug for WindowWrapper {
  1444. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1445. f.debug_struct("WindowWrapper")
  1446. .field("label", &self.label)
  1447. .field("inner", &self.inner)
  1448. .field("menu_items", &self.menu_items)
  1449. .finish()
  1450. }
  1451. }
  1452. #[derive(Debug, Clone)]
  1453. pub struct EventProxy<T: UserEvent>(WryEventLoopProxy<Message<T>>);
  1454. #[cfg(target_os = "ios")]
  1455. #[allow(clippy::non_send_fields_in_send_ty)]
  1456. unsafe impl<T: UserEvent> Sync for EventProxy<T> {}
  1457. impl<T: UserEvent> EventLoopProxy<T> for EventProxy<T> {
  1458. fn send_event(&self, event: T) -> Result<()> {
  1459. self
  1460. .0
  1461. .send_event(Message::UserEvent(event))
  1462. .map_err(|_| Error::EventLoopClosed)
  1463. }
  1464. }
  1465. pub trait PluginBuilder<T: UserEvent> {
  1466. type Plugin: Plugin<T>;
  1467. fn build(self, context: Context<T>) -> Self::Plugin;
  1468. }
  1469. pub trait Plugin<T: UserEvent> {
  1470. fn on_event(
  1471. &mut self,
  1472. event: &Event<Message<T>>,
  1473. event_loop: &EventLoopWindowTarget<Message<T>>,
  1474. proxy: &WryEventLoopProxy<Message<T>>,
  1475. control_flow: &mut ControlFlow,
  1476. context: EventLoopIterationContext<'_, T>,
  1477. web_context: &WebContextStore,
  1478. ) -> bool;
  1479. }
  1480. /// A Tauri [`Runtime`] wrapper around wry.
  1481. pub struct Wry<T: UserEvent> {
  1482. context: Context<T>,
  1483. plugins: Vec<Box<dyn Plugin<T>>>,
  1484. #[cfg(all(desktop, feature = "global-shortcut"))]
  1485. global_shortcut_manager_handle: GlobalShortcutManagerHandle<T>,
  1486. #[cfg(feature = "clipboard")]
  1487. clipboard_manager_handle: ClipboardManagerWrapper<T>,
  1488. event_loop: EventLoop<Message<T>>,
  1489. }
  1490. impl<T: UserEvent> fmt::Debug for Wry<T> {
  1491. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1492. let mut d = f.debug_struct("Wry");
  1493. d.field("main_thread_id", &self.context.main_thread_id)
  1494. .field("event_loop", &self.event_loop)
  1495. .field("windows", &self.context.main_thread.windows)
  1496. .field("web_context", &self.context.main_thread.web_context);
  1497. #[cfg(all(desktop, feature = "system-tray"))]
  1498. d.field(
  1499. "system_tray_manager",
  1500. &self.context.main_thread.system_tray_manager,
  1501. );
  1502. #[cfg(all(desktop, feature = "global-shortcut"))]
  1503. #[cfg(feature = "global-shortcut")]
  1504. d.field(
  1505. "global_shortcut_manager",
  1506. &self.context.main_thread.global_shortcut_manager,
  1507. )
  1508. .field(
  1509. "global_shortcut_manager_handle",
  1510. &self.global_shortcut_manager_handle,
  1511. );
  1512. #[cfg(feature = "clipboard")]
  1513. d.field(
  1514. "clipboard_manager",
  1515. &self.context.main_thread.clipboard_manager,
  1516. )
  1517. .field("clipboard_manager_handle", &self.clipboard_manager_handle);
  1518. d.finish()
  1519. }
  1520. }
  1521. /// A handle to the Wry runtime.
  1522. #[derive(Debug, Clone)]
  1523. pub struct WryHandle<T: UserEvent> {
  1524. context: Context<T>,
  1525. }
  1526. // SAFETY: this is safe since the `Context` usage is guarded on `send_user_message`.
  1527. #[allow(clippy::non_send_fields_in_send_ty)]
  1528. unsafe impl<T: UserEvent> Sync for WryHandle<T> {}
  1529. impl<T: UserEvent> WryHandle<T> {
  1530. /// Creates a new tao window using a callback, and returns its window id.
  1531. pub fn create_tao_window<F: FnOnce() -> (String, WryWindowBuilder) + Send + 'static>(
  1532. &self,
  1533. f: F,
  1534. ) -> Result<Weak<Window>> {
  1535. let (tx, rx) = channel();
  1536. send_user_message(
  1537. &self.context,
  1538. Message::CreateWindow(rand::random(), Box::new(f), tx),
  1539. )?;
  1540. rx.recv().unwrap()
  1541. }
  1542. /// Gets the [`WebviewId'] associated with the given [`WindowId`].
  1543. pub fn window_id(&self, window_id: WindowId) -> WebviewId {
  1544. *self
  1545. .context
  1546. .webview_id_map
  1547. .0
  1548. .lock()
  1549. .unwrap()
  1550. .get(&window_id)
  1551. .unwrap()
  1552. }
  1553. /// Send a message to the event loop.
  1554. pub fn send_event(&self, message: Message<T>) -> Result<()> {
  1555. self
  1556. .context
  1557. .proxy
  1558. .send_event(message)
  1559. .map_err(|_| Error::FailedToSendMessage)?;
  1560. Ok(())
  1561. }
  1562. }
  1563. impl<T: UserEvent> RuntimeHandle<T> for WryHandle<T> {
  1564. type Runtime = Wry<T>;
  1565. fn create_proxy(&self) -> EventProxy<T> {
  1566. EventProxy(self.context.proxy.clone())
  1567. }
  1568. // Creates a window by dispatching a message to the event loop.
  1569. // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
  1570. fn create_window(
  1571. &self,
  1572. pending: PendingWindow<T, Self::Runtime>,
  1573. ) -> Result<DetachedWindow<T, Self::Runtime>> {
  1574. self.context.create_webview(pending)
  1575. }
  1576. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
  1577. send_user_message(&self.context, Message::Task(Box::new(f)))
  1578. }
  1579. #[cfg(all(desktop, feature = "system-tray"))]
  1580. fn system_tray(
  1581. &self,
  1582. system_tray: SystemTray,
  1583. ) -> Result<<Self::Runtime as Runtime<T>>::TrayHandler> {
  1584. let id = system_tray.id;
  1585. let (tx, rx) = channel();
  1586. send_user_message(
  1587. &self.context,
  1588. Message::Tray(id, TrayMessage::Create(system_tray, tx)),
  1589. )?;
  1590. rx.recv().unwrap()?;
  1591. Ok(SystemTrayHandle {
  1592. context: self.context.clone(),
  1593. id,
  1594. proxy: self.context.proxy.clone(),
  1595. })
  1596. }
  1597. fn raw_display_handle(&self) -> RawDisplayHandle {
  1598. self.context.main_thread.window_target.raw_display_handle()
  1599. }
  1600. #[cfg(target_os = "macos")]
  1601. fn show(&self) -> tauri_runtime::Result<()> {
  1602. send_user_message(
  1603. &self.context,
  1604. Message::Application(ApplicationMessage::Show),
  1605. )
  1606. }
  1607. #[cfg(target_os = "macos")]
  1608. fn hide(&self) -> tauri_runtime::Result<()> {
  1609. send_user_message(
  1610. &self.context,
  1611. Message::Application(ApplicationMessage::Hide),
  1612. )
  1613. }
  1614. }
  1615. impl<T: UserEvent> Wry<T> {
  1616. fn init(event_loop: EventLoop<Message<T>>) -> Result<Self> {
  1617. let main_thread_id = current_thread().id();
  1618. let web_context = WebContextStore::default();
  1619. #[cfg(all(desktop, feature = "global-shortcut"))]
  1620. let global_shortcut_manager = Arc::new(Mutex::new(WryShortcutManager::new(&event_loop)));
  1621. #[cfg(feature = "clipboard")]
  1622. let clipboard_manager = Arc::new(Mutex::new(Clipboard::new()));
  1623. let windows = Arc::new(RefCell::new(HashMap::default()));
  1624. let webview_id_map = WebviewIdStore::default();
  1625. #[cfg(all(desktop, feature = "system-tray"))]
  1626. let system_tray_manager = Default::default();
  1627. let context = Context {
  1628. webview_id_map,
  1629. main_thread_id,
  1630. proxy: event_loop.create_proxy(),
  1631. main_thread: DispatcherMainThreadContext {
  1632. window_target: event_loop.deref().clone(),
  1633. web_context,
  1634. #[cfg(all(desktop, feature = "global-shortcut"))]
  1635. global_shortcut_manager,
  1636. #[cfg(feature = "clipboard")]
  1637. clipboard_manager,
  1638. windows,
  1639. #[cfg(all(desktop, feature = "system-tray"))]
  1640. system_tray_manager,
  1641. },
  1642. };
  1643. #[cfg(all(desktop, feature = "global-shortcut"))]
  1644. let global_shortcut_manager_handle = GlobalShortcutManagerHandle {
  1645. context: context.clone(),
  1646. shortcuts: Default::default(),
  1647. listeners: Default::default(),
  1648. };
  1649. #[cfg(feature = "clipboard")]
  1650. #[allow(clippy::redundant_clone)]
  1651. let clipboard_manager_handle = ClipboardManagerWrapper {
  1652. context: context.clone(),
  1653. };
  1654. Ok(Self {
  1655. context,
  1656. plugins: Default::default(),
  1657. #[cfg(all(desktop, feature = "global-shortcut"))]
  1658. global_shortcut_manager_handle,
  1659. #[cfg(feature = "clipboard")]
  1660. clipboard_manager_handle,
  1661. event_loop,
  1662. })
  1663. }
  1664. pub fn plugin<P: PluginBuilder<T> + 'static>(&mut self, plugin: P) {
  1665. self
  1666. .plugins
  1667. .push(Box::new(plugin.build(self.context.clone())));
  1668. }
  1669. }
  1670. impl<T: UserEvent> Runtime<T> for Wry<T> {
  1671. type Dispatcher = WryDispatcher<T>;
  1672. type Handle = WryHandle<T>;
  1673. #[cfg(all(desktop, feature = "global-shortcut"))]
  1674. type GlobalShortcutManager = GlobalShortcutManagerHandle<T>;
  1675. #[cfg(feature = "clipboard")]
  1676. type ClipboardManager = ClipboardManagerWrapper<T>;
  1677. #[cfg(all(desktop, feature = "system-tray"))]
  1678. type TrayHandler = SystemTrayHandle<T>;
  1679. type EventLoopProxy = EventProxy<T>;
  1680. fn new() -> Result<Self> {
  1681. let event_loop = EventLoop::<Message<T>>::with_user_event();
  1682. Self::init(event_loop)
  1683. }
  1684. #[cfg(any(windows, target_os = "linux"))]
  1685. fn new_any_thread() -> Result<Self> {
  1686. #[cfg(target_os = "linux")]
  1687. use wry::application::platform::unix::EventLoopExtUnix;
  1688. #[cfg(windows)]
  1689. use wry::application::platform::windows::EventLoopExtWindows;
  1690. let event_loop = EventLoop::<Message<T>>::new_any_thread();
  1691. Self::init(event_loop)
  1692. }
  1693. fn create_proxy(&self) -> EventProxy<T> {
  1694. EventProxy(self.event_loop.create_proxy())
  1695. }
  1696. fn handle(&self) -> Self::Handle {
  1697. WryHandle {
  1698. context: self.context.clone(),
  1699. }
  1700. }
  1701. #[cfg(all(desktop, feature = "global-shortcut"))]
  1702. fn global_shortcut_manager(&self) -> Self::GlobalShortcutManager {
  1703. self.global_shortcut_manager_handle.clone()
  1704. }
  1705. #[cfg(feature = "clipboard")]
  1706. fn clipboard_manager(&self) -> Self::ClipboardManager {
  1707. self.clipboard_manager_handle.clone()
  1708. }
  1709. fn create_window(&self, pending: PendingWindow<T, Self>) -> Result<DetachedWindow<T, Self>> {
  1710. let label = pending.label.clone();
  1711. let menu_ids = pending.menu_ids.clone();
  1712. let js_event_listeners = pending.js_event_listeners.clone();
  1713. let window_id = rand::random();
  1714. let webview = create_webview(
  1715. window_id,
  1716. &self.event_loop,
  1717. &self.context.main_thread.web_context,
  1718. self.context.clone(),
  1719. pending,
  1720. )?;
  1721. let dispatcher = WryDispatcher {
  1722. window_id,
  1723. context: self.context.clone(),
  1724. };
  1725. self
  1726. .context
  1727. .main_thread
  1728. .windows
  1729. .borrow_mut()
  1730. .insert(window_id, webview);
  1731. Ok(DetachedWindow {
  1732. label,
  1733. dispatcher,
  1734. menu_ids,
  1735. js_event_listeners,
  1736. })
  1737. }
  1738. #[cfg(all(desktop, feature = "system-tray"))]
  1739. fn system_tray(&self, mut system_tray: SystemTray) -> Result<Self::TrayHandler> {
  1740. let id = system_tray.id;
  1741. let mut listeners = Vec::new();
  1742. if let Some(l) = system_tray.on_event.take() {
  1743. listeners.push(Arc::new(l));
  1744. }
  1745. let (tray, items) = create_tray(WryTrayId(id), system_tray, &self.event_loop)?;
  1746. self
  1747. .context
  1748. .main_thread
  1749. .system_tray_manager
  1750. .trays
  1751. .lock()
  1752. .unwrap()
  1753. .insert(
  1754. id,
  1755. TrayContext {
  1756. tray: Arc::new(Mutex::new(Some(tray))),
  1757. listeners: Arc::new(Mutex::new(listeners)),
  1758. items: Arc::new(Mutex::new(items)),
  1759. },
  1760. );
  1761. Ok(SystemTrayHandle {
  1762. context: self.context.clone(),
  1763. id,
  1764. proxy: self.event_loop.create_proxy(),
  1765. })
  1766. }
  1767. #[cfg(all(desktop, feature = "system-tray"))]
  1768. fn on_system_tray_event<F: Fn(TrayId, &SystemTrayEvent) + Send + 'static>(&mut self, f: F) {
  1769. self
  1770. .context
  1771. .main_thread
  1772. .system_tray_manager
  1773. .global_listeners
  1774. .lock()
  1775. .unwrap()
  1776. .push(Arc::new(Box::new(f)));
  1777. }
  1778. #[cfg(target_os = "macos")]
  1779. fn set_activation_policy(&mut self, activation_policy: ActivationPolicy) {
  1780. self
  1781. .event_loop
  1782. .set_activation_policy(match activation_policy {
  1783. ActivationPolicy::Regular => WryActivationPolicy::Regular,
  1784. ActivationPolicy::Accessory => WryActivationPolicy::Accessory,
  1785. ActivationPolicy::Prohibited => WryActivationPolicy::Prohibited,
  1786. _ => unimplemented!(),
  1787. });
  1788. }
  1789. #[cfg(target_os = "macos")]
  1790. fn show(&self) {
  1791. self.event_loop.show_application();
  1792. }
  1793. #[cfg(target_os = "macos")]
  1794. fn hide(&self) {
  1795. self.event_loop.hide_application();
  1796. }
  1797. #[cfg(desktop)]
  1798. fn run_iteration<F: FnMut(RunEvent<T>) + 'static>(&mut self, mut callback: F) -> RunIteration {
  1799. use wry::application::platform::run_return::EventLoopExtRunReturn;
  1800. let windows = self.context.main_thread.windows.clone();
  1801. let webview_id_map = self.context.webview_id_map.clone();
  1802. let web_context = &self.context.main_thread.web_context;
  1803. let plugins = &mut self.plugins;
  1804. #[cfg(all(desktop, feature = "system-tray"))]
  1805. let system_tray_manager = self.context.main_thread.system_tray_manager.clone();
  1806. #[cfg(all(desktop, feature = "global-shortcut"))]
  1807. let global_shortcut_manager = self.context.main_thread.global_shortcut_manager.clone();
  1808. #[cfg(all(desktop, feature = "global-shortcut"))]
  1809. let global_shortcut_manager_handle = self.global_shortcut_manager_handle.clone();
  1810. #[cfg(feature = "clipboard")]
  1811. let clipboard_manager = self.context.main_thread.clipboard_manager.clone();
  1812. let mut iteration = RunIteration::default();
  1813. let proxy = self.event_loop.create_proxy();
  1814. self
  1815. .event_loop
  1816. .run_return(|event, event_loop, control_flow| {
  1817. *control_flow = ControlFlow::Wait;
  1818. if let Event::MainEventsCleared = &event {
  1819. *control_flow = ControlFlow::Exit;
  1820. }
  1821. for p in plugins.iter_mut() {
  1822. let prevent_default = p.on_event(
  1823. &event,
  1824. event_loop,
  1825. &proxy,
  1826. control_flow,
  1827. EventLoopIterationContext {
  1828. callback: &mut callback,
  1829. webview_id_map: webview_id_map.clone(),
  1830. windows: windows.clone(),
  1831. #[cfg(all(desktop, feature = "global-shortcut"))]
  1832. global_shortcut_manager: global_shortcut_manager.clone(),
  1833. #[cfg(all(desktop, feature = "global-shortcut"))]
  1834. global_shortcut_manager_handle: &global_shortcut_manager_handle,
  1835. #[cfg(feature = "clipboard")]
  1836. clipboard_manager: clipboard_manager.clone(),
  1837. #[cfg(all(desktop, feature = "system-tray"))]
  1838. system_tray_manager: system_tray_manager.clone(),
  1839. },
  1840. web_context,
  1841. );
  1842. if prevent_default {
  1843. return;
  1844. }
  1845. }
  1846. iteration = handle_event_loop(
  1847. event,
  1848. event_loop,
  1849. control_flow,
  1850. EventLoopIterationContext {
  1851. callback: &mut callback,
  1852. windows: windows.clone(),
  1853. webview_id_map: webview_id_map.clone(),
  1854. #[cfg(all(desktop, feature = "global-shortcut"))]
  1855. global_shortcut_manager: global_shortcut_manager.clone(),
  1856. #[cfg(all(desktop, feature = "global-shortcut"))]
  1857. global_shortcut_manager_handle: &global_shortcut_manager_handle,
  1858. #[cfg(feature = "clipboard")]
  1859. clipboard_manager: clipboard_manager.clone(),
  1860. #[cfg(all(desktop, feature = "system-tray"))]
  1861. system_tray_manager: system_tray_manager.clone(),
  1862. },
  1863. web_context,
  1864. );
  1865. });
  1866. iteration
  1867. }
  1868. fn run<F: FnMut(RunEvent<T>) + 'static>(self, mut callback: F) {
  1869. let windows = self.context.main_thread.windows.clone();
  1870. let webview_id_map = self.context.webview_id_map.clone();
  1871. let web_context = self.context.main_thread.web_context;
  1872. let mut plugins = self.plugins;
  1873. #[cfg(all(desktop, feature = "system-tray"))]
  1874. let system_tray_manager = self.context.main_thread.system_tray_manager;
  1875. #[cfg(all(desktop, feature = "global-shortcut"))]
  1876. let global_shortcut_manager = self.context.main_thread.global_shortcut_manager.clone();
  1877. #[cfg(all(desktop, feature = "global-shortcut"))]
  1878. let global_shortcut_manager_handle = self.global_shortcut_manager_handle.clone();
  1879. #[cfg(feature = "clipboard")]
  1880. let clipboard_manager = self.context.main_thread.clipboard_manager.clone();
  1881. let proxy = self.event_loop.create_proxy();
  1882. self.event_loop.run(move |event, event_loop, control_flow| {
  1883. for p in &mut plugins {
  1884. let prevent_default = p.on_event(
  1885. &event,
  1886. event_loop,
  1887. &proxy,
  1888. control_flow,
  1889. EventLoopIterationContext {
  1890. callback: &mut callback,
  1891. webview_id_map: webview_id_map.clone(),
  1892. windows: windows.clone(),
  1893. #[cfg(all(desktop, feature = "global-shortcut"))]
  1894. global_shortcut_manager: global_shortcut_manager.clone(),
  1895. #[cfg(all(desktop, feature = "global-shortcut"))]
  1896. global_shortcut_manager_handle: &global_shortcut_manager_handle,
  1897. #[cfg(feature = "clipboard")]
  1898. clipboard_manager: clipboard_manager.clone(),
  1899. #[cfg(all(desktop, feature = "system-tray"))]
  1900. system_tray_manager: system_tray_manager.clone(),
  1901. },
  1902. &web_context,
  1903. );
  1904. if prevent_default {
  1905. return;
  1906. }
  1907. }
  1908. handle_event_loop(
  1909. event,
  1910. event_loop,
  1911. control_flow,
  1912. EventLoopIterationContext {
  1913. callback: &mut callback,
  1914. webview_id_map: webview_id_map.clone(),
  1915. windows: windows.clone(),
  1916. #[cfg(all(desktop, feature = "global-shortcut"))]
  1917. global_shortcut_manager: global_shortcut_manager.clone(),
  1918. #[cfg(all(desktop, feature = "global-shortcut"))]
  1919. global_shortcut_manager_handle: &global_shortcut_manager_handle,
  1920. #[cfg(feature = "clipboard")]
  1921. clipboard_manager: clipboard_manager.clone(),
  1922. #[cfg(all(desktop, feature = "system-tray"))]
  1923. system_tray_manager: system_tray_manager.clone(),
  1924. },
  1925. &web_context,
  1926. );
  1927. })
  1928. }
  1929. }
  1930. pub struct EventLoopIterationContext<'a, T: UserEvent> {
  1931. pub callback: &'a mut (dyn FnMut(RunEvent<T>) + 'static),
  1932. pub webview_id_map: WebviewIdStore,
  1933. pub windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
  1934. #[cfg(all(desktop, feature = "global-shortcut"))]
  1935. pub global_shortcut_manager: Arc<Mutex<WryShortcutManager>>,
  1936. #[cfg(all(desktop, feature = "global-shortcut"))]
  1937. pub global_shortcut_manager_handle: &'a GlobalShortcutManagerHandle<T>,
  1938. #[cfg(feature = "clipboard")]
  1939. pub clipboard_manager: Arc<Mutex<Clipboard>>,
  1940. #[cfg(all(desktop, feature = "system-tray"))]
  1941. pub system_tray_manager: SystemTrayManager,
  1942. }
  1943. struct UserMessageContext {
  1944. windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
  1945. webview_id_map: WebviewIdStore,
  1946. #[cfg(all(desktop, feature = "global-shortcut"))]
  1947. global_shortcut_manager: Arc<Mutex<WryShortcutManager>>,
  1948. #[cfg(feature = "clipboard")]
  1949. clipboard_manager: Arc<Mutex<Clipboard>>,
  1950. #[cfg(all(desktop, feature = "system-tray"))]
  1951. system_tray_manager: SystemTrayManager,
  1952. }
  1953. fn handle_user_message<T: UserEvent>(
  1954. event_loop: &EventLoopWindowTarget<Message<T>>,
  1955. message: Message<T>,
  1956. context: UserMessageContext,
  1957. web_context: &WebContextStore,
  1958. ) -> RunIteration {
  1959. let UserMessageContext {
  1960. webview_id_map,
  1961. #[cfg(all(desktop, feature = "global-shortcut"))]
  1962. global_shortcut_manager,
  1963. #[cfg(feature = "clipboard")]
  1964. clipboard_manager,
  1965. windows,
  1966. #[cfg(all(desktop, feature = "system-tray"))]
  1967. system_tray_manager,
  1968. } = context;
  1969. match message {
  1970. Message::Task(task) => task(),
  1971. #[cfg(target_os = "macos")]
  1972. Message::Application(application_message) => match application_message {
  1973. ApplicationMessage::Show => {
  1974. event_loop.show_application();
  1975. }
  1976. ApplicationMessage::Hide => {
  1977. event_loop.hide_application();
  1978. }
  1979. },
  1980. Message::Window(id, window_message) => {
  1981. if let WindowMessage::UpdateMenuItem(item_id, update) = window_message {
  1982. if let Some(menu_items) = windows.borrow_mut().get_mut(&id).map(|w| &mut w.menu_items) {
  1983. if let Some(menu_items) = menu_items.as_mut() {
  1984. let item = menu_items.get_mut(&item_id).expect("menu item not found");
  1985. match update {
  1986. MenuUpdate::SetEnabled(enabled) => item.set_enabled(enabled),
  1987. MenuUpdate::SetTitle(title) => item.set_title(&title),
  1988. MenuUpdate::SetSelected(selected) => item.set_selected(selected),
  1989. #[cfg(target_os = "macos")]
  1990. MenuUpdate::SetNativeImage(image) => {
  1991. item.set_native_image(NativeImageWrapper::from(image).0)
  1992. }
  1993. }
  1994. }
  1995. }
  1996. } else {
  1997. let w = windows.borrow().get(&id).map(|w| {
  1998. (
  1999. w.inner.clone(),
  2000. w.window_event_listeners.clone(),
  2001. w.menu_event_listeners.clone(),
  2002. )
  2003. });
  2004. if let Some((Some(window), window_event_listeners, menu_event_listeners)) = w {
  2005. match window_message {
  2006. #[cfg(desktop)]
  2007. WindowMessage::WithWebview(f) => {
  2008. if let WindowHandle::Webview { inner: w, .. } = &window {
  2009. #[cfg(any(
  2010. target_os = "linux",
  2011. target_os = "dragonfly",
  2012. target_os = "freebsd",
  2013. target_os = "netbsd",
  2014. target_os = "openbsd"
  2015. ))]
  2016. {
  2017. use wry::webview::WebviewExtUnix;
  2018. f(w.webview());
  2019. }
  2020. #[cfg(target_os = "macos")]
  2021. {
  2022. use wry::webview::WebviewExtMacOS;
  2023. f(Webview {
  2024. webview: w.webview(),
  2025. manager: w.manager(),
  2026. ns_window: w.ns_window(),
  2027. });
  2028. }
  2029. #[cfg(windows)]
  2030. {
  2031. f(Webview {
  2032. controller: w.controller(),
  2033. });
  2034. }
  2035. }
  2036. }
  2037. WindowMessage::AddEventListener(id, listener) => {
  2038. window_event_listeners.lock().unwrap().insert(id, listener);
  2039. }
  2040. WindowMessage::AddMenuEventListener(id, listener) => {
  2041. menu_event_listeners.lock().unwrap().insert(id, listener);
  2042. }
  2043. #[cfg(any(debug_assertions, feature = "devtools"))]
  2044. WindowMessage::OpenDevTools => {
  2045. if let WindowHandle::Webview { inner: w, .. } = &window {
  2046. w.open_devtools();
  2047. }
  2048. }
  2049. #[cfg(any(debug_assertions, feature = "devtools"))]
  2050. WindowMessage::CloseDevTools => {
  2051. if let WindowHandle::Webview { inner: w, .. } = &window {
  2052. w.close_devtools();
  2053. }
  2054. }
  2055. #[cfg(any(debug_assertions, feature = "devtools"))]
  2056. WindowMessage::IsDevToolsOpen(tx) => {
  2057. if let WindowHandle::Webview { inner: w, .. } = &window {
  2058. tx.send(w.is_devtools_open()).unwrap();
  2059. } else {
  2060. tx.send(false).unwrap();
  2061. }
  2062. }
  2063. // Getters
  2064. WindowMessage::ScaleFactor(tx) => tx.send(window.scale_factor()).unwrap(),
  2065. WindowMessage::InnerPosition(tx) => tx
  2066. .send(
  2067. window
  2068. .inner_position()
  2069. .map(|p| PhysicalPositionWrapper(p).into())
  2070. .map_err(|_| Error::FailedToSendMessage),
  2071. )
  2072. .unwrap(),
  2073. WindowMessage::OuterPosition(tx) => tx
  2074. .send(
  2075. window
  2076. .outer_position()
  2077. .map(|p| PhysicalPositionWrapper(p).into())
  2078. .map_err(|_| Error::FailedToSendMessage),
  2079. )
  2080. .unwrap(),
  2081. WindowMessage::InnerSize(tx) => tx
  2082. .send(PhysicalSizeWrapper(window.inner_size()).into())
  2083. .unwrap(),
  2084. WindowMessage::OuterSize(tx) => tx
  2085. .send(PhysicalSizeWrapper(window.outer_size()).into())
  2086. .unwrap(),
  2087. WindowMessage::IsFullscreen(tx) => tx.send(window.fullscreen().is_some()).unwrap(),
  2088. WindowMessage::IsMinimized(tx) => tx.send(window.is_minimized()).unwrap(),
  2089. WindowMessage::IsMaximized(tx) => tx.send(window.is_maximized()).unwrap(),
  2090. WindowMessage::IsDecorated(tx) => tx.send(window.is_decorated()).unwrap(),
  2091. WindowMessage::IsResizable(tx) => tx.send(window.is_resizable()).unwrap(),
  2092. WindowMessage::IsVisible(tx) => tx.send(window.is_visible()).unwrap(),
  2093. WindowMessage::Title(tx) => tx.send(window.title()).unwrap(),
  2094. WindowMessage::IsMenuVisible(tx) => tx.send(window.is_menu_visible()).unwrap(),
  2095. WindowMessage::CurrentMonitor(tx) => tx.send(window.current_monitor()).unwrap(),
  2096. WindowMessage::PrimaryMonitor(tx) => tx.send(window.primary_monitor()).unwrap(),
  2097. WindowMessage::AvailableMonitors(tx) => {
  2098. tx.send(window.available_monitors().collect()).unwrap()
  2099. }
  2100. #[cfg(any(
  2101. target_os = "linux",
  2102. target_os = "dragonfly",
  2103. target_os = "freebsd",
  2104. target_os = "netbsd",
  2105. target_os = "openbsd"
  2106. ))]
  2107. WindowMessage::GtkWindow(tx) => {
  2108. tx.send(GtkWindow(window.gtk_window().clone())).unwrap()
  2109. }
  2110. WindowMessage::RawWindowHandle(tx) => tx
  2111. .send(RawWindowHandle(window.raw_window_handle()))
  2112. .unwrap(),
  2113. WindowMessage::Theme(tx) => {
  2114. tx.send(map_theme(&window.theme())).unwrap();
  2115. }
  2116. // Setters
  2117. WindowMessage::Center => {
  2118. let _ = center_window(&window, window.inner_size());
  2119. }
  2120. WindowMessage::RequestUserAttention(request_type) => {
  2121. window.request_user_attention(request_type.map(|r| r.0));
  2122. }
  2123. WindowMessage::SetResizable(resizable) => window.set_resizable(resizable),
  2124. WindowMessage::SetTitle(title) => window.set_title(&title),
  2125. WindowMessage::Maximize => window.set_maximized(true),
  2126. WindowMessage::Unmaximize => window.set_maximized(false),
  2127. WindowMessage::Minimize => window.set_minimized(true),
  2128. WindowMessage::Unminimize => window.set_minimized(false),
  2129. WindowMessage::ShowMenu => window.show_menu(),
  2130. WindowMessage::HideMenu => window.hide_menu(),
  2131. WindowMessage::Show => window.set_visible(true),
  2132. WindowMessage::Hide => window.set_visible(false),
  2133. WindowMessage::Close => {
  2134. panic!("cannot handle `WindowMessage::Close` on the main thread")
  2135. }
  2136. WindowMessage::SetDecorations(decorations) => window.set_decorations(decorations),
  2137. WindowMessage::SetAlwaysOnTop(always_on_top) => window.set_always_on_top(always_on_top),
  2138. WindowMessage::SetContentProtected(protected) => {
  2139. window.set_content_protection(protected)
  2140. }
  2141. WindowMessage::SetSize(size) => {
  2142. window.set_inner_size(SizeWrapper::from(size).0);
  2143. }
  2144. WindowMessage::SetMinSize(size) => {
  2145. window.set_min_inner_size(size.map(|s| SizeWrapper::from(s).0));
  2146. }
  2147. WindowMessage::SetMaxSize(size) => {
  2148. window.set_max_inner_size(size.map(|s| SizeWrapper::from(s).0));
  2149. }
  2150. WindowMessage::SetPosition(position) => {
  2151. window.set_outer_position(PositionWrapper::from(position).0)
  2152. }
  2153. WindowMessage::SetFullscreen(fullscreen) => {
  2154. if fullscreen {
  2155. window.set_fullscreen(Some(Fullscreen::Borderless(None)))
  2156. } else {
  2157. window.set_fullscreen(None)
  2158. }
  2159. }
  2160. WindowMessage::SetFocus => {
  2161. window.set_focus();
  2162. }
  2163. WindowMessage::SetIcon(icon) => {
  2164. window.set_window_icon(Some(icon));
  2165. }
  2166. #[allow(unused_variables)]
  2167. WindowMessage::SetSkipTaskbar(skip) => {
  2168. #[cfg(any(windows, target_os = "linux"))]
  2169. window.set_skip_taskbar(skip);
  2170. }
  2171. WindowMessage::SetCursorGrab(grab) => {
  2172. let _ = window.set_cursor_grab(grab);
  2173. }
  2174. WindowMessage::SetCursorVisible(visible) => {
  2175. window.set_cursor_visible(visible);
  2176. }
  2177. WindowMessage::SetCursorIcon(icon) => {
  2178. window.set_cursor_icon(CursorIconWrapper::from(icon).0);
  2179. }
  2180. WindowMessage::SetCursorPosition(position) => {
  2181. let _ = window.set_cursor_position(PositionWrapper::from(position).0);
  2182. }
  2183. WindowMessage::SetIgnoreCursorEvents(ignore) => {
  2184. let _ = window.set_ignore_cursor_events(ignore);
  2185. }
  2186. WindowMessage::DragWindow => {
  2187. let _ = window.drag_window();
  2188. }
  2189. WindowMessage::UpdateMenuItem(_id, _update) => {
  2190. // already handled
  2191. }
  2192. WindowMessage::RequestRedraw => {
  2193. window.request_redraw();
  2194. }
  2195. }
  2196. }
  2197. }
  2198. }
  2199. Message::Webview(id, webview_message) => match webview_message {
  2200. WebviewMessage::EvaluateScript(script) => {
  2201. if let Some(WindowHandle::Webview { inner: webview, .. }) =
  2202. windows.borrow().get(&id).and_then(|w| w.inner.as_ref())
  2203. {
  2204. if let Err(e) = webview.evaluate_script(&script) {
  2205. debug_eprintln!("{}", e);
  2206. }
  2207. }
  2208. }
  2209. WebviewMessage::Print => {
  2210. if let Some(WindowHandle::Webview { inner: webview, .. }) =
  2211. windows.borrow().get(&id).and_then(|w| w.inner.as_ref())
  2212. {
  2213. let _ = webview.print();
  2214. }
  2215. }
  2216. WebviewMessage::WebviewEvent(event) => {
  2217. let window_event_listeners = windows
  2218. .borrow()
  2219. .get(&id)
  2220. .map(|w| w.window_event_listeners.clone());
  2221. if let Some(window_event_listeners) = window_event_listeners {
  2222. if let Some(event) = WindowEventWrapper::from(&event).0 {
  2223. let listeners = window_event_listeners.lock().unwrap();
  2224. let handlers = listeners.values();
  2225. for handler in handlers {
  2226. handler(&event);
  2227. }
  2228. }
  2229. }
  2230. }
  2231. },
  2232. Message::CreateWebview(window_id, handler) => match handler(event_loop, web_context) {
  2233. Ok(webview) => {
  2234. windows.borrow_mut().insert(window_id, webview);
  2235. }
  2236. Err(e) => {
  2237. debug_eprintln!("{}", e);
  2238. }
  2239. },
  2240. Message::CreateWindow(window_id, handler, sender) => {
  2241. let (label, builder) = handler();
  2242. if let Ok(window) = builder.build(event_loop) {
  2243. webview_id_map.insert(window.id(), window_id);
  2244. let w = Arc::new(window);
  2245. windows.borrow_mut().insert(
  2246. window_id,
  2247. WindowWrapper {
  2248. label,
  2249. inner: Some(WindowHandle::Window(w.clone())),
  2250. menu_items: Default::default(),
  2251. window_event_listeners: Default::default(),
  2252. menu_event_listeners: Default::default(),
  2253. },
  2254. );
  2255. sender.send(Ok(Arc::downgrade(&w))).unwrap();
  2256. } else {
  2257. sender.send(Err(Error::CreateWindow)).unwrap();
  2258. }
  2259. }
  2260. #[cfg(all(desktop, feature = "system-tray"))]
  2261. Message::Tray(tray_id, tray_message) => {
  2262. let mut trays = system_tray_manager.trays.lock().unwrap();
  2263. if let TrayMessage::Create(tray, tx) = tray_message {
  2264. match create_tray(WryTrayId(tray_id), tray, event_loop) {
  2265. Ok((tray, items)) => {
  2266. trays.insert(
  2267. tray_id,
  2268. TrayContext {
  2269. tray: Arc::new(Mutex::new(Some(tray))),
  2270. listeners: Default::default(),
  2271. items: Arc::new(Mutex::new(items)),
  2272. },
  2273. );
  2274. tx.send(Ok(())).unwrap();
  2275. }
  2276. Err(e) => {
  2277. tx.send(Err(e)).unwrap();
  2278. }
  2279. }
  2280. } else if let Some(tray_context) = trays.get(&tray_id) {
  2281. match tray_message {
  2282. TrayMessage::UpdateItem(menu_id, update) => {
  2283. let mut tray = tray_context.items.as_ref().lock().unwrap();
  2284. let item = tray.get_mut(&menu_id).expect("menu item not found");
  2285. match update {
  2286. MenuUpdate::SetEnabled(enabled) => item.set_enabled(enabled),
  2287. MenuUpdate::SetTitle(title) => item.set_title(&title),
  2288. MenuUpdate::SetSelected(selected) => item.set_selected(selected),
  2289. #[cfg(target_os = "macos")]
  2290. MenuUpdate::SetNativeImage(image) => {
  2291. item.set_native_image(NativeImageWrapper::from(image).0)
  2292. }
  2293. }
  2294. }
  2295. TrayMessage::UpdateMenu(menu) => {
  2296. if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
  2297. let mut items = HashMap::new();
  2298. tray.set_menu(&to_wry_context_menu(&mut items, menu));
  2299. *tray_context.items.lock().unwrap() = items;
  2300. }
  2301. }
  2302. TrayMessage::UpdateIcon(icon) => {
  2303. if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
  2304. if let Ok(icon) = TrayIcon::try_from(icon) {
  2305. tray.set_icon(icon.0);
  2306. }
  2307. }
  2308. }
  2309. #[cfg(target_os = "macos")]
  2310. TrayMessage::UpdateIconAsTemplate(is_template) => {
  2311. if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
  2312. tray.set_icon_as_template(is_template);
  2313. }
  2314. }
  2315. #[cfg(target_os = "macos")]
  2316. TrayMessage::UpdateTitle(title) => {
  2317. if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
  2318. tray.set_title(&title);
  2319. }
  2320. }
  2321. TrayMessage::Create(_tray, _tx) => {
  2322. // already handled
  2323. }
  2324. TrayMessage::Destroy(tx) => {
  2325. *tray_context.tray.lock().unwrap() = None;
  2326. tray_context.listeners.lock().unwrap().clear();
  2327. tray_context.items.lock().unwrap().clear();
  2328. tx.send(Ok(())).unwrap();
  2329. }
  2330. }
  2331. }
  2332. }
  2333. #[cfg(all(desktop, feature = "global-shortcut"))]
  2334. Message::GlobalShortcut(message) => {
  2335. handle_global_shortcut_message(message, &global_shortcut_manager)
  2336. }
  2337. #[cfg(feature = "clipboard")]
  2338. Message::Clipboard(message) => handle_clipboard_message(message, &clipboard_manager),
  2339. Message::UserEvent(_) => (),
  2340. }
  2341. let it = RunIteration {
  2342. window_count: windows.borrow().len(),
  2343. };
  2344. it
  2345. }
  2346. fn handle_event_loop<T: UserEvent>(
  2347. event: Event<'_, Message<T>>,
  2348. event_loop: &EventLoopWindowTarget<Message<T>>,
  2349. control_flow: &mut ControlFlow,
  2350. context: EventLoopIterationContext<'_, T>,
  2351. web_context: &WebContextStore,
  2352. ) -> RunIteration {
  2353. let EventLoopIterationContext {
  2354. callback,
  2355. webview_id_map,
  2356. windows,
  2357. #[cfg(all(desktop, feature = "global-shortcut"))]
  2358. global_shortcut_manager,
  2359. #[cfg(all(desktop, feature = "global-shortcut"))]
  2360. global_shortcut_manager_handle,
  2361. #[cfg(feature = "clipboard")]
  2362. clipboard_manager,
  2363. #[cfg(all(desktop, feature = "system-tray"))]
  2364. system_tray_manager,
  2365. } = context;
  2366. if *control_flow != ControlFlow::Exit {
  2367. *control_flow = ControlFlow::Wait;
  2368. }
  2369. match event {
  2370. Event::NewEvents(StartCause::Init) => {
  2371. callback(RunEvent::Ready);
  2372. }
  2373. Event::NewEvents(StartCause::Poll) => {
  2374. callback(RunEvent::Resumed);
  2375. }
  2376. Event::MainEventsCleared => {
  2377. callback(RunEvent::MainEventsCleared);
  2378. }
  2379. Event::LoopDestroyed => {
  2380. callback(RunEvent::Exit);
  2381. }
  2382. #[cfg(all(desktop, feature = "global-shortcut"))]
  2383. Event::GlobalShortcutEvent(accelerator_id) => {
  2384. for (id, handler) in &*global_shortcut_manager_handle.listeners.lock().unwrap() {
  2385. if accelerator_id == *id {
  2386. handler();
  2387. }
  2388. }
  2389. }
  2390. Event::MenuEvent {
  2391. window_id,
  2392. menu_id,
  2393. origin: MenuType::MenuBar,
  2394. ..
  2395. } => {
  2396. #[allow(unused_mut)]
  2397. let mut window_id = window_id.unwrap(); // always Some on MenuBar event
  2398. #[cfg(target_os = "macos")]
  2399. {
  2400. // safety: we're only checking to see if the window_id is 0
  2401. // which is the value sent by macOS when the window is minimized (NSApplication::sharedApplication::mainWindow is null)
  2402. if window_id == unsafe { WindowId::dummy() } {
  2403. window_id = *webview_id_map.0.lock().unwrap().keys().next().unwrap();
  2404. }
  2405. }
  2406. let event = MenuEvent {
  2407. menu_item_id: menu_id.0,
  2408. };
  2409. let window_menu_event_listeners = {
  2410. // on macOS the window id might be the inspector window if it is detached
  2411. let window_id = if let Some(window_id) = webview_id_map.get(&window_id) {
  2412. window_id
  2413. } else {
  2414. *webview_id_map.0.lock().unwrap().values().next().unwrap()
  2415. };
  2416. windows
  2417. .borrow()
  2418. .get(&window_id)
  2419. .unwrap()
  2420. .menu_event_listeners
  2421. .clone()
  2422. };
  2423. let listeners = window_menu_event_listeners.lock().unwrap();
  2424. let handlers = listeners.values();
  2425. for handler in handlers {
  2426. handler(&event);
  2427. }
  2428. }
  2429. #[cfg(all(desktop, feature = "system-tray"))]
  2430. Event::MenuEvent {
  2431. window_id: _,
  2432. menu_id,
  2433. origin: MenuType::ContextMenu,
  2434. ..
  2435. } => {
  2436. let event = SystemTrayEvent::MenuItemClick(menu_id.0);
  2437. let trays = system_tray_manager.trays.lock().unwrap();
  2438. let trays_iter = trays.iter();
  2439. let (mut listeners, mut tray_id) = (None, 0);
  2440. for (id, tray_context) in trays_iter {
  2441. let has_menu = {
  2442. let items = tray_context.items.lock().unwrap();
  2443. items.contains_key(&menu_id.0)
  2444. };
  2445. if has_menu {
  2446. listeners.replace(tray_context.listeners.lock().unwrap().clone());
  2447. tray_id = *id;
  2448. break;
  2449. }
  2450. }
  2451. drop(trays);
  2452. if let Some(listeners) = listeners {
  2453. let handlers = listeners.iter();
  2454. for handler in handlers {
  2455. handler(&event);
  2456. }
  2457. let global_listeners = system_tray_manager.global_listeners.lock().unwrap();
  2458. let global_listeners_iter = global_listeners.iter();
  2459. for global_listener in global_listeners_iter {
  2460. global_listener(tray_id, &event);
  2461. }
  2462. }
  2463. }
  2464. #[cfg(all(desktop, feature = "system-tray"))]
  2465. Event::TrayEvent {
  2466. id,
  2467. bounds,
  2468. event,
  2469. position: _cursor_position,
  2470. ..
  2471. } => {
  2472. let (position, size) = (
  2473. PhysicalPositionWrapper(bounds.position).into(),
  2474. PhysicalSizeWrapper(bounds.size).into(),
  2475. );
  2476. let event = match event {
  2477. TrayEvent::RightClick => SystemTrayEvent::RightClick { position, size },
  2478. TrayEvent::DoubleClick => SystemTrayEvent::DoubleClick { position, size },
  2479. // default to left click
  2480. _ => SystemTrayEvent::LeftClick { position, size },
  2481. };
  2482. let trays = system_tray_manager.trays.lock().unwrap();
  2483. if let Some(tray_context) = trays.get(&id.0) {
  2484. let listeners = tray_context.listeners.lock().unwrap();
  2485. let iter = listeners.iter();
  2486. for handler in iter {
  2487. handler(&event);
  2488. }
  2489. }
  2490. let global_listeners = system_tray_manager.global_listeners.lock().unwrap();
  2491. let global_listeners_iter = global_listeners.iter();
  2492. for global_listener in global_listeners_iter {
  2493. global_listener(id.0, &event);
  2494. }
  2495. }
  2496. Event::WindowEvent {
  2497. event, window_id, ..
  2498. } => {
  2499. if let Some(window_id) = webview_id_map.get(&window_id) {
  2500. {
  2501. let windows_ref = windows.borrow();
  2502. if let Some(window) = windows_ref.get(&window_id) {
  2503. if let Some(event) = WindowEventWrapper::parse(&window.inner, &event).0 {
  2504. let label = window.label.clone();
  2505. let window_event_listeners = window.window_event_listeners.clone();
  2506. drop(windows_ref);
  2507. callback(RunEvent::WindowEvent {
  2508. label,
  2509. event: event.clone(),
  2510. });
  2511. let listeners = window_event_listeners.lock().unwrap();
  2512. let handlers = listeners.values();
  2513. for handler in handlers {
  2514. handler(&event);
  2515. }
  2516. }
  2517. }
  2518. }
  2519. match event {
  2520. WryWindowEvent::CloseRequested => {
  2521. on_close_requested(callback, window_id, windows.clone());
  2522. }
  2523. WryWindowEvent::Destroyed => {
  2524. let removed = windows.borrow_mut().remove(&window_id).is_some();
  2525. if removed {
  2526. let is_empty = windows.borrow().is_empty();
  2527. if is_empty {
  2528. let (tx, rx) = channel();
  2529. callback(RunEvent::ExitRequested { tx });
  2530. let recv = rx.try_recv();
  2531. let should_prevent = matches!(recv, Ok(ExitRequestedEventAction::Prevent));
  2532. if !should_prevent {
  2533. *control_flow = ControlFlow::Exit;
  2534. }
  2535. }
  2536. }
  2537. }
  2538. _ => {}
  2539. }
  2540. }
  2541. }
  2542. Event::UserEvent(message) => match message {
  2543. Message::Window(id, WindowMessage::Close) => {
  2544. on_window_close(id, windows.clone());
  2545. }
  2546. Message::UserEvent(t) => callback(RunEvent::UserEvent(t)),
  2547. message => {
  2548. return handle_user_message(
  2549. event_loop,
  2550. message,
  2551. UserMessageContext {
  2552. webview_id_map,
  2553. #[cfg(all(desktop, feature = "global-shortcut"))]
  2554. global_shortcut_manager,
  2555. #[cfg(feature = "clipboard")]
  2556. clipboard_manager,
  2557. windows,
  2558. #[cfg(all(desktop, feature = "system-tray"))]
  2559. system_tray_manager,
  2560. },
  2561. web_context,
  2562. );
  2563. }
  2564. },
  2565. _ => (),
  2566. }
  2567. let it = RunIteration {
  2568. window_count: windows.borrow().len(),
  2569. };
  2570. it
  2571. }
  2572. fn on_close_requested<'a, T: UserEvent>(
  2573. callback: &'a mut (dyn FnMut(RunEvent<T>) + 'static),
  2574. window_id: WebviewId,
  2575. windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
  2576. ) {
  2577. let (tx, rx) = channel();
  2578. let windows_ref = windows.borrow();
  2579. if let Some(w) = windows_ref.get(&window_id) {
  2580. let label = w.label.clone();
  2581. let window_event_listeners = w.window_event_listeners.clone();
  2582. drop(windows_ref);
  2583. let listeners = window_event_listeners.lock().unwrap();
  2584. let handlers = listeners.values();
  2585. for handler in handlers {
  2586. handler(&WindowEvent::CloseRequested {
  2587. signal_tx: tx.clone(),
  2588. });
  2589. }
  2590. callback(RunEvent::WindowEvent {
  2591. label,
  2592. event: WindowEvent::CloseRequested { signal_tx: tx },
  2593. });
  2594. if let Ok(true) = rx.try_recv() {
  2595. } else {
  2596. on_window_close(window_id, windows);
  2597. }
  2598. }
  2599. }
  2600. fn on_window_close(window_id: WebviewId, windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>) {
  2601. if let Some(mut window_wrapper) = windows.borrow_mut().get_mut(&window_id) {
  2602. window_wrapper.inner = None;
  2603. }
  2604. }
  2605. pub fn center_window(window: &Window, window_size: WryPhysicalSize<u32>) -> Result<()> {
  2606. if let Some(monitor) = window.current_monitor() {
  2607. let screen_size = monitor.size();
  2608. let monitor_pos = monitor.position();
  2609. let x = (screen_size.width as i32 - window_size.width as i32) / 2;
  2610. let y = (screen_size.height as i32 - window_size.height as i32) / 2;
  2611. window.set_outer_position(WryPhysicalPosition::new(
  2612. monitor_pos.x + x,
  2613. monitor_pos.y + y,
  2614. ));
  2615. Ok(())
  2616. } else {
  2617. Err(Error::FailedToGetMonitor)
  2618. }
  2619. }
  2620. fn to_wry_menu(
  2621. custom_menu_items: &mut HashMap<MenuHash, WryCustomMenuItem>,
  2622. menu: Menu,
  2623. ) -> MenuBar {
  2624. let mut wry_menu = MenuBar::new();
  2625. for item in menu.items {
  2626. match item {
  2627. MenuEntry::CustomItem(c) => {
  2628. let mut attributes = MenuItemAttributesWrapper::from(&c).0;
  2629. attributes = attributes.with_id(WryMenuId(c.id));
  2630. #[allow(unused_mut)]
  2631. let mut item = wry_menu.add_item(attributes);
  2632. #[cfg(target_os = "macos")]
  2633. if let Some(native_image) = c.native_image {
  2634. item.set_native_image(NativeImageWrapper::from(native_image).0);
  2635. }
  2636. custom_menu_items.insert(c.id, item);
  2637. }
  2638. MenuEntry::NativeItem(i) => {
  2639. wry_menu.add_native_item(MenuItemWrapper::from(i).0);
  2640. }
  2641. MenuEntry::Submenu(submenu) => {
  2642. wry_menu.add_submenu(
  2643. &submenu.title,
  2644. submenu.enabled,
  2645. to_wry_menu(custom_menu_items, submenu.inner),
  2646. );
  2647. }
  2648. }
  2649. }
  2650. wry_menu
  2651. }
  2652. fn create_webview<T: UserEvent>(
  2653. window_id: WebviewId,
  2654. event_loop: &EventLoopWindowTarget<Message<T>>,
  2655. web_context_store: &WebContextStore,
  2656. context: Context<T>,
  2657. pending: PendingWindow<T, Wry<T>>,
  2658. ) -> Result<WindowWrapper> {
  2659. #[allow(unused_mut)]
  2660. let PendingWindow {
  2661. webview_attributes,
  2662. uri_scheme_protocols,
  2663. mut window_builder,
  2664. ipc_handler,
  2665. label,
  2666. url,
  2667. menu_ids,
  2668. js_event_listeners,
  2669. ..
  2670. } = pending;
  2671. let webview_id_map = context.webview_id_map.clone();
  2672. #[cfg(windows)]
  2673. let proxy = context.proxy.clone();
  2674. let window_event_listeners = WindowEventListeners::default();
  2675. #[cfg(windows)]
  2676. {
  2677. window_builder.inner = window_builder
  2678. .inner
  2679. .with_drag_and_drop(webview_attributes.file_drop_handler_enabled);
  2680. }
  2681. #[cfg(target_os = "macos")]
  2682. {
  2683. if window_builder.tabbing_identifier.is_none()
  2684. || window_builder.inner.window.transparent
  2685. || !window_builder.inner.window.decorations
  2686. {
  2687. window_builder.inner = window_builder.inner.with_automatic_window_tabbing(false);
  2688. }
  2689. }
  2690. let is_window_transparent = window_builder.inner.window.transparent;
  2691. let menu_items = if let Some(menu) = window_builder.menu {
  2692. let mut menu_items = HashMap::new();
  2693. let menu = to_wry_menu(&mut menu_items, menu);
  2694. window_builder.inner = window_builder.inner.with_menu(menu);
  2695. Some(menu_items)
  2696. } else {
  2697. None
  2698. };
  2699. let window = window_builder.inner.build(event_loop).unwrap();
  2700. webview_id_map.insert(window.id(), window_id);
  2701. if window_builder.center {
  2702. let _ = center_window(&window, window.inner_size());
  2703. }
  2704. let mut webview_builder = WebViewBuilder::new(window)
  2705. .map_err(|e| Error::CreateWebview(Box::new(e)))?
  2706. .with_url(&url)
  2707. .unwrap() // safe to unwrap because we validate the URL beforehand
  2708. .with_transparent(is_window_transparent)
  2709. .with_accept_first_mouse(webview_attributes.accept_first_mouse);
  2710. if webview_attributes.file_drop_handler_enabled {
  2711. webview_builder = webview_builder
  2712. .with_file_drop_handler(create_file_drop_handler(window_event_listeners.clone()));
  2713. }
  2714. if let Some(user_agent) = webview_attributes.user_agent {
  2715. webview_builder = webview_builder.with_user_agent(&user_agent);
  2716. }
  2717. if let Some(handler) = ipc_handler {
  2718. webview_builder = webview_builder.with_ipc_handler(create_ipc_handler(
  2719. context,
  2720. label.clone(),
  2721. menu_ids,
  2722. js_event_listeners,
  2723. handler,
  2724. ));
  2725. }
  2726. for (scheme, protocol) in uri_scheme_protocols {
  2727. webview_builder = webview_builder.with_custom_protocol(scheme, move |wry_request| {
  2728. protocol(&HttpRequestWrapper::from(wry_request).0)
  2729. .map(|tauri_response| HttpResponseWrapper::from(tauri_response).0)
  2730. .map_err(|_| wry::Error::InitScriptError)
  2731. });
  2732. }
  2733. for script in webview_attributes.initialization_scripts {
  2734. webview_builder = webview_builder.with_initialization_script(&script);
  2735. }
  2736. let mut web_context = web_context_store.lock().expect("poisoned WebContext store");
  2737. let is_first_context = web_context.is_empty();
  2738. let automation_enabled = std::env::var("TAURI_AUTOMATION").as_deref() == Ok("true");
  2739. let web_context_key = // force a unique WebContext when automation is false;
  2740. // the context must be stored on the HashMap because it must outlive the WebView on macOS
  2741. if automation_enabled {
  2742. webview_attributes.data_directory.clone()
  2743. } else {
  2744. // random unique key
  2745. Some(Uuid::new_v4().as_hyphenated().to_string().into())
  2746. };
  2747. let entry = web_context.entry(web_context_key.clone());
  2748. let web_context = match entry {
  2749. Occupied(occupied) => occupied.into_mut(),
  2750. Vacant(vacant) => {
  2751. let mut web_context = WebContext::new(webview_attributes.data_directory);
  2752. web_context.set_allows_automation(if automation_enabled {
  2753. is_first_context
  2754. } else {
  2755. false
  2756. });
  2757. vacant.insert(web_context)
  2758. }
  2759. };
  2760. if webview_attributes.clipboard {
  2761. webview_builder.webview.clipboard = true;
  2762. }
  2763. #[cfg(any(debug_assertions, feature = "devtools"))]
  2764. {
  2765. webview_builder = webview_builder.with_devtools(true);
  2766. }
  2767. let webview = webview_builder
  2768. .with_web_context(web_context)
  2769. .build()
  2770. .map_err(|e| Error::CreateWebview(Box::new(e)))?;
  2771. #[cfg(windows)]
  2772. {
  2773. let controller = webview.controller();
  2774. let proxy_ = proxy.clone();
  2775. let mut token = EventRegistrationToken::default();
  2776. unsafe {
  2777. controller.add_GotFocus(
  2778. &FocusChangedEventHandler::create(Box::new(move |_, _| {
  2779. let _ = proxy_.send_event(Message::Webview(
  2780. window_id,
  2781. WebviewMessage::WebviewEvent(WebviewEvent::Focused(true)),
  2782. ));
  2783. Ok(())
  2784. })),
  2785. &mut token,
  2786. )
  2787. }
  2788. .unwrap();
  2789. unsafe {
  2790. controller.add_LostFocus(
  2791. &FocusChangedEventHandler::create(Box::new(move |_, _| {
  2792. let _ = proxy.send_event(Message::Webview(
  2793. window_id,
  2794. WebviewMessage::WebviewEvent(WebviewEvent::Focused(false)),
  2795. ));
  2796. Ok(())
  2797. })),
  2798. &mut token,
  2799. )
  2800. }
  2801. .unwrap();
  2802. }
  2803. Ok(WindowWrapper {
  2804. label,
  2805. inner: Some(WindowHandle::Webview {
  2806. inner: Arc::new(webview),
  2807. context_store: web_context_store.clone(),
  2808. context_key: if automation_enabled {
  2809. None
  2810. } else {
  2811. web_context_key
  2812. },
  2813. }),
  2814. menu_items,
  2815. window_event_listeners,
  2816. menu_event_listeners: Default::default(),
  2817. })
  2818. }
  2819. /// Create a wry ipc handler from a tauri ipc handler.
  2820. fn create_ipc_handler<T: UserEvent>(
  2821. context: Context<T>,
  2822. label: String,
  2823. menu_ids: Arc<Mutex<HashMap<MenuHash, MenuId>>>,
  2824. js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u64>>>>,
  2825. handler: WebviewIpcHandler<T, Wry<T>>,
  2826. ) -> Box<IpcHandler> {
  2827. Box::new(move |window, request| {
  2828. let window_id = context.webview_id_map.get(&window.id()).unwrap();
  2829. handler(
  2830. DetachedWindow {
  2831. dispatcher: WryDispatcher {
  2832. window_id,
  2833. context: context.clone(),
  2834. },
  2835. label: label.clone(),
  2836. menu_ids: menu_ids.clone(),
  2837. js_event_listeners: js_event_listeners.clone(),
  2838. },
  2839. request,
  2840. );
  2841. })
  2842. }
  2843. /// Create a wry file drop handler.
  2844. fn create_file_drop_handler(window_event_listeners: WindowEventListeners) -> Box<FileDropHandler> {
  2845. Box::new(move |_window, event| {
  2846. let event: FileDropEvent = FileDropEventWrapper(event).into();
  2847. let window_event = WindowEvent::FileDrop(event);
  2848. let listeners_map = window_event_listeners.lock().unwrap();
  2849. let has_listener = !listeners_map.is_empty();
  2850. let handlers = listeners_map.values();
  2851. for listener in handlers {
  2852. listener(&window_event);
  2853. }
  2854. // block the default OS action on file drop if we had a listener
  2855. has_listener
  2856. })
  2857. }