lib.rs 129 KB

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