lib.rs 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! [![](https://github.com/tauri-apps/tauri/raw/dev/.github/splash.png)](https://tauri.app)
  5. //!
  6. //! The [`wry`] Tauri [`Runtime`].
  7. //!
  8. //! None of the exposed API of this crate is stable, and it may break semver
  9. //! compatibility in the future. The major version only signifies the intended Tauri version.
  10. #![doc(
  11. html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png",
  12. html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/.github/icon.png"
  13. )]
  14. use http::Request;
  15. use raw_window_handle::{DisplayHandle, HasDisplayHandle, HasWindowHandle};
  16. use tauri_runtime::{
  17. dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
  18. monitor::Monitor,
  19. webview::{DetachedWebview, DownloadEvent, PendingWebview, WebviewIpcHandler},
  20. window::{
  21. CursorIcon, DetachedWindow, DragDropEvent, PendingWindow, RawWindow, WebviewEvent,
  22. WindowBuilder, WindowBuilderBase, WindowEvent, WindowId, WindowSizeConstraints,
  23. },
  24. DeviceEventFilter, Error, EventLoopProxy, ExitRequestedEventAction, Icon, ProgressBarState,
  25. ProgressBarStatus, Result, RunEvent, Runtime, RuntimeHandle, RuntimeInitArgs, UserAttentionType,
  26. UserEvent, WebviewDispatch, WebviewEventId, WindowDispatch, WindowEventId,
  27. };
  28. #[cfg(target_os = "macos")]
  29. use tao::platform::macos::{EventLoopWindowTargetExtMacOS, WindowBuilderExtMacOS};
  30. #[cfg(target_os = "linux")]
  31. use tao::platform::unix::{WindowBuilderExtUnix, WindowExtUnix};
  32. #[cfg(windows)]
  33. use tao::platform::windows::{WindowBuilderExtWindows, WindowExtWindows};
  34. #[cfg(windows)]
  35. use webview2_com::FocusChangedEventHandler;
  36. #[cfg(windows)]
  37. use windows::Win32::{Foundation::HWND, System::WinRT::EventRegistrationToken};
  38. #[cfg(windows)]
  39. use wry::WebViewBuilderExtWindows;
  40. use tao::{
  41. dpi::{
  42. LogicalPosition as TaoLogicalPosition, LogicalSize as TaoLogicalSize,
  43. PhysicalPosition as TaoPhysicalPosition, PhysicalSize as TaoPhysicalSize,
  44. Position as TaoPosition, Size as TaoSize,
  45. },
  46. event::{Event, StartCause, WindowEvent as TaoWindowEvent},
  47. event_loop::{
  48. ControlFlow, DeviceEventFilter as TaoDeviceEventFilter, EventLoop, EventLoopBuilder,
  49. EventLoopProxy as TaoEventLoopProxy, EventLoopWindowTarget,
  50. },
  51. monitor::MonitorHandle,
  52. window::{
  53. CursorIcon as TaoCursorIcon, Fullscreen, Icon as TaoWindowIcon,
  54. ProgressBarState as TaoProgressBarState, ProgressState as TaoProgressState, Theme as TaoTheme,
  55. UserAttentionType as TaoUserAttentionType,
  56. },
  57. };
  58. #[cfg(target_os = "macos")]
  59. use tauri_utils::TitleBarStyle;
  60. use tauri_utils::{config::WindowConfig, Theme};
  61. use url::Url;
  62. use wry::{
  63. DragDropEvent as WryDragDropEvent, ProxyConfig, ProxyEndpoint, WebContext, WebView,
  64. WebViewBuilder,
  65. };
  66. pub use tao;
  67. pub use tao::window::{Window, WindowBuilder as TaoWindowBuilder, WindowId as TaoWindowId};
  68. pub use wry;
  69. pub use wry::webview_version;
  70. #[cfg(windows)]
  71. use wry::WebViewExtWindows;
  72. #[cfg(target_os = "android")]
  73. use wry::{
  74. prelude::{dispatch, find_class},
  75. WebViewBuilderExtAndroid, WebViewExtAndroid,
  76. };
  77. #[cfg(not(any(
  78. target_os = "windows",
  79. target_os = "macos",
  80. target_os = "ios",
  81. target_os = "android"
  82. )))]
  83. use wry::{WebViewBuilderExtUnix, WebViewExtUnix};
  84. #[cfg(target_os = "macos")]
  85. pub use tao::platform::macos::{
  86. ActivationPolicy as TaoActivationPolicy, EventLoopExtMacOS, WindowExtMacOS,
  87. };
  88. #[cfg(target_os = "macos")]
  89. use tauri_runtime::ActivationPolicy;
  90. use std::{
  91. cell::RefCell,
  92. collections::{
  93. hash_map::Entry::{Occupied, Vacant},
  94. BTreeMap, HashMap,
  95. },
  96. fmt,
  97. ops::Deref,
  98. path::PathBuf,
  99. rc::Rc,
  100. sync::{
  101. atomic::{AtomicBool, AtomicU32, Ordering},
  102. mpsc::{channel, Sender},
  103. Arc, Mutex, Weak,
  104. },
  105. thread::{current as current_thread, ThreadId},
  106. };
  107. pub type WebviewId = u32;
  108. type IpcHandler = dyn Fn(Request<String>) + 'static;
  109. #[cfg(any(
  110. windows,
  111. target_os = "linux",
  112. target_os = "dragonfly",
  113. target_os = "freebsd",
  114. target_os = "netbsd",
  115. target_os = "openbsd"
  116. ))]
  117. mod undecorated_resizing;
  118. mod webview;
  119. pub use webview::Webview;
  120. pub type WebContextStore = Arc<Mutex<HashMap<Option<PathBuf>, WebContext>>>;
  121. // window
  122. pub type WindowEventHandler = Box<dyn Fn(&WindowEvent) + Send>;
  123. pub type WindowEventListeners = Arc<Mutex<HashMap<WindowEventId, WindowEventHandler>>>;
  124. pub type WebviewEventHandler = Box<dyn Fn(&WebviewEvent) + Send>;
  125. pub type WebviewEventListeners = Arc<Mutex<HashMap<WebviewEventId, WebviewEventHandler>>>;
  126. #[derive(Debug, Clone, Default)]
  127. pub struct WindowIdStore(Arc<Mutex<HashMap<TaoWindowId, WindowId>>>);
  128. impl WindowIdStore {
  129. pub fn insert(&self, w: TaoWindowId, id: WindowId) {
  130. self.0.lock().unwrap().insert(w, id);
  131. }
  132. fn get(&self, w: &TaoWindowId) -> Option<WindowId> {
  133. self.0.lock().unwrap().get(w).copied()
  134. }
  135. }
  136. #[macro_export]
  137. macro_rules! getter {
  138. ($self: ident, $rx: expr, $message: expr) => {{
  139. $crate::send_user_message(&$self.context, $message)?;
  140. $rx
  141. .recv()
  142. .map_err(|_| $crate::Error::FailedToReceiveMessage)
  143. }};
  144. }
  145. macro_rules! window_getter {
  146. ($self: ident, $message: expr) => {{
  147. let (tx, rx) = channel();
  148. getter!($self, rx, Message::Window($self.window_id, $message(tx)))
  149. }};
  150. }
  151. macro_rules! webview_getter {
  152. ($self: ident, $message: expr) => {{
  153. let (tx, rx) = channel();
  154. getter!(
  155. $self,
  156. rx,
  157. Message::Webview(
  158. *$self.window_id.lock().unwrap(),
  159. $self.webview_id,
  160. $message(tx)
  161. )
  162. )
  163. }};
  164. }
  165. pub(crate) fn send_user_message<T: UserEvent>(
  166. context: &Context<T>,
  167. message: Message<T>,
  168. ) -> Result<()> {
  169. if current_thread().id() == context.main_thread_id {
  170. handle_user_message(
  171. &context.main_thread.window_target,
  172. message,
  173. UserMessageContext {
  174. window_id_map: context.window_id_map.clone(),
  175. windows: context.main_thread.windows.clone(),
  176. },
  177. );
  178. Ok(())
  179. } else {
  180. context
  181. .proxy
  182. .send_event(message)
  183. .map_err(|_| Error::FailedToSendMessage)
  184. }
  185. }
  186. #[derive(Clone)]
  187. pub struct Context<T: UserEvent> {
  188. pub window_id_map: WindowIdStore,
  189. main_thread_id: ThreadId,
  190. pub proxy: TaoEventLoopProxy<Message<T>>,
  191. main_thread: DispatcherMainThreadContext<T>,
  192. plugins: Arc<Mutex<Vec<Box<dyn Plugin<T> + Send>>>>,
  193. next_window_id: Arc<AtomicU32>,
  194. next_webview_id: Arc<AtomicU32>,
  195. next_window_event_id: Arc<AtomicU32>,
  196. next_webview_event_id: Arc<AtomicU32>,
  197. next_webcontext_id: Arc<AtomicU32>,
  198. }
  199. impl<T: UserEvent> Context<T> {
  200. pub fn run_threaded<R, F>(&self, f: F) -> R
  201. where
  202. F: FnOnce(Option<&DispatcherMainThreadContext<T>>) -> R,
  203. {
  204. f(if current_thread().id() == self.main_thread_id {
  205. Some(&self.main_thread)
  206. } else {
  207. None
  208. })
  209. }
  210. fn next_window_id(&self) -> WindowId {
  211. self.next_window_id.fetch_add(1, Ordering::Relaxed).into()
  212. }
  213. fn next_webview_id(&self) -> WebviewId {
  214. self.next_webview_id.fetch_add(1, Ordering::Relaxed)
  215. }
  216. fn next_window_event_id(&self) -> u32 {
  217. self.next_window_event_id.fetch_add(1, Ordering::Relaxed)
  218. }
  219. fn next_webview_event_id(&self) -> u32 {
  220. self.next_webview_event_id.fetch_add(1, Ordering::Relaxed)
  221. }
  222. fn next_webcontext_id(&self) -> u32 {
  223. self.next_webcontext_id.fetch_add(1, Ordering::Relaxed)
  224. }
  225. }
  226. impl<T: UserEvent> Context<T> {
  227. fn create_window<F: Fn(RawWindow) + Send + 'static>(
  228. &self,
  229. pending: PendingWindow<T, Wry<T>>,
  230. after_window_creation: Option<F>,
  231. ) -> Result<DetachedWindow<T, Wry<T>>> {
  232. let label = pending.label.clone();
  233. let context = self.clone();
  234. let window_id = self.next_window_id();
  235. let webview_id = pending.webview.as_ref().map(|_| context.next_webview_id());
  236. send_user_message(
  237. self,
  238. Message::CreateWindow(
  239. window_id,
  240. Box::new(move |event_loop| {
  241. create_window(
  242. window_id,
  243. webview_id.unwrap_or_default(),
  244. event_loop,
  245. &context,
  246. pending,
  247. after_window_creation,
  248. )
  249. }),
  250. ),
  251. )?;
  252. let dispatcher = WryWindowDispatcher {
  253. window_id,
  254. context: self.clone(),
  255. };
  256. let detached_webview = webview_id.map(|id| DetachedWebview {
  257. label: label.clone(),
  258. dispatcher: WryWebviewDispatcher {
  259. window_id: Arc::new(Mutex::new(window_id)),
  260. webview_id: id,
  261. context: self.clone(),
  262. },
  263. });
  264. Ok(DetachedWindow {
  265. id: window_id,
  266. label,
  267. dispatcher,
  268. webview: detached_webview,
  269. })
  270. }
  271. fn create_webview(
  272. &self,
  273. window_id: WindowId,
  274. pending: PendingWebview<T, Wry<T>>,
  275. ) -> Result<DetachedWebview<T, Wry<T>>> {
  276. let label = pending.label.clone();
  277. let context = self.clone();
  278. let webview_id = self.next_webview_id();
  279. let window_id_wrapper = Arc::new(Mutex::new(window_id));
  280. let window_id_wrapper_ = window_id_wrapper.clone();
  281. send_user_message(
  282. self,
  283. Message::CreateWebview(
  284. window_id,
  285. Box::new(move |window| {
  286. create_webview(
  287. WebviewKind::WindowChild,
  288. window,
  289. window_id_wrapper_,
  290. webview_id,
  291. &context,
  292. pending,
  293. )
  294. }),
  295. ),
  296. )?;
  297. let dispatcher = WryWebviewDispatcher {
  298. window_id: window_id_wrapper,
  299. webview_id,
  300. context: self.clone(),
  301. };
  302. Ok(DetachedWebview { label, dispatcher })
  303. }
  304. }
  305. #[cfg(feature = "tracing")]
  306. #[derive(Debug, Clone, Default)]
  307. pub struct ActiveTraceSpanStore(Rc<RefCell<Vec<ActiveTracingSpan>>>);
  308. #[cfg(feature = "tracing")]
  309. impl ActiveTraceSpanStore {
  310. pub fn remove_window_draw(&self) {
  311. self
  312. .0
  313. .borrow_mut()
  314. .retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }));
  315. }
  316. }
  317. #[cfg(feature = "tracing")]
  318. #[derive(Debug)]
  319. pub enum ActiveTracingSpan {
  320. WindowDraw {
  321. id: TaoWindowId,
  322. span: tracing::span::EnteredSpan,
  323. },
  324. }
  325. #[derive(Debug)]
  326. pub struct WindowsStore(RefCell<BTreeMap<WindowId, WindowWrapper>>);
  327. // SAFETY: we ensure this type is only used on the main thread.
  328. #[allow(clippy::non_send_fields_in_send_ty)]
  329. unsafe impl Send for WindowsStore {}
  330. // SAFETY: we ensure this type is only used on the main thread.
  331. #[allow(clippy::non_send_fields_in_send_ty)]
  332. unsafe impl Sync for WindowsStore {}
  333. #[derive(Debug, Clone)]
  334. pub struct DispatcherMainThreadContext<T: UserEvent> {
  335. pub window_target: EventLoopWindowTarget<Message<T>>,
  336. pub web_context: WebContextStore,
  337. // changing this to an Rc will cause frequent app crashes.
  338. pub windows: Arc<WindowsStore>,
  339. #[cfg(feature = "tracing")]
  340. pub active_tracing_spans: ActiveTraceSpanStore,
  341. }
  342. // SAFETY: we ensure this type is only used on the main thread.
  343. #[allow(clippy::non_send_fields_in_send_ty)]
  344. unsafe impl<T: UserEvent> Send for DispatcherMainThreadContext<T> {}
  345. // SAFETY: we ensure this type is only used on the main thread.
  346. #[allow(clippy::non_send_fields_in_send_ty)]
  347. unsafe impl<T: UserEvent> Sync for DispatcherMainThreadContext<T> {}
  348. impl<T: UserEvent> fmt::Debug for Context<T> {
  349. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  350. f.debug_struct("Context")
  351. .field("main_thread_id", &self.main_thread_id)
  352. .field("proxy", &self.proxy)
  353. .field("main_thread", &self.main_thread)
  354. .finish()
  355. }
  356. }
  357. pub struct DeviceEventFilterWrapper(pub TaoDeviceEventFilter);
  358. impl From<DeviceEventFilter> for DeviceEventFilterWrapper {
  359. fn from(item: DeviceEventFilter) -> Self {
  360. match item {
  361. DeviceEventFilter::Always => Self(TaoDeviceEventFilter::Always),
  362. DeviceEventFilter::Never => Self(TaoDeviceEventFilter::Never),
  363. DeviceEventFilter::Unfocused => Self(TaoDeviceEventFilter::Unfocused),
  364. }
  365. }
  366. }
  367. pub struct RectWrapper(pub wry::Rect);
  368. impl From<tauri_runtime::Rect> for RectWrapper {
  369. fn from(value: tauri_runtime::Rect) -> Self {
  370. RectWrapper(wry::Rect {
  371. position: value.position,
  372. size: value.size,
  373. })
  374. }
  375. }
  376. /// Wrapper around a [`tao::window::Icon`] that can be created from an [`Icon`].
  377. pub struct TaoIcon(pub TaoWindowIcon);
  378. impl TryFrom<Icon<'_>> for TaoIcon {
  379. type Error = Error;
  380. fn try_from(icon: Icon<'_>) -> std::result::Result<Self, Self::Error> {
  381. TaoWindowIcon::from_rgba(icon.rgba.to_vec(), icon.width, icon.height)
  382. .map(Self)
  383. .map_err(|e| Error::InvalidIcon(Box::new(e)))
  384. }
  385. }
  386. pub struct WindowEventWrapper(pub Option<WindowEvent>);
  387. impl WindowEventWrapper {
  388. fn parse(window: &WindowWrapper, event: &TaoWindowEvent<'_>) -> Self {
  389. match event {
  390. // resized event from tao doesn't include a reliable size on macOS
  391. // because wry replaces the NSView
  392. TaoWindowEvent::Resized(_) => {
  393. if let Some(w) = &window.inner {
  394. let size = inner_size(
  395. w,
  396. &window.webviews,
  397. window.has_children.load(Ordering::Relaxed),
  398. );
  399. Self(Some(WindowEvent::Resized(PhysicalSizeWrapper(size).into())))
  400. } else {
  401. Self(None)
  402. }
  403. }
  404. e => e.into(),
  405. }
  406. }
  407. }
  408. pub fn map_theme(theme: &TaoTheme) -> Theme {
  409. match theme {
  410. TaoTheme::Light => Theme::Light,
  411. TaoTheme::Dark => Theme::Dark,
  412. _ => Theme::Light,
  413. }
  414. }
  415. #[cfg(target_os = "macos")]
  416. fn tao_activation_policy(activation_policy: ActivationPolicy) -> TaoActivationPolicy {
  417. match activation_policy {
  418. ActivationPolicy::Regular => TaoActivationPolicy::Regular,
  419. ActivationPolicy::Accessory => TaoActivationPolicy::Accessory,
  420. ActivationPolicy::Prohibited => TaoActivationPolicy::Prohibited,
  421. _ => unimplemented!(),
  422. }
  423. }
  424. impl<'a> From<&TaoWindowEvent<'a>> for WindowEventWrapper {
  425. fn from(event: &TaoWindowEvent<'a>) -> Self {
  426. let event = match event {
  427. TaoWindowEvent::Resized(size) => WindowEvent::Resized(PhysicalSizeWrapper(*size).into()),
  428. TaoWindowEvent::Moved(position) => {
  429. WindowEvent::Moved(PhysicalPositionWrapper(*position).into())
  430. }
  431. TaoWindowEvent::Destroyed => WindowEvent::Destroyed,
  432. TaoWindowEvent::ScaleFactorChanged {
  433. scale_factor,
  434. new_inner_size,
  435. } => WindowEvent::ScaleFactorChanged {
  436. scale_factor: *scale_factor,
  437. new_inner_size: PhysicalSizeWrapper(**new_inner_size).into(),
  438. },
  439. #[cfg(any(target_os = "linux", target_os = "macos"))]
  440. TaoWindowEvent::Focused(focused) => WindowEvent::Focused(*focused),
  441. TaoWindowEvent::ThemeChanged(theme) => WindowEvent::ThemeChanged(map_theme(theme)),
  442. _ => return Self(None),
  443. };
  444. Self(Some(event))
  445. }
  446. }
  447. pub struct MonitorHandleWrapper(pub MonitorHandle);
  448. impl From<MonitorHandleWrapper> for Monitor {
  449. fn from(monitor: MonitorHandleWrapper) -> Monitor {
  450. Self {
  451. name: monitor.0.name(),
  452. position: PhysicalPositionWrapper(monitor.0.position()).into(),
  453. size: PhysicalSizeWrapper(monitor.0.size()).into(),
  454. scale_factor: monitor.0.scale_factor(),
  455. }
  456. }
  457. }
  458. pub struct PhysicalPositionWrapper<T>(pub TaoPhysicalPosition<T>);
  459. impl<T> From<PhysicalPositionWrapper<T>> for PhysicalPosition<T> {
  460. fn from(position: PhysicalPositionWrapper<T>) -> Self {
  461. Self {
  462. x: position.0.x,
  463. y: position.0.y,
  464. }
  465. }
  466. }
  467. impl<T> From<PhysicalPosition<T>> for PhysicalPositionWrapper<T> {
  468. fn from(position: PhysicalPosition<T>) -> Self {
  469. Self(TaoPhysicalPosition {
  470. x: position.x,
  471. y: position.y,
  472. })
  473. }
  474. }
  475. struct LogicalPositionWrapper<T>(TaoLogicalPosition<T>);
  476. impl<T> From<LogicalPosition<T>> for LogicalPositionWrapper<T> {
  477. fn from(position: LogicalPosition<T>) -> Self {
  478. Self(TaoLogicalPosition {
  479. x: position.x,
  480. y: position.y,
  481. })
  482. }
  483. }
  484. pub struct PhysicalSizeWrapper<T>(pub TaoPhysicalSize<T>);
  485. impl<T> From<PhysicalSizeWrapper<T>> for PhysicalSize<T> {
  486. fn from(size: PhysicalSizeWrapper<T>) -> Self {
  487. Self {
  488. width: size.0.width,
  489. height: size.0.height,
  490. }
  491. }
  492. }
  493. impl<T> From<PhysicalSize<T>> for PhysicalSizeWrapper<T> {
  494. fn from(size: PhysicalSize<T>) -> Self {
  495. Self(TaoPhysicalSize {
  496. width: size.width,
  497. height: size.height,
  498. })
  499. }
  500. }
  501. struct LogicalSizeWrapper<T>(TaoLogicalSize<T>);
  502. impl<T> From<LogicalSize<T>> for LogicalSizeWrapper<T> {
  503. fn from(size: LogicalSize<T>) -> Self {
  504. Self(TaoLogicalSize {
  505. width: size.width,
  506. height: size.height,
  507. })
  508. }
  509. }
  510. pub struct SizeWrapper(pub TaoSize);
  511. impl From<Size> for SizeWrapper {
  512. fn from(size: Size) -> Self {
  513. match size {
  514. Size::Logical(s) => Self(TaoSize::Logical(LogicalSizeWrapper::from(s).0)),
  515. Size::Physical(s) => Self(TaoSize::Physical(PhysicalSizeWrapper::from(s).0)),
  516. }
  517. }
  518. }
  519. pub struct PositionWrapper(pub TaoPosition);
  520. impl From<Position> for PositionWrapper {
  521. fn from(position: Position) -> Self {
  522. match position {
  523. Position::Logical(s) => Self(TaoPosition::Logical(LogicalPositionWrapper::from(s).0)),
  524. Position::Physical(s) => Self(TaoPosition::Physical(PhysicalPositionWrapper::from(s).0)),
  525. }
  526. }
  527. }
  528. #[derive(Debug, Clone)]
  529. pub struct UserAttentionTypeWrapper(pub TaoUserAttentionType);
  530. impl From<UserAttentionType> for UserAttentionTypeWrapper {
  531. fn from(request_type: UserAttentionType) -> Self {
  532. let o = match request_type {
  533. UserAttentionType::Critical => TaoUserAttentionType::Critical,
  534. UserAttentionType::Informational => TaoUserAttentionType::Informational,
  535. };
  536. Self(o)
  537. }
  538. }
  539. #[derive(Debug)]
  540. pub struct CursorIconWrapper(pub TaoCursorIcon);
  541. impl From<CursorIcon> for CursorIconWrapper {
  542. fn from(icon: CursorIcon) -> Self {
  543. use CursorIcon::*;
  544. let i = match icon {
  545. Default => TaoCursorIcon::Default,
  546. Crosshair => TaoCursorIcon::Crosshair,
  547. Hand => TaoCursorIcon::Hand,
  548. Arrow => TaoCursorIcon::Arrow,
  549. Move => TaoCursorIcon::Move,
  550. Text => TaoCursorIcon::Text,
  551. Wait => TaoCursorIcon::Wait,
  552. Help => TaoCursorIcon::Help,
  553. Progress => TaoCursorIcon::Progress,
  554. NotAllowed => TaoCursorIcon::NotAllowed,
  555. ContextMenu => TaoCursorIcon::ContextMenu,
  556. Cell => TaoCursorIcon::Cell,
  557. VerticalText => TaoCursorIcon::VerticalText,
  558. Alias => TaoCursorIcon::Alias,
  559. Copy => TaoCursorIcon::Copy,
  560. NoDrop => TaoCursorIcon::NoDrop,
  561. Grab => TaoCursorIcon::Grab,
  562. Grabbing => TaoCursorIcon::Grabbing,
  563. AllScroll => TaoCursorIcon::AllScroll,
  564. ZoomIn => TaoCursorIcon::ZoomIn,
  565. ZoomOut => TaoCursorIcon::ZoomOut,
  566. EResize => TaoCursorIcon::EResize,
  567. NResize => TaoCursorIcon::NResize,
  568. NeResize => TaoCursorIcon::NeResize,
  569. NwResize => TaoCursorIcon::NwResize,
  570. SResize => TaoCursorIcon::SResize,
  571. SeResize => TaoCursorIcon::SeResize,
  572. SwResize => TaoCursorIcon::SwResize,
  573. WResize => TaoCursorIcon::WResize,
  574. EwResize => TaoCursorIcon::EwResize,
  575. NsResize => TaoCursorIcon::NsResize,
  576. NeswResize => TaoCursorIcon::NeswResize,
  577. NwseResize => TaoCursorIcon::NwseResize,
  578. ColResize => TaoCursorIcon::ColResize,
  579. RowResize => TaoCursorIcon::RowResize,
  580. _ => TaoCursorIcon::Default,
  581. };
  582. Self(i)
  583. }
  584. }
  585. pub struct ProgressStateWrapper(pub TaoProgressState);
  586. impl From<ProgressBarStatus> for ProgressStateWrapper {
  587. fn from(status: ProgressBarStatus) -> Self {
  588. let state = match status {
  589. ProgressBarStatus::None => TaoProgressState::None,
  590. ProgressBarStatus::Normal => TaoProgressState::Normal,
  591. ProgressBarStatus::Indeterminate => TaoProgressState::Indeterminate,
  592. ProgressBarStatus::Paused => TaoProgressState::Paused,
  593. ProgressBarStatus::Error => TaoProgressState::Error,
  594. };
  595. Self(state)
  596. }
  597. }
  598. pub struct ProgressBarStateWrapper(pub TaoProgressBarState);
  599. impl From<ProgressBarState> for ProgressBarStateWrapper {
  600. fn from(progress_state: ProgressBarState) -> Self {
  601. Self(TaoProgressBarState {
  602. progress: progress_state.progress,
  603. state: progress_state
  604. .status
  605. .map(|state| ProgressStateWrapper::from(state).0),
  606. desktop_filename: progress_state.desktop_filename,
  607. })
  608. }
  609. }
  610. #[derive(Clone, Default)]
  611. pub struct WindowBuilderWrapper {
  612. inner: TaoWindowBuilder,
  613. center: bool,
  614. #[cfg(target_os = "macos")]
  615. tabbing_identifier: Option<String>,
  616. }
  617. impl std::fmt::Debug for WindowBuilderWrapper {
  618. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  619. let mut s = f.debug_struct("WindowBuilderWrapper");
  620. s.field("inner", &self.inner).field("center", &self.center);
  621. #[cfg(target_os = "macos")]
  622. {
  623. s.field("tabbing_identifier", &self.tabbing_identifier);
  624. }
  625. s.finish()
  626. }
  627. }
  628. // SAFETY: this type is `Send` since `menu_items` are read only here
  629. #[allow(clippy::non_send_fields_in_send_ty)]
  630. unsafe impl Send for WindowBuilderWrapper {}
  631. impl WindowBuilderBase for WindowBuilderWrapper {}
  632. impl WindowBuilder for WindowBuilderWrapper {
  633. fn new() -> Self {
  634. #[allow(unused_mut)]
  635. let mut builder = Self::default().focused(true);
  636. #[cfg(target_os = "macos")]
  637. {
  638. // TODO: find a proper way to prevent webview being pushed out of the window.
  639. // Workround for issue: https://github.com/tauri-apps/tauri/issues/10225
  640. // The window requies `NSFullSizeContentViewWindowMask` flag to prevent devtools
  641. // pushing the content view out of the window.
  642. // By setting the default style to `TitleBarStyle::Visible` should fix the issue for most of the users.
  643. builder = builder.title_bar_style(TitleBarStyle::Visible);
  644. }
  645. builder
  646. }
  647. fn with_config(config: &WindowConfig) -> Self {
  648. let mut window = WindowBuilderWrapper::new();
  649. #[cfg(target_os = "macos")]
  650. {
  651. window = window
  652. .hidden_title(config.hidden_title)
  653. .title_bar_style(config.title_bar_style);
  654. if let Some(identifier) = &config.tabbing_identifier {
  655. window = window.tabbing_identifier(identifier);
  656. }
  657. }
  658. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  659. {
  660. window = window.transparent(config.transparent);
  661. }
  662. #[cfg(all(
  663. target_os = "macos",
  664. not(feature = "macos-private-api"),
  665. debug_assertions
  666. ))]
  667. if config.transparent {
  668. eprintln!(
  669. "The window is set to be transparent but the `macos-private-api` is not enabled.
  670. This can be enabled via the `tauri.macOSPrivateApi` configuration property <https://tauri.app/docs/api/config#tauri.macOSPrivateApi>
  671. ");
  672. }
  673. #[cfg(target_os = "linux")]
  674. {
  675. // Mouse event is disabled on Linux since sudden event bursts could block event loop.
  676. window.inner = window.inner.with_cursor_moved_event(false);
  677. }
  678. #[cfg(desktop)]
  679. {
  680. window = window
  681. .title(config.title.to_string())
  682. .inner_size(config.width, config.height)
  683. .visible(config.visible)
  684. .resizable(config.resizable)
  685. .fullscreen(config.fullscreen)
  686. .decorations(config.decorations)
  687. .maximized(config.maximized)
  688. .always_on_bottom(config.always_on_bottom)
  689. .always_on_top(config.always_on_top)
  690. .visible_on_all_workspaces(config.visible_on_all_workspaces)
  691. .content_protected(config.content_protected)
  692. .skip_taskbar(config.skip_taskbar)
  693. .theme(config.theme)
  694. .closable(config.closable)
  695. .maximizable(config.maximizable)
  696. .minimizable(config.minimizable)
  697. .shadow(config.shadow);
  698. let mut constraints = WindowSizeConstraints::default();
  699. if let Some(min_width) = config.min_width {
  700. constraints.min_width = Some(tao::dpi::LogicalUnit::new(min_width).into());
  701. }
  702. if let Some(min_height) = config.min_height {
  703. constraints.min_height = Some(tao::dpi::LogicalUnit::new(min_height).into());
  704. }
  705. if let Some(max_width) = config.max_width {
  706. constraints.max_width = Some(tao::dpi::LogicalUnit::new(max_width).into());
  707. }
  708. if let Some(max_height) = config.max_height {
  709. constraints.max_height = Some(tao::dpi::LogicalUnit::new(max_height).into());
  710. }
  711. window = window.inner_size_constraints(constraints);
  712. if let (Some(x), Some(y)) = (config.x, config.y) {
  713. window = window.position(x, y);
  714. }
  715. if config.center {
  716. window = window.center();
  717. }
  718. }
  719. window
  720. }
  721. fn center(mut self) -> Self {
  722. self.center = true;
  723. self
  724. }
  725. fn position(mut self, x: f64, y: f64) -> Self {
  726. self.inner = self.inner.with_position(TaoLogicalPosition::new(x, y));
  727. self
  728. }
  729. fn inner_size(mut self, width: f64, height: f64) -> Self {
  730. self.inner = self
  731. .inner
  732. .with_inner_size(TaoLogicalSize::new(width, height));
  733. self
  734. }
  735. fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
  736. self.inner = self
  737. .inner
  738. .with_min_inner_size(TaoLogicalSize::new(min_width, min_height));
  739. self
  740. }
  741. fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
  742. self.inner = self
  743. .inner
  744. .with_max_inner_size(TaoLogicalSize::new(max_width, max_height));
  745. self
  746. }
  747. fn inner_size_constraints(mut self, constraints: WindowSizeConstraints) -> Self {
  748. self.inner.window.inner_size_constraints = tao::window::WindowSizeConstraints {
  749. min_width: constraints.min_width,
  750. min_height: constraints.min_height,
  751. max_width: constraints.max_width,
  752. max_height: constraints.max_height,
  753. };
  754. self
  755. }
  756. fn resizable(mut self, resizable: bool) -> Self {
  757. self.inner = self.inner.with_resizable(resizable);
  758. self
  759. }
  760. fn maximizable(mut self, maximizable: bool) -> Self {
  761. self.inner = self.inner.with_maximizable(maximizable);
  762. self
  763. }
  764. fn minimizable(mut self, minimizable: bool) -> Self {
  765. self.inner = self.inner.with_minimizable(minimizable);
  766. self
  767. }
  768. fn closable(mut self, closable: bool) -> Self {
  769. self.inner = self.inner.with_closable(closable);
  770. self
  771. }
  772. fn title<S: Into<String>>(mut self, title: S) -> Self {
  773. self.inner = self.inner.with_title(title.into());
  774. self
  775. }
  776. fn fullscreen(mut self, fullscreen: bool) -> Self {
  777. self.inner = if fullscreen {
  778. self
  779. .inner
  780. .with_fullscreen(Some(Fullscreen::Borderless(None)))
  781. } else {
  782. self.inner.with_fullscreen(None)
  783. };
  784. self
  785. }
  786. fn focused(mut self, focused: bool) -> Self {
  787. self.inner = self.inner.with_focused(focused);
  788. self
  789. }
  790. fn maximized(mut self, maximized: bool) -> Self {
  791. self.inner = self.inner.with_maximized(maximized);
  792. self
  793. }
  794. fn visible(mut self, visible: bool) -> Self {
  795. self.inner = self.inner.with_visible(visible);
  796. self
  797. }
  798. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  799. fn transparent(mut self, transparent: bool) -> Self {
  800. self.inner = self.inner.with_transparent(transparent);
  801. self
  802. }
  803. fn decorations(mut self, decorations: bool) -> Self {
  804. self.inner = self.inner.with_decorations(decorations);
  805. self
  806. }
  807. fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
  808. self.inner = self.inner.with_always_on_bottom(always_on_bottom);
  809. self
  810. }
  811. fn always_on_top(mut self, always_on_top: bool) -> Self {
  812. self.inner = self.inner.with_always_on_top(always_on_top);
  813. self
  814. }
  815. fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
  816. self.inner = self
  817. .inner
  818. .with_visible_on_all_workspaces(visible_on_all_workspaces);
  819. self
  820. }
  821. fn content_protected(mut self, protected: bool) -> Self {
  822. self.inner = self.inner.with_content_protection(protected);
  823. self
  824. }
  825. fn shadow(#[allow(unused_mut)] mut self, _enable: bool) -> Self {
  826. #[cfg(windows)]
  827. {
  828. self.inner = self.inner.with_undecorated_shadow(_enable);
  829. }
  830. #[cfg(target_os = "macos")]
  831. {
  832. self.inner = self.inner.with_has_shadow(_enable);
  833. }
  834. self
  835. }
  836. #[cfg(windows)]
  837. fn owner(mut self, owner: HWND) -> Self {
  838. self.inner = self.inner.with_owner_window(owner.0 as _);
  839. self
  840. }
  841. #[cfg(windows)]
  842. fn parent(mut self, parent: HWND) -> Self {
  843. self.inner = self.inner.with_parent_window(parent.0 as _);
  844. self
  845. }
  846. #[cfg(target_os = "macos")]
  847. fn parent(mut self, parent: *mut std::ffi::c_void) -> Self {
  848. self.inner = self.inner.with_parent_window(parent);
  849. self
  850. }
  851. #[cfg(any(
  852. target_os = "linux",
  853. target_os = "dragonfly",
  854. target_os = "freebsd",
  855. target_os = "netbsd",
  856. target_os = "openbsd"
  857. ))]
  858. fn transient_for(mut self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
  859. self.inner = self.inner.with_transient_for(parent);
  860. self
  861. }
  862. #[cfg(windows)]
  863. fn drag_and_drop(mut self, enabled: bool) -> Self {
  864. self.inner = self.inner.with_drag_and_drop(enabled);
  865. self
  866. }
  867. #[cfg(target_os = "macos")]
  868. fn title_bar_style(mut self, style: TitleBarStyle) -> Self {
  869. match style {
  870. TitleBarStyle::Visible => {
  871. self.inner = self.inner.with_titlebar_transparent(false);
  872. // Fixes rendering issue when resizing window with devtools open (https://github.com/tauri-apps/tauri/issues/3914)
  873. self.inner = self.inner.with_fullsize_content_view(true);
  874. }
  875. TitleBarStyle::Transparent => {
  876. self.inner = self.inner.with_titlebar_transparent(true);
  877. self.inner = self.inner.with_fullsize_content_view(false);
  878. }
  879. TitleBarStyle::Overlay => {
  880. self.inner = self.inner.with_titlebar_transparent(true);
  881. self.inner = self.inner.with_fullsize_content_view(true);
  882. }
  883. unknown => {
  884. #[cfg(feature = "tracing")]
  885. tracing::warn!("unknown title bar style applied: {unknown}");
  886. #[cfg(not(feature = "tracing"))]
  887. eprintln!("unknown title bar style applied: {unknown}");
  888. }
  889. }
  890. self
  891. }
  892. #[cfg(target_os = "macos")]
  893. fn hidden_title(mut self, hidden: bool) -> Self {
  894. self.inner = self.inner.with_title_hidden(hidden);
  895. self
  896. }
  897. #[cfg(target_os = "macos")]
  898. fn tabbing_identifier(mut self, identifier: &str) -> Self {
  899. self.inner = self.inner.with_tabbing_identifier(identifier);
  900. self.tabbing_identifier.replace(identifier.into());
  901. self
  902. }
  903. fn icon(mut self, icon: Icon) -> Result<Self> {
  904. self.inner = self
  905. .inner
  906. .with_window_icon(Some(TaoIcon::try_from(icon)?.0));
  907. Ok(self)
  908. }
  909. #[cfg(any(windows, target_os = "linux"))]
  910. fn skip_taskbar(mut self, skip: bool) -> Self {
  911. self.inner = self.inner.with_skip_taskbar(skip);
  912. self
  913. }
  914. #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))]
  915. fn skip_taskbar(self, _skip: bool) -> Self {
  916. self
  917. }
  918. #[allow(unused_variables, unused_mut)]
  919. fn theme(mut self, theme: Option<Theme>) -> Self {
  920. self.inner = self.inner.with_theme(if let Some(t) = theme {
  921. match t {
  922. Theme::Dark => Some(TaoTheme::Dark),
  923. _ => Some(TaoTheme::Light),
  924. }
  925. } else {
  926. None
  927. });
  928. self
  929. }
  930. fn has_icon(&self) -> bool {
  931. self.inner.window.window_icon.is_some()
  932. }
  933. fn get_theme(&self) -> Option<Theme> {
  934. self.inner.window.preferred_theme.map(|theme| match theme {
  935. TaoTheme::Dark => Theme::Dark,
  936. _ => Theme::Light,
  937. })
  938. }
  939. }
  940. #[cfg(any(
  941. target_os = "linux",
  942. target_os = "dragonfly",
  943. target_os = "freebsd",
  944. target_os = "netbsd",
  945. target_os = "openbsd"
  946. ))]
  947. pub struct GtkWindow(pub gtk::ApplicationWindow);
  948. #[cfg(any(
  949. target_os = "linux",
  950. target_os = "dragonfly",
  951. target_os = "freebsd",
  952. target_os = "netbsd",
  953. target_os = "openbsd"
  954. ))]
  955. #[allow(clippy::non_send_fields_in_send_ty)]
  956. unsafe impl Send for GtkWindow {}
  957. #[cfg(any(
  958. target_os = "linux",
  959. target_os = "dragonfly",
  960. target_os = "freebsd",
  961. target_os = "netbsd",
  962. target_os = "openbsd"
  963. ))]
  964. pub struct GtkBox(pub gtk::Box);
  965. #[cfg(any(
  966. target_os = "linux",
  967. target_os = "dragonfly",
  968. target_os = "freebsd",
  969. target_os = "netbsd",
  970. target_os = "openbsd"
  971. ))]
  972. #[allow(clippy::non_send_fields_in_send_ty)]
  973. unsafe impl Send for GtkBox {}
  974. pub struct SendRawWindowHandle(pub raw_window_handle::RawWindowHandle);
  975. unsafe impl Send for SendRawWindowHandle {}
  976. #[cfg(target_os = "macos")]
  977. #[derive(Debug, Clone)]
  978. pub enum ApplicationMessage {
  979. Show,
  980. Hide,
  981. }
  982. pub enum WindowMessage {
  983. AddEventListener(WindowEventId, Box<dyn Fn(&WindowEvent) + Send>),
  984. // Getters
  985. ScaleFactor(Sender<f64>),
  986. InnerPosition(Sender<Result<PhysicalPosition<i32>>>),
  987. OuterPosition(Sender<Result<PhysicalPosition<i32>>>),
  988. InnerSize(Sender<PhysicalSize<u32>>),
  989. OuterSize(Sender<PhysicalSize<u32>>),
  990. IsFullscreen(Sender<bool>),
  991. IsMinimized(Sender<bool>),
  992. IsMaximized(Sender<bool>),
  993. IsFocused(Sender<bool>),
  994. IsDecorated(Sender<bool>),
  995. IsResizable(Sender<bool>),
  996. IsMaximizable(Sender<bool>),
  997. IsMinimizable(Sender<bool>),
  998. IsClosable(Sender<bool>),
  999. IsVisible(Sender<bool>),
  1000. Title(Sender<String>),
  1001. CurrentMonitor(Sender<Option<MonitorHandle>>),
  1002. PrimaryMonitor(Sender<Option<MonitorHandle>>),
  1003. MonitorFromPoint(Sender<Option<MonitorHandle>>, (f64, f64)),
  1004. AvailableMonitors(Sender<Vec<MonitorHandle>>),
  1005. #[cfg(any(
  1006. target_os = "linux",
  1007. target_os = "dragonfly",
  1008. target_os = "freebsd",
  1009. target_os = "netbsd",
  1010. target_os = "openbsd"
  1011. ))]
  1012. GtkWindow(Sender<GtkWindow>),
  1013. #[cfg(any(
  1014. target_os = "linux",
  1015. target_os = "dragonfly",
  1016. target_os = "freebsd",
  1017. target_os = "netbsd",
  1018. target_os = "openbsd"
  1019. ))]
  1020. GtkBox(Sender<GtkBox>),
  1021. RawWindowHandle(Sender<std::result::Result<SendRawWindowHandle, raw_window_handle::HandleError>>),
  1022. Theme(Sender<Theme>),
  1023. // Setters
  1024. Center,
  1025. RequestUserAttention(Option<UserAttentionTypeWrapper>),
  1026. SetResizable(bool),
  1027. SetMaximizable(bool),
  1028. SetMinimizable(bool),
  1029. SetClosable(bool),
  1030. SetTitle(String),
  1031. Maximize,
  1032. Unmaximize,
  1033. Minimize,
  1034. Unminimize,
  1035. Show,
  1036. Hide,
  1037. Close,
  1038. Destroy,
  1039. SetDecorations(bool),
  1040. SetShadow(bool),
  1041. SetAlwaysOnBottom(bool),
  1042. SetAlwaysOnTop(bool),
  1043. SetVisibleOnAllWorkspaces(bool),
  1044. SetContentProtected(bool),
  1045. SetSize(Size),
  1046. SetMinSize(Option<Size>),
  1047. SetMaxSize(Option<Size>),
  1048. SetSizeConstraints(WindowSizeConstraints),
  1049. SetPosition(Position),
  1050. SetFullscreen(bool),
  1051. SetFocus,
  1052. SetIcon(TaoWindowIcon),
  1053. SetSkipTaskbar(bool),
  1054. SetCursorGrab(bool),
  1055. SetCursorVisible(bool),
  1056. SetCursorIcon(CursorIcon),
  1057. SetCursorPosition(Position),
  1058. SetIgnoreCursorEvents(bool),
  1059. SetProgressBar(ProgressBarState),
  1060. SetTitleBarStyle(tauri_utils::TitleBarStyle),
  1061. DragWindow,
  1062. ResizeDragWindow(tauri_runtime::ResizeDirection),
  1063. RequestRedraw,
  1064. }
  1065. #[derive(Debug, Clone)]
  1066. pub enum SynthesizedWindowEvent {
  1067. Focused(bool),
  1068. DragDrop(DragDropEvent),
  1069. }
  1070. impl From<SynthesizedWindowEvent> for WindowEventWrapper {
  1071. fn from(event: SynthesizedWindowEvent) -> Self {
  1072. let event = match event {
  1073. SynthesizedWindowEvent::Focused(focused) => WindowEvent::Focused(focused),
  1074. SynthesizedWindowEvent::DragDrop(event) => WindowEvent::DragDrop(event),
  1075. };
  1076. Self(Some(event))
  1077. }
  1078. }
  1079. pub enum WebviewMessage {
  1080. AddEventListener(WebviewEventId, Box<dyn Fn(&WebviewEvent) + Send>),
  1081. #[cfg(not(all(feature = "tracing", not(target_os = "android"))))]
  1082. EvaluateScript(String),
  1083. #[cfg(all(feature = "tracing", not(target_os = "android")))]
  1084. EvaluateScript(String, Sender<()>, tracing::Span),
  1085. WebviewEvent(WebviewEvent),
  1086. SynthesizedWindowEvent(SynthesizedWindowEvent),
  1087. Navigate(Url),
  1088. Print,
  1089. Close,
  1090. SetPosition(Position),
  1091. SetSize(Size),
  1092. SetBounds(tauri_runtime::Rect),
  1093. SetFocus,
  1094. Reparent(WindowId, Sender<Result<()>>),
  1095. SetAutoResize(bool),
  1096. SetZoom(f64),
  1097. // Getters
  1098. Url(Sender<Result<String>>),
  1099. Bounds(Sender<Result<tauri_runtime::Rect>>),
  1100. Position(Sender<Result<PhysicalPosition<i32>>>),
  1101. Size(Sender<Result<PhysicalSize<u32>>>),
  1102. WithWebview(Box<dyn FnOnce(Webview) + Send>),
  1103. // Devtools
  1104. #[cfg(any(debug_assertions, feature = "devtools"))]
  1105. OpenDevTools,
  1106. #[cfg(any(debug_assertions, feature = "devtools"))]
  1107. CloseDevTools,
  1108. #[cfg(any(debug_assertions, feature = "devtools"))]
  1109. IsDevToolsOpen(Sender<bool>),
  1110. }
  1111. pub type CreateWindowClosure<T> =
  1112. Box<dyn FnOnce(&EventLoopWindowTarget<Message<T>>) -> Result<WindowWrapper> + Send>;
  1113. pub type CreateWebviewClosure = Box<dyn FnOnce(&Window) -> Result<WebviewWrapper> + Send>;
  1114. pub enum Message<T: 'static> {
  1115. Task(Box<dyn FnOnce() + Send>),
  1116. #[cfg(target_os = "macos")]
  1117. SetActivationPolicy(ActivationPolicy),
  1118. RequestExit(i32),
  1119. #[cfg(target_os = "macos")]
  1120. Application(ApplicationMessage),
  1121. Window(WindowId, WindowMessage),
  1122. Webview(WindowId, WebviewId, WebviewMessage),
  1123. CreateWebview(WindowId, CreateWebviewClosure),
  1124. CreateWindow(WindowId, CreateWindowClosure<T>),
  1125. CreateRawWindow(
  1126. WindowId,
  1127. Box<dyn FnOnce() -> (String, TaoWindowBuilder) + Send>,
  1128. Sender<Result<Weak<Window>>>,
  1129. ),
  1130. UserEvent(T),
  1131. }
  1132. impl<T: UserEvent> Clone for Message<T> {
  1133. fn clone(&self) -> Self {
  1134. match self {
  1135. Self::UserEvent(t) => Self::UserEvent(t.clone()),
  1136. _ => unimplemented!(),
  1137. }
  1138. }
  1139. }
  1140. /// The Tauri [`WebviewDispatch`] for [`Wry`].
  1141. #[derive(Debug, Clone)]
  1142. pub struct WryWebviewDispatcher<T: UserEvent> {
  1143. window_id: Arc<Mutex<WindowId>>,
  1144. webview_id: WebviewId,
  1145. context: Context<T>,
  1146. }
  1147. impl<T: UserEvent> WebviewDispatch<T> for WryWebviewDispatcher<T> {
  1148. type Runtime = Wry<T>;
  1149. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
  1150. send_user_message(&self.context, Message::Task(Box::new(f)))
  1151. }
  1152. fn on_webview_event<F: Fn(&WebviewEvent) + Send + 'static>(&self, f: F) -> WindowEventId {
  1153. let id = self.context.next_webview_event_id();
  1154. let _ = self.context.proxy.send_event(Message::Webview(
  1155. *self.window_id.lock().unwrap(),
  1156. self.webview_id,
  1157. WebviewMessage::AddEventListener(id, Box::new(f)),
  1158. ));
  1159. id
  1160. }
  1161. fn with_webview<F: FnOnce(Box<dyn std::any::Any>) + Send + 'static>(&self, f: F) -> Result<()> {
  1162. send_user_message(
  1163. &self.context,
  1164. Message::Webview(
  1165. *self.window_id.lock().unwrap(),
  1166. self.webview_id,
  1167. WebviewMessage::WithWebview(Box::new(move |webview| f(Box::new(webview)))),
  1168. ),
  1169. )
  1170. }
  1171. #[cfg(any(debug_assertions, feature = "devtools"))]
  1172. fn open_devtools(&self) {
  1173. let _ = send_user_message(
  1174. &self.context,
  1175. Message::Webview(
  1176. *self.window_id.lock().unwrap(),
  1177. self.webview_id,
  1178. WebviewMessage::OpenDevTools,
  1179. ),
  1180. );
  1181. }
  1182. #[cfg(any(debug_assertions, feature = "devtools"))]
  1183. fn close_devtools(&self) {
  1184. let _ = send_user_message(
  1185. &self.context,
  1186. Message::Webview(
  1187. *self.window_id.lock().unwrap(),
  1188. self.webview_id,
  1189. WebviewMessage::CloseDevTools,
  1190. ),
  1191. );
  1192. }
  1193. /// Gets the devtools window's current open state.
  1194. #[cfg(any(debug_assertions, feature = "devtools"))]
  1195. fn is_devtools_open(&self) -> Result<bool> {
  1196. webview_getter!(self, WebviewMessage::IsDevToolsOpen)
  1197. }
  1198. // Getters
  1199. fn url(&self) -> Result<String> {
  1200. webview_getter!(self, WebviewMessage::Url)?
  1201. }
  1202. fn bounds(&self) -> Result<tauri_runtime::Rect> {
  1203. webview_getter!(self, WebviewMessage::Bounds)?
  1204. }
  1205. fn position(&self) -> Result<PhysicalPosition<i32>> {
  1206. webview_getter!(self, WebviewMessage::Position)?
  1207. }
  1208. fn size(&self) -> Result<PhysicalSize<u32>> {
  1209. webview_getter!(self, WebviewMessage::Size)?
  1210. }
  1211. // Setters
  1212. fn navigate(&self, url: Url) -> Result<()> {
  1213. send_user_message(
  1214. &self.context,
  1215. Message::Webview(
  1216. *self.window_id.lock().unwrap(),
  1217. self.webview_id,
  1218. WebviewMessage::Navigate(url),
  1219. ),
  1220. )
  1221. }
  1222. fn print(&self) -> Result<()> {
  1223. send_user_message(
  1224. &self.context,
  1225. Message::Webview(
  1226. *self.window_id.lock().unwrap(),
  1227. self.webview_id,
  1228. WebviewMessage::Print,
  1229. ),
  1230. )
  1231. }
  1232. fn close(&self) -> Result<()> {
  1233. send_user_message(
  1234. &self.context,
  1235. Message::Webview(
  1236. *self.window_id.lock().unwrap(),
  1237. self.webview_id,
  1238. WebviewMessage::Close,
  1239. ),
  1240. )
  1241. }
  1242. fn set_bounds(&self, bounds: tauri_runtime::Rect) -> Result<()> {
  1243. send_user_message(
  1244. &self.context,
  1245. Message::Webview(
  1246. *self.window_id.lock().unwrap(),
  1247. self.webview_id,
  1248. WebviewMessage::SetBounds(bounds),
  1249. ),
  1250. )
  1251. }
  1252. fn set_size(&self, size: Size) -> Result<()> {
  1253. send_user_message(
  1254. &self.context,
  1255. Message::Webview(
  1256. *self.window_id.lock().unwrap(),
  1257. self.webview_id,
  1258. WebviewMessage::SetSize(size),
  1259. ),
  1260. )
  1261. }
  1262. fn set_position(&self, position: Position) -> Result<()> {
  1263. send_user_message(
  1264. &self.context,
  1265. Message::Webview(
  1266. *self.window_id.lock().unwrap(),
  1267. self.webview_id,
  1268. WebviewMessage::SetPosition(position),
  1269. ),
  1270. )
  1271. }
  1272. fn set_focus(&self) -> Result<()> {
  1273. send_user_message(
  1274. &self.context,
  1275. Message::Webview(
  1276. *self.window_id.lock().unwrap(),
  1277. self.webview_id,
  1278. WebviewMessage::SetFocus,
  1279. ),
  1280. )
  1281. }
  1282. fn reparent(&self, window_id: WindowId) -> Result<()> {
  1283. let mut current_window_id = self.window_id.lock().unwrap();
  1284. let (tx, rx) = channel();
  1285. send_user_message(
  1286. &self.context,
  1287. Message::Webview(
  1288. *current_window_id,
  1289. self.webview_id,
  1290. WebviewMessage::Reparent(window_id, tx),
  1291. ),
  1292. )?;
  1293. rx.recv().unwrap()?;
  1294. *current_window_id = window_id;
  1295. Ok(())
  1296. }
  1297. fn set_auto_resize(&self, auto_resize: bool) -> Result<()> {
  1298. send_user_message(
  1299. &self.context,
  1300. Message::Webview(
  1301. *self.window_id.lock().unwrap(),
  1302. self.webview_id,
  1303. WebviewMessage::SetAutoResize(auto_resize),
  1304. ),
  1305. )
  1306. }
  1307. #[cfg(all(feature = "tracing", not(target_os = "android")))]
  1308. fn eval_script<S: Into<String>>(&self, script: S) -> Result<()> {
  1309. // use a channel so the EvaluateScript task uses the current span as parent
  1310. let (tx, rx) = channel();
  1311. getter!(
  1312. self,
  1313. rx,
  1314. Message::Webview(
  1315. *self.window_id.lock().unwrap(),
  1316. self.webview_id,
  1317. WebviewMessage::EvaluateScript(script.into(), tx, tracing::Span::current()),
  1318. )
  1319. )
  1320. }
  1321. #[cfg(not(all(feature = "tracing", not(target_os = "android"))))]
  1322. fn eval_script<S: Into<String>>(&self, script: S) -> Result<()> {
  1323. send_user_message(
  1324. &self.context,
  1325. Message::Webview(
  1326. *self.window_id.lock().unwrap(),
  1327. self.webview_id,
  1328. WebviewMessage::EvaluateScript(script.into()),
  1329. ),
  1330. )
  1331. }
  1332. fn set_zoom(&self, scale_factor: f64) -> Result<()> {
  1333. send_user_message(
  1334. &self.context,
  1335. Message::Webview(
  1336. *self.window_id.lock().unwrap(),
  1337. self.webview_id,
  1338. WebviewMessage::SetZoom(scale_factor),
  1339. ),
  1340. )
  1341. }
  1342. }
  1343. /// The Tauri [`WindowDispatch`] for [`Wry`].
  1344. #[derive(Debug, Clone)]
  1345. pub struct WryWindowDispatcher<T: UserEvent> {
  1346. window_id: WindowId,
  1347. context: Context<T>,
  1348. }
  1349. // SAFETY: this is safe since the `Context` usage is guarded on `send_user_message`.
  1350. #[allow(clippy::non_send_fields_in_send_ty)]
  1351. unsafe impl<T: UserEvent> Sync for WryWindowDispatcher<T> {}
  1352. fn get_raw_window_handle<T: UserEvent>(
  1353. dispatcher: &WryWindowDispatcher<T>,
  1354. ) -> Result<std::result::Result<SendRawWindowHandle, raw_window_handle::HandleError>> {
  1355. window_getter!(dispatcher, WindowMessage::RawWindowHandle)
  1356. }
  1357. impl<T: UserEvent> WindowDispatch<T> for WryWindowDispatcher<T> {
  1358. type Runtime = Wry<T>;
  1359. type WindowBuilder = WindowBuilderWrapper;
  1360. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
  1361. send_user_message(&self.context, Message::Task(Box::new(f)))
  1362. }
  1363. fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> WindowEventId {
  1364. let id = self.context.next_window_event_id();
  1365. let _ = self.context.proxy.send_event(Message::Window(
  1366. self.window_id,
  1367. WindowMessage::AddEventListener(id, Box::new(f)),
  1368. ));
  1369. id
  1370. }
  1371. // Getters
  1372. fn scale_factor(&self) -> Result<f64> {
  1373. window_getter!(self, WindowMessage::ScaleFactor)
  1374. }
  1375. fn inner_position(&self) -> Result<PhysicalPosition<i32>> {
  1376. window_getter!(self, WindowMessage::InnerPosition)?
  1377. }
  1378. fn outer_position(&self) -> Result<PhysicalPosition<i32>> {
  1379. window_getter!(self, WindowMessage::OuterPosition)?
  1380. }
  1381. fn inner_size(&self) -> Result<PhysicalSize<u32>> {
  1382. window_getter!(self, WindowMessage::InnerSize)
  1383. }
  1384. fn outer_size(&self) -> Result<PhysicalSize<u32>> {
  1385. window_getter!(self, WindowMessage::OuterSize)
  1386. }
  1387. fn is_fullscreen(&self) -> Result<bool> {
  1388. window_getter!(self, WindowMessage::IsFullscreen)
  1389. }
  1390. fn is_minimized(&self) -> Result<bool> {
  1391. window_getter!(self, WindowMessage::IsMinimized)
  1392. }
  1393. fn is_maximized(&self) -> Result<bool> {
  1394. window_getter!(self, WindowMessage::IsMaximized)
  1395. }
  1396. fn is_focused(&self) -> Result<bool> {
  1397. window_getter!(self, WindowMessage::IsFocused)
  1398. }
  1399. /// Gets the window's current decoration state.
  1400. fn is_decorated(&self) -> Result<bool> {
  1401. window_getter!(self, WindowMessage::IsDecorated)
  1402. }
  1403. /// Gets the window's current resizable state.
  1404. fn is_resizable(&self) -> Result<bool> {
  1405. window_getter!(self, WindowMessage::IsResizable)
  1406. }
  1407. /// Gets the current native window's maximize button state
  1408. fn is_maximizable(&self) -> Result<bool> {
  1409. window_getter!(self, WindowMessage::IsMaximizable)
  1410. }
  1411. /// Gets the current native window's minimize button state
  1412. fn is_minimizable(&self) -> Result<bool> {
  1413. window_getter!(self, WindowMessage::IsMinimizable)
  1414. }
  1415. /// Gets the current native window's close button state
  1416. fn is_closable(&self) -> Result<bool> {
  1417. window_getter!(self, WindowMessage::IsClosable)
  1418. }
  1419. fn is_visible(&self) -> Result<bool> {
  1420. window_getter!(self, WindowMessage::IsVisible)
  1421. }
  1422. fn title(&self) -> Result<String> {
  1423. window_getter!(self, WindowMessage::Title)
  1424. }
  1425. fn current_monitor(&self) -> Result<Option<Monitor>> {
  1426. Ok(window_getter!(self, WindowMessage::CurrentMonitor)?.map(|m| MonitorHandleWrapper(m).into()))
  1427. }
  1428. fn primary_monitor(&self) -> Result<Option<Monitor>> {
  1429. Ok(window_getter!(self, WindowMessage::PrimaryMonitor)?.map(|m| MonitorHandleWrapper(m).into()))
  1430. }
  1431. fn monitor_from_point(&self, x: f64, y: f64) -> Result<Option<Monitor>> {
  1432. let (tx, rx) = channel();
  1433. let _ = send_user_message(
  1434. &self.context,
  1435. Message::Window(self.window_id, WindowMessage::MonitorFromPoint(tx, (x, y))),
  1436. );
  1437. Ok(
  1438. rx.recv()
  1439. .map_err(|_| crate::Error::FailedToReceiveMessage)?
  1440. .map(|m| MonitorHandleWrapper(m).into()),
  1441. )
  1442. }
  1443. fn available_monitors(&self) -> Result<Vec<Monitor>> {
  1444. Ok(
  1445. window_getter!(self, WindowMessage::AvailableMonitors)?
  1446. .into_iter()
  1447. .map(|m| MonitorHandleWrapper(m).into())
  1448. .collect(),
  1449. )
  1450. }
  1451. fn theme(&self) -> Result<Theme> {
  1452. window_getter!(self, WindowMessage::Theme)
  1453. }
  1454. #[cfg(any(
  1455. target_os = "linux",
  1456. target_os = "dragonfly",
  1457. target_os = "freebsd",
  1458. target_os = "netbsd",
  1459. target_os = "openbsd"
  1460. ))]
  1461. fn gtk_window(&self) -> Result<gtk::ApplicationWindow> {
  1462. window_getter!(self, WindowMessage::GtkWindow).map(|w| w.0)
  1463. }
  1464. #[cfg(any(
  1465. target_os = "linux",
  1466. target_os = "dragonfly",
  1467. target_os = "freebsd",
  1468. target_os = "netbsd",
  1469. target_os = "openbsd"
  1470. ))]
  1471. fn default_vbox(&self) -> Result<gtk::Box> {
  1472. window_getter!(self, WindowMessage::GtkBox).map(|w| w.0)
  1473. }
  1474. fn window_handle(
  1475. &self,
  1476. ) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
  1477. get_raw_window_handle(self)
  1478. .map_err(|_| raw_window_handle::HandleError::Unavailable)
  1479. .and_then(|r| r.map(|h| unsafe { raw_window_handle::WindowHandle::borrow_raw(h.0) }))
  1480. }
  1481. // Setters
  1482. fn center(&self) -> Result<()> {
  1483. send_user_message(
  1484. &self.context,
  1485. Message::Window(self.window_id, WindowMessage::Center),
  1486. )
  1487. }
  1488. fn request_user_attention(&self, request_type: Option<UserAttentionType>) -> Result<()> {
  1489. send_user_message(
  1490. &self.context,
  1491. Message::Window(
  1492. self.window_id,
  1493. WindowMessage::RequestUserAttention(request_type.map(Into::into)),
  1494. ),
  1495. )
  1496. }
  1497. // Creates a window by dispatching a message to the event loop.
  1498. // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
  1499. fn create_window<F: Fn(RawWindow) + Send + 'static>(
  1500. &mut self,
  1501. pending: PendingWindow<T, Self::Runtime>,
  1502. after_window_creation: Option<F>,
  1503. ) -> Result<DetachedWindow<T, Self::Runtime>> {
  1504. self.context.create_window(pending, after_window_creation)
  1505. }
  1506. // Creates a webview by dispatching a message to the event loop.
  1507. // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
  1508. fn create_webview(
  1509. &mut self,
  1510. pending: PendingWebview<T, Self::Runtime>,
  1511. ) -> Result<DetachedWebview<T, Self::Runtime>> {
  1512. self.context.create_webview(self.window_id, pending)
  1513. }
  1514. fn set_resizable(&self, resizable: bool) -> Result<()> {
  1515. send_user_message(
  1516. &self.context,
  1517. Message::Window(self.window_id, WindowMessage::SetResizable(resizable)),
  1518. )
  1519. }
  1520. fn set_maximizable(&self, maximizable: bool) -> Result<()> {
  1521. send_user_message(
  1522. &self.context,
  1523. Message::Window(self.window_id, WindowMessage::SetMaximizable(maximizable)),
  1524. )
  1525. }
  1526. fn set_minimizable(&self, minimizable: bool) -> Result<()> {
  1527. send_user_message(
  1528. &self.context,
  1529. Message::Window(self.window_id, WindowMessage::SetMinimizable(minimizable)),
  1530. )
  1531. }
  1532. fn set_closable(&self, closable: bool) -> Result<()> {
  1533. send_user_message(
  1534. &self.context,
  1535. Message::Window(self.window_id, WindowMessage::SetClosable(closable)),
  1536. )
  1537. }
  1538. fn set_title<S: Into<String>>(&self, title: S) -> Result<()> {
  1539. send_user_message(
  1540. &self.context,
  1541. Message::Window(self.window_id, WindowMessage::SetTitle(title.into())),
  1542. )
  1543. }
  1544. fn maximize(&self) -> Result<()> {
  1545. send_user_message(
  1546. &self.context,
  1547. Message::Window(self.window_id, WindowMessage::Maximize),
  1548. )
  1549. }
  1550. fn unmaximize(&self) -> Result<()> {
  1551. send_user_message(
  1552. &self.context,
  1553. Message::Window(self.window_id, WindowMessage::Unmaximize),
  1554. )
  1555. }
  1556. fn minimize(&self) -> Result<()> {
  1557. send_user_message(
  1558. &self.context,
  1559. Message::Window(self.window_id, WindowMessage::Minimize),
  1560. )
  1561. }
  1562. fn unminimize(&self) -> Result<()> {
  1563. send_user_message(
  1564. &self.context,
  1565. Message::Window(self.window_id, WindowMessage::Unminimize),
  1566. )
  1567. }
  1568. fn show(&self) -> Result<()> {
  1569. send_user_message(
  1570. &self.context,
  1571. Message::Window(self.window_id, WindowMessage::Show),
  1572. )
  1573. }
  1574. fn hide(&self) -> Result<()> {
  1575. send_user_message(
  1576. &self.context,
  1577. Message::Window(self.window_id, WindowMessage::Hide),
  1578. )
  1579. }
  1580. fn close(&self) -> Result<()> {
  1581. // NOTE: close cannot use the `send_user_message` function because it accesses the event loop callback
  1582. self
  1583. .context
  1584. .proxy
  1585. .send_event(Message::Window(self.window_id, WindowMessage::Close))
  1586. .map_err(|_| Error::FailedToSendMessage)
  1587. }
  1588. fn destroy(&self) -> Result<()> {
  1589. // NOTE: destroy cannot use the `send_user_message` function because it accesses the event loop callback
  1590. self
  1591. .context
  1592. .proxy
  1593. .send_event(Message::Window(self.window_id, WindowMessage::Destroy))
  1594. .map_err(|_| Error::FailedToSendMessage)
  1595. }
  1596. fn set_decorations(&self, decorations: bool) -> Result<()> {
  1597. send_user_message(
  1598. &self.context,
  1599. Message::Window(self.window_id, WindowMessage::SetDecorations(decorations)),
  1600. )
  1601. }
  1602. fn set_shadow(&self, enable: bool) -> Result<()> {
  1603. send_user_message(
  1604. &self.context,
  1605. Message::Window(self.window_id, WindowMessage::SetShadow(enable)),
  1606. )
  1607. }
  1608. fn set_always_on_bottom(&self, always_on_bottom: bool) -> Result<()> {
  1609. send_user_message(
  1610. &self.context,
  1611. Message::Window(
  1612. self.window_id,
  1613. WindowMessage::SetAlwaysOnBottom(always_on_bottom),
  1614. ),
  1615. )
  1616. }
  1617. fn set_always_on_top(&self, always_on_top: bool) -> Result<()> {
  1618. send_user_message(
  1619. &self.context,
  1620. Message::Window(self.window_id, WindowMessage::SetAlwaysOnTop(always_on_top)),
  1621. )
  1622. }
  1623. fn set_visible_on_all_workspaces(&self, visible_on_all_workspaces: bool) -> Result<()> {
  1624. send_user_message(
  1625. &self.context,
  1626. Message::Window(
  1627. self.window_id,
  1628. WindowMessage::SetVisibleOnAllWorkspaces(visible_on_all_workspaces),
  1629. ),
  1630. )
  1631. }
  1632. fn set_content_protected(&self, protected: bool) -> Result<()> {
  1633. send_user_message(
  1634. &self.context,
  1635. Message::Window(
  1636. self.window_id,
  1637. WindowMessage::SetContentProtected(protected),
  1638. ),
  1639. )
  1640. }
  1641. fn set_size(&self, size: Size) -> Result<()> {
  1642. send_user_message(
  1643. &self.context,
  1644. Message::Window(self.window_id, WindowMessage::SetSize(size)),
  1645. )
  1646. }
  1647. fn set_min_size(&self, size: Option<Size>) -> Result<()> {
  1648. send_user_message(
  1649. &self.context,
  1650. Message::Window(self.window_id, WindowMessage::SetMinSize(size)),
  1651. )
  1652. }
  1653. fn set_max_size(&self, size: Option<Size>) -> Result<()> {
  1654. send_user_message(
  1655. &self.context,
  1656. Message::Window(self.window_id, WindowMessage::SetMaxSize(size)),
  1657. )
  1658. }
  1659. fn set_size_constraints(&self, constraints: WindowSizeConstraints) -> Result<()> {
  1660. send_user_message(
  1661. &self.context,
  1662. Message::Window(
  1663. self.window_id,
  1664. WindowMessage::SetSizeConstraints(constraints),
  1665. ),
  1666. )
  1667. }
  1668. fn set_position(&self, position: Position) -> Result<()> {
  1669. send_user_message(
  1670. &self.context,
  1671. Message::Window(self.window_id, WindowMessage::SetPosition(position)),
  1672. )
  1673. }
  1674. fn set_fullscreen(&self, fullscreen: bool) -> Result<()> {
  1675. send_user_message(
  1676. &self.context,
  1677. Message::Window(self.window_id, WindowMessage::SetFullscreen(fullscreen)),
  1678. )
  1679. }
  1680. fn set_focus(&self) -> Result<()> {
  1681. send_user_message(
  1682. &self.context,
  1683. Message::Window(self.window_id, WindowMessage::SetFocus),
  1684. )
  1685. }
  1686. fn set_icon(&self, icon: Icon) -> Result<()> {
  1687. send_user_message(
  1688. &self.context,
  1689. Message::Window(
  1690. self.window_id,
  1691. WindowMessage::SetIcon(TaoIcon::try_from(icon)?.0),
  1692. ),
  1693. )
  1694. }
  1695. fn set_skip_taskbar(&self, skip: bool) -> Result<()> {
  1696. send_user_message(
  1697. &self.context,
  1698. Message::Window(self.window_id, WindowMessage::SetSkipTaskbar(skip)),
  1699. )
  1700. }
  1701. fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
  1702. send_user_message(
  1703. &self.context,
  1704. Message::Window(self.window_id, WindowMessage::SetCursorGrab(grab)),
  1705. )
  1706. }
  1707. fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
  1708. send_user_message(
  1709. &self.context,
  1710. Message::Window(self.window_id, WindowMessage::SetCursorVisible(visible)),
  1711. )
  1712. }
  1713. fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
  1714. send_user_message(
  1715. &self.context,
  1716. Message::Window(self.window_id, WindowMessage::SetCursorIcon(icon)),
  1717. )
  1718. }
  1719. fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  1720. send_user_message(
  1721. &self.context,
  1722. Message::Window(
  1723. self.window_id,
  1724. WindowMessage::SetCursorPosition(position.into()),
  1725. ),
  1726. )
  1727. }
  1728. fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
  1729. send_user_message(
  1730. &self.context,
  1731. Message::Window(self.window_id, WindowMessage::SetIgnoreCursorEvents(ignore)),
  1732. )
  1733. }
  1734. fn start_dragging(&self) -> Result<()> {
  1735. send_user_message(
  1736. &self.context,
  1737. Message::Window(self.window_id, WindowMessage::DragWindow),
  1738. )
  1739. }
  1740. fn start_resize_dragging(&self, direction: tauri_runtime::ResizeDirection) -> Result<()> {
  1741. send_user_message(
  1742. &self.context,
  1743. Message::Window(self.window_id, WindowMessage::ResizeDragWindow(direction)),
  1744. )
  1745. }
  1746. fn set_progress_bar(&self, progress_state: ProgressBarState) -> Result<()> {
  1747. send_user_message(
  1748. &self.context,
  1749. Message::Window(
  1750. self.window_id,
  1751. WindowMessage::SetProgressBar(progress_state),
  1752. ),
  1753. )
  1754. }
  1755. fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> Result<()> {
  1756. send_user_message(
  1757. &self.context,
  1758. Message::Window(self.window_id, WindowMessage::SetTitleBarStyle(style)),
  1759. )
  1760. }
  1761. }
  1762. #[derive(Clone)]
  1763. pub struct WebviewWrapper {
  1764. label: String,
  1765. id: WebviewId,
  1766. inner: Rc<WebView>,
  1767. context_store: WebContextStore,
  1768. webview_event_listeners: WebviewEventListeners,
  1769. // the key of the WebContext if it's not shared
  1770. context_key: Option<PathBuf>,
  1771. bounds: Arc<Mutex<Option<WebviewBounds>>>,
  1772. }
  1773. impl Deref for WebviewWrapper {
  1774. type Target = WebView;
  1775. #[inline(always)]
  1776. fn deref(&self) -> &Self::Target {
  1777. &self.inner
  1778. }
  1779. }
  1780. impl Drop for WebviewWrapper {
  1781. fn drop(&mut self) {
  1782. if Rc::get_mut(&mut self.inner).is_some() {
  1783. self.context_store.lock().unwrap().remove(&self.context_key);
  1784. }
  1785. }
  1786. }
  1787. pub struct WindowWrapper {
  1788. label: String,
  1789. inner: Option<Arc<Window>>,
  1790. // whether this window has child webviews
  1791. // or it's just a container for a single webview
  1792. has_children: AtomicBool,
  1793. webviews: Vec<WebviewWrapper>,
  1794. window_event_listeners: WindowEventListeners,
  1795. #[cfg(windows)]
  1796. is_window_transparent: bool,
  1797. #[cfg(windows)]
  1798. surface: Option<softbuffer::Surface<Arc<Window>, Arc<Window>>>,
  1799. }
  1800. impl fmt::Debug for WindowWrapper {
  1801. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1802. f.debug_struct("WindowWrapper")
  1803. .field("label", &self.label)
  1804. .field("inner", &self.inner)
  1805. .finish()
  1806. }
  1807. }
  1808. #[derive(Debug, Clone)]
  1809. pub struct EventProxy<T: UserEvent>(TaoEventLoopProxy<Message<T>>);
  1810. #[cfg(target_os = "ios")]
  1811. #[allow(clippy::non_send_fields_in_send_ty)]
  1812. unsafe impl<T: UserEvent> Sync for EventProxy<T> {}
  1813. impl<T: UserEvent> EventLoopProxy<T> for EventProxy<T> {
  1814. fn send_event(&self, event: T) -> Result<()> {
  1815. self
  1816. .0
  1817. .send_event(Message::UserEvent(event))
  1818. .map_err(|_| Error::EventLoopClosed)
  1819. }
  1820. }
  1821. pub trait PluginBuilder<T: UserEvent> {
  1822. type Plugin: Plugin<T>;
  1823. fn build(self, context: Context<T>) -> Self::Plugin;
  1824. }
  1825. pub trait Plugin<T: UserEvent> {
  1826. fn on_event(
  1827. &mut self,
  1828. event: &Event<Message<T>>,
  1829. event_loop: &EventLoopWindowTarget<Message<T>>,
  1830. proxy: &TaoEventLoopProxy<Message<T>>,
  1831. control_flow: &mut ControlFlow,
  1832. context: EventLoopIterationContext<'_, T>,
  1833. web_context: &WebContextStore,
  1834. ) -> bool;
  1835. }
  1836. /// A Tauri [`Runtime`] wrapper around wry.
  1837. pub struct Wry<T: UserEvent> {
  1838. context: Context<T>,
  1839. event_loop: EventLoop<Message<T>>,
  1840. }
  1841. impl<T: UserEvent> fmt::Debug for Wry<T> {
  1842. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1843. f.debug_struct("Wry")
  1844. .field("main_thread_id", &self.context.main_thread_id)
  1845. .field("event_loop", &self.event_loop)
  1846. .field("windows", &self.context.main_thread.windows)
  1847. .field("web_context", &self.context.main_thread.web_context)
  1848. .finish()
  1849. }
  1850. }
  1851. /// A handle to the Wry runtime.
  1852. #[derive(Debug, Clone)]
  1853. pub struct WryHandle<T: UserEvent> {
  1854. context: Context<T>,
  1855. }
  1856. // SAFETY: this is safe since the `Context` usage is guarded on `send_user_message`.
  1857. #[allow(clippy::non_send_fields_in_send_ty)]
  1858. unsafe impl<T: UserEvent> Sync for WryHandle<T> {}
  1859. impl<T: UserEvent> WryHandle<T> {
  1860. /// Creates a new tao window using a callback, and returns its window id.
  1861. pub fn create_tao_window<F: FnOnce() -> (String, TaoWindowBuilder) + Send + 'static>(
  1862. &self,
  1863. f: F,
  1864. ) -> Result<Weak<Window>> {
  1865. let id = self.context.next_window_id();
  1866. let (tx, rx) = channel();
  1867. send_user_message(&self.context, Message::CreateRawWindow(id, Box::new(f), tx))?;
  1868. rx.recv().unwrap()
  1869. }
  1870. /// Gets the [`WebviewId'] associated with the given [`WindowId`].
  1871. pub fn window_id(&self, window_id: TaoWindowId) -> WindowId {
  1872. *self
  1873. .context
  1874. .window_id_map
  1875. .0
  1876. .lock()
  1877. .unwrap()
  1878. .get(&window_id)
  1879. .unwrap()
  1880. }
  1881. /// Send a message to the event loop.
  1882. pub fn send_event(&self, message: Message<T>) -> Result<()> {
  1883. self
  1884. .context
  1885. .proxy
  1886. .send_event(message)
  1887. .map_err(|_| Error::FailedToSendMessage)?;
  1888. Ok(())
  1889. }
  1890. pub fn plugin<P: PluginBuilder<T> + 'static>(&mut self, plugin: P)
  1891. where
  1892. <P as PluginBuilder<T>>::Plugin: Send,
  1893. {
  1894. self
  1895. .context
  1896. .plugins
  1897. .lock()
  1898. .unwrap()
  1899. .push(Box::new(plugin.build(self.context.clone())));
  1900. }
  1901. }
  1902. impl<T: UserEvent> RuntimeHandle<T> for WryHandle<T> {
  1903. type Runtime = Wry<T>;
  1904. fn create_proxy(&self) -> EventProxy<T> {
  1905. EventProxy(self.context.proxy.clone())
  1906. }
  1907. #[cfg(target_os = "macos")]
  1908. fn set_activation_policy(&self, activation_policy: ActivationPolicy) -> Result<()> {
  1909. send_user_message(
  1910. &self.context,
  1911. Message::SetActivationPolicy(activation_policy),
  1912. )
  1913. }
  1914. fn request_exit(&self, code: i32) -> Result<()> {
  1915. // NOTE: request_exit cannot use the `send_user_message` function because it accesses the event loop callback
  1916. self
  1917. .context
  1918. .proxy
  1919. .send_event(Message::RequestExit(code))
  1920. .map_err(|_| Error::FailedToSendMessage)
  1921. }
  1922. // Creates a window by dispatching a message to the event loop.
  1923. // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
  1924. fn create_window<F: Fn(RawWindow) + Send + 'static>(
  1925. &self,
  1926. pending: PendingWindow<T, Self::Runtime>,
  1927. after_window_creation: Option<F>,
  1928. ) -> Result<DetachedWindow<T, Self::Runtime>> {
  1929. self.context.create_window(pending, after_window_creation)
  1930. }
  1931. // Creates a webview by dispatching a message to the event loop.
  1932. // Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
  1933. fn create_webview(
  1934. &self,
  1935. window_id: WindowId,
  1936. pending: PendingWebview<T, Self::Runtime>,
  1937. ) -> Result<DetachedWebview<T, Self::Runtime>> {
  1938. self.context.create_webview(window_id, pending)
  1939. }
  1940. fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()> {
  1941. send_user_message(&self.context, Message::Task(Box::new(f)))
  1942. }
  1943. fn display_handle(&self) -> std::result::Result<DisplayHandle, raw_window_handle::HandleError> {
  1944. self.context.main_thread.window_target.display_handle()
  1945. }
  1946. fn primary_monitor(&self) -> Option<Monitor> {
  1947. self
  1948. .context
  1949. .main_thread
  1950. .window_target
  1951. .primary_monitor()
  1952. .map(|m| MonitorHandleWrapper(m).into())
  1953. }
  1954. fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor> {
  1955. self
  1956. .context
  1957. .main_thread
  1958. .window_target
  1959. .monitor_from_point(x, y)
  1960. .map(|m| MonitorHandleWrapper(m).into())
  1961. }
  1962. fn available_monitors(&self) -> Vec<Monitor> {
  1963. self
  1964. .context
  1965. .main_thread
  1966. .window_target
  1967. .available_monitors()
  1968. .map(|m| MonitorHandleWrapper(m).into())
  1969. .collect()
  1970. }
  1971. fn cursor_position(&self) -> Result<PhysicalPosition<f64>> {
  1972. self
  1973. .context
  1974. .main_thread
  1975. .window_target
  1976. .cursor_position()
  1977. .map(PhysicalPositionWrapper)
  1978. .map(Into::into)
  1979. .map_err(|_| Error::FailedToGetCursorPosition)
  1980. }
  1981. #[cfg(target_os = "macos")]
  1982. fn show(&self) -> tauri_runtime::Result<()> {
  1983. send_user_message(
  1984. &self.context,
  1985. Message::Application(ApplicationMessage::Show),
  1986. )
  1987. }
  1988. #[cfg(target_os = "macos")]
  1989. fn hide(&self) -> tauri_runtime::Result<()> {
  1990. send_user_message(
  1991. &self.context,
  1992. Message::Application(ApplicationMessage::Hide),
  1993. )
  1994. }
  1995. #[cfg(target_os = "android")]
  1996. fn find_class<'a>(
  1997. &self,
  1998. env: &mut jni::JNIEnv<'a>,
  1999. activity: &jni::objects::JObject<'_>,
  2000. name: impl Into<String>,
  2001. ) -> std::result::Result<jni::objects::JClass<'a>, jni::errors::Error> {
  2002. find_class(env, activity, name.into())
  2003. }
  2004. #[cfg(target_os = "android")]
  2005. fn run_on_android_context<F>(&self, f: F)
  2006. where
  2007. F: FnOnce(&mut jni::JNIEnv, &jni::objects::JObject, &jni::objects::JObject) + Send + 'static,
  2008. {
  2009. dispatch(f)
  2010. }
  2011. }
  2012. impl<T: UserEvent> Wry<T> {
  2013. fn init_with_builder(
  2014. mut event_loop_builder: EventLoopBuilder<Message<T>>,
  2015. #[allow(unused_variables)] args: RuntimeInitArgs,
  2016. ) -> Result<Self> {
  2017. #[cfg(windows)]
  2018. if let Some(hook) = args.msg_hook {
  2019. use tao::platform::windows::EventLoopBuilderExtWindows;
  2020. event_loop_builder.with_msg_hook(hook);
  2021. }
  2022. #[cfg(any(
  2023. target_os = "linux",
  2024. target_os = "dragonfly",
  2025. target_os = "freebsd",
  2026. target_os = "netbsd",
  2027. target_os = "openbsd"
  2028. ))]
  2029. if let Some(app_id) = args.app_id {
  2030. use tao::platform::unix::EventLoopBuilderExtUnix;
  2031. event_loop_builder.with_app_id(app_id);
  2032. }
  2033. Self::init(event_loop_builder.build())
  2034. }
  2035. fn init(event_loop: EventLoop<Message<T>>) -> Result<Self> {
  2036. let main_thread_id = current_thread().id();
  2037. let web_context = WebContextStore::default();
  2038. let windows = Arc::new(WindowsStore(RefCell::new(BTreeMap::default())));
  2039. let window_id_map = WindowIdStore::default();
  2040. let context = Context {
  2041. window_id_map,
  2042. main_thread_id,
  2043. proxy: event_loop.create_proxy(),
  2044. main_thread: DispatcherMainThreadContext {
  2045. window_target: event_loop.deref().clone(),
  2046. web_context,
  2047. windows,
  2048. #[cfg(feature = "tracing")]
  2049. active_tracing_spans: Default::default(),
  2050. },
  2051. plugins: Default::default(),
  2052. next_window_id: Default::default(),
  2053. next_webview_id: Default::default(),
  2054. next_window_event_id: Default::default(),
  2055. next_webview_event_id: Default::default(),
  2056. next_webcontext_id: Default::default(),
  2057. };
  2058. Ok(Self {
  2059. context,
  2060. event_loop,
  2061. })
  2062. }
  2063. }
  2064. impl<T: UserEvent> Runtime<T> for Wry<T> {
  2065. type WindowDispatcher = WryWindowDispatcher<T>;
  2066. type WebviewDispatcher = WryWebviewDispatcher<T>;
  2067. type Handle = WryHandle<T>;
  2068. type EventLoopProxy = EventProxy<T>;
  2069. fn new(args: RuntimeInitArgs) -> Result<Self> {
  2070. Self::init_with_builder(EventLoopBuilder::<Message<T>>::with_user_event(), args)
  2071. }
  2072. #[cfg(any(
  2073. target_os = "linux",
  2074. target_os = "dragonfly",
  2075. target_os = "freebsd",
  2076. target_os = "netbsd",
  2077. target_os = "openbsd"
  2078. ))]
  2079. fn new_any_thread(args: RuntimeInitArgs) -> Result<Self> {
  2080. use tao::platform::unix::EventLoopBuilderExtUnix;
  2081. let mut event_loop_builder = EventLoopBuilder::<Message<T>>::with_user_event();
  2082. event_loop_builder.with_any_thread(true);
  2083. Self::init_with_builder(event_loop_builder, args)
  2084. }
  2085. #[cfg(windows)]
  2086. fn new_any_thread(args: RuntimeInitArgs) -> Result<Self> {
  2087. use tao::platform::windows::EventLoopBuilderExtWindows;
  2088. let mut event_loop_builder = EventLoopBuilder::<Message<T>>::with_user_event();
  2089. event_loop_builder.with_any_thread(true);
  2090. Self::init_with_builder(event_loop_builder, args)
  2091. }
  2092. fn create_proxy(&self) -> EventProxy<T> {
  2093. EventProxy(self.event_loop.create_proxy())
  2094. }
  2095. fn handle(&self) -> Self::Handle {
  2096. WryHandle {
  2097. context: self.context.clone(),
  2098. }
  2099. }
  2100. fn create_window<F: Fn(RawWindow) + Send + 'static>(
  2101. &self,
  2102. pending: PendingWindow<T, Self>,
  2103. after_window_creation: Option<F>,
  2104. ) -> Result<DetachedWindow<T, Self>> {
  2105. let label = pending.label.clone();
  2106. let window_id = self.context.next_window_id();
  2107. let webview_id = pending
  2108. .webview
  2109. .as_ref()
  2110. .map(|_| self.context.next_webview_id());
  2111. let window = create_window(
  2112. window_id,
  2113. webview_id.unwrap_or_default(),
  2114. &self.event_loop,
  2115. &self.context,
  2116. pending,
  2117. after_window_creation,
  2118. )?;
  2119. let dispatcher = WryWindowDispatcher {
  2120. window_id,
  2121. context: self.context.clone(),
  2122. };
  2123. self
  2124. .context
  2125. .main_thread
  2126. .windows
  2127. .0
  2128. .borrow_mut()
  2129. .insert(window_id, window);
  2130. let detached_webview = webview_id.map(|id| DetachedWebview {
  2131. label: label.clone(),
  2132. dispatcher: WryWebviewDispatcher {
  2133. window_id: Arc::new(Mutex::new(window_id)),
  2134. webview_id: id,
  2135. context: self.context.clone(),
  2136. },
  2137. });
  2138. Ok(DetachedWindow {
  2139. id: window_id,
  2140. label,
  2141. dispatcher,
  2142. webview: detached_webview,
  2143. })
  2144. }
  2145. fn create_webview(
  2146. &self,
  2147. window_id: WindowId,
  2148. pending: PendingWebview<T, Self>,
  2149. ) -> Result<DetachedWebview<T, Self>> {
  2150. let label = pending.label.clone();
  2151. let window = self
  2152. .context
  2153. .main_thread
  2154. .windows
  2155. .0
  2156. .borrow()
  2157. .get(&window_id)
  2158. .and_then(|w| w.inner.clone());
  2159. if let Some(window) = window {
  2160. let window_id_wrapper = Arc::new(Mutex::new(window_id));
  2161. let webview_id = self.context.next_webview_id();
  2162. let webview = create_webview(
  2163. WebviewKind::WindowChild,
  2164. &window,
  2165. window_id_wrapper.clone(),
  2166. webview_id,
  2167. &self.context,
  2168. pending,
  2169. )?;
  2170. self
  2171. .context
  2172. .main_thread
  2173. .windows
  2174. .0
  2175. .borrow_mut()
  2176. .get_mut(&window_id)
  2177. .map(|w| {
  2178. w.webviews.push(webview);
  2179. w.has_children.store(true, Ordering::Relaxed);
  2180. w
  2181. });
  2182. let dispatcher = WryWebviewDispatcher {
  2183. window_id: window_id_wrapper,
  2184. webview_id,
  2185. context: self.context.clone(),
  2186. };
  2187. Ok(DetachedWebview { label, dispatcher })
  2188. } else {
  2189. Err(Error::WindowNotFound)
  2190. }
  2191. }
  2192. fn primary_monitor(&self) -> Option<Monitor> {
  2193. self
  2194. .context
  2195. .main_thread
  2196. .window_target
  2197. .primary_monitor()
  2198. .map(|m| MonitorHandleWrapper(m).into())
  2199. }
  2200. fn monitor_from_point(&self, x: f64, y: f64) -> Option<Monitor> {
  2201. self
  2202. .context
  2203. .main_thread
  2204. .window_target
  2205. .monitor_from_point(x, y)
  2206. .map(|m| MonitorHandleWrapper(m).into())
  2207. }
  2208. fn available_monitors(&self) -> Vec<Monitor> {
  2209. self
  2210. .context
  2211. .main_thread
  2212. .window_target
  2213. .available_monitors()
  2214. .map(|m| MonitorHandleWrapper(m).into())
  2215. .collect()
  2216. }
  2217. fn cursor_position(&self) -> Result<PhysicalPosition<f64>> {
  2218. self
  2219. .context
  2220. .main_thread
  2221. .window_target
  2222. .cursor_position()
  2223. .map(PhysicalPositionWrapper)
  2224. .map(Into::into)
  2225. .map_err(|_| Error::FailedToGetCursorPosition)
  2226. }
  2227. #[cfg(target_os = "macos")]
  2228. fn set_activation_policy(&mut self, activation_policy: ActivationPolicy) {
  2229. self
  2230. .event_loop
  2231. .set_activation_policy(tao_activation_policy(activation_policy));
  2232. }
  2233. #[cfg(target_os = "macos")]
  2234. fn show(&self) {
  2235. self.event_loop.show_application();
  2236. }
  2237. #[cfg(target_os = "macos")]
  2238. fn hide(&self) {
  2239. self.event_loop.hide_application();
  2240. }
  2241. fn set_device_event_filter(&mut self, filter: DeviceEventFilter) {
  2242. self
  2243. .event_loop
  2244. .set_device_event_filter(DeviceEventFilterWrapper::from(filter).0);
  2245. }
  2246. #[cfg(desktop)]
  2247. fn run_iteration<F: FnMut(RunEvent<T>) + 'static>(&mut self, mut callback: F) {
  2248. use tao::platform::run_return::EventLoopExtRunReturn;
  2249. let windows = self.context.main_thread.windows.clone();
  2250. let window_id_map = self.context.window_id_map.clone();
  2251. let web_context = &self.context.main_thread.web_context;
  2252. let plugins = self.context.plugins.clone();
  2253. #[cfg(feature = "tracing")]
  2254. let active_tracing_spans = self.context.main_thread.active_tracing_spans.clone();
  2255. let proxy = self.event_loop.create_proxy();
  2256. self
  2257. .event_loop
  2258. .run_return(|event, event_loop, control_flow| {
  2259. *control_flow = ControlFlow::Wait;
  2260. if let Event::MainEventsCleared = &event {
  2261. *control_flow = ControlFlow::Exit;
  2262. }
  2263. for p in plugins.lock().unwrap().iter_mut() {
  2264. let prevent_default = p.on_event(
  2265. &event,
  2266. event_loop,
  2267. &proxy,
  2268. control_flow,
  2269. EventLoopIterationContext {
  2270. callback: &mut callback,
  2271. window_id_map: window_id_map.clone(),
  2272. windows: windows.clone(),
  2273. #[cfg(feature = "tracing")]
  2274. active_tracing_spans: active_tracing_spans.clone(),
  2275. },
  2276. web_context,
  2277. );
  2278. if prevent_default {
  2279. return;
  2280. }
  2281. }
  2282. handle_event_loop(
  2283. event,
  2284. event_loop,
  2285. control_flow,
  2286. EventLoopIterationContext {
  2287. callback: &mut callback,
  2288. windows: windows.clone(),
  2289. window_id_map: window_id_map.clone(),
  2290. #[cfg(feature = "tracing")]
  2291. active_tracing_spans: active_tracing_spans.clone(),
  2292. },
  2293. );
  2294. });
  2295. }
  2296. fn run<F: FnMut(RunEvent<T>) + 'static>(self, mut callback: F) {
  2297. let windows = self.context.main_thread.windows.clone();
  2298. let window_id_map = self.context.window_id_map.clone();
  2299. let web_context = self.context.main_thread.web_context;
  2300. let plugins = self.context.plugins.clone();
  2301. #[cfg(feature = "tracing")]
  2302. let active_tracing_spans = self.context.main_thread.active_tracing_spans.clone();
  2303. let proxy = self.event_loop.create_proxy();
  2304. self.event_loop.run(move |event, event_loop, control_flow| {
  2305. for p in plugins.lock().unwrap().iter_mut() {
  2306. let prevent_default = p.on_event(
  2307. &event,
  2308. event_loop,
  2309. &proxy,
  2310. control_flow,
  2311. EventLoopIterationContext {
  2312. callback: &mut callback,
  2313. window_id_map: window_id_map.clone(),
  2314. windows: windows.clone(),
  2315. #[cfg(feature = "tracing")]
  2316. active_tracing_spans: active_tracing_spans.clone(),
  2317. },
  2318. &web_context,
  2319. );
  2320. if prevent_default {
  2321. return;
  2322. }
  2323. }
  2324. handle_event_loop(
  2325. event,
  2326. event_loop,
  2327. control_flow,
  2328. EventLoopIterationContext {
  2329. callback: &mut callback,
  2330. window_id_map: window_id_map.clone(),
  2331. windows: windows.clone(),
  2332. #[cfg(feature = "tracing")]
  2333. active_tracing_spans: active_tracing_spans.clone(),
  2334. },
  2335. );
  2336. })
  2337. }
  2338. }
  2339. pub struct EventLoopIterationContext<'a, T: UserEvent> {
  2340. pub callback: &'a mut (dyn FnMut(RunEvent<T>) + 'static),
  2341. pub window_id_map: WindowIdStore,
  2342. pub windows: Arc<WindowsStore>,
  2343. #[cfg(feature = "tracing")]
  2344. pub active_tracing_spans: ActiveTraceSpanStore,
  2345. }
  2346. struct UserMessageContext {
  2347. windows: Arc<WindowsStore>,
  2348. window_id_map: WindowIdStore,
  2349. }
  2350. fn handle_user_message<T: UserEvent>(
  2351. event_loop: &EventLoopWindowTarget<Message<T>>,
  2352. message: Message<T>,
  2353. context: UserMessageContext,
  2354. ) {
  2355. let UserMessageContext {
  2356. window_id_map,
  2357. windows,
  2358. } = context;
  2359. match message {
  2360. Message::Task(task) => task(),
  2361. #[cfg(target_os = "macos")]
  2362. Message::SetActivationPolicy(activation_policy) => {
  2363. event_loop.set_activation_policy_at_runtime(tao_activation_policy(activation_policy))
  2364. }
  2365. Message::RequestExit(_code) => panic!("cannot handle RequestExit on the main thread"),
  2366. #[cfg(target_os = "macos")]
  2367. Message::Application(application_message) => match application_message {
  2368. ApplicationMessage::Show => {
  2369. event_loop.show_application();
  2370. }
  2371. ApplicationMessage::Hide => {
  2372. event_loop.hide_application();
  2373. }
  2374. },
  2375. Message::Window(id, window_message) => {
  2376. let w = windows.0.borrow().get(&id).map(|w| {
  2377. (
  2378. w.inner.clone(),
  2379. w.webviews.clone(),
  2380. w.has_children.load(Ordering::Relaxed),
  2381. w.window_event_listeners.clone(),
  2382. )
  2383. });
  2384. if let Some((Some(window), webviews, has_children, window_event_listeners)) = w {
  2385. match window_message {
  2386. WindowMessage::AddEventListener(id, listener) => {
  2387. window_event_listeners.lock().unwrap().insert(id, listener);
  2388. }
  2389. // Getters
  2390. WindowMessage::ScaleFactor(tx) => tx.send(window.scale_factor()).unwrap(),
  2391. WindowMessage::InnerPosition(tx) => tx
  2392. .send(
  2393. window
  2394. .inner_position()
  2395. .map(|p| PhysicalPositionWrapper(p).into())
  2396. .map_err(|_| Error::FailedToSendMessage),
  2397. )
  2398. .unwrap(),
  2399. WindowMessage::OuterPosition(tx) => tx
  2400. .send(
  2401. window
  2402. .outer_position()
  2403. .map(|p| PhysicalPositionWrapper(p).into())
  2404. .map_err(|_| Error::FailedToSendMessage),
  2405. )
  2406. .unwrap(),
  2407. WindowMessage::InnerSize(tx) => tx
  2408. .send(PhysicalSizeWrapper(inner_size(&window, &webviews, has_children)).into())
  2409. .unwrap(),
  2410. WindowMessage::OuterSize(tx) => tx
  2411. .send(PhysicalSizeWrapper(window.outer_size()).into())
  2412. .unwrap(),
  2413. WindowMessage::IsFullscreen(tx) => tx.send(window.fullscreen().is_some()).unwrap(),
  2414. WindowMessage::IsMinimized(tx) => tx.send(window.is_minimized()).unwrap(),
  2415. WindowMessage::IsMaximized(tx) => tx.send(window.is_maximized()).unwrap(),
  2416. WindowMessage::IsFocused(tx) => tx.send(window.is_focused()).unwrap(),
  2417. WindowMessage::IsDecorated(tx) => tx.send(window.is_decorated()).unwrap(),
  2418. WindowMessage::IsResizable(tx) => tx.send(window.is_resizable()).unwrap(),
  2419. WindowMessage::IsMaximizable(tx) => tx.send(window.is_maximizable()).unwrap(),
  2420. WindowMessage::IsMinimizable(tx) => tx.send(window.is_minimizable()).unwrap(),
  2421. WindowMessage::IsClosable(tx) => tx.send(window.is_closable()).unwrap(),
  2422. WindowMessage::IsVisible(tx) => tx.send(window.is_visible()).unwrap(),
  2423. WindowMessage::Title(tx) => tx.send(window.title()).unwrap(),
  2424. WindowMessage::CurrentMonitor(tx) => tx.send(window.current_monitor()).unwrap(),
  2425. WindowMessage::PrimaryMonitor(tx) => tx.send(window.primary_monitor()).unwrap(),
  2426. WindowMessage::MonitorFromPoint(tx, (x, y)) => {
  2427. tx.send(window.monitor_from_point(x, y)).unwrap()
  2428. }
  2429. WindowMessage::AvailableMonitors(tx) => {
  2430. tx.send(window.available_monitors().collect()).unwrap()
  2431. }
  2432. #[cfg(any(
  2433. target_os = "linux",
  2434. target_os = "dragonfly",
  2435. target_os = "freebsd",
  2436. target_os = "netbsd",
  2437. target_os = "openbsd"
  2438. ))]
  2439. WindowMessage::GtkWindow(tx) => tx.send(GtkWindow(window.gtk_window().clone())).unwrap(),
  2440. #[cfg(any(
  2441. target_os = "linux",
  2442. target_os = "dragonfly",
  2443. target_os = "freebsd",
  2444. target_os = "netbsd",
  2445. target_os = "openbsd"
  2446. ))]
  2447. WindowMessage::GtkBox(tx) => tx
  2448. .send(GtkBox(window.default_vbox().unwrap().clone()))
  2449. .unwrap(),
  2450. WindowMessage::RawWindowHandle(tx) => tx
  2451. .send(
  2452. window
  2453. .window_handle()
  2454. .map(|h| SendRawWindowHandle(h.as_raw())),
  2455. )
  2456. .unwrap(),
  2457. WindowMessage::Theme(tx) => {
  2458. tx.send(map_theme(&window.theme())).unwrap();
  2459. }
  2460. // Setters
  2461. WindowMessage::Center => {
  2462. #[cfg(not(target_os = "macos"))]
  2463. if let Some(monitor) = window.current_monitor() {
  2464. #[allow(unused_mut)]
  2465. let mut window_size = window.outer_size();
  2466. #[cfg(windows)]
  2467. if window.is_decorated() {
  2468. use windows::Win32::Foundation::RECT;
  2469. use windows::Win32::Graphics::Dwm::{
  2470. DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS,
  2471. };
  2472. let mut rect = RECT::default();
  2473. let result = unsafe {
  2474. DwmGetWindowAttribute(
  2475. HWND(window.hwnd() as _),
  2476. DWMWA_EXTENDED_FRAME_BOUNDS,
  2477. &mut rect as *mut _ as *mut _,
  2478. std::mem::size_of::<RECT>() as u32,
  2479. )
  2480. };
  2481. if result.is_ok() {
  2482. window_size.height = (rect.bottom - rect.top) as u32;
  2483. }
  2484. }
  2485. window.set_outer_position(calculate_window_center_position(window_size, monitor));
  2486. }
  2487. #[cfg(target_os = "macos")]
  2488. {
  2489. use cocoa::{appkit::NSWindow, base::id};
  2490. let ns_window: id = window.ns_window() as _;
  2491. unsafe { ns_window.center() };
  2492. }
  2493. }
  2494. WindowMessage::RequestUserAttention(request_type) => {
  2495. window.request_user_attention(request_type.map(|r| r.0));
  2496. }
  2497. WindowMessage::SetResizable(resizable) => {
  2498. window.set_resizable(resizable);
  2499. #[cfg(windows)]
  2500. if !resizable {
  2501. undecorated_resizing::detach_resize_handler(window.hwnd());
  2502. } else if !window.is_decorated() {
  2503. undecorated_resizing::attach_resize_handler(window.hwnd());
  2504. }
  2505. }
  2506. WindowMessage::SetMaximizable(maximizable) => window.set_maximizable(maximizable),
  2507. WindowMessage::SetMinimizable(minimizable) => window.set_minimizable(minimizable),
  2508. WindowMessage::SetClosable(closable) => window.set_closable(closable),
  2509. WindowMessage::SetTitle(title) => window.set_title(&title),
  2510. WindowMessage::Maximize => window.set_maximized(true),
  2511. WindowMessage::Unmaximize => window.set_maximized(false),
  2512. WindowMessage::Minimize => window.set_minimized(true),
  2513. WindowMessage::Unminimize => window.set_minimized(false),
  2514. WindowMessage::Show => window.set_visible(true),
  2515. WindowMessage::Hide => window.set_visible(false),
  2516. WindowMessage::Close => {
  2517. panic!("cannot handle `WindowMessage::Close` on the main thread")
  2518. }
  2519. WindowMessage::Destroy => {
  2520. panic!("cannot handle `WindowMessage::Destroy` on the main thread")
  2521. }
  2522. WindowMessage::SetDecorations(decorations) => {
  2523. window.set_decorations(decorations);
  2524. #[cfg(windows)]
  2525. if decorations {
  2526. undecorated_resizing::detach_resize_handler(window.hwnd());
  2527. } else if window.is_resizable() {
  2528. undecorated_resizing::attach_resize_handler(window.hwnd());
  2529. }
  2530. }
  2531. WindowMessage::SetShadow(_enable) => {
  2532. #[cfg(windows)]
  2533. window.set_undecorated_shadow(_enable);
  2534. #[cfg(target_os = "macos")]
  2535. window.set_has_shadow(_enable);
  2536. }
  2537. WindowMessage::SetAlwaysOnBottom(always_on_bottom) => {
  2538. window.set_always_on_bottom(always_on_bottom)
  2539. }
  2540. WindowMessage::SetAlwaysOnTop(always_on_top) => window.set_always_on_top(always_on_top),
  2541. WindowMessage::SetVisibleOnAllWorkspaces(visible_on_all_workspaces) => {
  2542. window.set_visible_on_all_workspaces(visible_on_all_workspaces)
  2543. }
  2544. WindowMessage::SetContentProtected(protected) => window.set_content_protection(protected),
  2545. WindowMessage::SetSize(size) => {
  2546. window.set_inner_size(SizeWrapper::from(size).0);
  2547. }
  2548. WindowMessage::SetMinSize(size) => {
  2549. window.set_min_inner_size(size.map(|s| SizeWrapper::from(s).0));
  2550. }
  2551. WindowMessage::SetMaxSize(size) => {
  2552. window.set_max_inner_size(size.map(|s| SizeWrapper::from(s).0));
  2553. }
  2554. WindowMessage::SetSizeConstraints(constraints) => {
  2555. window.set_inner_size_constraints(tao::window::WindowSizeConstraints {
  2556. min_width: constraints.min_width,
  2557. min_height: constraints.min_height,
  2558. max_width: constraints.max_width,
  2559. max_height: constraints.max_height,
  2560. });
  2561. }
  2562. WindowMessage::SetPosition(position) => {
  2563. window.set_outer_position(PositionWrapper::from(position).0)
  2564. }
  2565. WindowMessage::SetFullscreen(fullscreen) => {
  2566. if fullscreen {
  2567. window.set_fullscreen(Some(Fullscreen::Borderless(None)))
  2568. } else {
  2569. window.set_fullscreen(None)
  2570. }
  2571. }
  2572. WindowMessage::SetFocus => {
  2573. window.set_focus();
  2574. }
  2575. WindowMessage::SetIcon(icon) => {
  2576. window.set_window_icon(Some(icon));
  2577. }
  2578. #[allow(unused_variables)]
  2579. WindowMessage::SetSkipTaskbar(skip) => {
  2580. #[cfg(any(windows, target_os = "linux"))]
  2581. window.set_skip_taskbar(skip);
  2582. }
  2583. WindowMessage::SetCursorGrab(grab) => {
  2584. let _ = window.set_cursor_grab(grab);
  2585. }
  2586. WindowMessage::SetCursorVisible(visible) => {
  2587. window.set_cursor_visible(visible);
  2588. }
  2589. WindowMessage::SetCursorIcon(icon) => {
  2590. window.set_cursor_icon(CursorIconWrapper::from(icon).0);
  2591. }
  2592. WindowMessage::SetCursorPosition(position) => {
  2593. let _ = window.set_cursor_position(PositionWrapper::from(position).0);
  2594. }
  2595. WindowMessage::SetIgnoreCursorEvents(ignore) => {
  2596. let _ = window.set_ignore_cursor_events(ignore);
  2597. }
  2598. WindowMessage::DragWindow => {
  2599. let _ = window.drag_window();
  2600. }
  2601. WindowMessage::ResizeDragWindow(direction) => {
  2602. let _ = window.drag_resize_window(match direction {
  2603. tauri_runtime::ResizeDirection::East => tao::window::ResizeDirection::East,
  2604. tauri_runtime::ResizeDirection::North => tao::window::ResizeDirection::North,
  2605. tauri_runtime::ResizeDirection::NorthEast => tao::window::ResizeDirection::NorthEast,
  2606. tauri_runtime::ResizeDirection::NorthWest => tao::window::ResizeDirection::NorthWest,
  2607. tauri_runtime::ResizeDirection::South => tao::window::ResizeDirection::South,
  2608. tauri_runtime::ResizeDirection::SouthEast => tao::window::ResizeDirection::SouthEast,
  2609. tauri_runtime::ResizeDirection::SouthWest => tao::window::ResizeDirection::SouthWest,
  2610. tauri_runtime::ResizeDirection::West => tao::window::ResizeDirection::West,
  2611. });
  2612. }
  2613. WindowMessage::RequestRedraw => {
  2614. window.request_redraw();
  2615. }
  2616. WindowMessage::SetProgressBar(progress_state) => {
  2617. window.set_progress_bar(ProgressBarStateWrapper::from(progress_state).0);
  2618. }
  2619. WindowMessage::SetTitleBarStyle(_style) => {
  2620. #[cfg(target_os = "macos")]
  2621. match _style {
  2622. TitleBarStyle::Visible => {
  2623. window.set_titlebar_transparent(false);
  2624. window.set_fullsize_content_view(true);
  2625. }
  2626. TitleBarStyle::Transparent => {
  2627. window.set_titlebar_transparent(true);
  2628. window.set_fullsize_content_view(false);
  2629. }
  2630. TitleBarStyle::Overlay => {
  2631. window.set_titlebar_transparent(true);
  2632. window.set_fullsize_content_view(true);
  2633. }
  2634. unknown => {
  2635. #[cfg(feature = "tracing")]
  2636. tracing::warn!("unknown title bar style applied: {unknown}");
  2637. #[cfg(not(feature = "tracing"))]
  2638. eprintln!("unknown title bar style applied: {unknown}");
  2639. }
  2640. };
  2641. }
  2642. }
  2643. }
  2644. }
  2645. Message::Webview(window_id, webview_id, webview_message) => {
  2646. #[cfg(any(
  2647. target_os = "macos",
  2648. windows,
  2649. target_os = "linux",
  2650. target_os = "dragonfly",
  2651. target_os = "freebsd",
  2652. target_os = "netbsd",
  2653. target_os = "openbsd"
  2654. ))]
  2655. if let WebviewMessage::Reparent(new_parent_window_id, tx) = webview_message {
  2656. let webview_handle = windows.0.borrow_mut().get_mut(&window_id).and_then(|w| {
  2657. w.webviews
  2658. .iter()
  2659. .position(|w| w.id == webview_id)
  2660. .map(|webview_index| w.webviews.remove(webview_index))
  2661. });
  2662. if let Some(webview) = webview_handle {
  2663. if let Some((Some(new_parent_window), new_parent_window_webviews)) = windows
  2664. .0
  2665. .borrow_mut()
  2666. .get_mut(&new_parent_window_id)
  2667. .map(|w| (w.inner.clone(), &mut w.webviews))
  2668. {
  2669. #[cfg(target_os = "macos")]
  2670. let reparent_result = {
  2671. use wry::WebViewExtMacOS;
  2672. webview.inner.reparent(new_parent_window.ns_window() as _)
  2673. };
  2674. #[cfg(windows)]
  2675. let reparent_result = { webview.inner.reparent(new_parent_window.hwnd()) };
  2676. #[cfg(any(
  2677. target_os = "linux",
  2678. target_os = "dragonfly",
  2679. target_os = "freebsd",
  2680. target_os = "netbsd",
  2681. target_os = "openbsd"
  2682. ))]
  2683. let reparent_result = {
  2684. if let Some(container) = new_parent_window.default_vbox() {
  2685. webview.inner.reparent(container)
  2686. } else {
  2687. Err(wry::Error::MessageSender)
  2688. }
  2689. };
  2690. match reparent_result {
  2691. Ok(_) => {
  2692. new_parent_window_webviews.push(webview);
  2693. tx.send(Ok(())).unwrap();
  2694. }
  2695. Err(e) => {
  2696. log::error!("failed to reparent webview: {e}");
  2697. tx.send(Err(Error::FailedToSendMessage)).unwrap();
  2698. }
  2699. }
  2700. }
  2701. } else {
  2702. tx.send(Err(Error::FailedToSendMessage)).unwrap();
  2703. }
  2704. return;
  2705. }
  2706. let webview_handle = windows.0.borrow().get(&window_id).map(|w| {
  2707. (
  2708. w.inner.clone(),
  2709. w.webviews.iter().find(|w| w.id == webview_id).cloned(),
  2710. )
  2711. });
  2712. if let Some((Some(window), Some(webview))) = webview_handle {
  2713. match webview_message {
  2714. WebviewMessage::WebviewEvent(_) => { /* already handled */ }
  2715. WebviewMessage::SynthesizedWindowEvent(_) => { /* already handled */ }
  2716. WebviewMessage::Reparent(_window_id, _tx) => { /* already handled */ }
  2717. WebviewMessage::AddEventListener(id, listener) => {
  2718. webview
  2719. .webview_event_listeners
  2720. .lock()
  2721. .unwrap()
  2722. .insert(id, listener);
  2723. }
  2724. #[cfg(all(feature = "tracing", not(target_os = "android")))]
  2725. WebviewMessage::EvaluateScript(script, tx, span) => {
  2726. let _span = span.entered();
  2727. if let Err(e) = webview.evaluate_script(&script) {
  2728. log::error!("{}", e);
  2729. }
  2730. tx.send(()).unwrap();
  2731. }
  2732. #[cfg(not(all(feature = "tracing", not(target_os = "android"))))]
  2733. WebviewMessage::EvaluateScript(script) => {
  2734. if let Err(e) = webview.evaluate_script(&script) {
  2735. log::error!("{}", e);
  2736. }
  2737. }
  2738. WebviewMessage::Navigate(url) => {
  2739. if let Err(e) = webview.load_url(url.as_str()) {
  2740. log::error!("failed to navigate to url {}: {}", url, e);
  2741. }
  2742. }
  2743. WebviewMessage::Print => {
  2744. let _ = webview.print();
  2745. }
  2746. WebviewMessage::Close => {
  2747. windows.0.borrow_mut().get_mut(&window_id).map(|window| {
  2748. if let Some(i) = window.webviews.iter().position(|w| w.id == webview.id) {
  2749. window.webviews.remove(i);
  2750. }
  2751. window
  2752. });
  2753. }
  2754. WebviewMessage::SetBounds(bounds) => {
  2755. let bounds: RectWrapper = bounds.into();
  2756. let bounds = bounds.0;
  2757. if let Some(b) = &mut *webview.bounds.lock().unwrap() {
  2758. let scale_factor = window.scale_factor();
  2759. let size = bounds.size.to_logical::<f32>(scale_factor);
  2760. let position = bounds.position.to_logical::<f32>(scale_factor);
  2761. let window_size = window.inner_size().to_logical::<f32>(scale_factor);
  2762. b.width_rate = size.width / window_size.width;
  2763. b.height_rate = size.height / window_size.height;
  2764. b.x_rate = position.x / window_size.width;
  2765. b.y_rate = position.y / window_size.height;
  2766. }
  2767. if let Err(e) = webview.set_bounds(bounds) {
  2768. log::error!("failed to set webview size: {e}");
  2769. }
  2770. }
  2771. WebviewMessage::SetSize(size) => match webview.bounds() {
  2772. Ok(mut bounds) => {
  2773. bounds.size = size;
  2774. let scale_factor = window.scale_factor();
  2775. let size = size.to_logical::<f32>(scale_factor);
  2776. if let Some(b) = &mut *webview.bounds.lock().unwrap() {
  2777. let window_size = window.inner_size().to_logical::<f32>(scale_factor);
  2778. b.width_rate = size.width / window_size.width;
  2779. b.height_rate = size.height / window_size.height;
  2780. }
  2781. if let Err(e) = webview.set_bounds(bounds) {
  2782. log::error!("failed to set webview size: {e}");
  2783. }
  2784. }
  2785. Err(e) => {
  2786. log::error!("failed to get webview bounds: {e}");
  2787. }
  2788. },
  2789. WebviewMessage::SetPosition(position) => match webview.bounds() {
  2790. Ok(mut bounds) => {
  2791. bounds.position = position;
  2792. let scale_factor = window.scale_factor();
  2793. let position = position.to_logical::<f32>(scale_factor);
  2794. if let Some(b) = &mut *webview.bounds.lock().unwrap() {
  2795. let window_size = window.inner_size().to_logical::<f32>(scale_factor);
  2796. b.x_rate = position.x / window_size.width;
  2797. b.y_rate = position.y / window_size.height;
  2798. }
  2799. if let Err(e) = webview.set_bounds(bounds) {
  2800. log::error!("failed to set webview position: {e}");
  2801. }
  2802. }
  2803. Err(e) => {
  2804. log::error!("failed to get webview bounds: {e}");
  2805. }
  2806. },
  2807. WebviewMessage::SetZoom(scale_factor) => {
  2808. if let Err(e) = webview.zoom(scale_factor) {
  2809. log::error!("failed to set webview zoom: {e}");
  2810. }
  2811. }
  2812. // Getters
  2813. WebviewMessage::Url(tx) => {
  2814. tx.send(
  2815. webview
  2816. .url()
  2817. .map(|u| u.parse().expect("invalid webview URL"))
  2818. .map_err(|_| Error::FailedToSendMessage),
  2819. )
  2820. .unwrap();
  2821. }
  2822. WebviewMessage::Bounds(tx) => {
  2823. tx.send(
  2824. webview
  2825. .bounds()
  2826. .map(|bounds| tauri_runtime::Rect {
  2827. size: bounds.size,
  2828. position: bounds.position,
  2829. })
  2830. .map_err(|_| Error::FailedToSendMessage),
  2831. )
  2832. .unwrap();
  2833. }
  2834. WebviewMessage::Position(tx) => {
  2835. tx.send(
  2836. webview
  2837. .bounds()
  2838. .map(|bounds| bounds.position.to_physical(window.scale_factor()))
  2839. .map_err(|_| Error::FailedToSendMessage),
  2840. )
  2841. .unwrap();
  2842. }
  2843. WebviewMessage::Size(tx) => {
  2844. tx.send(
  2845. webview
  2846. .bounds()
  2847. .map(|bounds| bounds.size.to_physical(window.scale_factor()))
  2848. .map_err(|_| Error::FailedToSendMessage),
  2849. )
  2850. .unwrap();
  2851. }
  2852. WebviewMessage::SetFocus => {
  2853. if let Err(e) = webview.focus() {
  2854. log::error!("failed to focus webview: {e}");
  2855. }
  2856. }
  2857. WebviewMessage::SetAutoResize(auto_resize) => match webview.bounds() {
  2858. Ok(bounds) => {
  2859. let scale_factor = window.scale_factor();
  2860. let window_size = window.inner_size().to_logical::<f32>(scale_factor);
  2861. *webview.bounds.lock().unwrap() = if auto_resize {
  2862. let size = bounds.size.to_logical::<f32>(scale_factor);
  2863. let position = bounds.position.to_logical::<f32>(scale_factor);
  2864. Some(WebviewBounds {
  2865. x_rate: position.x / window_size.width,
  2866. y_rate: position.y / window_size.height,
  2867. width_rate: size.width / window_size.width,
  2868. height_rate: size.height / window_size.height,
  2869. })
  2870. } else {
  2871. None
  2872. };
  2873. }
  2874. Err(e) => {
  2875. log::error!("failed to get webview bounds: {e}");
  2876. }
  2877. },
  2878. WebviewMessage::WithWebview(f) => {
  2879. #[cfg(any(
  2880. target_os = "linux",
  2881. target_os = "dragonfly",
  2882. target_os = "freebsd",
  2883. target_os = "netbsd",
  2884. target_os = "openbsd"
  2885. ))]
  2886. {
  2887. f(webview.webview());
  2888. }
  2889. #[cfg(target_os = "macos")]
  2890. {
  2891. use wry::WebViewExtMacOS;
  2892. f(Webview {
  2893. webview: webview.webview(),
  2894. manager: webview.manager(),
  2895. ns_window: webview.ns_window(),
  2896. });
  2897. }
  2898. #[cfg(target_os = "ios")]
  2899. {
  2900. use tao::platform::ios::WindowExtIOS;
  2901. use wry::WebViewExtIOS;
  2902. f(Webview {
  2903. webview: webview.inner.webview(),
  2904. manager: webview.inner.manager(),
  2905. view_controller: window.ui_view_controller() as cocoa::base::id,
  2906. });
  2907. }
  2908. #[cfg(windows)]
  2909. {
  2910. f(Webview {
  2911. controller: webview.controller(),
  2912. });
  2913. }
  2914. #[cfg(target_os = "android")]
  2915. {
  2916. f(webview.handle())
  2917. }
  2918. }
  2919. #[cfg(any(debug_assertions, feature = "devtools"))]
  2920. WebviewMessage::OpenDevTools => {
  2921. webview.open_devtools();
  2922. }
  2923. #[cfg(any(debug_assertions, feature = "devtools"))]
  2924. WebviewMessage::CloseDevTools => {
  2925. webview.close_devtools();
  2926. }
  2927. #[cfg(any(debug_assertions, feature = "devtools"))]
  2928. WebviewMessage::IsDevToolsOpen(tx) => {
  2929. tx.send(webview.is_devtools_open()).unwrap();
  2930. }
  2931. }
  2932. }
  2933. }
  2934. Message::CreateWebview(window_id, handler) => {
  2935. let window = windows
  2936. .0
  2937. .borrow()
  2938. .get(&window_id)
  2939. .and_then(|w| w.inner.clone());
  2940. if let Some(window) = window {
  2941. match handler(&window) {
  2942. Ok(webview) => {
  2943. windows.0.borrow_mut().get_mut(&window_id).map(|w| {
  2944. w.webviews.push(webview);
  2945. w.has_children.store(true, Ordering::Relaxed);
  2946. w
  2947. });
  2948. }
  2949. Err(e) => {
  2950. log::error!("{}", e);
  2951. }
  2952. }
  2953. }
  2954. }
  2955. Message::CreateWindow(window_id, handler) => match handler(event_loop) {
  2956. Ok(webview) => {
  2957. windows.0.borrow_mut().insert(window_id, webview);
  2958. }
  2959. Err(e) => {
  2960. log::error!("{}", e);
  2961. }
  2962. },
  2963. Message::CreateRawWindow(window_id, handler, sender) => {
  2964. let (label, builder) = handler();
  2965. #[cfg(windows)]
  2966. let is_window_transparent = builder.window.transparent;
  2967. if let Ok(window) = builder.build(event_loop) {
  2968. window_id_map.insert(window.id(), window_id);
  2969. let window = Arc::new(window);
  2970. #[cfg(windows)]
  2971. let surface = if is_window_transparent {
  2972. if let Ok(context) = softbuffer::Context::new(window.clone()) {
  2973. if let Ok(mut surface) = softbuffer::Surface::new(&context, window.clone()) {
  2974. clear_window_surface(&window, &mut surface);
  2975. Some(surface)
  2976. } else {
  2977. None
  2978. }
  2979. } else {
  2980. None
  2981. }
  2982. } else {
  2983. None
  2984. };
  2985. windows.0.borrow_mut().insert(
  2986. window_id,
  2987. WindowWrapper {
  2988. label,
  2989. has_children: AtomicBool::new(false),
  2990. inner: Some(window.clone()),
  2991. window_event_listeners: Default::default(),
  2992. webviews: Vec::new(),
  2993. #[cfg(windows)]
  2994. is_window_transparent,
  2995. #[cfg(windows)]
  2996. surface,
  2997. },
  2998. );
  2999. sender.send(Ok(Arc::downgrade(&window))).unwrap();
  3000. } else {
  3001. sender.send(Err(Error::CreateWindow)).unwrap();
  3002. }
  3003. }
  3004. Message::UserEvent(_) => (),
  3005. }
  3006. }
  3007. fn handle_event_loop<T: UserEvent>(
  3008. event: Event<'_, Message<T>>,
  3009. event_loop: &EventLoopWindowTarget<Message<T>>,
  3010. control_flow: &mut ControlFlow,
  3011. context: EventLoopIterationContext<'_, T>,
  3012. ) {
  3013. let EventLoopIterationContext {
  3014. callback,
  3015. window_id_map,
  3016. windows,
  3017. #[cfg(feature = "tracing")]
  3018. active_tracing_spans,
  3019. } = context;
  3020. if *control_flow != ControlFlow::Exit {
  3021. *control_flow = ControlFlow::Wait;
  3022. }
  3023. match event {
  3024. Event::NewEvents(StartCause::Init) => {
  3025. callback(RunEvent::Ready);
  3026. }
  3027. Event::NewEvents(StartCause::Poll) => {
  3028. callback(RunEvent::Resumed);
  3029. }
  3030. Event::MainEventsCleared => {
  3031. callback(RunEvent::MainEventsCleared);
  3032. }
  3033. Event::LoopDestroyed => {
  3034. callback(RunEvent::Exit);
  3035. }
  3036. #[cfg(windows)]
  3037. Event::RedrawRequested(id) => {
  3038. if let Some(window_id) = window_id_map.get(&id) {
  3039. let mut windows_ref = windows.0.borrow_mut();
  3040. if let Some(window) = windows_ref.get_mut(&window_id) {
  3041. if window.is_window_transparent {
  3042. if let Some(surface) = &mut window.surface {
  3043. if let Some(window) = &window.inner {
  3044. clear_window_surface(window, surface)
  3045. }
  3046. }
  3047. }
  3048. }
  3049. }
  3050. }
  3051. #[cfg(feature = "tracing")]
  3052. Event::RedrawEventsCleared => {
  3053. active_tracing_spans.remove_window_draw();
  3054. }
  3055. Event::UserEvent(Message::Webview(
  3056. window_id,
  3057. webview_id,
  3058. WebviewMessage::WebviewEvent(event),
  3059. )) => {
  3060. let windows_ref = windows.0.borrow();
  3061. if let Some(window) = windows_ref.get(&window_id) {
  3062. if let Some(webview) = window.webviews.iter().find(|w| w.id == webview_id) {
  3063. let label = webview.label.clone();
  3064. let webview_event_listeners = webview.webview_event_listeners.clone();
  3065. drop(windows_ref);
  3066. callback(RunEvent::WebviewEvent {
  3067. label,
  3068. event: event.clone(),
  3069. });
  3070. let listeners = webview_event_listeners.lock().unwrap();
  3071. let handlers = listeners.values();
  3072. for handler in handlers {
  3073. handler(&event);
  3074. }
  3075. }
  3076. }
  3077. }
  3078. Event::UserEvent(Message::Webview(
  3079. window_id,
  3080. _webview_id,
  3081. WebviewMessage::SynthesizedWindowEvent(event),
  3082. )) => {
  3083. if let Some(event) = WindowEventWrapper::from(event).0 {
  3084. let windows_ref = windows.0.borrow();
  3085. let window = windows_ref.get(&window_id);
  3086. if let Some(window) = window {
  3087. let label = window.label.clone();
  3088. let window_event_listeners = window.window_event_listeners.clone();
  3089. drop(windows_ref);
  3090. callback(RunEvent::WindowEvent {
  3091. label,
  3092. event: event.clone(),
  3093. });
  3094. let listeners = window_event_listeners.lock().unwrap();
  3095. let handlers = listeners.values();
  3096. for handler in handlers {
  3097. handler(&event);
  3098. }
  3099. }
  3100. }
  3101. }
  3102. Event::WindowEvent {
  3103. event, window_id, ..
  3104. } => {
  3105. if let Some(window_id) = window_id_map.get(&window_id) {
  3106. {
  3107. let windows_ref = windows.0.borrow();
  3108. if let Some(window) = windows_ref.get(&window_id) {
  3109. if let Some(event) = WindowEventWrapper::parse(window, &event).0 {
  3110. let label = window.label.clone();
  3111. let window_event_listeners = window.window_event_listeners.clone();
  3112. drop(windows_ref);
  3113. callback(RunEvent::WindowEvent {
  3114. label,
  3115. event: event.clone(),
  3116. });
  3117. let listeners = window_event_listeners.lock().unwrap();
  3118. let handlers = listeners.values();
  3119. for handler in handlers {
  3120. handler(&event);
  3121. }
  3122. }
  3123. }
  3124. }
  3125. match event {
  3126. #[cfg(windows)]
  3127. TaoWindowEvent::ThemeChanged(theme) => {
  3128. if let Some(window) = windows.0.borrow().get(&window_id) {
  3129. for webview in &window.webviews {
  3130. let theme = match theme {
  3131. TaoTheme::Dark => wry::Theme::Dark,
  3132. TaoTheme::Light => wry::Theme::Light,
  3133. _ => wry::Theme::Light,
  3134. };
  3135. if let Err(e) = webview.set_theme(theme) {
  3136. log::error!("failed to set theme: {e}");
  3137. }
  3138. }
  3139. }
  3140. }
  3141. TaoWindowEvent::CloseRequested => {
  3142. on_close_requested(callback, window_id, windows);
  3143. }
  3144. TaoWindowEvent::Destroyed => {
  3145. let removed = windows.0.borrow_mut().remove(&window_id).is_some();
  3146. if removed {
  3147. let is_empty = windows.0.borrow().is_empty();
  3148. if is_empty {
  3149. let (tx, rx) = channel();
  3150. callback(RunEvent::ExitRequested { code: None, tx });
  3151. let recv = rx.try_recv();
  3152. let should_prevent = matches!(recv, Ok(ExitRequestedEventAction::Prevent));
  3153. if !should_prevent {
  3154. *control_flow = ControlFlow::Exit;
  3155. }
  3156. }
  3157. }
  3158. }
  3159. TaoWindowEvent::Resized(size) => {
  3160. if let Some((Some(window), webviews)) = windows
  3161. .0
  3162. .borrow()
  3163. .get(&window_id)
  3164. .map(|w| (w.inner.clone(), w.webviews.clone()))
  3165. {
  3166. let size = size.to_logical::<f32>(window.scale_factor());
  3167. for webview in webviews {
  3168. if let Some(b) = &*webview.bounds.lock().unwrap() {
  3169. if let Err(e) = webview.set_bounds(wry::Rect {
  3170. position: LogicalPosition::new(size.width * b.x_rate, size.height * b.y_rate)
  3171. .into(),
  3172. size: LogicalSize::new(size.width * b.width_rate, size.height * b.height_rate)
  3173. .into(),
  3174. }) {
  3175. log::error!("failed to autoresize webview: {e}");
  3176. }
  3177. }
  3178. }
  3179. }
  3180. }
  3181. _ => {}
  3182. }
  3183. }
  3184. }
  3185. Event::UserEvent(message) => match message {
  3186. Message::RequestExit(code) => {
  3187. let (tx, rx) = channel();
  3188. callback(RunEvent::ExitRequested {
  3189. code: Some(code),
  3190. tx,
  3191. });
  3192. let recv = rx.try_recv();
  3193. let should_prevent = matches!(recv, Ok(ExitRequestedEventAction::Prevent));
  3194. if !should_prevent {
  3195. *control_flow = ControlFlow::Exit;
  3196. }
  3197. }
  3198. Message::Window(id, WindowMessage::Close) => {
  3199. on_close_requested(callback, id, windows);
  3200. }
  3201. Message::Window(id, WindowMessage::Destroy) => {
  3202. on_window_close(id, windows);
  3203. }
  3204. Message::UserEvent(t) => callback(RunEvent::UserEvent(t)),
  3205. message => {
  3206. handle_user_message(
  3207. event_loop,
  3208. message,
  3209. UserMessageContext {
  3210. window_id_map,
  3211. windows,
  3212. },
  3213. );
  3214. }
  3215. },
  3216. #[cfg(any(target_os = "macos", target_os = "ios"))]
  3217. Event::Opened { urls } => {
  3218. callback(RunEvent::Opened { urls });
  3219. }
  3220. #[cfg(target_os = "macos")]
  3221. Event::Reopen {
  3222. has_visible_windows,
  3223. ..
  3224. } => callback(RunEvent::Reopen {
  3225. has_visible_windows,
  3226. }),
  3227. _ => (),
  3228. }
  3229. }
  3230. fn on_close_requested<'a, T: UserEvent>(
  3231. callback: &'a mut (dyn FnMut(RunEvent<T>) + 'static),
  3232. window_id: WindowId,
  3233. windows: Arc<WindowsStore>,
  3234. ) {
  3235. let (tx, rx) = channel();
  3236. let windows_ref = windows.0.borrow();
  3237. if let Some(w) = windows_ref.get(&window_id) {
  3238. let label = w.label.clone();
  3239. let window_event_listeners = w.window_event_listeners.clone();
  3240. drop(windows_ref);
  3241. let listeners = window_event_listeners.lock().unwrap();
  3242. let handlers = listeners.values();
  3243. for handler in handlers {
  3244. handler(&WindowEvent::CloseRequested {
  3245. signal_tx: tx.clone(),
  3246. });
  3247. }
  3248. callback(RunEvent::WindowEvent {
  3249. label,
  3250. event: WindowEvent::CloseRequested { signal_tx: tx },
  3251. });
  3252. if let Ok(true) = rx.try_recv() {
  3253. } else {
  3254. on_window_close(window_id, windows);
  3255. }
  3256. }
  3257. }
  3258. fn on_window_close(window_id: WindowId, windows: Arc<WindowsStore>) {
  3259. if let Some(window_wrapper) = windows.0.borrow_mut().get_mut(&window_id) {
  3260. window_wrapper.inner = None;
  3261. #[cfg(windows)]
  3262. window_wrapper.surface.take();
  3263. }
  3264. }
  3265. fn parse_proxy_url(url: &Url) -> Result<ProxyConfig> {
  3266. let host = url.host().map(|h| h.to_string()).unwrap_or_default();
  3267. let port = url.port().map(|p| p.to_string()).unwrap_or_default();
  3268. if url.scheme() == "http" {
  3269. let config = ProxyConfig::Http(ProxyEndpoint { host, port });
  3270. Ok(config)
  3271. } else if url.scheme() == "socks5" {
  3272. let config = ProxyConfig::Socks5(ProxyEndpoint { host, port });
  3273. Ok(config)
  3274. } else {
  3275. Err(Error::InvalidProxyUrl)
  3276. }
  3277. }
  3278. fn create_window<T: UserEvent, F: Fn(RawWindow) + Send + 'static>(
  3279. window_id: WindowId,
  3280. webview_id: u32,
  3281. event_loop: &EventLoopWindowTarget<Message<T>>,
  3282. context: &Context<T>,
  3283. pending: PendingWindow<T, Wry<T>>,
  3284. after_window_creation: Option<F>,
  3285. ) -> Result<WindowWrapper> {
  3286. #[allow(unused_mut)]
  3287. let PendingWindow {
  3288. mut window_builder,
  3289. label,
  3290. webview,
  3291. } = pending;
  3292. #[cfg(feature = "tracing")]
  3293. let _webview_create_span = tracing::debug_span!("wry::webview::create").entered();
  3294. #[cfg(feature = "tracing")]
  3295. let window_draw_span = tracing::debug_span!("wry::window::draw").entered();
  3296. #[cfg(feature = "tracing")]
  3297. let window_create_span =
  3298. tracing::debug_span!(parent: &window_draw_span, "wry::window::create").entered();
  3299. let window_event_listeners = WindowEventListeners::default();
  3300. #[cfg(windows)]
  3301. let is_window_transparent = window_builder.inner.window.transparent;
  3302. #[cfg(target_os = "macos")]
  3303. {
  3304. if window_builder.tabbing_identifier.is_none()
  3305. || window_builder.inner.window.transparent
  3306. || !window_builder.inner.window.decorations
  3307. {
  3308. window_builder.inner = window_builder.inner.with_automatic_window_tabbing(false);
  3309. }
  3310. }
  3311. #[cfg(desktop)]
  3312. if window_builder.center {
  3313. let monitor = if let Some(window_position) = &window_builder.inner.window.position {
  3314. event_loop.available_monitors().find(|m| {
  3315. let monitor_pos = m.position();
  3316. let monitor_size = m.size();
  3317. // type annotations required for 32bit targets.
  3318. let window_position: LogicalPosition<i32> = window_position.to_logical(m.scale_factor());
  3319. monitor_pos.x <= window_position.x
  3320. && window_position.x <= monitor_pos.x + monitor_size.width as i32
  3321. && monitor_pos.y <= window_position.y
  3322. && window_position.y <= monitor_pos.y + monitor_size.height as i32
  3323. })
  3324. } else {
  3325. event_loop.primary_monitor()
  3326. };
  3327. if let Some(monitor) = monitor {
  3328. let desired_size = window_builder
  3329. .inner
  3330. .window
  3331. .inner_size
  3332. .unwrap_or_else(|| TaoPhysicalSize::new(800, 600).into());
  3333. let scale_factor = monitor.scale_factor();
  3334. #[allow(unused_mut)]
  3335. let mut window_size = window_builder
  3336. .inner
  3337. .window
  3338. .inner_size_constraints
  3339. .clamp(desired_size, scale_factor)
  3340. .to_physical::<u32>(scale_factor);
  3341. #[cfg(windows)]
  3342. {
  3343. if window_builder.inner.window.decorations {
  3344. use windows::Win32::UI::WindowsAndMessaging::{AdjustWindowRect, WS_OVERLAPPEDWINDOW};
  3345. let mut rect = windows::Win32::Foundation::RECT::default();
  3346. let result = unsafe { AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false) };
  3347. if result.is_ok() {
  3348. window_size.width += (rect.right - rect.left) as u32;
  3349. // rect.bottom is made out of shadow, and we don't care about it
  3350. window_size.height += -rect.top as u32;
  3351. }
  3352. }
  3353. }
  3354. let position = calculate_window_center_position(window_size, monitor);
  3355. let logical_position = position.to_logical::<f64>(scale_factor);
  3356. window_builder = window_builder.position(logical_position.x, logical_position.y);
  3357. }
  3358. }
  3359. let window = window_builder.inner.build(event_loop).unwrap();
  3360. #[cfg(feature = "tracing")]
  3361. {
  3362. drop(window_create_span);
  3363. context
  3364. .main_thread
  3365. .active_tracing_spans
  3366. .0
  3367. .borrow_mut()
  3368. .push(ActiveTracingSpan::WindowDraw {
  3369. id: window.id(),
  3370. span: window_draw_span,
  3371. });
  3372. }
  3373. context.window_id_map.insert(window.id(), window_id);
  3374. if let Some(handler) = after_window_creation {
  3375. let raw = RawWindow {
  3376. #[cfg(windows)]
  3377. hwnd: window.hwnd(),
  3378. #[cfg(any(
  3379. target_os = "linux",
  3380. target_os = "dragonfly",
  3381. target_os = "freebsd",
  3382. target_os = "netbsd",
  3383. target_os = "openbsd"
  3384. ))]
  3385. gtk_window: window.gtk_window(),
  3386. #[cfg(any(
  3387. target_os = "linux",
  3388. target_os = "dragonfly",
  3389. target_os = "freebsd",
  3390. target_os = "netbsd",
  3391. target_os = "openbsd"
  3392. ))]
  3393. default_vbox: window.default_vbox(),
  3394. _marker: &std::marker::PhantomData,
  3395. };
  3396. handler(raw);
  3397. }
  3398. let mut webviews = Vec::new();
  3399. if let Some(webview) = webview {
  3400. webviews.push(create_webview(
  3401. #[cfg(feature = "unstable")]
  3402. WebviewKind::WindowChild,
  3403. #[cfg(not(feature = "unstable"))]
  3404. WebviewKind::WindowContent,
  3405. &window,
  3406. Arc::new(Mutex::new(window_id)),
  3407. webview_id,
  3408. context,
  3409. webview,
  3410. )?);
  3411. }
  3412. let window = Arc::new(window);
  3413. #[cfg(windows)]
  3414. let surface = if is_window_transparent {
  3415. if let Ok(context) = softbuffer::Context::new(window.clone()) {
  3416. if let Ok(mut surface) = softbuffer::Surface::new(&context, window.clone()) {
  3417. clear_window_surface(&window, &mut surface);
  3418. Some(surface)
  3419. } else {
  3420. None
  3421. }
  3422. } else {
  3423. None
  3424. }
  3425. } else {
  3426. None
  3427. };
  3428. Ok(WindowWrapper {
  3429. label,
  3430. has_children: AtomicBool::new(false),
  3431. inner: Some(window),
  3432. webviews,
  3433. window_event_listeners,
  3434. #[cfg(windows)]
  3435. is_window_transparent,
  3436. #[cfg(windows)]
  3437. surface,
  3438. })
  3439. }
  3440. /// the kind of the webview
  3441. #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
  3442. enum WebviewKind {
  3443. // webview is the entire window content
  3444. WindowContent,
  3445. // webview is a child of the window, which can contain other webviews too
  3446. WindowChild,
  3447. }
  3448. #[derive(Debug, Clone)]
  3449. struct WebviewBounds {
  3450. x_rate: f32,
  3451. y_rate: f32,
  3452. width_rate: f32,
  3453. height_rate: f32,
  3454. }
  3455. fn create_webview<T: UserEvent>(
  3456. kind: WebviewKind,
  3457. window: &Window,
  3458. window_id: Arc<Mutex<WindowId>>,
  3459. id: WebviewId,
  3460. context: &Context<T>,
  3461. pending: PendingWebview<T, Wry<T>>,
  3462. ) -> Result<WebviewWrapper> {
  3463. #[allow(unused_mut)]
  3464. let PendingWebview {
  3465. webview_attributes,
  3466. uri_scheme_protocols,
  3467. label,
  3468. ipc_handler,
  3469. url,
  3470. ..
  3471. } = pending;
  3472. let builder = match kind {
  3473. #[cfg(not(any(
  3474. target_os = "windows",
  3475. target_os = "macos",
  3476. target_os = "ios",
  3477. target_os = "android"
  3478. )))]
  3479. WebviewKind::WindowChild => {
  3480. // only way to account for menu bar height, and also works for multiwebviews :)
  3481. let vbox = window.default_vbox().unwrap();
  3482. WebViewBuilder::new_gtk(vbox)
  3483. }
  3484. #[cfg(any(
  3485. target_os = "windows",
  3486. target_os = "macos",
  3487. target_os = "ios",
  3488. target_os = "android"
  3489. ))]
  3490. WebviewKind::WindowChild => WebViewBuilder::new_as_child(&window),
  3491. WebviewKind::WindowContent => {
  3492. #[cfg(any(
  3493. target_os = "windows",
  3494. target_os = "macos",
  3495. target_os = "ios",
  3496. target_os = "android"
  3497. ))]
  3498. let builder = WebViewBuilder::new(&window);
  3499. #[cfg(not(any(
  3500. target_os = "windows",
  3501. target_os = "macos",
  3502. target_os = "ios",
  3503. target_os = "android"
  3504. )))]
  3505. let builder = {
  3506. let vbox = window.default_vbox().unwrap();
  3507. WebViewBuilder::new_gtk(vbox)
  3508. };
  3509. builder
  3510. }
  3511. };
  3512. let mut webview_builder = builder
  3513. .with_focused(window.is_focused())
  3514. .with_url(&url)
  3515. .with_transparent(webview_attributes.transparent)
  3516. .with_accept_first_mouse(webview_attributes.accept_first_mouse)
  3517. .with_hotkeys_zoom(webview_attributes.zoom_hotkeys_enabled);
  3518. if webview_attributes.drag_drop_handler_enabled {
  3519. let proxy = context.proxy.clone();
  3520. let window_id_ = window_id.clone();
  3521. webview_builder = webview_builder.with_drag_drop_handler(move |event| {
  3522. let event = match event {
  3523. WryDragDropEvent::Enter {
  3524. paths,
  3525. position: (x, y),
  3526. } => DragDropEvent::Enter {
  3527. paths,
  3528. position: PhysicalPosition::new(x as _, y as _),
  3529. },
  3530. WryDragDropEvent::Over { position: (x, y) } => DragDropEvent::Over {
  3531. position: PhysicalPosition::new(x as _, y as _),
  3532. },
  3533. WryDragDropEvent::Drop {
  3534. paths,
  3535. position: (x, y),
  3536. } => DragDropEvent::Drop {
  3537. paths,
  3538. position: PhysicalPosition::new(x as _, y as _),
  3539. },
  3540. WryDragDropEvent::Leave => DragDropEvent::Leave,
  3541. _ => unimplemented!(),
  3542. };
  3543. let message = if kind == WebviewKind::WindowContent {
  3544. WebviewMessage::SynthesizedWindowEvent(SynthesizedWindowEvent::DragDrop(event))
  3545. } else {
  3546. WebviewMessage::WebviewEvent(WebviewEvent::DragDrop(event))
  3547. };
  3548. let _ = proxy.send_event(Message::Webview(*window_id_.lock().unwrap(), id, message));
  3549. true
  3550. });
  3551. }
  3552. if let Some(navigation_handler) = pending.navigation_handler {
  3553. webview_builder = webview_builder.with_navigation_handler(move |url| {
  3554. url
  3555. .parse()
  3556. .map(|url| navigation_handler(&url))
  3557. .unwrap_or(true)
  3558. });
  3559. }
  3560. let webview_bounds = if let Some(bounds) = webview_attributes.bounds {
  3561. let bounds: RectWrapper = bounds.into();
  3562. let bounds = bounds.0;
  3563. let scale_factor = window.scale_factor();
  3564. let position = bounds.position.to_logical::<f32>(scale_factor);
  3565. let size = bounds.size.to_logical::<f32>(scale_factor);
  3566. webview_builder = webview_builder.with_bounds(bounds);
  3567. let window_size = window.inner_size().to_logical::<f32>(scale_factor);
  3568. if webview_attributes.auto_resize {
  3569. Some(WebviewBounds {
  3570. x_rate: position.x / window_size.width,
  3571. y_rate: position.y / window_size.height,
  3572. width_rate: size.width / window_size.width,
  3573. height_rate: size.height / window_size.height,
  3574. })
  3575. } else {
  3576. None
  3577. }
  3578. } else {
  3579. #[cfg(feature = "unstable")]
  3580. {
  3581. webview_builder = webview_builder.with_bounds(wry::Rect {
  3582. position: LogicalPosition::new(0, 0).into(),
  3583. size: window.inner_size().into(),
  3584. });
  3585. Some(WebviewBounds {
  3586. x_rate: 0.,
  3587. y_rate: 0.,
  3588. width_rate: 1.,
  3589. height_rate: 1.,
  3590. })
  3591. }
  3592. #[cfg(not(feature = "unstable"))]
  3593. None
  3594. };
  3595. if let Some(download_handler) = pending.download_handler {
  3596. let download_handler_ = download_handler.clone();
  3597. webview_builder = webview_builder.with_download_started_handler(move |url, path| {
  3598. if let Ok(url) = url.parse() {
  3599. download_handler_(DownloadEvent::Requested {
  3600. url,
  3601. destination: path,
  3602. })
  3603. } else {
  3604. false
  3605. }
  3606. });
  3607. webview_builder = webview_builder.with_download_completed_handler(move |url, path, success| {
  3608. if let Ok(url) = url.parse() {
  3609. download_handler(DownloadEvent::Finished { url, path, success });
  3610. }
  3611. });
  3612. }
  3613. if let Some(page_load_handler) = pending.on_page_load_handler {
  3614. webview_builder = webview_builder.with_on_page_load_handler(move |event, url| {
  3615. let _ = url.parse().map(|url| {
  3616. page_load_handler(
  3617. url,
  3618. match event {
  3619. wry::PageLoadEvent::Started => tauri_runtime::webview::PageLoadEvent::Started,
  3620. wry::PageLoadEvent::Finished => tauri_runtime::webview::PageLoadEvent::Finished,
  3621. },
  3622. )
  3623. });
  3624. });
  3625. }
  3626. if let Some(user_agent) = webview_attributes.user_agent {
  3627. webview_builder = webview_builder.with_user_agent(&user_agent);
  3628. }
  3629. if let Some(proxy_url) = webview_attributes.proxy_url {
  3630. let config = parse_proxy_url(&proxy_url)?;
  3631. webview_builder = webview_builder.with_proxy_config(config);
  3632. }
  3633. #[cfg(windows)]
  3634. {
  3635. if let Some(additional_browser_args) = webview_attributes.additional_browser_args {
  3636. webview_builder = webview_builder.with_additional_browser_args(&additional_browser_args);
  3637. }
  3638. webview_builder = webview_builder.with_theme(match window.theme() {
  3639. TaoTheme::Dark => wry::Theme::Dark,
  3640. TaoTheme::Light => wry::Theme::Light,
  3641. _ => wry::Theme::Light,
  3642. });
  3643. }
  3644. #[cfg(windows)]
  3645. {
  3646. webview_builder = webview_builder.with_https_scheme(false);
  3647. }
  3648. webview_builder = webview_builder.with_ipc_handler(create_ipc_handler(
  3649. kind,
  3650. window_id.clone(),
  3651. id,
  3652. context.clone(),
  3653. label.clone(),
  3654. ipc_handler,
  3655. ));
  3656. for (scheme, protocol) in uri_scheme_protocols {
  3657. webview_builder =
  3658. webview_builder.with_asynchronous_custom_protocol(scheme, move |request, responder| {
  3659. protocol(
  3660. request,
  3661. Box::new(move |response| responder.respond(response)),
  3662. )
  3663. });
  3664. }
  3665. for script in webview_attributes.initialization_scripts {
  3666. webview_builder = webview_builder.with_initialization_script(&script);
  3667. }
  3668. let mut web_context = context
  3669. .main_thread
  3670. .web_context
  3671. .lock()
  3672. .expect("poisoned WebContext store");
  3673. let is_first_context = web_context.is_empty();
  3674. let automation_enabled = std::env::var("TAURI_WEBVIEW_AUTOMATION").as_deref() == Ok("true");
  3675. let web_context_key = // force a unique WebContext when automation is false;
  3676. // the context must be stored on the HashMap because it must outlive the WebView on macOS
  3677. if automation_enabled {
  3678. webview_attributes.data_directory.clone()
  3679. } else {
  3680. // unique key
  3681. let key = context.next_webcontext_id().to_string().into();
  3682. Some(key)
  3683. };
  3684. let entry = web_context.entry(web_context_key.clone());
  3685. let web_context = match entry {
  3686. Occupied(occupied) => occupied.into_mut(),
  3687. Vacant(vacant) => {
  3688. let mut web_context = WebContext::new(webview_attributes.data_directory);
  3689. web_context.set_allows_automation(if automation_enabled {
  3690. is_first_context
  3691. } else {
  3692. false
  3693. });
  3694. vacant.insert(web_context)
  3695. }
  3696. };
  3697. if webview_attributes.clipboard {
  3698. webview_builder.attrs.clipboard = true;
  3699. }
  3700. if webview_attributes.incognito {
  3701. webview_builder.attrs.incognito = true;
  3702. }
  3703. #[cfg(any(debug_assertions, feature = "devtools"))]
  3704. {
  3705. webview_builder = webview_builder.with_devtools(true);
  3706. }
  3707. #[cfg(target_os = "android")]
  3708. {
  3709. if let Some(on_webview_created) = pending.on_webview_created {
  3710. webview_builder = webview_builder.on_webview_created(move |ctx| {
  3711. on_webview_created(tauri_runtime::webview::CreationContext {
  3712. env: ctx.env,
  3713. activity: ctx.activity,
  3714. webview: ctx.webview,
  3715. })
  3716. });
  3717. }
  3718. }
  3719. let webview = webview_builder
  3720. .with_web_context(web_context)
  3721. .build()
  3722. .map_err(|e| Error::CreateWebview(Box::new(e)))?;
  3723. if kind == WebviewKind::WindowContent {
  3724. #[cfg(any(
  3725. target_os = "linux",
  3726. target_os = "dragonfly",
  3727. target_os = "freebsd",
  3728. target_os = "netbsd",
  3729. target_os = "openbsd"
  3730. ))]
  3731. undecorated_resizing::attach_resize_handler(&webview);
  3732. #[cfg(windows)]
  3733. if window.is_resizable() && !window.is_decorated() {
  3734. undecorated_resizing::attach_resize_handler(window.hwnd());
  3735. }
  3736. }
  3737. #[cfg(windows)]
  3738. if kind == WebviewKind::WindowContent {
  3739. let controller = webview.controller();
  3740. let proxy = context.proxy.clone();
  3741. let proxy_ = proxy.clone();
  3742. let window_id_ = window_id.clone();
  3743. let mut token = EventRegistrationToken::default();
  3744. unsafe {
  3745. controller.add_GotFocus(
  3746. &FocusChangedEventHandler::create(Box::new(move |_, _| {
  3747. let _ = proxy.send_event(Message::Webview(
  3748. *window_id_.lock().unwrap(),
  3749. id,
  3750. WebviewMessage::SynthesizedWindowEvent(SynthesizedWindowEvent::Focused(true)),
  3751. ));
  3752. Ok(())
  3753. })),
  3754. &mut token,
  3755. )
  3756. }
  3757. .unwrap();
  3758. unsafe {
  3759. controller.add_LostFocus(
  3760. &FocusChangedEventHandler::create(Box::new(move |_, _| {
  3761. let _ = proxy_.send_event(Message::Webview(
  3762. *window_id.lock().unwrap(),
  3763. id,
  3764. WebviewMessage::SynthesizedWindowEvent(SynthesizedWindowEvent::Focused(false)),
  3765. ));
  3766. Ok(())
  3767. })),
  3768. &mut token,
  3769. )
  3770. }
  3771. .unwrap();
  3772. }
  3773. Ok(WebviewWrapper {
  3774. label,
  3775. id,
  3776. inner: Rc::new(webview),
  3777. context_store: context.main_thread.web_context.clone(),
  3778. webview_event_listeners: Default::default(),
  3779. context_key: if automation_enabled {
  3780. None
  3781. } else {
  3782. web_context_key
  3783. },
  3784. bounds: Arc::new(Mutex::new(webview_bounds)),
  3785. })
  3786. }
  3787. /// Create a wry ipc handler from a tauri ipc handler.
  3788. fn create_ipc_handler<T: UserEvent>(
  3789. _kind: WebviewKind,
  3790. window_id: Arc<Mutex<WindowId>>,
  3791. webview_id: WebviewId,
  3792. context: Context<T>,
  3793. label: String,
  3794. ipc_handler: Option<WebviewIpcHandler<T, Wry<T>>>,
  3795. ) -> Box<IpcHandler> {
  3796. Box::new(move |request| {
  3797. if let Some(handler) = &ipc_handler {
  3798. handler(
  3799. DetachedWebview {
  3800. label: label.clone(),
  3801. dispatcher: WryWebviewDispatcher {
  3802. window_id: window_id.clone(),
  3803. webview_id,
  3804. context: context.clone(),
  3805. },
  3806. },
  3807. request,
  3808. );
  3809. }
  3810. })
  3811. }
  3812. #[cfg(target_os = "macos")]
  3813. fn inner_size(
  3814. window: &Window,
  3815. webviews: &[WebviewWrapper],
  3816. has_children: bool,
  3817. ) -> TaoPhysicalSize<u32> {
  3818. if !has_children && !webviews.is_empty() {
  3819. use wry::WebViewExtMacOS;
  3820. let webview = webviews.first().unwrap();
  3821. let view_frame = unsafe { cocoa::appkit::NSView::frame(webview.webview()) };
  3822. let logical: TaoLogicalSize<f64> = (view_frame.size.width, view_frame.size.height).into();
  3823. return logical.to_physical(window.scale_factor());
  3824. }
  3825. window.inner_size()
  3826. }
  3827. #[cfg(not(target_os = "macos"))]
  3828. #[allow(unused_variables)]
  3829. fn inner_size(
  3830. window: &Window,
  3831. webviews: &[WebviewWrapper],
  3832. has_children: bool,
  3833. ) -> TaoPhysicalSize<u32> {
  3834. window.inner_size()
  3835. }
  3836. fn calculate_window_center_position(
  3837. window_size: TaoPhysicalSize<u32>,
  3838. target_monitor: MonitorHandle,
  3839. ) -> TaoPhysicalPosition<i32> {
  3840. #[cfg(windows)]
  3841. {
  3842. use tao::platform::windows::MonitorHandleExtWindows;
  3843. use windows::Win32::Graphics::Gdi::{GetMonitorInfoW, HMONITOR, MONITORINFO};
  3844. let mut monitor_info = MONITORINFO {
  3845. cbSize: std::mem::size_of::<MONITORINFO>() as u32,
  3846. ..Default::default()
  3847. };
  3848. let status =
  3849. unsafe { GetMonitorInfoW(HMONITOR(target_monitor.hmonitor() as _), &mut monitor_info) };
  3850. if status.into() {
  3851. let available_width = monitor_info.rcWork.right - monitor_info.rcWork.left;
  3852. let available_height = monitor_info.rcWork.bottom - monitor_info.rcWork.top;
  3853. let x = (available_width - window_size.width as i32) / 2 + monitor_info.rcWork.left;
  3854. let y = (available_height - window_size.height as i32) / 2 + monitor_info.rcWork.top;
  3855. return TaoPhysicalPosition::new(x, y);
  3856. }
  3857. }
  3858. let screen_size = target_monitor.size();
  3859. let monitor_pos = target_monitor.position();
  3860. let x = (screen_size.width as i32 - window_size.width as i32) / 2 + monitor_pos.x;
  3861. let y = (screen_size.height as i32 - window_size.height as i32) / 2 + monitor_pos.y;
  3862. TaoPhysicalPosition::new(x, y)
  3863. }
  3864. #[cfg(windows)]
  3865. fn clear_window_surface(
  3866. window: &Window,
  3867. surface: &mut softbuffer::Surface<Arc<Window>, Arc<Window>>,
  3868. ) {
  3869. let size = window.inner_size();
  3870. if let (Some(width), Some(height)) = (
  3871. std::num::NonZeroU32::new(size.width),
  3872. std::num::NonZeroU32::new(size.height),
  3873. ) {
  3874. surface.resize(width, height).unwrap();
  3875. let mut buffer = surface.buffer_mut().unwrap();
  3876. buffer.fill(0);
  3877. let _ = buffer.present();
  3878. }
  3879. }