12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505 |
- // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
- // SPDX-License-Identifier: Apache-2.0
- // SPDX-License-Identifier: MIT
- /**
- * Provides APIs to create windows, communicate with other windows and manipulate the current window.
- *
- * This package is also accessible with `window.__TAURI__.window` when `tauri.conf.json > build > withGlobalTauri` is set to true.
- *
- * The APIs must be allowlisted on `tauri.conf.json`:
- * ```json
- * {
- * "tauri": {
- * "allowlist": {
- * "window": {
- * "all": true, // enable all window APIs
- * "create": true, // enable window creation
- * "center": true,
- * "requestUserAttention": true,
- * "setResizable": true,
- * "setTitle": true,
- * "maximize": true,
- * "unmaximize": true,
- * "minimize": true,
- * "unminimize": true,
- * "show": true,
- * "hide": true,
- * "close": true,
- * "setDecorations": true,
- * "setAlwaysOnTop": true,
- * "setSize": true,
- * "setMinSize": true,
- * "setMaxSize": true,
- * "setPosition": true,
- * "setFullscreen": true,
- * "setFocus": true,
- * "setIcon": true,
- * "setSkipTaskbar": true,
- * "setCursorGrab": true,
- * "setCursorVisible": true,
- * "setCursorIcon": true,
- * "setCursorPosition": true,
- * "startDragging": true,
- * "print": true
- * }
- * }
- * }
- * }
- * ```
- * It is recommended to allowlist only the APIs you use for optimal bundle size and security.
- *
- * # Window events
- *
- * Events can be listened using `appWindow.listen`:
- * ```typescript
- * import { appWindow } from '@tauri-apps/api/window'
- * appWindow.listen('tauri://move', ({ event, payload }) => {
- * const { x, y } = payload // payload here is a `PhysicalPosition`
- * })
- * ```
- *
- * Window-specific events emitted by the backend:
- *
- * #### 'tauri://resize'
- * Emitted when the size of the window has changed.
- * *EventPayload*:
- * ```typescript
- * type ResizePayload = PhysicalSize
- * ```
- *
- * #### 'tauri://move'
- * Emitted when the position of the window has changed.
- * *EventPayload*:
- * ```typescript
- * type MovePayload = PhysicalPosition
- * ```
- *
- * #### 'tauri://close-requested'
- * Emitted when the user requests the window to be closed.
- * If a listener is registered for this event, Tauri won't close the window so you must call `appWindow.close()` manually.
- *
- * #### 'tauri://focus'
- * Emitted when the window gains focus.
- *
- * #### 'tauri://blur'
- * Emitted when the window loses focus.
- *
- * #### 'tauri://scale-change'
- * Emitted when the window's scale factor has changed.
- * The following user actions can cause DPI changes:
- * - Changing the display's resolution.
- * - Changing the display's scale factor (e.g. in Control Panel on Windows).
- * - Moving the window to a display with a different scale factor.
- * *Event payload*:
- * ```typescript
- * interface ScaleFactorChanged {
- * scaleFactor: number
- * size: PhysicalSize
- * }
- * ```
- *
- * #### 'tauri://menu'
- * Emitted when a menu item is clicked.
- * *EventPayload*:
- * ```typescript
- * type MenuClicked = string
- * ```
- *
- * @module
- */
- import { invokeTauriCommand } from './helpers/tauri'
- import type { EventName, EventCallback, UnlistenFn } from './event'
- import { emit, listen, once } from './helpers/event'
- type Theme = 'light' | 'dark'
- /** Allows you to retrieve information about a given monitor. */
- interface Monitor {
- /** Human-readable name of the monitor */
- name: string | null
- /** The monitor's resolution. */
- size: PhysicalSize
- /** the Top-left corner position of the monitor relative to the larger full screen area. */
- position: PhysicalPosition
- /** The scale factor that can be used to map physical pixels to logical pixels. */
- scaleFactor: number
- }
- /** A size represented in logical pixels. */
- class LogicalSize {
- type = 'Logical'
- width: number
- height: number
- constructor(width: number, height: number) {
- this.width = width
- this.height = height
- }
- }
- /** A size represented in physical pixels. */
- class PhysicalSize {
- type = 'Physical'
- width: number
- height: number
- constructor(width: number, height: number) {
- this.width = width
- this.height = height
- }
- /** Converts the physical size to a logical one. */
- toLogical(scaleFactor: number): LogicalSize {
- return new LogicalSize(this.width / scaleFactor, this.height / scaleFactor)
- }
- }
- /** A position represented in logical pixels. */
- class LogicalPosition {
- type = 'Logical'
- x: number
- y: number
- constructor(x: number, y: number) {
- this.x = x
- this.y = y
- }
- }
- /** A position represented in physical pixels. */
- class PhysicalPosition {
- type = 'Physical'
- x: number
- y: number
- constructor(x: number, y: number) {
- this.x = x
- this.y = y
- }
- /** Converts the physical position to a logical one. */
- toLogical(scaleFactor: number): LogicalPosition {
- return new LogicalPosition(this.x / scaleFactor, this.y / scaleFactor)
- }
- }
- /** @ignore */
- interface WindowDef {
- label: string
- }
- /** @ignore */
- declare global {
- interface Window {
- __TAURI_METADATA__: {
- __windows: WindowDef[]
- __currentWindow: WindowDef
- }
- }
- }
- /** Attention type to request on a window. */
- enum UserAttentionType {
- /**
- * #### Platform-specific
- * - **macOS:** Bounces the dock icon until the application is in focus.
- * - **Windows:** Flashes both the window and the taskbar button until the application is in focus.
- */
- Critical = 1,
- /**
- * #### Platform-specific
- * - **macOS:** Bounces the dock icon once.
- * - **Windows:** Flashes the taskbar button until the application is in focus.
- */
- Informational
- }
- export type CursorIcon =
- | 'default'
- | 'crosshair'
- | 'hand'
- | 'arrow'
- | 'move'
- | 'text'
- | 'wait'
- | 'help'
- | 'progress'
- // something cannot be done
- | 'notAllowed'
- | 'contextMenu'
- | 'cell'
- | 'verticalText'
- | 'alias'
- | 'copy'
- | 'noDrop'
- // something can be grabbed
- | 'grab'
- /// something is grabbed
- | 'grabbing'
- | 'allScroll'
- | 'zoomIn'
- | 'zoomOut'
- // edge is to be moved
- | 'eResize'
- | 'nResize'
- | 'neResize'
- | 'nwResize'
- | 'sResize'
- | 'seResize'
- | 'swResize'
- | 'wResize'
- | 'ewResize'
- | 'nsResize'
- | 'neswResize'
- | 'nwseResize'
- | 'colResize'
- | 'rowResize'
- /**
- * Get an instance of `WebviewWindow` for the current webview window.
- *
- * @return The current WebviewWindow.
- */
- function getCurrent(): WebviewWindow {
- return new WebviewWindow(window.__TAURI_METADATA__.__currentWindow.label, {
- // @ts-expect-error
- skip: true
- })
- }
- /**
- * Gets an instance of `WebviewWindow` for all available webview windows.
- *
- * @return The list of WebviewWindow.
- */
- function getAll(): WebviewWindow[] {
- return window.__TAURI_METADATA__.__windows.map(
- (w) =>
- new WebviewWindow(w.label, {
- // @ts-expect-error
- skip: true
- })
- )
- }
- /** @ignore */
- // events that are emitted right here instead of by the created webview
- const localTauriEvents = ['tauri://created', 'tauri://error']
- /** @ignore */
- export type WindowLabel = string
- /**
- * A webview window handle allows emitting and listening to events from the backend that are tied to the window.
- */
- class WebviewWindowHandle {
- /** The window label. It is a unique identifier for the window, can be used to reference it later. */
- label: WindowLabel
- /** Local event listeners. */
- listeners: { [key: string]: Array<EventCallback<any>> }
- constructor(label: WindowLabel) {
- this.label = label
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- this.listeners = Object.create(null)
- }
- /**
- * Listen to an event emitted by the backend that is tied to the webview window.
- *
- * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
- * @param handler Event handler.
- * @returns A promise resolving to a function to unlisten to the event.
- */
- async listen<T>(
- event: EventName,
- handler: EventCallback<T>
- ): Promise<UnlistenFn> {
- if (this._handleTauriEvent(event, handler)) {
- return Promise.resolve(() => {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, security/detect-object-injection
- const listeners = this.listeners[event]
- listeners.splice(listeners.indexOf(handler), 1)
- })
- }
- return listen(event, this.label, handler)
- }
- /**
- * Listen to an one-off event emitted by the backend that is tied to the webview window.
- *
- * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
- * @param handler Event handler.
- * @returns A promise resolving to a function to unlisten to the event.
- */
- async once<T>(event: string, handler: EventCallback<T>): Promise<UnlistenFn> {
- if (this._handleTauriEvent(event, handler)) {
- return Promise.resolve(() => {
- // eslint-disable-next-line security/detect-object-injection
- const listeners = this.listeners[event]
- listeners.splice(listeners.indexOf(handler), 1)
- })
- }
- return once(event, this.label, handler)
- }
- /**
- * Emits an event to the backend, tied to the webview window.
- *
- * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
- * @param payload Event payload.
- */
- async emit(event: string, payload?: unknown): Promise<void> {
- if (localTauriEvents.includes(event)) {
- // eslint-disable-next-line
- for (const handler of this.listeners[event] || []) {
- handler({ event, id: -1, windowLabel: this.label, payload })
- }
- return Promise.resolve()
- }
- return emit(event, this.label, payload)
- }
- _handleTauriEvent<T>(event: string, handler: EventCallback<T>): boolean {
- if (localTauriEvents.includes(event)) {
- if (!(event in this.listeners)) {
- // eslint-disable-next-line
- this.listeners[event] = [handler]
- } else {
- // eslint-disable-next-line
- this.listeners[event].push(handler)
- }
- return true
- }
- return false
- }
- }
- /**
- * Manage the current window object.
- */
- class WindowManager extends WebviewWindowHandle {
- // Getters
- /** The scale factor that can be used to map physical pixels to logical pixels. */
- async scaleFactor(): Promise<number> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'scaleFactor'
- }
- }
- }
- })
- }
- /** The position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop. */
- async innerPosition(): Promise<PhysicalPosition> {
- return invokeTauriCommand<{ x: number; y: number }>({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'innerPosition'
- }
- }
- }
- }).then(({ x, y }) => new PhysicalPosition(x, y))
- }
- /** The position of the top-left hand corner of the window relative to the top-left hand corner of the desktop. */
- async outerPosition(): Promise<PhysicalPosition> {
- return invokeTauriCommand<{ x: number; y: number }>({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'outerPosition'
- }
- }
- }
- }).then(({ x, y }) => new PhysicalPosition(x, y))
- }
- /**
- * The physical size of the window's client area.
- * The client area is the content of the window, excluding the title bar and borders.
- */
- async innerSize(): Promise<PhysicalSize> {
- return invokeTauriCommand<{ width: number; height: number }>({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'innerSize'
- }
- }
- }
- }).then(({ width, height }) => new PhysicalSize(width, height))
- }
- /**
- * The physical size of the entire window.
- * These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
- */
- async outerSize(): Promise<PhysicalSize> {
- return invokeTauriCommand<{ width: number; height: number }>({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'outerSize'
- }
- }
- }
- }).then(({ width, height }) => new PhysicalSize(width, height))
- }
- /** Gets the window's current fullscreen state. */
- async isFullscreen(): Promise<boolean> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'isFullscreen'
- }
- }
- }
- })
- }
- /** Gets the window's current maximized state. */
- async isMaximized(): Promise<boolean> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'isMaximized'
- }
- }
- }
- })
- }
- /** Gets the window's current decorated state. */
- async isDecorated(): Promise<boolean> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'isDecorated'
- }
- }
- }
- })
- }
- /** Gets the window's current resizable state. */
- async isResizable(): Promise<boolean> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'isResizable'
- }
- }
- }
- })
- }
- /** Gets the window's current visible state. */
- async isVisible(): Promise<boolean> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'isVisible'
- }
- }
- }
- })
- }
- /** Gets the window's current visible state. */
- async theme(): Promise<Theme | null> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'theme'
- }
- }
- }
- })
- }
- // Setters
- /**
- * Centers the window.
- *
- * @param resizable
- * @returns A promise indicating the success or failure of the operation.
- */
- async center(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'center'
- }
- }
- }
- })
- }
- /**
- * Requests user attention to the window, this has no effect if the application
- * is already focused. How requesting for user attention manifests is platform dependent,
- * see `UserAttentionType` for details.
- *
- * Providing `null` will unset the request for user attention. Unsetting the request for
- * user attention might not be done automatically by the WM when the window receives input.
- *
- * #### Platform-specific
- *
- * - **macOS:** `null` has no effect.
- * - **Linux:** Urgency levels have the same effect.
- *
- * @param resizable
- * @returns A promise indicating the success or failure of the operation.
- */
- async requestUserAttention(
- requestType: UserAttentionType | null
- ): Promise<void> {
- let requestType_ = null
- if (requestType) {
- if (requestType === UserAttentionType.Critical) {
- requestType_ = { type: 'Critical' }
- } else {
- requestType_ = { type: 'Informational' }
- }
- }
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'requestUserAttention',
- payload: requestType_
- }
- }
- }
- })
- }
- /**
- * Updates the window resizable flag.
- *
- * @param resizable
- * @returns A promise indicating the success or failure of the operation.
- */
- async setResizable(resizable: boolean): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setResizable',
- payload: resizable
- }
- }
- }
- })
- }
- /**
- * Sets the window title.
- *
- * @param title The new title
- * @returns A promise indicating the success or failure of the operation.
- */
- async setTitle(title: string): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setTitle',
- payload: title
- }
- }
- }
- })
- }
- /**
- * Maximizes the window.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async maximize(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'maximize'
- }
- }
- }
- })
- }
- /**
- * Unmaximizes the window.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async unmaximize(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'unmaximize'
- }
- }
- }
- })
- }
- /**
- * Toggles the window maximized state.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async toggleMaximize(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'toggleMaximize'
- }
- }
- }
- })
- }
- /**
- * Minimizes the window.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async minimize(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'minimize'
- }
- }
- }
- })
- }
- /**
- * Unminimizes the window.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async unminimize(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'unminimize'
- }
- }
- }
- })
- }
- /**
- * Sets the window visibility to true.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async show(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'show'
- }
- }
- }
- })
- }
- /**
- * Sets the window visibility to false.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async hide(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'hide'
- }
- }
- }
- })
- }
- /**
- * Closes the window.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async close(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'close'
- }
- }
- }
- })
- }
- /**
- * Whether the window should have borders and bars.
- *
- * @param decorations Whether the window should have borders and bars.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setDecorations(decorations: boolean): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setDecorations',
- payload: decorations
- }
- }
- }
- })
- }
- /**
- * Whether the window should always be on top of other windows.
- *
- * @param alwaysOnTop Whether the window should always be on top of other windows or not.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setAlwaysOnTop(alwaysOnTop: boolean): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setAlwaysOnTop',
- payload: alwaysOnTop
- }
- }
- }
- })
- }
- /**
- * Resizes the window with a new inner size.
- * @example
- * ```typescript
- * import { appWindow, LogicalSize } from '@tauri-apps/api/window'
- * await appWindow.setSize(new LogicalSize(600, 500))
- * ```
- *
- * @param size The logical or physical inner size.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setSize(size: LogicalSize | PhysicalSize): Promise<void> {
- if (!size || (size.type !== 'Logical' && size.type !== 'Physical')) {
- throw new Error(
- 'the `size` argument must be either a LogicalSize or a PhysicalSize instance'
- )
- }
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setSize',
- payload: {
- type: size.type,
- data: {
- width: size.width,
- height: size.height
- }
- }
- }
- }
- }
- })
- }
- /**
- * Sets the window minimum inner size. If the `size` argument is not provided, the constraint is unset.
- * @example
- * ```typescript
- * import { appWindow, PhysicalSize } from '@tauri-apps/api/window'
- * await appWindow.setMinSize(new PhysicalSize(600, 500))
- * ```
- *
- * @param size The logical or physical inner size, or `null` to unset the constraint.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setMinSize(
- size: LogicalSize | PhysicalSize | null | undefined
- ): Promise<void> {
- if (size && size.type !== 'Logical' && size.type !== 'Physical') {
- throw new Error(
- 'the `size` argument must be either a LogicalSize or a PhysicalSize instance'
- )
- }
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setMinSize',
- payload: size
- ? {
- type: size.type,
- data: {
- width: size.width,
- height: size.height
- }
- }
- : null
- }
- }
- }
- })
- }
- /**
- * Sets the window maximum inner size. If the `size` argument is undefined, the constraint is unset.
- * @example
- * ```typescript
- * import { appWindow, LogicalSize } from '@tauri-apps/api/window'
- * await appWindow.setMaxSize(new LogicalSize(600, 500))
- * ```
- *
- * @param size The logical or physical inner size, or `null` to unset the constraint.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setMaxSize(
- size: LogicalSize | PhysicalSize | null | undefined
- ): Promise<void> {
- if (size && size.type !== 'Logical' && size.type !== 'Physical') {
- throw new Error(
- 'the `size` argument must be either a LogicalSize or a PhysicalSize instance'
- )
- }
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setMaxSize',
- payload: size
- ? {
- type: size.type,
- data: {
- width: size.width,
- height: size.height
- }
- }
- : null
- }
- }
- }
- })
- }
- /**
- * Sets the window outer position.
- * @example
- * ```typescript
- * import { appWindow, LogicalPosition } from '@tauri-apps/api/window'
- * await appWindow.setPosition(new LogicalPosition(600, 500))
- * ```
- *
- * @param position The new position, in logical or physical pixels.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setPosition(
- position: LogicalPosition | PhysicalPosition
- ): Promise<void> {
- if (
- !position ||
- (position.type !== 'Logical' && position.type !== 'Physical')
- ) {
- throw new Error(
- 'the `position` argument must be either a LogicalPosition or a PhysicalPosition instance'
- )
- }
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setPosition',
- payload: {
- type: position.type,
- data: {
- x: position.x,
- y: position.y
- }
- }
- }
- }
- }
- })
- }
- /**
- * Sets the window fullscreen state.
- *
- * @param fullscreen Whether the window should go to fullscreen or not.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setFullscreen(fullscreen: boolean): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setFullscreen',
- payload: fullscreen
- }
- }
- }
- })
- }
- /**
- * Bring the window to front and focus.
- *
- * @returns A promise indicating the success or failure of the operation.
- */
- async setFocus(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setFocus'
- }
- }
- }
- })
- }
- /**
- * Sets the window icon.
- *
- * Note that you need the `icon-ico` or `icon-png` Cargo features to use this API.
- * To enable it, change your Cargo.toml file:
- * ```toml
- * [dependencies]
- * tauri = { version = "...", features = ["...", "icon-png"] }
- * ```
- *
- * @param icon Icon bytes or path to the icon file.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setIcon(icon: string | Uint8Array): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setIcon',
- payload: {
- // correctly serialize Uint8Arrays
- icon: typeof icon === 'string' ? icon : Array.from(icon)
- }
- }
- }
- }
- })
- }
- /**
- * Whether to show the window icon in the task bar or not.
- *
- * @param skip true to hide window icon, false to show it.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setSkipTaskbar(skip: boolean): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setSkipTaskbar',
- payload: skip
- }
- }
- }
- })
- }
- /**
- * Grabs the cursor, preventing it from leaving the window.
- *
- * There's no guarantee that the cursor will be hidden. You should
- * hide it by yourself if you want so.
- *
- * #### Platform-specific
- *
- * - **Linux:** Unsupported.
- * - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
- *
- * @param grab `true` to grab the cursor icon, `false` to release it.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setCursorGrab(grab: boolean): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setCursorGrab',
- payload: grab
- }
- }
- }
- })
- }
- /**
- * Modifies the cursor's visibility.
- *
- * #### Platform-specific
- *
- * - **Windows:** The cursor is only hidden within the confines of the window.
- * - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
- * outside of the window.
- *
- * @param visible If `false`, this will hide the cursor. If `true`, this will show the cursor.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setCursorVisible(visible: boolean): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setCursorVisible',
- payload: visible
- }
- }
- }
- })
- }
- /**
- * Modifies the cursor icon of the window.
- *
- * @param icon The new cursor icon.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setCursorIcon(icon: CursorIcon): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setCursorIcon',
- payload: icon
- }
- }
- }
- })
- }
- /**
- * Changes the position of the cursor in window coordinates.
- *
- * @param position The new cursor position.
- * @returns A promise indicating the success or failure of the operation.
- */
- async setCursorPosition(
- position: LogicalPosition | PhysicalPosition
- ): Promise<void> {
- if (
- !position ||
- (position.type !== 'Logical' && position.type !== 'Physical')
- ) {
- throw new Error(
- 'the `position` argument must be either a LogicalPosition or a PhysicalPosition instance'
- )
- }
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'setCursorPosition',
- payload: {
- type: position.type,
- data: {
- x: position.x,
- y: position.y
- }
- }
- }
- }
- }
- })
- }
- /**
- * Starts dragging the window.
- *
- * @return A promise indicating the success or failure of the operation.
- */
- async startDragging(): Promise<void> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- label: this.label,
- cmd: {
- type: 'startDragging'
- }
- }
- }
- })
- }
- }
- /**
- * Create new webview windows and get a handle to existing ones.
- *
- * Windows are identified by a *label* a unique identifier that can be used to reference it later.
- * It may only contain alphanumeric characters `a-zA-Z` plus the following special characters `-`, `/`, `:` and `_`.
- *
- * @example
- * ```typescript
- * // loading embedded asset:
- * const webview = new WebviewWindow('theUniqueLabel', {
- * url: 'path/to/page.html'
- * })
- * // alternatively, load a remote URL:
- * const webview = new WebviewWindow('theUniqueLabel', {
- * url: 'https://github.com/tauri-apps/tauri'
- * })
- *
- * webview.once('tauri://created', function () {
- * // webview window successfully created
- * })
- * webview.once('tauri://error', function (e) {
- * // an error happened creating the webview window
- * })
- *
- * // emit an event to the backend
- * await webview.emit("some event", "data")
- * // listen to an event from the backend
- * const unlisten = await webview.listen("event name", e => {})
- * unlisten()
- * ```
- */
- class WebviewWindow extends WindowManager {
- /**
- * Creates a new WebviewWindow.
- * * @param label The unique webview window label. Must be alphanumeric: `a-zA-Z-/:_`.
- * @returns The WebviewWindow instance to communicate with the webview.
- */
- constructor(label: WindowLabel, options: WindowOptions = {}) {
- super(label)
- // @ts-expect-error
- if (!options?.skip) {
- invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'createWebview',
- data: {
- options: {
- label,
- ...options
- }
- }
- }
- })
- .then(async () => this.emit('tauri://created'))
- .catch(async (e: string) => this.emit('tauri://error', e))
- }
- }
- /**
- * Gets the WebviewWindow for the webview associated with the given label.
- *
- * @param label The webview window label.
- * @returns The WebviewWindow instance to communicate with the webview or null if the webview doesn't exist.
- */
- static getByLabel(label: string): WebviewWindow | null {
- if (getAll().some((w) => w.label === label)) {
- // @ts-expect-error
- return new WebviewWindow(label, { skip: true })
- }
- return null
- }
- }
- /** The WebviewWindow for the current window. */
- let appWindow: WebviewWindow
- if ('__TAURI_METADATA__' in window) {
- appWindow = new WebviewWindow(
- window.__TAURI_METADATA__.__currentWindow.label,
- {
- // @ts-expect-error
- skip: true
- }
- )
- } else {
- console.warn(
- `Could not find "window.__TAURI_METADATA__". The "appWindow" value will reference the "main" window label.\nNote that this is not an issue if running this frontend on a browser instead of a Tauri window.`
- )
- appWindow = new WebviewWindow('main', {
- // @ts-expect-error
- skip: true
- })
- }
- /** Configuration for the window to create. */
- interface WindowOptions {
- /**
- * Remote URL or local file path to open.
- *
- * - URL such as `https://github.com/tauri-apps` is opened directly on a Tauri window.
- * - data: URL such as `data:text/html,<html>...` is only supported with the `window-data-url` Cargo feature for the `tauri` dependency.
- * - local file path or route such as `/path/to/page.html` or `/users` is appended to the application URL (the devServer URL on development, or `tauri://localhost/` and `https://tauri.localhost/` on production).
- */
- url?: string
- /** Show window in the center of the screen.. */
- center?: boolean
- /** The initial vertical position. Only applies if `y` is also set. */
- x?: number
- /** The initial horizontal position. Only applies if `x` is also set. */
- y?: number
- /** The initial width. */
- width?: number
- /** The initial height. */
- height?: number
- /** The minimum width. Only applies if `minHeight` is also set. */
- minWidth?: number
- /** The minimum height. Only applies if `minWidth` is also set. */
- minHeight?: number
- /** The maximum width. Only applies if `maxHeight` is also set. */
- maxWidth?: number
- /** The maximum height. Only applies if `maxWidth` is also set. */
- maxHeight?: number
- /** Whether the window is resizable or not. */
- resizable?: boolean
- /** Window title. */
- title?: string
- /** Whether the window is in fullscreen mode or not. */
- fullscreen?: boolean
- /** Whether the window will be initially hidden or focused. */
- focus?: boolean
- /**
- * Whether the window is transparent or not.
- * Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri.conf.json > tauri > macOSPrivateApi`.
- * WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
- */
- transparent?: boolean
- /** Whether the window should be maximized upon creation or not. */
- maximized?: boolean
- /** Whether the window should be immediately visible upon creation or not. */
- visible?: boolean
- /** Whether the window should have borders and bars or not. */
- decorations?: boolean
- /** Whether the window should always be on top of other windows or not. */
- alwaysOnTop?: boolean
- /** Whether or not the window icon should be added to the taskbar. */
- skipTaskbar?: boolean
- /**
- * Whether the file drop is enabled or not on the webview. By default it is enabled.
- *
- * Disabling it is required to use drag and drop on the frontend on Windows.
- */
- fileDropEnabled?: boolean
- /**
- * The initial window theme. Defaults to the system theme.
- *
- * Only implemented on Windows.
- */
- theme?: Theme
- }
- /**
- * Returns the monitor on which the window currently resides.
- * Returns `null` if current monitor can't be detected.
- */
- async function currentMonitor(): Promise<Monitor | null> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- cmd: {
- type: 'currentMonitor'
- }
- }
- }
- })
- }
- /**
- * Returns the primary monitor of the system.
- * Returns `null` if it can't identify any monitor as a primary one.
- */
- async function primaryMonitor(): Promise<Monitor | null> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- cmd: {
- type: 'primaryMonitor'
- }
- }
- }
- })
- }
- /** Returns the list of all the monitors available on the system. */
- async function availableMonitors(): Promise<Monitor[]> {
- return invokeTauriCommand({
- __tauriModule: 'Window',
- message: {
- cmd: 'manage',
- data: {
- cmd: {
- type: 'availableMonitors'
- }
- }
- }
- })
- }
- export {
- WebviewWindow,
- WebviewWindowHandle,
- WindowManager,
- getCurrent,
- getAll,
- appWindow,
- LogicalSize,
- PhysicalSize,
- LogicalPosition,
- PhysicalPosition,
- UserAttentionType,
- currentMonitor,
- primaryMonitor,
- availableMonitors
- }
- export type { Theme, Monitor, WindowOptions }
|