lib.rs 94 KB

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