lib.rs 122 KB

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