diff --git a/.changes/emit-raw-api.md b/.changes/emit-raw-api.md new file mode 100644 index 000000000000..2220ae78cd71 --- /dev/null +++ b/.changes/emit-raw-api.md @@ -0,0 +1,5 @@ +--- +"@tauri-apps/api": minor:feat +--- + +Optimize raw Uint8Array/ArrayBuffer/number[] payloads on the event system via the emit2 and emitTo2 functions. diff --git a/.changes/event-emit-raw.md b/.changes/event-emit-raw.md new file mode 100644 index 000000000000..f980793bea8e --- /dev/null +++ b/.changes/event-emit-raw.md @@ -0,0 +1,5 @@ +--- +"tauri": minor:feat +--- + +Allow sending raw binary payloads using the event system through `Emitter::emit_raw` and `Emitter::emit_raw_to`. diff --git a/.changes/listen-raw-binary-payload.md b/.changes/listen-raw-binary-payload.md new file mode 100644 index 000000000000..6704d73e92f7 --- /dev/null +++ b/.changes/listen-raw-binary-payload.md @@ -0,0 +1,5 @@ +--- +"tauri": minor:feat +--- + +Allow reading raw binary payloads using the event system through [`Event::payload_raw`]. diff --git a/crates/tauri/scripts/bundle.global.js b/crates/tauri/scripts/bundle.global.js index 870ac2ec68eb..0853fd3af51e 100644 --- a/crates/tauri/scripts/bundle.global.js +++ b/crates/tauri/scripts/bundle.global.js @@ -1 +1 @@ -var __TAURI_IIFE__=function(e){"use strict";function n(e,n,t,i){if("a"===t&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof n?e!==n||!i:!n.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===t?i:"a"===t?i.call(e):i?i.value:n.get(e)}function t(e,n,t,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof n?e!==n||!r:!n.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,t):r?r.value=t:n.set(e,t),t}var i,r,s,a,l;"function"==typeof SuppressedError&&SuppressedError;const o="__TAURI_TO_IPC_KEY__";function u(e,n=!1){return window.__TAURI_INTERNALS__.transformCallback(e,n)}class c{constructor(e){i.set(this,void 0),r.set(this,0),s.set(this,[]),a.set(this,void 0),t(this,i,e||(()=>{}),"f"),this.id=u(e=>{const l=e.index;if("end"in e)return void(l==n(this,r,"f")?this.cleanupCallback():t(this,a,l,"f"));const o=e.message;if(l==n(this,r,"f")){for(n(this,i,"f").call(this,o),t(this,r,n(this,r,"f")+1,"f");n(this,r,"f")in n(this,s,"f");){const e=n(this,s,"f")[n(this,r,"f")];n(this,i,"f").call(this,e),delete n(this,s,"f")[n(this,r,"f")],t(this,r,n(this,r,"f")+1,"f")}n(this,r,"f")===n(this,a,"f")&&this.cleanupCallback()}else n(this,s,"f")[l]=o})}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(e){t(this,i,e,"f")}get onmessage(){return n(this,i,"f")}[(i=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[o]()}}class d{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return p(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}}async function p(e,n={},t){return window.__TAURI_INTERNALS__.invoke(e,n,t)}class h{get rid(){return n(this,l,"f")}constructor(e){l.set(this,void 0),t(this,l,e,"f")}async close(){return p("plugin:resources|close",{rid:this.rid})}}l=new WeakMap;var w=Object.freeze({__proto__:null,Channel:c,PluginListener:d,Resource:h,SERIALIZE_TO_IPC_FN:o,addPluginListener:async function(e,n,t){const i=new c(t);try{return p(`plugin:${e}|register_listener`,{event:n,handler:i}).then(()=>new d(e,n,i.id))}catch{return p(`plugin:${e}|registerListener`,{event:n,handler:i}).then(()=>new d(e,n,i.id))}},checkPermissions:async function(e){return p(`plugin:${e}|check_permissions`)},convertFileSrc:function(e,n="asset"){return window.__TAURI_INTERNALS__.convertFileSrc(e,n)},invoke:p,isTauri:function(){return!!(globalThis||window).isTauri},requestPermissions:async function(e){return p(`plugin:${e}|request_permissions`)},transformCallback:u});class _ extends h{constructor(e){super(e)}static async new(e,n,t){return p("plugin:image|new",{rgba:y(e),width:n,height:t}).then(e=>new _(e))}static async fromBytes(e){return p("plugin:image|from_bytes",{bytes:y(e)}).then(e=>new _(e))}static async fromPath(e){return p("plugin:image|from_path",{path:e}).then(e=>new _(e))}async rgba(){return p("plugin:image|rgba",{rid:this.rid}).then(e=>new Uint8Array(e))}async size(){return p("plugin:image|size",{rid:this.rid})}}function y(e){return null==e?null:"string"==typeof e?e:e instanceof _?e.rid:e}var g,b=Object.freeze({__proto__:null,Image:_,transformImage:y});!function(e){e.Nsis="nsis",e.Msi="msi",e.Deb="deb",e.Rpm="rpm",e.AppImage="appimage",e.App="app"}(g||(g={}));var m=Object.freeze({__proto__:null,get BundleType(){return g},defaultWindowIcon:async function(){return p("plugin:app|default_window_icon").then(e=>e?new _(e):null)},fetchDataStoreIdentifiers:async function(){return p("plugin:app|fetch_data_store_identifiers")},getBundleType:async function(){return p("plugin:app|bundle_type")},getIdentifier:async function(){return p("plugin:app|identifier")},getName:async function(){return p("plugin:app|name")},getTauriVersion:async function(){return p("plugin:app|tauri_version")},getVersion:async function(){return p("plugin:app|version")},hide:async function(){return p("plugin:app|app_hide")},removeDataStore:async function(e){return p("plugin:app|remove_data_store",{uuid:e})},setDockVisibility:async function(e){return p("plugin:app|set_dock_visibility",{visible:e})},setTheme:async function(e){return p("plugin:app|set_app_theme",{theme:e})},show:async function(){return p("plugin:app|app_show")}});class f{constructor(...e){this.type="Logical",1===e.length?"Logical"in e[0]?(this.width=e[0].Logical.width,this.height=e[0].Logical.height):(this.width=e[0].width,this.height=e[0].height):(this.width=e[0],this.height=e[1])}toPhysical(e){return new v(this.width*e,this.height*e)}[o](){return{width:this.width,height:this.height}}toJSON(){return this[o]()}}class v{constructor(...e){this.type="Physical",1===e.length?"Physical"in e[0]?(this.width=e[0].Physical.width,this.height=e[0].Physical.height):(this.width=e[0].width,this.height=e[0].height):(this.width=e[0],this.height=e[1])}toLogical(e){return new f(this.width/e,this.height/e)}[o](){return{width:this.width,height:this.height}}toJSON(){return this[o]()}}class k{constructor(e){this.size=e}toLogical(e){return this.size instanceof f?this.size:this.size.toLogical(e)}toPhysical(e){return this.size instanceof v?this.size:this.size.toPhysical(e)}[o](){return{[`${this.size.type}`]:{width:this.size.width,height:this.size.height}}}toJSON(){return this[o]()}}class A{constructor(...e){this.type="Logical",1===e.length?"Logical"in e[0]?(this.x=e[0].Logical.x,this.y=e[0].Logical.y):(this.x=e[0].x,this.y=e[0].y):(this.x=e[0],this.y=e[1])}toPhysical(e){return new T(this.x*e,this.y*e)}[o](){return{x:this.x,y:this.y}}toJSON(){return this[o]()}}class T{constructor(...e){this.type="Physical",1===e.length?"Physical"in e[0]?(this.x=e[0].Physical.x,this.y=e[0].Physical.y):(this.x=e[0].x,this.y=e[0].y):(this.x=e[0],this.y=e[1])}toLogical(e){return new A(this.x/e,this.y/e)}[o](){return{x:this.x,y:this.y}}toJSON(){return this[o]()}}class I{constructor(e){this.position=e}toLogical(e){return this.position instanceof A?this.position:this.position.toLogical(e)}toPhysical(e){return this.position instanceof T?this.position:this.position.toPhysical(e)}[o](){return{[`${this.position.type}`]:{x:this.position.x,y:this.position.y}}}toJSON(){return this[o]()}}var E,R=Object.freeze({__proto__:null,LogicalPosition:A,LogicalSize:f,PhysicalPosition:T,PhysicalSize:v,Position:I,Size:k});async function D(e,n){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,n),await p("plugin:event|unlisten",{event:e,eventId:n})}async function S(e,n,t){var i;const r="string"==typeof(null==t?void 0:t.target)?{kind:"AnyLabel",label:t.target}:null!==(i=null==t?void 0:t.target)&&void 0!==i?i:{kind:"Any"};return p("plugin:event|listen",{event:e,target:r,handler:u(n)}).then(n=>async()=>D(e,n))}async function N(e,n,t){return S(e,t=>{D(e,t.id),n(t)},t)}async function L(e,n){await p("plugin:event|emit",{event:e,payload:n})}async function C(e,n,t){const i="string"==typeof e?{kind:"AnyLabel",label:e}:e;await p("plugin:event|emit_to",{target:i,event:n,payload:t})}!function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"}(E||(E={}));var x,P,z,W=Object.freeze({__proto__:null,get TauriEvent(){return E},emit:L,emitTo:C,listen:S,once:N});function O(e){var n;if("items"in e)e.items=null===(n=e.items)||void 0===n?void 0:n.map(e=>"rid"in e?e:O(e));else if("action"in e&&e.action){const n=new c;return n.onmessage=e.action,delete e.action,{...e,handler:n}}return e}async function U(e,n){const t=new c;if(n&&"object"==typeof n&&("action"in n&&n.action&&(t.onmessage=n.action,delete n.action),"item"in n&&n.item&&"object"==typeof n.item&&"About"in n.item&&n.item.About&&"object"==typeof n.item.About&&"icon"in n.item.About&&n.item.About.icon&&(n.item.About.icon=y(n.item.About.icon)),"icon"in n&&n.icon&&(n.icon=y(n.icon)),"items"in n&&n.items)){function i(e){var n;return"rid"in e?[e.rid,e.kind]:("item"in e&&"object"==typeof e.item&&(null===(n=e.item.About)||void 0===n?void 0:n.icon)&&(e.item.About.icon=y(e.item.About.icon)),"icon"in e&&e.icon&&(e.icon=y(e.icon)),"items"in e&&e.items&&(e.items=e.items.map(i)),O(e))}n.items=n.items.map(i)}return p("plugin:menu|new",{kind:e,options:n,handler:t})}class F extends h{get id(){return n(this,x,"f")}get kind(){return n(this,P,"f")}constructor(e,n,i){super(e),x.set(this,void 0),P.set(this,void 0),t(this,x,n,"f"),t(this,P,i,"f")}}x=new WeakMap,P=new WeakMap;class M extends F{constructor(e,n){super(e,n,"MenuItem")}static async new(e){return U("MenuItem",e).then(([e,n])=>new M(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async setAccelerator(e){return p("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:e})}}class B extends F{constructor(e,n){super(e,n,"Check")}static async new(e){return U("Check",e).then(([e,n])=>new B(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async setAccelerator(e){return p("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:e})}async isChecked(){return p("plugin:menu|is_checked",{rid:this.rid})}async setChecked(e){return p("plugin:menu|set_checked",{rid:this.rid,checked:e})}}!function(e){e.Add="Add",e.Advanced="Advanced",e.Bluetooth="Bluetooth",e.Bookmarks="Bookmarks",e.Caution="Caution",e.ColorPanel="ColorPanel",e.ColumnView="ColumnView",e.Computer="Computer",e.EnterFullScreen="EnterFullScreen",e.Everyone="Everyone",e.ExitFullScreen="ExitFullScreen",e.FlowView="FlowView",e.Folder="Folder",e.FolderBurnable="FolderBurnable",e.FolderSmart="FolderSmart",e.FollowLinkFreestanding="FollowLinkFreestanding",e.FontPanel="FontPanel",e.GoLeft="GoLeft",e.GoRight="GoRight",e.Home="Home",e.IChatTheater="IChatTheater",e.IconView="IconView",e.Info="Info",e.InvalidDataFreestanding="InvalidDataFreestanding",e.LeftFacingTriangle="LeftFacingTriangle",e.ListView="ListView",e.LockLocked="LockLocked",e.LockUnlocked="LockUnlocked",e.MenuMixedState="MenuMixedState",e.MenuOnState="MenuOnState",e.MobileMe="MobileMe",e.MultipleDocuments="MultipleDocuments",e.Network="Network",e.Path="Path",e.PreferencesGeneral="PreferencesGeneral",e.QuickLook="QuickLook",e.RefreshFreestanding="RefreshFreestanding",e.Refresh="Refresh",e.Remove="Remove",e.RevealFreestanding="RevealFreestanding",e.RightFacingTriangle="RightFacingTriangle",e.Share="Share",e.Slideshow="Slideshow",e.SmartBadge="SmartBadge",e.StatusAvailable="StatusAvailable",e.StatusNone="StatusNone",e.StatusPartiallyAvailable="StatusPartiallyAvailable",e.StatusUnavailable="StatusUnavailable",e.StopProgressFreestanding="StopProgressFreestanding",e.StopProgress="StopProgress",e.TrashEmpty="TrashEmpty",e.TrashFull="TrashFull",e.User="User",e.UserAccounts="UserAccounts",e.UserGroup="UserGroup",e.UserGuest="UserGuest"}(z||(z={}));class V extends F{constructor(e,n){super(e,n,"Icon")}static async new(e){return U("Icon",e).then(([e,n])=>new V(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async setAccelerator(e){return p("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:e})}async setIcon(e){return p("plugin:menu|set_icon",{rid:this.rid,kind:this.kind,icon:y(e)})}}class G extends F{constructor(e,n){super(e,n,"Predefined")}static async new(e){return U("Predefined",e).then(([e,n])=>new G(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}}function j([e,n,t]){switch(t){case"Submenu":return new H(e,n);case"Predefined":return new G(e,n);case"Check":return new B(e,n);case"Icon":return new V(e,n);default:return new M(e,n)}}class H extends F{constructor(e,n){super(e,n,"Submenu")}static async new(e){return U("Submenu",e).then(([e,n])=>new H(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async append(e){return p("plugin:menu|append",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async prepend(e){return p("plugin:menu|prepend",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async insert(e,n){return p("plugin:menu|insert",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e),position:n})}async remove(e){return p("plugin:menu|remove",{rid:this.rid,kind:this.kind,item:[e.rid,e.kind]})}async removeAt(e){return p("plugin:menu|remove_at",{rid:this.rid,kind:this.kind,position:e}).then(j)}async items(){return p("plugin:menu|items",{rid:this.rid,kind:this.kind}).then(e=>e.map(j))}async get(e){return p("plugin:menu|get",{rid:this.rid,kind:this.kind,id:e}).then(e=>e?j(e):null)}async popup(e,n){var t;return p("plugin:menu|popup",{rid:this.rid,kind:this.kind,window:null!==(t=null==n?void 0:n.label)&&void 0!==t?t:null,at:e instanceof I?e:e?new I(e):null})}async setAsWindowsMenuForNSApp(){return p("plugin:menu|set_as_windows_menu_for_nsapp",{rid:this.rid})}async setAsHelpMenuForNSApp(){return p("plugin:menu|set_as_help_menu_for_nsapp",{rid:this.rid})}async setIcon(e){return p("plugin:menu|set_icon",{rid:this.rid,kind:this.kind,icon:y(e)})}}class $ extends F{constructor(e,n){super(e,n,"Menu")}static async new(e){return U("Menu",e).then(([e,n])=>new $(e,n))}static async default(){return p("plugin:menu|create_default").then(([e,n])=>new $(e,n))}async append(e){return p("plugin:menu|append",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async prepend(e){return p("plugin:menu|prepend",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async insert(e,n){return p("plugin:menu|insert",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e),position:n})}async remove(e){return p("plugin:menu|remove",{rid:this.rid,kind:this.kind,item:[e.rid,e.kind]})}async removeAt(e){return p("plugin:menu|remove_at",{rid:this.rid,kind:this.kind,position:e}).then(j)}async items(){return p("plugin:menu|items",{rid:this.rid,kind:this.kind}).then(e=>e.map(j))}async get(e){return p("plugin:menu|get",{rid:this.rid,kind:this.kind,id:e}).then(e=>e?j(e):null)}async popup(e,n){var t;return p("plugin:menu|popup",{rid:this.rid,kind:this.kind,window:null!==(t=null==n?void 0:n.label)&&void 0!==t?t:null,at:e instanceof I?e:e?new I(e):null})}async setAsAppMenu(){return p("plugin:menu|set_as_app_menu",{rid:this.rid}).then(e=>e?new $(e[0],e[1]):null)}async setAsWindowMenu(e){var n;return p("plugin:menu|set_as_window_menu",{rid:this.rid,window:null!==(n=null==e?void 0:e.label)&&void 0!==n?n:null}).then(e=>e?new $(e[0],e[1]):null)}}var q=Object.freeze({__proto__:null,CheckMenuItem:B,IconMenuItem:V,Menu:$,MenuItem:M,get NativeIcon(){return z},PredefinedMenuItem:G,Submenu:H,itemFromKind:j});function J(){var e,n;window.__TAURI_INTERNALS__=null!==(e=window.__TAURI_INTERNALS__)&&void 0!==e?e:{},window.__TAURI_EVENT_PLUGIN_INTERNALS__=null!==(n=window.__TAURI_EVENT_PLUGIN_INTERNALS__)&&void 0!==n?n:{}}var Q,Z=Object.freeze({__proto__:null,clearMocks:function(){"object"==typeof window.__TAURI_INTERNALS__&&(delete window.__TAURI_INTERNALS__.invoke,delete window.__TAURI_INTERNALS__.transformCallback,delete window.__TAURI_INTERNALS__.unregisterCallback,delete window.__TAURI_INTERNALS__.runCallback,delete window.__TAURI_INTERNALS__.callbacks,delete window.__TAURI_INTERNALS__.convertFileSrc,delete window.__TAURI_INTERNALS__.metadata,"object"==typeof window.__TAURI_EVENT_PLUGIN_INTERNALS__&&delete window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener)},mockConvertFileSrc:function(e){J(),window.__TAURI_INTERNALS__.convertFileSrc=function(n,t="asset"){const i=encodeURIComponent(n);return"windows"===e?`http://${t}.localhost/${i}`:`${t}://localhost/${i}`}},mockIPC:function(e,n){function t(e,n){switch(e){case"plugin:event|listen":return function(e){i.has(e.event)||i.set(e.event,[]);return i.get(e.event).push(e.handler),e.handler}(n);case"plugin:event|emit":return function(e){const n=i.get(e.event)||[];for(const t of n)a(t,e);return null}(n);case"plugin:event|unlisten":return function(e){const n=i.get(e.event);if(n){const t=n.indexOf(e.id);-1!==t&&n.splice(t,1)}}(n)}}J();const i=new Map,r=new Map;function s(e){r.delete(e)}function a(e,n){const t=r.get(e);t?t(n):console.warn(`[TAURI] Couldn't find callback id ${e}. This might happen when the app is reloaded while Rust is running an asynchronous operation.`)}window.__TAURI_INTERNALS__.invoke=async function(i,r,s){return(null==n?void 0:n.shouldMockEvents)&&function(e){return e.startsWith("plugin:event|")}(i)?t(i,r):e(i,r)},window.__TAURI_INTERNALS__.transformCallback=function(e,n=!1){const t=window.crypto.getRandomValues(new Uint32Array(1))[0];return r.set(t,i=>(n&&s(t),e&&e(i))),t},window.__TAURI_INTERNALS__.unregisterCallback=s,window.__TAURI_INTERNALS__.runCallback=a,window.__TAURI_INTERNALS__.callbacks=r,window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener=function(e,n){s(n)}},mockWindows:function(e,...n){J(),window.__TAURI_INTERNALS__.metadata={currentWindow:{label:e},currentWebview:{windowLabel:e,label:e}}}});!function(e){e[e.Audio=1]="Audio",e[e.Cache=2]="Cache",e[e.Config=3]="Config",e[e.Data=4]="Data",e[e.LocalData=5]="LocalData",e[e.Document=6]="Document",e[e.Download=7]="Download",e[e.Picture=8]="Picture",e[e.Public=9]="Public",e[e.Video=10]="Video",e[e.Resource=11]="Resource",e[e.Temp=12]="Temp",e[e.AppConfig=13]="AppConfig",e[e.AppData=14]="AppData",e[e.AppLocalData=15]="AppLocalData",e[e.AppCache=16]="AppCache",e[e.AppLog=17]="AppLog",e[e.Desktop=18]="Desktop",e[e.Executable=19]="Executable",e[e.Font=20]="Font",e[e.Home=21]="Home",e[e.Runtime=22]="Runtime",e[e.Template=23]="Template"}(Q||(Q={}));var K=Object.freeze({__proto__:null,get BaseDirectory(){return Q},appCacheDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.AppCache})},appConfigDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.AppConfig})},appDataDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.AppData})},appLocalDataDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.AppLocalData})},appLogDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.AppLog})},audioDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Audio})},basename:async function(e,n){return p("plugin:path|basename",{path:e,ext:n})},cacheDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Cache})},configDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Config})},dataDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Data})},delimiter:function(){return window.__TAURI_INTERNALS__.plugins.path.delimiter},desktopDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Desktop})},dirname:async function(e){return p("plugin:path|dirname",{path:e})},documentDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Document})},downloadDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Download})},executableDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Executable})},extname:async function(e){return p("plugin:path|extname",{path:e})},fontDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Font})},homeDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Home})},isAbsolute:async function(e){return p("plugin:path|is_absolute",{path:e})},join:async function(...e){return p("plugin:path|join",{paths:e})},localDataDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.LocalData})},normalize:async function(e){return p("plugin:path|normalize",{path:e})},pictureDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Picture})},publicDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Public})},resolve:async function(...e){return p("plugin:path|resolve",{paths:e})},resolveResource:async function(e){return p("plugin:path|resolve_directory",{directory:Q.Resource,path:e})},resourceDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Resource})},runtimeDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Runtime})},sep:function(){return window.__TAURI_INTERNALS__.plugins.path.sep},tempDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Temp})},templateDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Template})},videoDir:async function(){return p("plugin:path|resolve_directory",{directory:Q.Video})}});class Y extends h{constructor(e,n){super(e),this.id=n}static async getById(e){return p("plugin:tray|get_by_id",{id:e}).then(n=>n?new Y(n,e):null)}static async removeById(e){return p("plugin:tray|remove_by_id",{id:e})}static async new(e){(null==e?void 0:e.menu)&&(e.menu=[e.menu.rid,e.menu.kind]),(null==e?void 0:e.icon)&&(e.icon=y(e.icon));const n=new c;if(null==e?void 0:e.action){const t=e.action;n.onmessage=e=>t(function(e){const n=e;return n.position=new T(e.position),n.rect.position=new T(e.rect.position),n.rect.size=new v(e.rect.size),n}(e)),delete e.action}return p("plugin:tray|new",{options:null!=e?e:{},handler:n}).then(([e,n])=>new Y(e,n))}async setIcon(e){let n=null;return e&&(n=y(e)),p("plugin:tray|set_icon",{rid:this.rid,icon:n})}async setMenu(e){return e&&(e=[e.rid,e.kind]),p("plugin:tray|set_menu",{rid:this.rid,menu:e})}async setTooltip(e){return p("plugin:tray|set_tooltip",{rid:this.rid,tooltip:e})}async setTitle(e){return p("plugin:tray|set_title",{rid:this.rid,title:e})}async setVisible(e){return p("plugin:tray|set_visible",{rid:this.rid,visible:e})}async setTempDirPath(e){return p("plugin:tray|set_temp_dir_path",{rid:this.rid,path:e})}async setIconAsTemplate(e){return p("plugin:tray|set_icon_as_template",{rid:this.rid,asTemplate:e})}async setMenuOnLeftClick(e){return p("plugin:tray|set_show_menu_on_left_click",{rid:this.rid,onLeft:e})}async setShowMenuOnLeftClick(e){return p("plugin:tray|set_show_menu_on_left_click",{rid:this.rid,onLeft:e})}}var X,ee,ne=Object.freeze({__proto__:null,TrayIcon:Y});!function(e){e[e.Critical=1]="Critical",e[e.Informational=2]="Informational"}(X||(X={}));class te{constructor(e){this._preventDefault=!1,this.event=e.event,this.id=e.id}preventDefault(){this._preventDefault=!0}isPreventDefault(){return this._preventDefault}}function ie(){return new ae(window.__TAURI_INTERNALS__.metadata.currentWindow.label,{skip:!0})}async function re(){return p("plugin:window|get_all_windows").then(e=>e.map(e=>new ae(e,{skip:!0})))}!function(e){e.None="none",e.Normal="normal",e.Indeterminate="indeterminate",e.Paused="paused",e.Error="error"}(ee||(ee={}));const se=["tauri://created","tauri://error"];class ae{constructor(e,n={}){var t;this.label=e,this.listeners=Object.create(null),(null==n?void 0:n.skip)||p("plugin:window|create",{options:{...n,parent:"string"==typeof n.parent?n.parent:null===(t=n.parent)||void 0===t?void 0:t.label,label:e}}).then(async()=>this.emit("tauri://created")).catch(async e=>this.emit("tauri://error",e))}static async getByLabel(e){var n;return null!==(n=(await re()).find(n=>n.label===e))&&void 0!==n?n:null}static getCurrent(){return ie()}static async getAll(){return re()}static async getFocusedWindow(){for(const e of await re())if(await e.isFocused())return e;return null}async listen(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:S(e,n,{target:{kind:"Window",label:this.label}})}async once(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:N(e,n,{target:{kind:"Window",label:this.label}})}async emit(e,n){if(!se.includes(e))return L(e,n);for(const t of this.listeners[e]||[])t({event:e,id:-1,payload:n})}async emitTo(e,n,t){if(!se.includes(n))return C(e,n,t);for(const e of this.listeners[n]||[])e({event:n,id:-1,payload:t})}_handleTauriEvent(e,n){return!!se.includes(e)&&(e in this.listeners?this.listeners[e].push(n):this.listeners[e]=[n],!0)}async scaleFactor(){return p("plugin:window|scale_factor",{label:this.label})}async innerPosition(){return p("plugin:window|inner_position",{label:this.label}).then(e=>new T(e))}async outerPosition(){return p("plugin:window|outer_position",{label:this.label}).then(e=>new T(e))}async innerSize(){return p("plugin:window|inner_size",{label:this.label}).then(e=>new v(e))}async outerSize(){return p("plugin:window|outer_size",{label:this.label}).then(e=>new v(e))}async isFullscreen(){return p("plugin:window|is_fullscreen",{label:this.label})}async isMinimized(){return p("plugin:window|is_minimized",{label:this.label})}async isMaximized(){return p("plugin:window|is_maximized",{label:this.label})}async isFocused(){return p("plugin:window|is_focused",{label:this.label})}async isDecorated(){return p("plugin:window|is_decorated",{label:this.label})}async isResizable(){return p("plugin:window|is_resizable",{label:this.label})}async isMaximizable(){return p("plugin:window|is_maximizable",{label:this.label})}async isMinimizable(){return p("plugin:window|is_minimizable",{label:this.label})}async isClosable(){return p("plugin:window|is_closable",{label:this.label})}async isVisible(){return p("plugin:window|is_visible",{label:this.label})}async title(){return p("plugin:window|title",{label:this.label})}async theme(){return p("plugin:window|theme",{label:this.label})}async isAlwaysOnTop(){return p("plugin:window|is_always_on_top",{label:this.label})}async center(){return p("plugin:window|center",{label:this.label})}async requestUserAttention(e){let n=null;return e&&(n=e===X.Critical?{type:"Critical"}:{type:"Informational"}),p("plugin:window|request_user_attention",{label:this.label,value:n})}async setResizable(e){return p("plugin:window|set_resizable",{label:this.label,value:e})}async setEnabled(e){return p("plugin:window|set_enabled",{label:this.label,value:e})}async isEnabled(){return p("plugin:window|is_enabled",{label:this.label})}async setMaximizable(e){return p("plugin:window|set_maximizable",{label:this.label,value:e})}async setMinimizable(e){return p("plugin:window|set_minimizable",{label:this.label,value:e})}async setClosable(e){return p("plugin:window|set_closable",{label:this.label,value:e})}async setTitle(e){return p("plugin:window|set_title",{label:this.label,value:e})}async maximize(){return p("plugin:window|maximize",{label:this.label})}async unmaximize(){return p("plugin:window|unmaximize",{label:this.label})}async toggleMaximize(){return p("plugin:window|toggle_maximize",{label:this.label})}async minimize(){return p("plugin:window|minimize",{label:this.label})}async unminimize(){return p("plugin:window|unminimize",{label:this.label})}async show(){return p("plugin:window|show",{label:this.label})}async hide(){return p("plugin:window|hide",{label:this.label})}async close(){return p("plugin:window|close",{label:this.label})}async destroy(){return p("plugin:window|destroy",{label:this.label})}async setDecorations(e){return p("plugin:window|set_decorations",{label:this.label,value:e})}async setShadow(e){return p("plugin:window|set_shadow",{label:this.label,value:e})}async setEffects(e){return p("plugin:window|set_effects",{label:this.label,value:e})}async clearEffects(){return p("plugin:window|set_effects",{label:this.label,value:null})}async setAlwaysOnTop(e){return p("plugin:window|set_always_on_top",{label:this.label,value:e})}async setAlwaysOnBottom(e){return p("plugin:window|set_always_on_bottom",{label:this.label,value:e})}async setContentProtected(e){return p("plugin:window|set_content_protected",{label:this.label,value:e})}async setSize(e){return p("plugin:window|set_size",{label:this.label,value:e instanceof k?e:new k(e)})}async setMinSize(e){return p("plugin:window|set_min_size",{label:this.label,value:e instanceof k?e:e?new k(e):null})}async setMaxSize(e){return p("plugin:window|set_max_size",{label:this.label,value:e instanceof k?e:e?new k(e):null})}async setSizeConstraints(e){function n(e){return e?{Logical:e}:null}return p("plugin:window|set_size_constraints",{label:this.label,value:{minWidth:n(null==e?void 0:e.minWidth),minHeight:n(null==e?void 0:e.minHeight),maxWidth:n(null==e?void 0:e.maxWidth),maxHeight:n(null==e?void 0:e.maxHeight)}})}async setPosition(e){return p("plugin:window|set_position",{label:this.label,value:e instanceof I?e:new I(e)})}async setFullscreen(e){return p("plugin:window|set_fullscreen",{label:this.label,value:e})}async setSimpleFullscreen(e){return p("plugin:window|set_simple_fullscreen",{label:this.label,value:e})}async setFocus(){return p("plugin:window|set_focus",{label:this.label})}async setFocusable(e){return p("plugin:window|set_focusable",{label:this.label,value:e})}async setIcon(e){return p("plugin:window|set_icon",{label:this.label,value:y(e)})}async setSkipTaskbar(e){return p("plugin:window|set_skip_taskbar",{label:this.label,value:e})}async setCursorGrab(e){return p("plugin:window|set_cursor_grab",{label:this.label,value:e})}async setCursorVisible(e){return p("plugin:window|set_cursor_visible",{label:this.label,value:e})}async setCursorIcon(e){return p("plugin:window|set_cursor_icon",{label:this.label,value:e})}async setBackgroundColor(e){return p("plugin:window|set_background_color",{color:e})}async setCursorPosition(e){return p("plugin:window|set_cursor_position",{label:this.label,value:e instanceof I?e:new I(e)})}async setIgnoreCursorEvents(e){return p("plugin:window|set_ignore_cursor_events",{label:this.label,value:e})}async startDragging(){return p("plugin:window|start_dragging",{label:this.label})}async startResizeDragging(e){return p("plugin:window|start_resize_dragging",{label:this.label,value:e})}async setBadgeCount(e){return p("plugin:window|set_badge_count",{label:this.label,value:e})}async setBadgeLabel(e){return p("plugin:window|set_badge_label",{label:this.label,value:e})}async setOverlayIcon(e){return p("plugin:window|set_overlay_icon",{label:this.label,value:e?y(e):void 0})}async setProgressBar(e){return p("plugin:window|set_progress_bar",{label:this.label,value:e})}async setVisibleOnAllWorkspaces(e){return p("plugin:window|set_visible_on_all_workspaces",{label:this.label,value:e})}async setTitleBarStyle(e){return p("plugin:window|set_title_bar_style",{label:this.label,value:e})}async setTheme(e){return p("plugin:window|set_theme",{label:this.label,value:e})}async onResized(e){return this.listen(E.WINDOW_RESIZED,n=>{n.payload=new v(n.payload),e(n)})}async onMoved(e){return this.listen(E.WINDOW_MOVED,n=>{n.payload=new T(n.payload),e(n)})}async onCloseRequested(e){return this.listen(E.WINDOW_CLOSE_REQUESTED,async n=>{const t=new te(n);await e(t),t.isPreventDefault()||await this.destroy()})}async onDragDropEvent(e){const n=await this.listen(E.DRAG_ENTER,n=>{e({...n,payload:{type:"enter",paths:n.payload.paths,position:new T(n.payload.position)}})}),t=await this.listen(E.DRAG_OVER,n=>{e({...n,payload:{type:"over",position:new T(n.payload.position)}})}),i=await this.listen(E.DRAG_DROP,n=>{e({...n,payload:{type:"drop",paths:n.payload.paths,position:new T(n.payload.position)}})}),r=await this.listen(E.DRAG_LEAVE,n=>{e({...n,payload:{type:"leave"}})});return()=>{n(),i(),t(),r()}}async onFocusChanged(e){const n=await this.listen(E.WINDOW_FOCUS,n=>{e({...n,payload:!0})}),t=await this.listen(E.WINDOW_BLUR,n=>{e({...n,payload:!1})});return()=>{n(),t()}}async onScaleChanged(e){return this.listen(E.WINDOW_SCALE_FACTOR_CHANGED,e)}async onThemeChanged(e){return this.listen(E.WINDOW_THEME_CHANGED,e)}}var le,oe,ue,ce;function de(e){return null===e?null:{name:e.name,scaleFactor:e.scaleFactor,position:new T(e.position),size:new v(e.size),workArea:{position:new T(e.workArea.position),size:new v(e.workArea.size)}}}!function(e){e.Disabled="disabled",e.Throttle="throttle",e.Suspend="suspend"}(le||(le={})),function(e){e.Default="default",e.FluentOverlay="fluentOverlay"}(oe||(oe={})),function(e){e.AppearanceBased="appearanceBased",e.Light="light",e.Dark="dark",e.MediumLight="mediumLight",e.UltraDark="ultraDark",e.Titlebar="titlebar",e.Selection="selection",e.Menu="menu",e.Popover="popover",e.Sidebar="sidebar",e.HeaderView="headerView",e.Sheet="sheet",e.WindowBackground="windowBackground",e.HudWindow="hudWindow",e.FullScreenUI="fullScreenUI",e.Tooltip="tooltip",e.ContentBackground="contentBackground",e.UnderWindowBackground="underWindowBackground",e.UnderPageBackground="underPageBackground",e.Mica="mica",e.Blur="blur",e.Acrylic="acrylic",e.Tabbed="tabbed",e.TabbedDark="tabbedDark",e.TabbedLight="tabbedLight"}(ue||(ue={})),function(e){e.FollowsWindowActiveState="followsWindowActiveState",e.Active="active",e.Inactive="inactive"}(ce||(ce={}));var pe=Object.freeze({__proto__:null,CloseRequestedEvent:te,get Effect(){return ue},get EffectState(){return ce},LogicalPosition:A,LogicalSize:f,PhysicalPosition:T,PhysicalSize:v,get ProgressBarStatus(){return ee},get UserAttentionType(){return X},Window:ae,availableMonitors:async function(){return p("plugin:window|available_monitors").then(e=>e.map(de))},currentMonitor:async function(){return p("plugin:window|current_monitor").then(de)},cursorPosition:async function(){return p("plugin:window|cursor_position").then(e=>new T(e))},getAllWindows:re,getCurrentWindow:ie,monitorFromPoint:async function(e,n){return p("plugin:window|monitor_from_point",{x:e,y:n}).then(de)},primaryMonitor:async function(){return p("plugin:window|primary_monitor").then(de)}});function he(){return new ye(ie(),window.__TAURI_INTERNALS__.metadata.currentWebview.label,{skip:!0})}async function we(){return p("plugin:webview|get_all_webviews").then(e=>e.map(e=>new ye(new ae(e.windowLabel,{skip:!0}),e.label,{skip:!0})))}const _e=["tauri://created","tauri://error"];class ye{constructor(e,n,t){this.window=e,this.label=n,this.listeners=Object.create(null),(null==t?void 0:t.skip)||p("plugin:webview|create_webview",{windowLabel:e.label,options:{...t,label:n}}).then(async()=>this.emit("tauri://created")).catch(async e=>this.emit("tauri://error",e))}static async getByLabel(e){var n;return null!==(n=(await we()).find(n=>n.label===e))&&void 0!==n?n:null}static getCurrent(){return he()}static async getAll(){return we()}async listen(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:S(e,n,{target:{kind:"Webview",label:this.label}})}async once(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:N(e,n,{target:{kind:"Webview",label:this.label}})}async emit(e,n){if(!_e.includes(e))return L(e,n);for(const t of this.listeners[e]||[])t({event:e,id:-1,payload:n})}async emitTo(e,n,t){if(!_e.includes(n))return C(e,n,t);for(const e of this.listeners[n]||[])e({event:n,id:-1,payload:t})}_handleTauriEvent(e,n){return!!_e.includes(e)&&(e in this.listeners?this.listeners[e].push(n):this.listeners[e]=[n],!0)}async position(){return p("plugin:webview|webview_position",{label:this.label}).then(e=>new T(e))}async size(){return p("plugin:webview|webview_size",{label:this.label}).then(e=>new v(e))}async close(){return p("plugin:webview|webview_close",{label:this.label})}async setSize(e){return p("plugin:webview|set_webview_size",{label:this.label,value:e instanceof k?e:new k(e)})}async setPosition(e){return p("plugin:webview|set_webview_position",{label:this.label,value:e instanceof I?e:new I(e)})}async setFocus(){return p("plugin:webview|set_webview_focus",{label:this.label})}async setAutoResize(e){return p("plugin:webview|set_webview_auto_resize",{label:this.label,value:e})}async hide(){return p("plugin:webview|webview_hide",{label:this.label})}async show(){return p("plugin:webview|webview_show",{label:this.label})}async setZoom(e){return p("plugin:webview|set_webview_zoom",{label:this.label,value:e})}async reparent(e){return p("plugin:webview|reparent",{label:this.label,window:"string"==typeof e?e:e.label})}async clearAllBrowsingData(){return p("plugin:webview|clear_all_browsing_data")}async setBackgroundColor(e){return p("plugin:webview|set_webview_background_color",{color:e})}async onDragDropEvent(e){const n=await this.listen(E.DRAG_ENTER,n=>{e({...n,payload:{type:"enter",paths:n.payload.paths,position:new T(n.payload.position)}})}),t=await this.listen(E.DRAG_OVER,n=>{e({...n,payload:{type:"over",position:new T(n.payload.position)}})}),i=await this.listen(E.DRAG_DROP,n=>{e({...n,payload:{type:"drop",paths:n.payload.paths,position:new T(n.payload.position)}})}),r=await this.listen(E.DRAG_LEAVE,n=>{e({...n,payload:{type:"leave"}})});return()=>{n(),i(),t(),r()}}}var ge,be,me=Object.freeze({__proto__:null,Webview:ye,getAllWebviews:we,getCurrentWebview:he});function fe(){const e=he();return new ke(e.label,{skip:!0})}async function ve(){return p("plugin:window|get_all_windows").then(e=>e.map(e=>new ke(e,{skip:!0})))}class ke{constructor(e,n={}){var t;this.label=e,this.listeners=Object.create(null),(null==n?void 0:n.skip)||p("plugin:webview|create_webview_window",{options:{...n,parent:"string"==typeof n.parent?n.parent:null===(t=n.parent)||void 0===t?void 0:t.label,label:e}}).then(async()=>this.emit("tauri://created")).catch(async e=>this.emit("tauri://error",e))}static async getByLabel(e){var n;const t=null!==(n=(await ve()).find(n=>n.label===e))&&void 0!==n?n:null;return t?new ke(t.label,{skip:!0}):null}static getCurrent(){return fe()}static async getAll(){return ve()}async listen(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:S(e,n,{target:{kind:"WebviewWindow",label:this.label}})}async once(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:N(e,n,{target:{kind:"WebviewWindow",label:this.label}})}async setBackgroundColor(e){return p("plugin:window|set_background_color",{color:e}).then(()=>p("plugin:webview|set_webview_background_color",{color:e}))}}ge=ke,be=[ae,ye],(Array.isArray(be)?be:[be]).forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(n=>{var t;"object"==typeof ge.prototype&&ge.prototype&&n in ge.prototype||Object.defineProperty(ge.prototype,n,null!==(t=Object.getOwnPropertyDescriptor(e.prototype,n))&&void 0!==t?t:Object.create(null))})});var Ae=Object.freeze({__proto__:null,WebviewWindow:ke,getAllWebviewWindows:ve,getCurrentWebviewWindow:fe});return e.app=m,e.core=w,e.dpi=R,e.event=W,e.image=b,e.menu=q,e.mocks=Z,e.path=K,e.tray=ne,e.webview=me,e.webviewWindow=Ae,e.window=pe,e}({});window.__TAURI__=__TAURI_IIFE__; +var __TAURI_IIFE__=function(e){"use strict";function n(e,n,t,i){if("a"===t&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof n?e!==n||!i:!n.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===t?i:"a"===t?i.call(e):i?i.value:n.get(e)}function t(e,n,t,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof n?e!==n||!r:!n.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,t):r?r.value=t:n.set(e,t),t}var i,r,s,a,l;"function"==typeof SuppressedError&&SuppressedError;const o="__TAURI_TO_IPC_KEY__";function u(e,n=!1){return window.__TAURI_INTERNALS__.transformCallback(e,n)}class c{constructor(e){i.set(this,void 0),r.set(this,0),s.set(this,[]),a.set(this,void 0),t(this,i,e||(()=>{}),"f"),this.id=u(e=>{const l=e.index;if("end"in e)return void(l==n(this,r,"f")?this.cleanupCallback():t(this,a,l,"f"));const o=e.message;if(l==n(this,r,"f")){for(n(this,i,"f").call(this,o),t(this,r,n(this,r,"f")+1,"f");n(this,r,"f")in n(this,s,"f");){const e=n(this,s,"f")[n(this,r,"f")];n(this,i,"f").call(this,e),delete n(this,s,"f")[n(this,r,"f")],t(this,r,n(this,r,"f")+1,"f")}n(this,r,"f")===n(this,a,"f")&&this.cleanupCallback()}else n(this,s,"f")[l]=o})}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(e){t(this,i,e,"f")}get onmessage(){return n(this,i,"f")}[(i=new WeakMap,r=new WeakMap,s=new WeakMap,a=new WeakMap,o)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[o]()}}class d{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return p(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}}async function p(e,n={},t){return window.__TAURI_INTERNALS__.invoke(e,n,t)}class h{get rid(){return n(this,l,"f")}constructor(e){l.set(this,void 0),t(this,l,e,"f")}async close(){return p("plugin:resources|close",{rid:this.rid})}}l=new WeakMap;var w=Object.freeze({__proto__:null,Channel:c,PluginListener:d,Resource:h,SERIALIZE_TO_IPC_FN:o,addPluginListener:async function(e,n,t){const i=new c(t);try{return p(`plugin:${e}|register_listener`,{event:n,handler:i}).then(()=>new d(e,n,i.id))}catch{return p(`plugin:${e}|registerListener`,{event:n,handler:i}).then(()=>new d(e,n,i.id))}},checkPermissions:async function(e){return p(`plugin:${e}|check_permissions`)},convertFileSrc:function(e,n="asset"){return window.__TAURI_INTERNALS__.convertFileSrc(e,n)},invoke:p,isTauri:function(){return!!(globalThis||window).isTauri},requestPermissions:async function(e){return p(`plugin:${e}|request_permissions`)},transformCallback:u});class _ extends h{constructor(e){super(e)}static async new(e,n,t){return p("plugin:image|new",{rgba:y(e),width:n,height:t}).then(e=>new _(e))}static async fromBytes(e){return p("plugin:image|from_bytes",{bytes:y(e)}).then(e=>new _(e))}static async fromPath(e){return p("plugin:image|from_path",{path:e}).then(e=>new _(e))}async rgba(){return p("plugin:image|rgba",{rid:this.rid}).then(e=>new Uint8Array(e))}async size(){return p("plugin:image|size",{rid:this.rid})}}function y(e){return null==e?null:"string"==typeof e?e:e instanceof _?e.rid:e}var g,b=Object.freeze({__proto__:null,Image:_,transformImage:y});!function(e){e.Nsis="nsis",e.Msi="msi",e.Deb="deb",e.Rpm="rpm",e.AppImage="appimage",e.App="app"}(g||(g={}));var m=Object.freeze({__proto__:null,get BundleType(){return g},defaultWindowIcon:async function(){return p("plugin:app|default_window_icon").then(e=>e?new _(e):null)},fetchDataStoreIdentifiers:async function(){return p("plugin:app|fetch_data_store_identifiers")},getBundleType:async function(){return p("plugin:app|bundle_type")},getIdentifier:async function(){return p("plugin:app|identifier")},getName:async function(){return p("plugin:app|name")},getTauriVersion:async function(){return p("plugin:app|tauri_version")},getVersion:async function(){return p("plugin:app|version")},hide:async function(){return p("plugin:app|app_hide")},removeDataStore:async function(e){return p("plugin:app|remove_data_store",{uuid:e})},setDockVisibility:async function(e){return p("plugin:app|set_dock_visibility",{visible:e})},setTheme:async function(e){return p("plugin:app|set_app_theme",{theme:e})},show:async function(){return p("plugin:app|app_show")}});class f{constructor(...e){this.type="Logical",1===e.length?"Logical"in e[0]?(this.width=e[0].Logical.width,this.height=e[0].Logical.height):(this.width=e[0].width,this.height=e[0].height):(this.width=e[0],this.height=e[1])}toPhysical(e){return new v(this.width*e,this.height*e)}[o](){return{width:this.width,height:this.height}}toJSON(){return this[o]()}}class v{constructor(...e){this.type="Physical",1===e.length?"Physical"in e[0]?(this.width=e[0].Physical.width,this.height=e[0].Physical.height):(this.width=e[0].width,this.height=e[0].height):(this.width=e[0],this.height=e[1])}toLogical(e){return new f(this.width/e,this.height/e)}[o](){return{width:this.width,height:this.height}}toJSON(){return this[o]()}}class k{constructor(e){this.size=e}toLogical(e){return this.size instanceof f?this.size:this.size.toLogical(e)}toPhysical(e){return this.size instanceof v?this.size:this.size.toPhysical(e)}[o](){return{[`${this.size.type}`]:{width:this.size.width,height:this.size.height}}}toJSON(){return this[o]()}}class A{constructor(...e){this.type="Logical",1===e.length?"Logical"in e[0]?(this.x=e[0].Logical.x,this.y=e[0].Logical.y):(this.x=e[0].x,this.y=e[0].y):(this.x=e[0],this.y=e[1])}toPhysical(e){return new T(this.x*e,this.y*e)}[o](){return{x:this.x,y:this.y}}toJSON(){return this[o]()}}class T{constructor(...e){this.type="Physical",1===e.length?"Physical"in e[0]?(this.x=e[0].Physical.x,this.y=e[0].Physical.y):(this.x=e[0].x,this.y=e[0].y):(this.x=e[0],this.y=e[1])}toLogical(e){return new A(this.x/e,this.y/e)}[o](){return{x:this.x,y:this.y}}toJSON(){return this[o]()}}class I{constructor(e){this.position=e}toLogical(e){return this.position instanceof A?this.position:this.position.toLogical(e)}toPhysical(e){return this.position instanceof T?this.position:this.position.toPhysical(e)}[o](){return{[`${this.position.type}`]:{x:this.position.x,y:this.position.y}}}toJSON(){return this[o]()}}var E,R=Object.freeze({__proto__:null,LogicalPosition:A,LogicalSize:f,PhysicalPosition:T,PhysicalSize:v,Position:I,Size:k});async function D(e,n){window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener(e,n),await p("plugin:event|unlisten",{event:e,eventId:n})}async function N(e,n,t){var i;const r="string"==typeof(null==t?void 0:t.target)?{kind:"AnyLabel",label:t.target}:null!==(i=null==t?void 0:t.target)&&void 0!==i?i:{kind:"Any"};return p("plugin:event|listen",{event:e,target:r,handler:u(n)}).then(n=>async()=>D(e,n))}async function S(e,n,t){return N(e,t=>{D(e,t.id),n(t)},t)}async function L(e,n){await p("plugin:event|emit",{event:e,payload:n})}async function C(e,n){await p("plugin:event|emit",n,{headers:{"Tauri-Event-Name":e}})}async function x(e,n,t){const i="string"==typeof e?{kind:"AnyLabel",label:e}:e;await p("plugin:event|emit_to",{event:n,payload:t,target:i})}async function P(e,n,t){const i="string"==typeof e?{kind:"AnyLabel",label:e}:e;await p("plugin:event|emit_to",t,{headers:{"Tauri-Event-Name":n,"Tauri-Event-Target":JSON.stringify(i)}})}!function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"}(E||(E={}));var z,W,O,U=Object.freeze({__proto__:null,get TauriEvent(){return E},emit:L,emit2:C,emitTo:x,emitTo2:P,listen:N,once:S});function F(e){var n;if("items"in e)e.items=null===(n=e.items)||void 0===n?void 0:n.map(e=>"rid"in e?e:F(e));else if("action"in e&&e.action){const n=new c;return n.onmessage=e.action,delete e.action,{...e,handler:n}}return e}async function M(e,n){const t=new c;if(n&&"object"==typeof n&&("action"in n&&n.action&&(t.onmessage=n.action,delete n.action),"item"in n&&n.item&&"object"==typeof n.item&&"About"in n.item&&n.item.About&&"object"==typeof n.item.About&&"icon"in n.item.About&&n.item.About.icon&&(n.item.About.icon=y(n.item.About.icon)),"icon"in n&&n.icon&&(n.icon=y(n.icon)),"items"in n&&n.items)){function i(e){var n;return"rid"in e?[e.rid,e.kind]:("item"in e&&"object"==typeof e.item&&(null===(n=e.item.About)||void 0===n?void 0:n.icon)&&(e.item.About.icon=y(e.item.About.icon)),"icon"in e&&e.icon&&(e.icon=y(e.icon)),"items"in e&&e.items&&(e.items=e.items.map(i)),F(e))}n.items=n.items.map(i)}return p("plugin:menu|new",{kind:e,options:n,handler:t})}class B extends h{get id(){return n(this,z,"f")}get kind(){return n(this,W,"f")}constructor(e,n,i){super(e),z.set(this,void 0),W.set(this,void 0),t(this,z,n,"f"),t(this,W,i,"f")}}z=new WeakMap,W=new WeakMap;class V extends B{constructor(e,n){super(e,n,"MenuItem")}static async new(e){return M("MenuItem",e).then(([e,n])=>new V(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async setAccelerator(e){return p("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:e})}}class G extends B{constructor(e,n){super(e,n,"Check")}static async new(e){return M("Check",e).then(([e,n])=>new G(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async setAccelerator(e){return p("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:e})}async isChecked(){return p("plugin:menu|is_checked",{rid:this.rid})}async setChecked(e){return p("plugin:menu|set_checked",{rid:this.rid,checked:e})}}!function(e){e.Add="Add",e.Advanced="Advanced",e.Bluetooth="Bluetooth",e.Bookmarks="Bookmarks",e.Caution="Caution",e.ColorPanel="ColorPanel",e.ColumnView="ColumnView",e.Computer="Computer",e.EnterFullScreen="EnterFullScreen",e.Everyone="Everyone",e.ExitFullScreen="ExitFullScreen",e.FlowView="FlowView",e.Folder="Folder",e.FolderBurnable="FolderBurnable",e.FolderSmart="FolderSmart",e.FollowLinkFreestanding="FollowLinkFreestanding",e.FontPanel="FontPanel",e.GoLeft="GoLeft",e.GoRight="GoRight",e.Home="Home",e.IChatTheater="IChatTheater",e.IconView="IconView",e.Info="Info",e.InvalidDataFreestanding="InvalidDataFreestanding",e.LeftFacingTriangle="LeftFacingTriangle",e.ListView="ListView",e.LockLocked="LockLocked",e.LockUnlocked="LockUnlocked",e.MenuMixedState="MenuMixedState",e.MenuOnState="MenuOnState",e.MobileMe="MobileMe",e.MultipleDocuments="MultipleDocuments",e.Network="Network",e.Path="Path",e.PreferencesGeneral="PreferencesGeneral",e.QuickLook="QuickLook",e.RefreshFreestanding="RefreshFreestanding",e.Refresh="Refresh",e.Remove="Remove",e.RevealFreestanding="RevealFreestanding",e.RightFacingTriangle="RightFacingTriangle",e.Share="Share",e.Slideshow="Slideshow",e.SmartBadge="SmartBadge",e.StatusAvailable="StatusAvailable",e.StatusNone="StatusNone",e.StatusPartiallyAvailable="StatusPartiallyAvailable",e.StatusUnavailable="StatusUnavailable",e.StopProgressFreestanding="StopProgressFreestanding",e.StopProgress="StopProgress",e.TrashEmpty="TrashEmpty",e.TrashFull="TrashFull",e.User="User",e.UserAccounts="UserAccounts",e.UserGroup="UserGroup",e.UserGuest="UserGuest"}(O||(O={}));class j extends B{constructor(e,n){super(e,n,"Icon")}static async new(e){return M("Icon",e).then(([e,n])=>new j(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async setAccelerator(e){return p("plugin:menu|set_accelerator",{rid:this.rid,kind:this.kind,accelerator:e})}async setIcon(e){return p("plugin:menu|set_icon",{rid:this.rid,kind:this.kind,icon:y(e)})}}class H extends B{constructor(e,n){super(e,n,"Predefined")}static async new(e){return M("Predefined",e).then(([e,n])=>new H(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}}function $([e,n,t]){switch(t){case"Submenu":return new J(e,n);case"Predefined":return new H(e,n);case"Check":return new G(e,n);case"Icon":return new j(e,n);default:return new V(e,n)}}class J extends B{constructor(e,n){super(e,n,"Submenu")}static async new(e){return M("Submenu",e).then(([e,n])=>new J(e,n))}async text(){return p("plugin:menu|text",{rid:this.rid,kind:this.kind})}async setText(e){return p("plugin:menu|set_text",{rid:this.rid,kind:this.kind,text:e})}async isEnabled(){return p("plugin:menu|is_enabled",{rid:this.rid,kind:this.kind})}async setEnabled(e){return p("plugin:menu|set_enabled",{rid:this.rid,kind:this.kind,enabled:e})}async append(e){return p("plugin:menu|append",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async prepend(e){return p("plugin:menu|prepend",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async insert(e,n){return p("plugin:menu|insert",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e),position:n})}async remove(e){return p("plugin:menu|remove",{rid:this.rid,kind:this.kind,item:[e.rid,e.kind]})}async removeAt(e){return p("plugin:menu|remove_at",{rid:this.rid,kind:this.kind,position:e}).then($)}async items(){return p("plugin:menu|items",{rid:this.rid,kind:this.kind}).then(e=>e.map($))}async get(e){return p("plugin:menu|get",{rid:this.rid,kind:this.kind,id:e}).then(e=>e?$(e):null)}async popup(e,n){var t;return p("plugin:menu|popup",{rid:this.rid,kind:this.kind,window:null!==(t=null==n?void 0:n.label)&&void 0!==t?t:null,at:e instanceof I?e:e?new I(e):null})}async setAsWindowsMenuForNSApp(){return p("plugin:menu|set_as_windows_menu_for_nsapp",{rid:this.rid})}async setAsHelpMenuForNSApp(){return p("plugin:menu|set_as_help_menu_for_nsapp",{rid:this.rid})}async setIcon(e){return p("plugin:menu|set_icon",{rid:this.rid,kind:this.kind,icon:y(e)})}}class q extends B{constructor(e,n){super(e,n,"Menu")}static async new(e){return M("Menu",e).then(([e,n])=>new q(e,n))}static async default(){return p("plugin:menu|create_default").then(([e,n])=>new q(e,n))}async append(e){return p("plugin:menu|append",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async prepend(e){return p("plugin:menu|prepend",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e)})}async insert(e,n){return p("plugin:menu|insert",{rid:this.rid,kind:this.kind,items:(Array.isArray(e)?e:[e]).map(e=>"rid"in e?[e.rid,e.kind]:e),position:n})}async remove(e){return p("plugin:menu|remove",{rid:this.rid,kind:this.kind,item:[e.rid,e.kind]})}async removeAt(e){return p("plugin:menu|remove_at",{rid:this.rid,kind:this.kind,position:e}).then($)}async items(){return p("plugin:menu|items",{rid:this.rid,kind:this.kind}).then(e=>e.map($))}async get(e){return p("plugin:menu|get",{rid:this.rid,kind:this.kind,id:e}).then(e=>e?$(e):null)}async popup(e,n){var t;return p("plugin:menu|popup",{rid:this.rid,kind:this.kind,window:null!==(t=null==n?void 0:n.label)&&void 0!==t?t:null,at:e instanceof I?e:e?new I(e):null})}async setAsAppMenu(){return p("plugin:menu|set_as_app_menu",{rid:this.rid}).then(e=>e?new q(e[0],e[1]):null)}async setAsWindowMenu(e){var n;return p("plugin:menu|set_as_window_menu",{rid:this.rid,window:null!==(n=null==e?void 0:e.label)&&void 0!==n?n:null}).then(e=>e?new q(e[0],e[1]):null)}}var Q=Object.freeze({__proto__:null,CheckMenuItem:G,IconMenuItem:j,Menu:q,MenuItem:V,get NativeIcon(){return O},PredefinedMenuItem:H,Submenu:J,itemFromKind:$});function Z(){var e,n;window.__TAURI_INTERNALS__=null!==(e=window.__TAURI_INTERNALS__)&&void 0!==e?e:{},window.__TAURI_EVENT_PLUGIN_INTERNALS__=null!==(n=window.__TAURI_EVENT_PLUGIN_INTERNALS__)&&void 0!==n?n:{}}var K,Y=Object.freeze({__proto__:null,clearMocks:function(){"object"==typeof window.__TAURI_INTERNALS__&&(delete window.__TAURI_INTERNALS__.invoke,delete window.__TAURI_INTERNALS__.transformCallback,delete window.__TAURI_INTERNALS__.unregisterCallback,delete window.__TAURI_INTERNALS__.runCallback,delete window.__TAURI_INTERNALS__.callbacks,delete window.__TAURI_INTERNALS__.convertFileSrc,delete window.__TAURI_INTERNALS__.metadata,"object"==typeof window.__TAURI_EVENT_PLUGIN_INTERNALS__&&delete window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener)},mockConvertFileSrc:function(e){Z(),window.__TAURI_INTERNALS__.convertFileSrc=function(n,t="asset"){const i=encodeURIComponent(n);return"windows"===e?`http://${t}.localhost/${i}`:`${t}://localhost/${i}`}},mockIPC:function(e,n){function t(e,n){switch(e){case"plugin:event|listen":return function(e){i.has(e.event)||i.set(e.event,[]);return i.get(e.event).push(e.handler),e.handler}(n);case"plugin:event|emit":return function(e){const n=i.get(e.event)||[];for(const t of n)a(t,e);return null}(n);case"plugin:event|unlisten":return function(e){const n=i.get(e.event);if(n){const t=n.indexOf(e.id);-1!==t&&n.splice(t,1)}}(n)}}Z();const i=new Map,r=new Map;function s(e){r.delete(e)}function a(e,n){const t=r.get(e);t?t(n):console.warn(`[TAURI] Couldn't find callback id ${e}. This might happen when the app is reloaded while Rust is running an asynchronous operation.`)}window.__TAURI_INTERNALS__.invoke=async function(i,r,s){return(null==n?void 0:n.shouldMockEvents)&&function(e){return e.startsWith("plugin:event|")}(i)?t(i,r):e(i,r)},window.__TAURI_INTERNALS__.transformCallback=function(e,n=!1){const t=window.crypto.getRandomValues(new Uint32Array(1))[0];return r.set(t,i=>(n&&s(t),e&&e(i))),t},window.__TAURI_INTERNALS__.unregisterCallback=s,window.__TAURI_INTERNALS__.runCallback=a,window.__TAURI_INTERNALS__.callbacks=r,window.__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener=function(e,n){s(n)}},mockWindows:function(e,...n){Z(),window.__TAURI_INTERNALS__.metadata={currentWindow:{label:e},currentWebview:{windowLabel:e,label:e}}}});!function(e){e[e.Audio=1]="Audio",e[e.Cache=2]="Cache",e[e.Config=3]="Config",e[e.Data=4]="Data",e[e.LocalData=5]="LocalData",e[e.Document=6]="Document",e[e.Download=7]="Download",e[e.Picture=8]="Picture",e[e.Public=9]="Public",e[e.Video=10]="Video",e[e.Resource=11]="Resource",e[e.Temp=12]="Temp",e[e.AppConfig=13]="AppConfig",e[e.AppData=14]="AppData",e[e.AppLocalData=15]="AppLocalData",e[e.AppCache=16]="AppCache",e[e.AppLog=17]="AppLog",e[e.Desktop=18]="Desktop",e[e.Executable=19]="Executable",e[e.Font=20]="Font",e[e.Home=21]="Home",e[e.Runtime=22]="Runtime",e[e.Template=23]="Template"}(K||(K={}));var X=Object.freeze({__proto__:null,get BaseDirectory(){return K},appCacheDir:async function(){return p("plugin:path|resolve_directory",{directory:K.AppCache})},appConfigDir:async function(){return p("plugin:path|resolve_directory",{directory:K.AppConfig})},appDataDir:async function(){return p("plugin:path|resolve_directory",{directory:K.AppData})},appLocalDataDir:async function(){return p("plugin:path|resolve_directory",{directory:K.AppLocalData})},appLogDir:async function(){return p("plugin:path|resolve_directory",{directory:K.AppLog})},audioDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Audio})},basename:async function(e,n){return p("plugin:path|basename",{path:e,ext:n})},cacheDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Cache})},configDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Config})},dataDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Data})},delimiter:function(){return window.__TAURI_INTERNALS__.plugins.path.delimiter},desktopDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Desktop})},dirname:async function(e){return p("plugin:path|dirname",{path:e})},documentDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Document})},downloadDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Download})},executableDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Executable})},extname:async function(e){return p("plugin:path|extname",{path:e})},fontDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Font})},homeDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Home})},isAbsolute:async function(e){return p("plugin:path|is_absolute",{path:e})},join:async function(...e){return p("plugin:path|join",{paths:e})},localDataDir:async function(){return p("plugin:path|resolve_directory",{directory:K.LocalData})},normalize:async function(e){return p("plugin:path|normalize",{path:e})},pictureDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Picture})},publicDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Public})},resolve:async function(...e){return p("plugin:path|resolve",{paths:e})},resolveResource:async function(e){return p("plugin:path|resolve_directory",{directory:K.Resource,path:e})},resourceDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Resource})},runtimeDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Runtime})},sep:function(){return window.__TAURI_INTERNALS__.plugins.path.sep},tempDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Temp})},templateDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Template})},videoDir:async function(){return p("plugin:path|resolve_directory",{directory:K.Video})}});class ee extends h{constructor(e,n){super(e),this.id=n}static async getById(e){return p("plugin:tray|get_by_id",{id:e}).then(n=>n?new ee(n,e):null)}static async removeById(e){return p("plugin:tray|remove_by_id",{id:e})}static async new(e){(null==e?void 0:e.menu)&&(e.menu=[e.menu.rid,e.menu.kind]),(null==e?void 0:e.icon)&&(e.icon=y(e.icon));const n=new c;if(null==e?void 0:e.action){const t=e.action;n.onmessage=e=>t(function(e){const n=e;return n.position=new T(e.position),n.rect.position=new T(e.rect.position),n.rect.size=new v(e.rect.size),n}(e)),delete e.action}return p("plugin:tray|new",{options:null!=e?e:{},handler:n}).then(([e,n])=>new ee(e,n))}async setIcon(e){let n=null;return e&&(n=y(e)),p("plugin:tray|set_icon",{rid:this.rid,icon:n})}async setMenu(e){return e&&(e=[e.rid,e.kind]),p("plugin:tray|set_menu",{rid:this.rid,menu:e})}async setTooltip(e){return p("plugin:tray|set_tooltip",{rid:this.rid,tooltip:e})}async setTitle(e){return p("plugin:tray|set_title",{rid:this.rid,title:e})}async setVisible(e){return p("plugin:tray|set_visible",{rid:this.rid,visible:e})}async setTempDirPath(e){return p("plugin:tray|set_temp_dir_path",{rid:this.rid,path:e})}async setIconAsTemplate(e){return p("plugin:tray|set_icon_as_template",{rid:this.rid,asTemplate:e})}async setMenuOnLeftClick(e){return p("plugin:tray|set_show_menu_on_left_click",{rid:this.rid,onLeft:e})}async setShowMenuOnLeftClick(e){return p("plugin:tray|set_show_menu_on_left_click",{rid:this.rid,onLeft:e})}}var ne,te,ie=Object.freeze({__proto__:null,TrayIcon:ee});!function(e){e[e.Critical=1]="Critical",e[e.Informational=2]="Informational"}(ne||(ne={}));class re{constructor(e){this._preventDefault=!1,this.event=e.event,this.id=e.id}preventDefault(){this._preventDefault=!0}isPreventDefault(){return this._preventDefault}}function se(){return new oe(window.__TAURI_INTERNALS__.metadata.currentWindow.label,{skip:!0})}async function ae(){return p("plugin:window|get_all_windows").then(e=>e.map(e=>new oe(e,{skip:!0})))}!function(e){e.None="none",e.Normal="normal",e.Indeterminate="indeterminate",e.Paused="paused",e.Error="error"}(te||(te={}));const le=["tauri://created","tauri://error"];class oe{constructor(e,n={}){var t;this.label=e,this.listeners=Object.create(null),(null==n?void 0:n.skip)||p("plugin:window|create",{options:{...n,parent:"string"==typeof n.parent?n.parent:null===(t=n.parent)||void 0===t?void 0:t.label,label:e}}).then(async()=>this.emit("tauri://created")).catch(async e=>this.emit("tauri://error",e))}static async getByLabel(e){var n;return null!==(n=(await ae()).find(n=>n.label===e))&&void 0!==n?n:null}static getCurrent(){return se()}static async getAll(){return ae()}static async getFocusedWindow(){for(const e of await ae())if(await e.isFocused())return e;return null}async listen(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:N(e,n,{target:{kind:"Window",label:this.label}})}async once(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:S(e,n,{target:{kind:"Window",label:this.label}})}async emit(e,n){if(!le.includes(e))return L(e,n);for(const t of this.listeners[e]||[])t({event:e,id:-1,payload:n})}async emit2(e,n){if(!le.includes(e))return C(e,n);for(const t of this.listeners[e]||[])t({event:e,id:-1,payload:n})}async emitTo(e,n,t){if(!le.includes(n))return x(e,n,t);for(const e of this.listeners[n]||[])e({event:n,id:-1,payload:t})}async emitTo2(e,n,t){if(!le.includes(n))return P(e,n,t);for(const e of this.listeners[n]||[])e({event:n,id:-1,payload:t})}_handleTauriEvent(e,n){return!!le.includes(e)&&(e in this.listeners?this.listeners[e].push(n):this.listeners[e]=[n],!0)}async scaleFactor(){return p("plugin:window|scale_factor",{label:this.label})}async innerPosition(){return p("plugin:window|inner_position",{label:this.label}).then(e=>new T(e))}async outerPosition(){return p("plugin:window|outer_position",{label:this.label}).then(e=>new T(e))}async innerSize(){return p("plugin:window|inner_size",{label:this.label}).then(e=>new v(e))}async outerSize(){return p("plugin:window|outer_size",{label:this.label}).then(e=>new v(e))}async isFullscreen(){return p("plugin:window|is_fullscreen",{label:this.label})}async isMinimized(){return p("plugin:window|is_minimized",{label:this.label})}async isMaximized(){return p("plugin:window|is_maximized",{label:this.label})}async isFocused(){return p("plugin:window|is_focused",{label:this.label})}async isDecorated(){return p("plugin:window|is_decorated",{label:this.label})}async isResizable(){return p("plugin:window|is_resizable",{label:this.label})}async isMaximizable(){return p("plugin:window|is_maximizable",{label:this.label})}async isMinimizable(){return p("plugin:window|is_minimizable",{label:this.label})}async isClosable(){return p("plugin:window|is_closable",{label:this.label})}async isVisible(){return p("plugin:window|is_visible",{label:this.label})}async title(){return p("plugin:window|title",{label:this.label})}async theme(){return p("plugin:window|theme",{label:this.label})}async isAlwaysOnTop(){return p("plugin:window|is_always_on_top",{label:this.label})}async center(){return p("plugin:window|center",{label:this.label})}async requestUserAttention(e){let n=null;return e&&(n=e===ne.Critical?{type:"Critical"}:{type:"Informational"}),p("plugin:window|request_user_attention",{label:this.label,value:n})}async setResizable(e){return p("plugin:window|set_resizable",{label:this.label,value:e})}async setEnabled(e){return p("plugin:window|set_enabled",{label:this.label,value:e})}async isEnabled(){return p("plugin:window|is_enabled",{label:this.label})}async setMaximizable(e){return p("plugin:window|set_maximizable",{label:this.label,value:e})}async setMinimizable(e){return p("plugin:window|set_minimizable",{label:this.label,value:e})}async setClosable(e){return p("plugin:window|set_closable",{label:this.label,value:e})}async setTitle(e){return p("plugin:window|set_title",{label:this.label,value:e})}async maximize(){return p("plugin:window|maximize",{label:this.label})}async unmaximize(){return p("plugin:window|unmaximize",{label:this.label})}async toggleMaximize(){return p("plugin:window|toggle_maximize",{label:this.label})}async minimize(){return p("plugin:window|minimize",{label:this.label})}async unminimize(){return p("plugin:window|unminimize",{label:this.label})}async show(){return p("plugin:window|show",{label:this.label})}async hide(){return p("plugin:window|hide",{label:this.label})}async close(){return p("plugin:window|close",{label:this.label})}async destroy(){return p("plugin:window|destroy",{label:this.label})}async setDecorations(e){return p("plugin:window|set_decorations",{label:this.label,value:e})}async setShadow(e){return p("plugin:window|set_shadow",{label:this.label,value:e})}async setEffects(e){return p("plugin:window|set_effects",{label:this.label,value:e})}async clearEffects(){return p("plugin:window|set_effects",{label:this.label,value:null})}async setAlwaysOnTop(e){return p("plugin:window|set_always_on_top",{label:this.label,value:e})}async setAlwaysOnBottom(e){return p("plugin:window|set_always_on_bottom",{label:this.label,value:e})}async setContentProtected(e){return p("plugin:window|set_content_protected",{label:this.label,value:e})}async setSize(e){return p("plugin:window|set_size",{label:this.label,value:e instanceof k?e:new k(e)})}async setMinSize(e){return p("plugin:window|set_min_size",{label:this.label,value:e instanceof k?e:e?new k(e):null})}async setMaxSize(e){return p("plugin:window|set_max_size",{label:this.label,value:e instanceof k?e:e?new k(e):null})}async setSizeConstraints(e){function n(e){return e?{Logical:e}:null}return p("plugin:window|set_size_constraints",{label:this.label,value:{minWidth:n(null==e?void 0:e.minWidth),minHeight:n(null==e?void 0:e.minHeight),maxWidth:n(null==e?void 0:e.maxWidth),maxHeight:n(null==e?void 0:e.maxHeight)}})}async setPosition(e){return p("plugin:window|set_position",{label:this.label,value:e instanceof I?e:new I(e)})}async setFullscreen(e){return p("plugin:window|set_fullscreen",{label:this.label,value:e})}async setSimpleFullscreen(e){return p("plugin:window|set_simple_fullscreen",{label:this.label,value:e})}async setFocus(){return p("plugin:window|set_focus",{label:this.label})}async setFocusable(e){return p("plugin:window|set_focusable",{label:this.label,value:e})}async setIcon(e){return p("plugin:window|set_icon",{label:this.label,value:y(e)})}async setSkipTaskbar(e){return p("plugin:window|set_skip_taskbar",{label:this.label,value:e})}async setCursorGrab(e){return p("plugin:window|set_cursor_grab",{label:this.label,value:e})}async setCursorVisible(e){return p("plugin:window|set_cursor_visible",{label:this.label,value:e})}async setCursorIcon(e){return p("plugin:window|set_cursor_icon",{label:this.label,value:e})}async setBackgroundColor(e){return p("plugin:window|set_background_color",{color:e})}async setCursorPosition(e){return p("plugin:window|set_cursor_position",{label:this.label,value:e instanceof I?e:new I(e)})}async setIgnoreCursorEvents(e){return p("plugin:window|set_ignore_cursor_events",{label:this.label,value:e})}async startDragging(){return p("plugin:window|start_dragging",{label:this.label})}async startResizeDragging(e){return p("plugin:window|start_resize_dragging",{label:this.label,value:e})}async setBadgeCount(e){return p("plugin:window|set_badge_count",{label:this.label,value:e})}async setBadgeLabel(e){return p("plugin:window|set_badge_label",{label:this.label,value:e})}async setOverlayIcon(e){return p("plugin:window|set_overlay_icon",{label:this.label,value:e?y(e):void 0})}async setProgressBar(e){return p("plugin:window|set_progress_bar",{label:this.label,value:e})}async setVisibleOnAllWorkspaces(e){return p("plugin:window|set_visible_on_all_workspaces",{label:this.label,value:e})}async setTitleBarStyle(e){return p("plugin:window|set_title_bar_style",{label:this.label,value:e})}async setTheme(e){return p("plugin:window|set_theme",{label:this.label,value:e})}async onResized(e){return this.listen(E.WINDOW_RESIZED,n=>{n.payload=new v(n.payload),e(n)})}async onMoved(e){return this.listen(E.WINDOW_MOVED,n=>{n.payload=new T(n.payload),e(n)})}async onCloseRequested(e){return this.listen(E.WINDOW_CLOSE_REQUESTED,async n=>{const t=new re(n);await e(t),t.isPreventDefault()||await this.destroy()})}async onDragDropEvent(e){const n=await this.listen(E.DRAG_ENTER,n=>{e({...n,payload:{type:"enter",paths:n.payload.paths,position:new T(n.payload.position)}})}),t=await this.listen(E.DRAG_OVER,n=>{e({...n,payload:{type:"over",position:new T(n.payload.position)}})}),i=await this.listen(E.DRAG_DROP,n=>{e({...n,payload:{type:"drop",paths:n.payload.paths,position:new T(n.payload.position)}})}),r=await this.listen(E.DRAG_LEAVE,n=>{e({...n,payload:{type:"leave"}})});return()=>{n(),i(),t(),r()}}async onFocusChanged(e){const n=await this.listen(E.WINDOW_FOCUS,n=>{e({...n,payload:!0})}),t=await this.listen(E.WINDOW_BLUR,n=>{e({...n,payload:!1})});return()=>{n(),t()}}async onScaleChanged(e){return this.listen(E.WINDOW_SCALE_FACTOR_CHANGED,e)}async onThemeChanged(e){return this.listen(E.WINDOW_THEME_CHANGED,e)}}var ue,ce,de,pe;function he(e){return null===e?null:{name:e.name,scaleFactor:e.scaleFactor,position:new T(e.position),size:new v(e.size),workArea:{position:new T(e.workArea.position),size:new v(e.workArea.size)}}}!function(e){e.Disabled="disabled",e.Throttle="throttle",e.Suspend="suspend"}(ue||(ue={})),function(e){e.Default="default",e.FluentOverlay="fluentOverlay"}(ce||(ce={})),function(e){e.AppearanceBased="appearanceBased",e.Light="light",e.Dark="dark",e.MediumLight="mediumLight",e.UltraDark="ultraDark",e.Titlebar="titlebar",e.Selection="selection",e.Menu="menu",e.Popover="popover",e.Sidebar="sidebar",e.HeaderView="headerView",e.Sheet="sheet",e.WindowBackground="windowBackground",e.HudWindow="hudWindow",e.FullScreenUI="fullScreenUI",e.Tooltip="tooltip",e.ContentBackground="contentBackground",e.UnderWindowBackground="underWindowBackground",e.UnderPageBackground="underPageBackground",e.Mica="mica",e.Blur="blur",e.Acrylic="acrylic",e.Tabbed="tabbed",e.TabbedDark="tabbedDark",e.TabbedLight="tabbedLight"}(de||(de={})),function(e){e.FollowsWindowActiveState="followsWindowActiveState",e.Active="active",e.Inactive="inactive"}(pe||(pe={}));var we=Object.freeze({__proto__:null,CloseRequestedEvent:re,get Effect(){return de},get EffectState(){return pe},LogicalPosition:A,LogicalSize:f,PhysicalPosition:T,PhysicalSize:v,get ProgressBarStatus(){return te},get UserAttentionType(){return ne},Window:oe,availableMonitors:async function(){return p("plugin:window|available_monitors").then(e=>e.map(he))},currentMonitor:async function(){return p("plugin:window|current_monitor").then(he)},cursorPosition:async function(){return p("plugin:window|cursor_position").then(e=>new T(e))},getAllWindows:ae,getCurrentWindow:se,monitorFromPoint:async function(e,n){return p("plugin:window|monitor_from_point",{x:e,y:n}).then(he)},primaryMonitor:async function(){return p("plugin:window|primary_monitor").then(he)}});function _e(){return new be(se(),window.__TAURI_INTERNALS__.metadata.currentWebview.label,{skip:!0})}async function ye(){return p("plugin:webview|get_all_webviews").then(e=>e.map(e=>new be(new oe(e.windowLabel,{skip:!0}),e.label,{skip:!0})))}const ge=["tauri://created","tauri://error"];class be{constructor(e,n,t){this.window=e,this.label=n,this.listeners=Object.create(null),(null==t?void 0:t.skip)||p("plugin:webview|create_webview",{windowLabel:e.label,options:{...t,label:n}}).then(async()=>this.emit("tauri://created")).catch(async e=>this.emit("tauri://error",e))}static async getByLabel(e){var n;return null!==(n=(await ye()).find(n=>n.label===e))&&void 0!==n?n:null}static getCurrent(){return _e()}static async getAll(){return ye()}async listen(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:N(e,n,{target:{kind:"Webview",label:this.label}})}async once(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:S(e,n,{target:{kind:"Webview",label:this.label}})}async emit(e,n){if(!ge.includes(e))return L(e,n);for(const t of this.listeners[e]||[])t({event:e,id:-1,payload:n})}async emit2(e,n){if(!ge.includes(e))return C(e,n);for(const t of this.listeners[e]||[])t({event:e,id:-1,payload:n})}async emitTo(e,n,t){if(!ge.includes(n))return x(e,n,t);for(const e of this.listeners[n]||[])e({event:n,id:-1,payload:t})}async emitTo2(e,n,t){if(!ge.includes(n))return P(e,n,t);for(const e of this.listeners[n]||[])e({event:n,id:-1,payload:t})}_handleTauriEvent(e,n){return!!ge.includes(e)&&(e in this.listeners?this.listeners[e].push(n):this.listeners[e]=[n],!0)}async position(){return p("plugin:webview|webview_position",{label:this.label}).then(e=>new T(e))}async size(){return p("plugin:webview|webview_size",{label:this.label}).then(e=>new v(e))}async close(){return p("plugin:webview|webview_close",{label:this.label})}async setSize(e){return p("plugin:webview|set_webview_size",{label:this.label,value:e instanceof k?e:new k(e)})}async setPosition(e){return p("plugin:webview|set_webview_position",{label:this.label,value:e instanceof I?e:new I(e)})}async setFocus(){return p("plugin:webview|set_webview_focus",{label:this.label})}async setAutoResize(e){return p("plugin:webview|set_webview_auto_resize",{label:this.label,value:e})}async hide(){return p("plugin:webview|webview_hide",{label:this.label})}async show(){return p("plugin:webview|webview_show",{label:this.label})}async setZoom(e){return p("plugin:webview|set_webview_zoom",{label:this.label,value:e})}async reparent(e){return p("plugin:webview|reparent",{label:this.label,window:"string"==typeof e?e:e.label})}async clearAllBrowsingData(){return p("plugin:webview|clear_all_browsing_data")}async setBackgroundColor(e){return p("plugin:webview|set_webview_background_color",{color:e})}async onDragDropEvent(e){const n=await this.listen(E.DRAG_ENTER,n=>{e({...n,payload:{type:"enter",paths:n.payload.paths,position:new T(n.payload.position)}})}),t=await this.listen(E.DRAG_OVER,n=>{e({...n,payload:{type:"over",position:new T(n.payload.position)}})}),i=await this.listen(E.DRAG_DROP,n=>{e({...n,payload:{type:"drop",paths:n.payload.paths,position:new T(n.payload.position)}})}),r=await this.listen(E.DRAG_LEAVE,n=>{e({...n,payload:{type:"leave"}})});return()=>{n(),i(),t(),r()}}}var me,fe,ve=Object.freeze({__proto__:null,Webview:be,getAllWebviews:ye,getCurrentWebview:_e});function ke(){const e=_e();return new Te(e.label,{skip:!0})}async function Ae(){return p("plugin:window|get_all_windows").then(e=>e.map(e=>new Te(e,{skip:!0})))}class Te{constructor(e,n={}){var t;this.label=e,this.listeners=Object.create(null),(null==n?void 0:n.skip)||p("plugin:webview|create_webview_window",{options:{...n,parent:"string"==typeof n.parent?n.parent:null===(t=n.parent)||void 0===t?void 0:t.label,label:e}}).then(async()=>this.emit("tauri://created")).catch(async e=>this.emit("tauri://error",e))}static async getByLabel(e){var n;const t=null!==(n=(await Ae()).find(n=>n.label===e))&&void 0!==n?n:null;return t?new Te(t.label,{skip:!0}):null}static getCurrent(){return ke()}static async getAll(){return Ae()}async listen(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:N(e,n,{target:{kind:"WebviewWindow",label:this.label}})}async once(e,n){return this._handleTauriEvent(e,n)?()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)}:S(e,n,{target:{kind:"WebviewWindow",label:this.label}})}async setBackgroundColor(e){return p("plugin:window|set_background_color",{color:e}).then(()=>p("plugin:webview|set_webview_background_color",{color:e}))}}me=Te,fe=[oe,be],(Array.isArray(fe)?fe:[fe]).forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(n=>{var t;"object"==typeof me.prototype&&me.prototype&&n in me.prototype||Object.defineProperty(me.prototype,n,null!==(t=Object.getOwnPropertyDescriptor(e.prototype,n))&&void 0!==t?t:Object.create(null))})});var Ie=Object.freeze({__proto__:null,WebviewWindow:Te,getAllWebviewWindows:Ae,getCurrentWebviewWindow:ke});return e.app=m,e.core=w,e.dpi=R,e.event=U,e.image=b,e.menu=Q,e.mocks=Y,e.path=X,e.tray=ie,e.webview=ve,e.webviewWindow=Ie,e.window=we,e}({});window.__TAURI__=__TAURI_IIFE__; diff --git a/crates/tauri/src/app.rs b/crates/tauri/src/app.rs index 06a3abe44876..3eac3d9b884e 100644 --- a/crates/tauri/src/app.rs +++ b/crates/tauri/src/app.rs @@ -8,7 +8,7 @@ use crate::{ channel::ChannelDataIpcQueue, CallbackFn, CommandArg, CommandItem, Invoke, InvokeError, InvokeHandler, InvokeResponseBody, }, - manager::{webview::UriSchemeProtocol, AppManager, Asset}, + manager::{webview::UriSchemeProtocol, AppManager, Asset, EventPayloadStore}, plugin::{Plugin, PluginStore}, resources::ResourceTable, runtime::{ @@ -2260,6 +2260,7 @@ tauri::Builder::default() }); app.manage(ChannelDataIpcQueue::default()); + app.manage(EventPayloadStore::default()); app.handle.plugin(crate::ipc::channel::plugin())?; let handle = app.handle(); diff --git a/crates/tauri/src/event/listener.rs b/crates/tauri/src/event/listener.rs index 7dc52d5084e4..49e514f6b1d1 100644 --- a/crates/tauri/src/event/listener.rs +++ b/crates/tauri/src/event/listener.rs @@ -201,7 +201,11 @@ impl Listeners { let handlers = handlers.filter(|(_, h)| match_any_or_filter(&h.target, &filter)); for (&id, Handler { callback, .. }) in handlers { maybe_pending = true; - (callback)(Event::new(id, emit_args.payload.clone())) + (callback)(Event::new( + id, + emit_args.payload.clone(), + emit_args.raw.clone(), + )) } } } @@ -266,6 +270,37 @@ impl Listeners { }) } + /// Filters the webviews that are matched by the filter has a JS listener for the given event + pub(crate) fn webiews_matching_event_filter<'a, R, I, F>( + &self, + webviews: I, + emit_args: &EmitArgs, + filter: Option, + ) -> Vec<&'a Webview> + where + R: Runtime, + I: Iterator>, + F: Fn(&EventTarget) -> bool, + { + let event = &emit_args.event; + let js_listeners = self.inner.js_event_listeners.lock().unwrap(); + webviews + .filter(|webview| { + if let Some(handlers) = js_listeners.get(webview.label()).and_then(|s| s.get(event)) { + let ids = handlers + .iter() + .filter(|handler| match_any_or_filter(&handler.target, &filter)) + .map(|handler| handler.id) + .collect::>(); + if !ids.is_empty() { + return true; + } + } + false + }) + .collect() + } + pub(crate) fn emit_js_filter<'a, R, I, F>( &self, mut webviews: I, diff --git a/crates/tauri/src/event/mod.rs b/crates/tauri/src/event/mod.rs index 27a1d5865c79..d1fd5520f148 100644 --- a/crates/tauri/src/event/mod.rs +++ b/crates/tauri/src/event/mod.rs @@ -13,7 +13,11 @@ mod event_name; pub(crate) use event_name::EventName; -use crate::ipc::CallbackFn; +use crate::{ + event::plugin::{FETCH_EVENT_PAYLOAD_COMMAND, PAYLOAD_ID_HEADER_NAME}, + ipc::CallbackFn, + manager::BINARY_EVENT_PAYLOAD_PREFIX, +}; /// Unique id of an event. pub type EventId = u32; @@ -119,6 +123,8 @@ pub struct EmitArgs { event: EventName, /// Serialized payload. payload: String, + /// Raw payload bytes. + raw: Option>, } impl EmitArgs { @@ -128,17 +134,33 @@ impl EmitArgs { Ok(EmitArgs { event: event.into_owned(), payload: serde_json::to_string(payload)?, + raw: None, }) } - pub fn new_str(event: EventName<&str>, payload: String) -> crate::Result { + pub fn new_raw( + event: EventName<&str>, + payload: &S, + raw_data: Vec, + ) -> crate::Result { #[cfg(feature = "tracing")] - let _span = tracing::debug_span!("window::emit::json").entered(); + let _span = tracing::debug_span!("window::emit::serialize").entered(); Ok(EmitArgs { event: event.into_owned(), - payload, + payload: serde_json::to_string(payload)?, + raw: Some(raw_data), }) } + + pub fn new_str(event: EventName<&str>, payload: String) -> Self { + #[cfg(feature = "tracing")] + let _span = tracing::debug_span!("window::emit::json").entered(); + EmitArgs { + event: event.into_owned(), + payload, + raw: None, + } + } } /// An event that was emitted. @@ -146,11 +168,12 @@ impl EmitArgs { pub struct Event { id: EventId, data: String, + raw: Option>, } impl Event { - fn new(id: EventId, data: String) -> Self { - Self { id, data } + fn new(id: EventId, data: String, raw: Option>) -> Self { + Self { id, data, raw } } /// The [`EventId`] of the handler that was triggered. @@ -159,9 +182,28 @@ impl Event { } /// The event payload. + /// + /// Note that you must use [`Self::payload_raw`] for events emitted with a binary payload. pub fn payload(&self) -> &str { &self.data } + + /// Consumes the event and return its payload. + /// + /// Note that you must use [`Self::into_payload_raw`] for events emitted with a binary payload. + pub fn into_payload(self) -> String { + self.data + } + + /// The event payload bytes. + pub fn payload_raw(&self) -> &[u8] { + self.raw.as_deref().unwrap_or(self.data.as_bytes()) + } + + /// Consumes the event and return its payload bytes. + pub fn into_payload_raw(self) -> Vec { + self.raw.unwrap_or_else(|| self.data.into_bytes()) + } } pub(crate) fn listen_js_script( @@ -224,8 +266,15 @@ pub(crate) fn unlisten_js_script( pub(crate) fn event_initialization_script(function_name: &str, listeners: &str) -> String { format!( "Object.defineProperty(window, '{function_name}', {{ - value: function (eventData, ids) {{ + value: async function (eventData, ids) {{ const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || [] + + if (typeof eventData.payload === 'string' && eventData.payload.startsWith('{BINARY_EVENT_PAYLOAD_PREFIX}')) {{ + const payloadId = eventData.payload.slice('{BINARY_EVENT_PAYLOAD_PREFIX}'.length) + const data = await window.__TAURI_INTERNALS__.invoke('{FETCH_EVENT_PAYLOAD_COMMAND}', null, {{ headers: {{ '{PAYLOAD_ID_HEADER_NAME}': payloadId }} }}) + eventData.payload = data + }} + for (const id of ids) {{ const listener = listeners[id] if (listener) {{ @@ -235,7 +284,7 @@ pub(crate) fn event_initialization_script(function_name: &str, listeners: &str) }} }} }}); - " + ", ) } diff --git a/crates/tauri/src/event/plugin.rs b/crates/tauri/src/event/plugin.rs index fcdcddd66a26..4ef461945e66 100644 --- a/crates/tauri/src/event/plugin.rs +++ b/crates/tauri/src/event/plugin.rs @@ -1,16 +1,23 @@ +use serde::Deserialize; // Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT -use serde_json::Value as JsonValue; use serialize_to_javascript::{default_template, DefaultTemplate, Template}; +use crate::ipc::{InvokeBody, Request, Response}; +use crate::manager::EventPayloadStore; use crate::plugin::{Builder, TauriPlugin}; use crate::{command, ipc::CallbackFn, EventId, Result, Runtime}; -use crate::{AppHandle, Emitter, Manager, Webview}; +use crate::{AppHandle, Emitter, Manager, State, Webview}; use super::EventName; use super::EventTarget; +const EVENT_NAME_HEADER_NAME: &str = "Tauri-Event-Name"; +const EVENT_TARGET_HEADER_NAME: &str = "Tauri-Event-Target"; +pub const FETCH_EVENT_PAYLOAD_COMMAND: &str = "plugin:event|fetch_payload"; +pub const PAYLOAD_ID_HEADER_NAME: &str = "Tauri-Payload-Id"; + #[command(root = "crate")] async fn listen( webview: Webview, @@ -31,22 +38,106 @@ async fn unlisten( } #[command(root = "crate")] -async fn emit( - app: AppHandle, +async fn emit(app: AppHandle, request: Request<'_>) -> Result<()> { + if let Some(event_header) = request + .headers() + .get(EVENT_NAME_HEADER_NAME) + .and_then(|v| v.to_str().ok()) + { + let event = EventName::new(event_header)?; + match request.body() { + InvokeBody::Json(payload) => app.emit(event.as_str(), payload), + InvokeBody::Raw(payload) => app.emit_raw(event.as_str(), payload.clone()), + } + } else if let InvokeBody::Json(payload) = request.body() { + let args: EmitArgs = serde_json::from_value(payload.clone())?; + app.emit(args.event.as_str(), args.payload) + } else { + Err(anyhow::anyhow!("unexpected emit request format").into()) + } +} + +#[derive(Deserialize)] +struct EmitArgs { event: EventName, - payload: Option, -) -> Result<()> { - app.emit(event.as_str(), payload) + payload: Option, } #[command(root = "crate")] -async fn emit_to( - app: AppHandle, - target: EventTarget, +async fn emit_to(app: AppHandle, request: Request<'_>) -> Result<()> { + if let Some(event_header) = request + .headers() + .get(EVENT_NAME_HEADER_NAME) + .and_then(|v| v.to_str().ok()) + { + let event = EventName::new(event_header)?; + let target = if let Some(target_header) = request + .headers() + .get(EVENT_TARGET_HEADER_NAME) + .and_then(|v| v.to_str().ok()) + { + serde_json::from_str::(target_header)? + } else { + return Err(anyhow::anyhow!("missing event target header").into()); + }; + + match request.body() { + InvokeBody::Json(payload) => app.emit_to(target, event.as_str(), payload), + InvokeBody::Raw(payload) => app.emit_raw_to(target, event.as_str(), payload.clone()), + } + } else if let InvokeBody::Json(payload) = request.body() { + let args: EmitToArgs = serde_json::from_value(payload.clone())?; + app.emit_to(args.target, args.event.as_str(), args.payload) + } else { + Err(anyhow::anyhow!("unexpected emit request format").into()) + } +} + +#[derive(Deserialize)] +struct EmitToArgs { event: EventName, - payload: Option, -) -> Result<()> { - app.emit_to(target, event.as_str(), payload) + payload: Option, + target: EventTarget, +} + +#[command(root = "crate")] +fn fetch_payload( + request: Request<'_>, + store: State<'_, EventPayloadStore>, +) -> std::result::Result { + if let Some(id) = request + .headers() + .get(PAYLOAD_ID_HEADER_NAME) + .and_then(|v| v.to_str().ok()) + .and_then(|id| id.parse().ok()) + { + let r = if let Some(data) = store.0.lock().unwrap().get(&id) { + // fetch_add returns the previous value so we must +1 + let read_count = data + .read_count + .fetch_add(1, std::sync::atomic::Ordering::Relaxed) + + 1; + + Ok(( + Response::new(data.payload.clone()), + read_count == data.target_count, + )) + } else { + Err("data not found") + }; + + match r { + Ok((response, done)) => { + if done { + store.0.lock().unwrap().remove(&id); + } + Ok(response) + } + Err(e) => Err(e), + } + } else { + Err("missing payload id header") + } } /// Initializes the event plugin. @@ -70,7 +161,7 @@ pub(crate) fn init>(manager: &M) -> TauriPlugin { Builder::new("event") .invoke_handler(crate::generate_handler![ #![plugin(event)] - listen, unlisten, emit, emit_to + listen, unlisten, emit, emit_to, fetch_payload ]) .js_init_script( init_script diff --git a/crates/tauri/src/lib.rs b/crates/tauri/src/lib.rs index 68a58edcc137..d5af7e5054c5 100644 --- a/crates/tauri/src/lib.rs +++ b/crates/tauri/src/lib.rs @@ -990,6 +990,16 @@ pub trait Emitter: sealed::ManagerBase { self.manager().emit(event, payload) } + /// Similar to [`Emitter::emit`] but the payload is raw binary data. + /// + /// This function is optimized to emit event with large binary payloads, + /// avoiding serialization costs. + fn emit_raw(&self, event: &str, payload: Vec) -> Result<()> { + let event = EventName::new(event)?; + let payload = EmitPayload::<()>::Binary(payload); + self.manager().emit(event, payload) + } + /// Emits an event to all [targets](EventTarget) matching the given target. /// /// # Examples @@ -1032,6 +1042,16 @@ pub trait Emitter: sealed::ManagerBase { self.manager().emit_to(target.into(), event, payload) } + /// Similar to [`Emitter::emit_to`] but the payload is json serialized. + fn emit_raw_to(&self, target: I, event: &str, payload: Vec) -> Result<()> + where + I: Into, + { + let event = EventName::new(event)?; + let payload = EmitPayload::<()>::Binary(payload); + self.manager().emit_to(target.into(), event, payload) + } + /// Emits an event to all [targets](EventTarget) based on the given filter. /// /// # Examples diff --git a/crates/tauri/src/manager/mod.rs b/crates/tauri/src/manager/mod.rs index b97d9fbece6a..1c35a6ac42b0 100644 --- a/crates/tauri/src/manager/mod.rs +++ b/crates/tauri/src/manager/mod.rs @@ -6,7 +6,10 @@ use std::{ borrow::Cow, collections::HashMap, fmt, - sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard}, + sync::{ + atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}, + Arc, Mutex, MutexGuard, + }, }; use serde::Serialize; @@ -38,6 +41,9 @@ mod tray; pub mod webview; pub mod window; +static EVENT_ID_COUNTER: AtomicU32 = AtomicU32::new(0); +pub const BINARY_EVENT_PAYLOAD_PREFIX: &str = "__tauri_event_payload_id__:"; + #[derive(Default)] /// Spaced and quoted Content-Security-Policy hash values. struct CspHashStrings { @@ -249,6 +255,7 @@ impl fmt::Debug for AppManager { pub(crate) enum EmitPayload<'a, S: Serialize> { Serialize(&'a S), Str(String), + Binary(Vec), } impl AppManager { @@ -546,16 +553,48 @@ impl AppManager { event: EventName<&str>, payload: EmitPayload<'_, S>, ) -> crate::Result<()> { + let webviews = self + .webview + .webviews_lock() + .values() + .cloned() + .collect::>(); + #[cfg(feature = "tracing")] let _span = tracing::debug_span!("emit::run").entered(); let emit_args = match payload { EmitPayload::Serialize(payload) => EmitArgs::new(event, payload)?, - EmitPayload::Str(payload) => EmitArgs::new_str(event, payload)?, + EmitPayload::Str(payload) => EmitArgs::new_str(event, payload), + EmitPayload::Binary(payload) => { + let id = EVENT_ID_COUNTER.fetch_add(1, Ordering::Relaxed); + + if !webviews.is_empty() { + self + .state() + .get::() + .0 + .lock() + .unwrap() + .insert( + id, + PendingEventPayload { + target_count: webviews.len(), + read_count: AtomicUsize::new(0), + payload: payload.clone(), + }, + ); + } + EmitArgs::new_raw( + event, + &format!("{BINARY_EVENT_PAYLOAD_PREFIX}{id}"), + payload, + )? + } }; let listeners = self.listeners(); - listeners.emit_js(self.webview.webviews_lock().values(), &emit_args)?; + listeners.emit_js(webviews.iter(), &emit_args)?; listeners.emit(emit_args)?; Ok(()) @@ -577,18 +616,50 @@ impl AppManager { { #[cfg(feature = "tracing")] let _span = tracing::debug_span!("emit::run").entered(); + + let listeners = self.listeners(); + let webviews = self + .webview + .webviews_lock() + .values() + .cloned() + .collect::>(); + let emit_args = match payload { EmitPayload::Serialize(payload) => EmitArgs::new(event, payload)?, - EmitPayload::Str(payload) => EmitArgs::new_str(event, payload)?, - }; + EmitPayload::Str(payload) => EmitArgs::new_str(event, payload), + EmitPayload::Binary(payload) => { + let id = EVENT_ID_COUNTER.fetch_add(1, Ordering::Relaxed); + let emit_args = EmitArgs::new_raw( + event, + &format!("{BINARY_EVENT_PAYLOAD_PREFIX}{id}"), + payload.clone(), + )?; + + if !webviews.is_empty() { + self + .state() + .get::() + .0 + .lock() + .unwrap() + .insert( + id, + PendingEventPayload { + target_count: listeners + .webiews_matching_event_filter(webviews.iter(), &emit_args, Some(&filter)) + .len(), + read_count: AtomicUsize::new(0), + payload, + }, + ); + } - let listeners = self.listeners(); + emit_args + } + }; - listeners.emit_js_filter( - self.webview.webviews_lock().values(), - &emit_args, - Some(&filter), - )?; + listeners.emit_js_filter(webviews.iter(), &emit_args, Some(&filter))?; listeners.emit_filter(emit_args, Some(filter))?; @@ -714,6 +785,16 @@ impl AppManager { } } +/// Maps a binary event payload id to a pending payload that must be send to the JavaScript side via the IPC. +#[derive(Default, Clone)] +pub struct EventPayloadStore(pub Arc>>); + +pub struct PendingEventPayload { + pub target_count: usize, + pub read_count: AtomicUsize, + pub payload: Vec, +} + #[cfg(test)] mod tests { use super::replace_with_callback; diff --git a/crates/tauri/src/webview/mod.rs b/crates/tauri/src/webview/mod.rs index c185e7c62124..1f5f43919666 100644 --- a/crates/tauri/src/webview/mod.rs +++ b/crates/tauri/src/webview/mod.rs @@ -1802,6 +1802,7 @@ tauri::Builder::default() if (plugin_command.is_some() || has_app_acl_manifest) // TODO: Remove this special check in v3 && request.cmd != crate::ipc::channel::FETCH_CHANNEL_DATA_COMMAND + && request.cmd != crate::event::plugin::FETCH_EVENT_PAYLOAD_COMMAND && invoke.acl.is_none() { #[cfg(debug_assertions)] diff --git a/examples/api/src-tauri/src/lib.rs b/examples/api/src-tauri/src/lib.rs index 73a573672fab..1181fd28822b 100644 --- a/examples/api/src-tauri/src/lib.rs +++ b/examples/api/src-tauri/src/lib.rs @@ -164,6 +164,15 @@ pub fn run_app) + Send + 'static>( .emit("rust-event", Some(reply)) .expect("failed to emit"); }); + + let webview_ = webview.clone(); + webview.listen("raw-js-event", move |event| { + println!("got raw-js-event with message '{:?}'", event.payload_raw()); + + webview_ + .emit_raw("raw-rust-event", event.into_payload_raw()) + .expect("failed to emit"); + }); } }); diff --git a/examples/api/src/views/Communication.svelte b/examples/api/src/views/Communication.svelte index 5c62d0936b5e..cac315d801a5 100644 --- a/examples/api/src/views/Communication.svelte +++ b/examples/api/src/views/Communication.svelte @@ -4,16 +4,25 @@ import { onMount, onDestroy } from 'svelte' let { onMessage } = $props() - let unlisten + const unlisten = [] const webviewWindow = getCurrentWebviewWindow() onMount(async () => { - unlisten = await webviewWindow.listen('rust-event', onMessage) + const unlistenFn1 = await webviewWindow.listen('rust-event', onMessage) + unlisten.push(unlistenFn1) + const unlistenFn2 = await webviewWindow.listen('raw-rust-event', (event) => { + onMessage({ + event: event.event, + id: event.id, + payload: Array.from(new Uint8Array(event.payload)), + }) + }) + unlisten.push(unlistenFn2) }) onDestroy(() => { - if (unlisten) { - unlisten() + for (const unlistenFn of unlisten) { + unlistenFn() } }) @@ -55,6 +64,10 @@ function emitEvent() { webviewWindow.emit('js-event', 'this is the payload string') } + + function emitRawEvent() { + webviewWindow.emit2('raw-js-event', new Uint8Array([1, 2, 3])) + }
@@ -65,6 +78,9 @@ +
diff --git a/packages/api/src/event.ts b/packages/api/src/event.ts index 1cf0f542a32d..6a23e2e17201 100644 --- a/packages/api/src/event.ts +++ b/packages/api/src/event.ts @@ -172,6 +172,8 @@ async function once( /** * Emits an event to all {@link EventTarget|targets}. * + * Prefer {@link emit2} to send binary data. + * * @example * ```typescript * import { emit } from '@tauri-apps/api/event'; @@ -184,15 +186,36 @@ async function once( * @since 1.0.0 */ async function emit(event: string, payload?: T): Promise { - await invoke('plugin:event|emit', { - event, - payload + await invoke('plugin:event|emit', { event, payload }) +} + +/** + * Emits an event to all {@link EventTarget|targets}. + * + * This function is similar to {@link emit} but it is optimized for binary payloads. + * + * @example + * ```typescript + * import { emit2 } from '@tauri-apps/api/event'; + * await emit2('frontend-loaded', { loggedIn: true, token: 'authToken' }); + * ``` + * + * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`. + * @param payload Event payload. + * + * @since 2.10.0 + */ +async function emit2(event: string, payload?: T): Promise { + await invoke('plugin:event|emit', payload as any, { + headers: { 'Tauri-Event-Name': event } }) } /** * Emits an event to all {@link EventTarget|targets} matching the given target. * + * Prefer {@link emitTo2} to send binary data. + * * @example * ```typescript * import { emitTo } from '@tauri-apps/api/event'; @@ -212,10 +235,38 @@ async function emitTo( ): Promise { const eventTarget: EventTarget = typeof target === 'string' ? { kind: 'AnyLabel', label: target } : target - await invoke('plugin:event|emit_to', { - target: eventTarget, - event, - payload + await invoke('plugin:event|emit_to', { event, payload, target: eventTarget }) +} + +/** + * Emits an event to all {@link EventTarget|targets} matching the given target. + * + * This function is similar to {@link emitTo} but it is optimized for binary payloads. + * + * @example + * ```typescript + * import { emitTo2 } from '@tauri-apps/api/event'; + * await emitTo2('main', 'frontend-loaded', { loggedIn: true, token: 'authToken' }); + * ``` + * + * @param target Label of the target Window/Webview/WebviewWindow or raw {@link EventTarget} object. + * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`. + * @param payload Event payload. + * + * @since 2.10.0 + */ +async function emitTo2( + target: EventTarget | string, + event: string, + payload?: T +): Promise { + const eventTarget: EventTarget = + typeof target === 'string' ? { kind: 'AnyLabel', label: target } : target + await invoke('plugin:event|emit_to', payload as any, { + headers: { + 'Tauri-Event-Name': event, + 'Tauri-Event-Target': JSON.stringify(eventTarget) + } }) } @@ -228,4 +279,4 @@ export type { Options } -export { listen, once, emit, emitTo, TauriEvent } +export { listen, once, emit, emitTo, emit2, emitTo2, TauriEvent } diff --git a/packages/api/src/webview.ts b/packages/api/src/webview.ts index cf78dffe6874..d004012425a3 100644 --- a/packages/api/src/webview.ts +++ b/packages/api/src/webview.ts @@ -25,7 +25,9 @@ import { // imported for documentation purposes type EventTarget, emit, + emit2, emitTo, + emitTo2, listen, once } from './event' @@ -313,6 +315,8 @@ class Webview { /** * Emits an event to all {@link EventTarget|targets}. * + * Prefer {@link Webview.emit2} to send binary data. + * * @example * ```typescript * import { getCurrentWebview } from '@tauri-apps/api/webview'; @@ -337,9 +341,40 @@ class Webview { return emit(event, payload) } + /** + * Emits an event to all {@link EventTarget|targets}. + * + * This function is similar to {@link Webview.emit} but it is optimized for binary payloads. + * + * @example + * ```typescript + * import { getCurrentWebview } from '@tauri-apps/api/webview'; + * await getCurrentWebview().emit('webview-loaded', { loggedIn: true, token: 'authToken' }); + * ``` + * + * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`. + * @param payload Event payload. + */ + async emit2(event: string, payload?: T): Promise { + if (localTauriEvents.includes(event)) { + // eslint-disable-next-line + for (const handler of this.listeners[event] || []) { + handler({ + event, + id: -1, + payload + }) + } + return + } + return emit2(event, payload) + } + /** * Emits an event to all {@link EventTarget|targets} matching the given target. * + * Prefer {@link Webview.emitTo2} to send binary data. + * * @example * ```typescript * import { getCurrentWebview } from '@tauri-apps/api/webview'; @@ -369,6 +404,40 @@ class Webview { return emitTo(target, event, payload) } + /** + * Emits an event to all {@link EventTarget|targets} matching the given target. + * + * This function is similar to {@link Webview.emitTo} but it is optimized for binary payloads. + * + * @example + * ```typescript + * import { getCurrentWebview } from '@tauri-apps/api/webview'; + * await getCurrentWebview().emitTo('main', 'webview-loaded', { loggedIn: true, token: 'authToken' }); + * ``` + * + * @param target Label of the target Window/Webview/WebviewWindow or raw {@link EventTarget} object. + * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`. + * @param payload Event payload. + */ + async emitTo2( + target: string | EventTarget, + event: string, + payload?: T + ): Promise { + if (localTauriEvents.includes(event)) { + // eslint-disable-next-line + for (const handler of this.listeners[event] || []) { + handler({ + event, + id: -1, + payload + }) + } + return + } + return emitTo2(target, event, payload) + } + /** @ignore */ _handleTauriEvent(event: string, handler: EventCallback): boolean { if (localTauriEvents.includes(event)) { diff --git a/packages/api/src/window.ts b/packages/api/src/window.ts index e89a8ae6c2d0..7f60a3264a6b 100644 --- a/packages/api/src/window.ts +++ b/packages/api/src/window.ts @@ -30,7 +30,9 @@ import { // imported for documentation purposes type EventTarget, emit, + emit2, emitTo, + emitTo2, listen, once } from './event' @@ -437,6 +439,9 @@ class Window { /** * Emits an event to all {@link EventTarget|targets}. + * + * Prefer {@link Window.emit2} to send binary data. + * * @example * ```typescript * import { getCurrentWindow } from '@tauri-apps/api/window'; @@ -461,9 +466,40 @@ class Window { return emit(event, payload) } + /** + * Emits an event to all {@link EventTarget|targets}. + * + * This function is similar to {@link Window.emit} but it is optimized for binary payloads. + * + * @example + * ```typescript + * import { getCurrentWindow } from '@tauri-apps/api/window'; + * await getCurrentWindow().emit('window-loaded', { loggedIn: true, token: 'authToken' }); + * ``` + * + * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`. + * @param payload Event payload. + */ + async emit2(event: string, payload?: T): Promise { + if (localTauriEvents.includes(event)) { + // eslint-disable-next-line + for (const handler of this.listeners[event] || []) { + handler({ + event, + id: -1, + payload + }) + } + return + } + return emit2(event, payload) + } + /** * Emits an event to all {@link EventTarget|targets} matching the given target. * + * Prefer {@link Window.emitTo2} to send binary data. + * * @example * ```typescript * import { getCurrentWindow } from '@tauri-apps/api/window'; @@ -492,6 +528,39 @@ class Window { return emitTo(target, event, payload) } + /** + * Emits an event to all {@link EventTarget|targets} matching the given target. + * + * This function is similar to {@link Window.emitTo} but it is optimized for binary payloads. + * + * @example + * ```typescript + * import { getCurrentWindow } from '@tauri-apps/api/window'; + * await getCurrentWindow().emit('main', 'window-loaded', { loggedIn: true, token: 'authToken' }); + * ``` + * @param target Label of the target Window/Webview/WebviewWindow or raw {@link EventTarget} object. + * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`. + * @param payload Event payload. + */ + async emitTo2( + target: string | EventTarget, + event: string, + payload?: T + ): Promise { + if (localTauriEvents.includes(event)) { + // eslint-disable-next-line security/detect-object-injection + for (const handler of this.listeners[event] || []) { + handler({ + event, + id: -1, + payload + }) + } + return + } + return emitTo2(target, event, payload) + } + /** @ignore */ _handleTauriEvent(event: string, handler: EventCallback): boolean { if (localTauriEvents.includes(event)) {