snapshot of https://github.com/tauri-apps/plugins-workspace.git (v2, 2026-09-23; blobs > 131072B omitted)
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-23 17:17:10 +05:00
commit 9ad64ec987
1469 changed files with 115067 additions and 0 deletions

View File

@@ -0,0 +1,165 @@
# Changelog
## \[2.4.1]
- [`93426f85`](https://github.com/tauri-apps/plugins-workspace/commit/93426f85120f49beb9f40222bff45185a32d54a9) Fixed an issue that caused docs.rs builds to fail. No user facing changes.
## \[2.4.0]
- [`6a8f2558`](https://github.com/tauri-apps/plugins-workspace/commit/6a8f25587852b958a9e48b8c2e8884cc94a7dc7f) ([#2619](https://github.com/tauri-apps/plugins-workspace/pull/2619) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Making `flags` optional in the `saveWindowState`, `restoreState`, `restoreStateCurrent` JavaScripts APIs, leaving it empty will make it use plugin's default flags
## \[2.3.0]
- [`f209b2f2`](https://github.com/tauri-apps/plugins-workspace/commit/f209b2f23cb29133c97ad5961fb46ef794dbe063) ([#2804](https://github.com/tauri-apps/plugins-workspace/pull/2804) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated tauri to 2.6
## \[2.2.3]
- [`f634e524`](https://github.com/tauri-apps/plugins-workspace/commit/f634e5248ebe428f8305a59f74c13fc15147fb8e) This is an "empty" release to update the plugins' source files on crates.io and docs.rs. This should fix docs.rs build failures for projects using tauri plugins as dependencies.
## \[2.2.2]
- [`a35fea50`](https://github.com/tauri-apps/plugins-workspace/commit/a35fea501560a3d126aad09b59600d9f1a731a9e) ([#2583](https://github.com/tauri-apps/plugins-workspace/pull/2583)) Fix window size gets bigger/smaller on secondary monitor with a different scaling than the primary one
## \[2.2.1]
- [`0ec895c3`](https://github.com/tauri-apps/plugins-workspace/commit/0ec895c378d4700cf8d7a002c6d9829f3c015b9f) ([#2330](https://github.com/tauri-apps/plugins-workspace/pull/2330) by [@thewh1teagle](https://github.com/tauri-apps/plugins-workspace/../../thewh1teagle)) Add `Builder::with_filter` callback to exclude specific windows from saving their state. This allows for more flexibility by enabling dynamic exclusion of windows based on custom logic.
## \[2.2.0]
- [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
## \[2.0.2]
- [`cfb3ec0e`](https://github.com/tauri-apps/plugins-workspace/commit/cfb3ec0e21cab8010fbc1d7ef82aa65d86c3cfa9) ([#2007](https://github.com/tauri-apps/plugins-workspace/pull/2007) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) On macOS the plugin now (temporarily) ignores the maximized state for undecorated windows on resize events to fix app freezes.
## \[2.0.1]
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
## \[2.0.0]
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
## \[2.0.0-rc.5]
- [`7a37355e`](https://github.com/tauri-apps/plugins-workspace/commit/7a37355e177772cbddf24397d5a23280e00558af) ([#1787](https://github.com/tauri-apps/plugins-workspace/pull/1787) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix deadlock when trying to restore window states on initial load
## \[2.0.0-rc.4]
- [`204e5aac`](https://github.com/tauri-apps/plugins-workspace/commit/204e5aacad7e8f99a9a08f4a45cfed83643c1cc0) ([#1743](https://github.com/tauri-apps/plugins-workspace/pull/1743)) Fix can't restore a minimized window's size and position properly
### breaking
- [`204e5aac`](https://github.com/tauri-apps/plugins-workspace/commit/204e5aacad7e8f99a9a08f4a45cfed83643c1cc0) ([#1743](https://github.com/tauri-apps/plugins-workspace/pull/1743)) Window's size is now stored in physical size instead of logical size
## \[2.0.0-rc.3]
- [`17e8014b`](https://github.com/tauri-apps/plugins-workspace/commit/17e8014b6993602ddad21e8f5dcb625de1eea2c0) ([#1702](https://github.com/tauri-apps/plugins-workspace/pull/1702) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix saving a minimized window's state changes its position to -32000
## \[2.0.0-rc.1]
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
## \[2.0.0-rc.1]
- [`2c00c029`](https://github.com/tauri-apps/plugins-workspace/commit/2c00c0292c9127b81567de46691e8c0f73557261) ([#1630](https://github.com/tauri-apps/plugins-workspace/pull/1630) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Fixed an issue that caused multi-word IIFE names to not be formatted correctly. For example the `barcode-scanner` was defined as `window.__TAURI_PLUGIN_CLIPBOARDMANAGER__` instead of `window.__TAURI_PLUGIN_CLIPBOARD_MANAGER__`.
## \[2.0.0-rc.0]
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
## \[2.0.0-beta.9]
- [`99d6ac0f`](https://github.com/tauri-apps/plugins-workspace/commit/99d6ac0f9506a6a4a1aa59c728157190a7441af6) ([#1606](https://github.com/tauri-apps/plugins-workspace/pull/1606) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) The JS packages now specify the *minimum* `@tauri-apps/api` version instead of a single exact version.
- [`6de87966`](https://github.com/tauri-apps/plugins-workspace/commit/6de87966ecc00ad9d91c25be452f1f46bd2b7e1f) ([#1597](https://github.com/tauri-apps/plugins-workspace/pull/1597) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Update to tauri beta.25.
## \[2.0.0-beta.8]
- [`22a17980`](https://github.com/tauri-apps/plugins-workspace/commit/22a17980ff4f6f8c40adb1b8f4ffc6dae2fe7e30) ([#1537](https://github.com/tauri-apps/plugins-workspace/pull/1537) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri beta.24.
## \[2.0.0-beta.7]
- [`76daee7a`](https://github.com/tauri-apps/plugins-workspace/commit/76daee7aafece34de3092c86e531cf9eb1138989) ([#1512](https://github.com/tauri-apps/plugins-workspace/pull/1512) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update to tauri beta.23.
## \[2.0.0-beta.6]
- [`9013854f`](https://github.com/tauri-apps/plugins-workspace/commit/9013854f42a49a230b9dbb9d02774765528a923f)([#1382](https://github.com/tauri-apps/plugins-workspace/pull/1382)) Update to tauri beta.22.
## \[2.0.0-beta.5]
- [`430bd6f4`](https://github.com/tauri-apps/plugins-workspace/commit/430bd6f4f379bee5d232ae6b098ae131db7f178a)([#1363](https://github.com/tauri-apps/plugins-workspace/pull/1363)) Update to tauri beta.20.
## \[2.0.0-beta.7]
- [`d9de5b19`](https://github.com/tauri-apps/plugins-workspace/commit/d9de5b19d1e950c06f0915ae92a862acb266d108)([#1283](https://github.com/tauri-apps/plugins-workspace/pull/1283)) Implement `WindowExt` for `WebviewWindow`.
## \[2.0.0-beta.4]
- [`bd1ed590`](https://github.com/tauri-apps/plugins-workspace/commit/bd1ed5903ffcce5500310dac1e59e8c67674ef1e)([#1237](https://github.com/tauri-apps/plugins-workspace/pull/1237)) Update to tauri beta.17.
## \[2.0.0-beta.3]
- [`0e9541f`](https://github.com/tauri-apps/plugins-workspace/commit/0e9541fe8990395de7cc8887bc46b3f3665b44e1)([#1138](https://github.com/tauri-apps/plugins-workspace/pull/1138)) Add `Builder::with_filename` to support using a custom filename. Also add `AppHandleExt::file_name` and a similar function in JS, to retrieve it later.
## \[2.0.0-beta.4]
- [`c013fa5`](https://github.com/tauri-apps/plugins-workspace/commit/c013fa52cd66885cf457a64e75373cb2066bc849)([#1078](https://github.com/tauri-apps/plugins-workspace/pull/1078)) **Breaking change**: Changed the format of the state file from bincode to json. Also changed the filename to from `.window-state` to `.window-state.json`.
## \[2.0.0-beta.3]
- [`a04ea2f`](https://github.com/tauri-apps/plugins-workspace/commit/a04ea2f38294d5a3987578283badc8eec87a7752)([#1071](https://github.com/tauri-apps/plugins-workspace/pull/1071)) The global API script is now only added to the binary when the `withGlobalTauri` config is true.
## \[2.0.0-beta.2]
- [`99bea25`](https://github.com/tauri-apps/plugins-workspace/commit/99bea2559c2c0648c2519c50a18cd124dacef57b)([#1005](https://github.com/tauri-apps/plugins-workspace/pull/1005)) Update to tauri beta.8.
## \[2.0.0-beta.1]
- [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
## \[2.0.0-beta.0]
- [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
- [`14f59615`](https://github.com/tauri-apps/plugins-workspace/commit/14f5961569c7d759d8d6d836352c787484594bd5) Address a couple of issues with restoring positions:
- Fix restoring window positions correctly when the top-left corner of the window was outside of the monitor.
- Fix restore maximization state only maximized on main monitor.
## \[2.0.0-alpha.5]
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.13.
## \[2.0.0-alpha.4]
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.12.
## \[2.0.0-alpha.3]
- [`e438e0a`](https://github.com/tauri-apps/plugins-workspace/commit/e438e0a62d4b430a5159f05f13ecd397dd891a0d)([#676](https://github.com/tauri-apps/plugins-workspace/pull/676)) Update to @tauri-apps/api v2.0.0-alpha.11.
## \[2.0.0-alpha.2]
- [`5c13736`](https://github.com/tauri-apps/plugins-workspace/commit/5c137365c60790e8d4037d449e8237aa3fffdab0)([#673](https://github.com/tauri-apps/plugins-workspace/pull/673)) Update to @tauri-apps/api v2.0.0-alpha.9.
- [`beb6b13`](https://github.com/tauri-apps/plugins-workspace/commit/beb6b139eb669dc0346b3de919aed024f649b9d2)([#675](https://github.com/tauri-apps/plugins-workspace/pull/675)) Fix usage of no longer available `__TAURI_METADATA__` API.
## \[2.0.0-alpha.2]
- [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
## \[2.0.0-alpha.1]
- [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
- [`84b3612`](https://github.com/tauri-apps/plugins-workspace/commit/84b3612393e3d0d4faeebe1e61cb7d7973556503)([#436](https://github.com/tauri-apps/plugins-workspace/pull/436)) Correctly propagate the promise inside `saveWindowState`, `restoreState` and `restoreStateCurrent` so callers can choose to `await` them.
## \[2.0.0-alpha.0]
- [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!
## \[0.1.1]
- Address a couple of issues with restoring positions:
- Fix restoring window positions correctly when the top-left corner of the window was outside of the monitor.
- Fix restore maximization state only maximized on main monitor.

View File

@@ -0,0 +1,35 @@
[package]
name = "tauri-plugin-window-state"
version = "2.4.1"
description = "Save window positions and sizes and restore them when the app is reopened."
authors = { workspace = true }
license = { workspace = true }
edition = { workspace = true }
rust-version = { workspace = true }
repository = { workspace = true }
links = "tauri-plugin-window-state"
exclude = [
"/banner.png",
"/guest-js",
"/package.json",
"/rollup.config.js",
"/tsconfig.json",
]
[package.metadata.platforms.support]
windows = { level = "full", notes = "" }
linux = { level = "full", notes = "" }
macos = { level = "full", notes = "" }
android = { level = "none", notes = "" }
ios = { level = "none", notes = "" }
[build-dependencies]
tauri-plugin = { workspace = true, features = ["build"] }
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
log = { workspace = true }
thiserror = { workspace = true }
bitflags = "2"

View File

@@ -0,0 +1,20 @@
SPDXVersion: SPDX-2.1
DataLicense: CC0-1.0
PackageName: tauri
DataFormat: SPDXRef-1
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
PackageHomePage: https://tauri.app
PackageLicenseDeclared: Apache-2.0
PackageLicenseDeclared: MIT
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
and small desktop applications using a web frontend.
</text>
PackageComment: <text>The package includes the following libraries; see
Relationship information.
</text>
Created: 2019-05-20T09:00:00Z
PackageDownloadLocation: git://github.com/tauri-apps/tauri
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
Creator: Person: Daniel Thompson-Yvetot

View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 - Present Tauri Apps Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,122 @@
![plugin-window-state](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/window-state/banner.png)
Save window positions and sizes and restore them when the app is reopened.
| Platform | Supported |
| -------- | --------- |
| Linux | ✓ |
| Windows | ✓ |
| macOS | ✓ |
| Android | x |
| iOS | x |
## Install
_This plugin requires a Rust version of at least **1.77.2**_
There are three general methods of installation that we can recommend.
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
2. Pull sources directly from Github using git tags / revision hashes (most secure)
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
Install the Core plugin by adding the following to your `Cargo.toml` file:
`src-tauri/Cargo.toml`
```toml
[dependencies]
tauri-plugin-window-state = "2.0.0"
# alternatively with Git:
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
```sh
pnpm add @tauri-apps/plugin-window-state
# or
npm add @tauri-apps/plugin-window-state
# or
yarn add @tauri-apps/plugin-window-state
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/lib.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_window_state::Builder::default().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all windows will remember their state when the app is being closed and will restore to their previous state on the next launch.
Optionally you can also tell the plugin to save the state of all open window to disk by using the `save_window_state()` method exposed by the `AppHandleExt` trait:
```rust
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
// `tauri::AppHandle` now has the following additional method
app.save_window_state(StateFlags::all()); // will save the state of all open windows to disk
```
or through Javascript
```javascript
import { saveWindowState, StateFlags } from '@tauri-apps/plugin-window-state'
saveWindowState(StateFlags.ALL)
```
To manually restore a windows state from disk you can call the `restore_state()` method exposed by the `WindowExt` trait:
```rust
use tauri_plugin_window_state::{WindowExt, StateFlags};
// all `Window` types now have the following additional method
window.restore_state(StateFlags::all()); // will restore the windows state from disk
```
or through Javascript
```javascript
import {
restoreStateCurrent,
StateFlags
} from '@tauri-apps/plugin-window-state'
restoreStateCurrent(StateFlags.ALL)
```
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Partners
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
</tr>
</tbody>
</table>
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.

View File

@@ -0,0 +1,23 @@
# Security Policy
**Do not report security vulnerabilities through public GitHub issues.**
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
Include as much of the following information:
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
- The location of the affected source code (tag/branch/commit or direct URL)
- Any special configuration required to reproduce the issue
- The distribution affected or used to help us with reproduction of the issue
- Step-by-step instructions to reproduce the issue
- Ideally a reproduction repository
- Impact of the issue, including how an attacker might exploit the issue
We prefer to receive reports in English.
## Contact
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).

View File

@@ -0,0 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_WINDOW_STATE__=function(t,e,n){"use strict";var a;async function i(t,n){await e.invoke("plugin:window-state|restore_state",{label:t,flags:n})}return t.StateFlags=void 0,(a=t.StateFlags||(t.StateFlags={}))[a.SIZE=1]="SIZE",a[a.POSITION=2]="POSITION",a[a.MAXIMIZED=4]="MAXIMIZED",a[a.VISIBLE=8]="VISIBLE",a[a.DECORATIONS=16]="DECORATIONS",a[a.FULLSCREEN=32]="FULLSCREEN",a[a.ALL=63]="ALL",t.filename=async function(){return await e.invoke("plugin:window-state|filename")},t.restoreState=i,t.restoreStateCurrent=async function(t){await i(n.getCurrentWindow().label,t)},t.saveWindowState=async function(t){await e.invoke("plugin:window-state|save_window_state",{flags:t})},t}({},window.__TAURI__.core,window.__TAURI__.window);Object.defineProperty(window.__TAURI__,"windowState",{value:__TAURI_PLUGIN_WINDOW_STATE__})}

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

View File

@@ -0,0 +1,11 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
const COMMANDS: &[&str] = &["save_window_state", "restore_state", "filename"];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.build();
}

View File

@@ -0,0 +1,106 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/**
* Save and restore window positions and sizes.
*
* @module
*/
import { invoke } from '@tauri-apps/api/core'
import { type WindowLabel, getCurrentWindow } from '@tauri-apps/api/window'
/**
* Flags controlling which parts of a window's state are saved and restored.
* Combine multiple flags with the bitwise OR operator (`|`).
*/
export enum StateFlags {
/** Save and restore the window size. */
SIZE = 1 << 0,
/** Save and restore the window position. */
POSITION = 1 << 1,
/** Save and restore whether the window is maximized. */
MAXIMIZED = 1 << 2,
/** Save and restore whether the window is visible. */
VISIBLE = 1 << 3,
/** Save and restore whether the window has decorations. */
DECORATIONS = 1 << 4,
/** Save and restore whether the window is fullscreen. */
FULLSCREEN = 1 << 5,
/** Save and restore every flag above. */
ALL = SIZE | POSITION | MAXIMIZED | VISIBLE | DECORATIONS | FULLSCREEN
}
/**
* Save the state of all open windows to disk.
*
* @example
* ```typescript
* import { saveWindowState, StateFlags } from '@tauri-apps/plugin-window-state';
*
* await saveWindowState(StateFlags.ALL);
* ```
*
* @param flags Which parts of the state to save. Defaults to the flags passed to the plugin `Builder` (all flags if none were set).
* @since 2.0.0
*/
async function saveWindowState(flags?: StateFlags): Promise<void> {
await invoke('plugin:window-state|save_window_state', { flags })
}
/**
* Restore the state for the specified window from disk.
*
* @example
* ```typescript
* import { restoreState, StateFlags } from '@tauri-apps/plugin-window-state';
*
* await restoreState('main', StateFlags.ALL);
* ```
*
* @param label The label of the window to restore.
* @param flags Which parts of the state to restore. Defaults to the flags passed to the plugin `Builder` (all flags if none were set).
* @since 2.0.0
*/
async function restoreState(
label: WindowLabel,
flags?: StateFlags
): Promise<void> {
await invoke('plugin:window-state|restore_state', { label, flags })
}
/**
* Restore the state for the current window from disk.
*
* @example
* ```typescript
* import { restoreStateCurrent, StateFlags } from '@tauri-apps/plugin-window-state';
*
* await restoreStateCurrent(StateFlags.ALL);
* ```
*
* @param flags Which parts of the state to restore. Defaults to the flags passed to the plugin `Builder` (all flags if none were set).
* @since 2.0.0
*/
async function restoreStateCurrent(flags?: StateFlags): Promise<void> {
await restoreState(getCurrentWindow().label, flags)
}
/**
* Get the name of the file used to store window state.
*
* @example
* ```typescript
* import { filename } from '@tauri-apps/plugin-window-state';
*
* const name = await filename();
* ```
*
* @returns A promise resolving to the name of the file used to store window state.
* @since 2.0.0
*/
async function filename(): Promise<string> {
return await invoke('plugin:window-state|filename')
}
export { restoreState, restoreStateCurrent, saveWindowState, filename }

View File

@@ -0,0 +1,30 @@
{
"name": "@tauri-apps/plugin-window-state",
"version": "2.4.1",
"description": "Save window positions and sizes and restore them when the app is reopened.",
"license": "MIT OR Apache-2.0",
"authors": [
"Tauri Programme within The Commons Conservancy"
],
"repository": "https://github.com/tauri-apps/plugins-workspace",
"type": "module",
"types": "./dist-js/index.d.ts",
"main": "./dist-js/index.cjs",
"module": "./dist-js/index.js",
"exports": {
"types": "./dist-js/index.d.ts",
"import": "./dist-js/index.js",
"require": "./dist-js/index.cjs"
},
"scripts": {
"build": "rollup -c"
},
"files": [
"dist-js",
"README.md",
"LICENSE"
],
"dependencies": {
"@tauri-apps/api": "^2.11.0"
}
}

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-filename"
description = "Enables the filename command without any pre-configured scope."
commands.allow = ["filename"]
[[permission]]
identifier = "deny-filename"
description = "Denies the filename command without any pre-configured scope."
commands.deny = ["filename"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-restore-state"
description = "Enables the restore_state command without any pre-configured scope."
commands.allow = ["restore_state"]
[[permission]]
identifier = "deny-restore-state"
description = "Denies the restore_state command without any pre-configured scope."
commands.deny = ["restore_state"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-save-window-state"
description = "Enables the save_window_state command without any pre-configured scope."
commands.allow = ["save_window_state"]
[[permission]]
identifier = "deny-save-window-state"
description = "Denies the save_window_state command without any pre-configured scope."
commands.deny = ["save_window_state"]

View File

@@ -0,0 +1,102 @@
## Default Permission
This permission set configures what kind of
operations are available from the window state plugin.
#### Granted Permissions
All operations are enabled by default.
#### This default permission set includes the following:
- `allow-filename`
- `allow-restore-state`
- `allow-save-window-state`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`window-state:allow-filename`
</td>
<td>
Enables the filename command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`window-state:deny-filename`
</td>
<td>
Denies the filename command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`window-state:allow-restore-state`
</td>
<td>
Enables the restore_state command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`window-state:deny-restore-state`
</td>
<td>
Denies the restore_state command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`window-state:allow-save-window-state`
</td>
<td>
Enables the save_window_state command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`window-state:deny-save-window-state`
</td>
<td>
Denies the save_window_state command without any pre-configured scope.
</td>
</tr>
</table>

View File

@@ -0,0 +1,17 @@
"$schema" = "schemas/schema.json"
[default]
description = """
This permission set configures what kind of
operations are available from the window state plugin.
#### Granted Permissions
All operations are enabled by default.
"""
permissions = [
"allow-filename",
"allow-restore-state",
"allow-save-window-state",
]

View File

@@ -0,0 +1,342 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "PermissionFile",
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
"type": "object",
"properties": {
"default": {
"description": "The default permission set for the plugin",
"anyOf": [
{
"$ref": "#/definitions/DefaultPermission"
},
{
"type": "null"
}
]
},
"set": {
"description": "A list of permissions sets defined",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionSet"
}
},
"permission": {
"description": "A list of inlined permissions",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/Permission"
}
}
},
"definitions": {
"DefaultPermission": {
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
"type": "object",
"required": [
"permissions"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"description": {
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"PermissionSet": {
"description": "A set of direct permissions grouped together under a new name.",
"type": "object",
"required": [
"description",
"identifier",
"permissions"
],
"properties": {
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does.",
"type": "string"
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionKind"
}
}
}
},
"Permission": {
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
"type": "object",
"required": [
"identifier"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"commands": {
"description": "Allowed or denied commands when using this permission.",
"default": {
"allow": [],
"deny": []
},
"allOf": [
{
"$ref": "#/definitions/Commands"
}
]
},
"scope": {
"description": "Allowed or denied scoped when using this permission.",
"allOf": [
{
"$ref": "#/definitions/Scopes"
}
]
},
"platforms": {
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Target"
}
}
}
},
"Commands": {
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
"type": "object",
"properties": {
"allow": {
"description": "Allowed command.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
},
"deny": {
"description": "Denied command, which takes priority.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Scopes": {
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
"type": "object",
"properties": {
"allow": {
"description": "Data that defines what is allowed by the scope.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
},
"deny": {
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
}
}
},
"Value": {
"description": "All supported ACL values.",
"anyOf": [
{
"description": "Represents a null JSON value.",
"type": "null"
},
{
"description": "Represents a [`bool`].",
"type": "boolean"
},
{
"description": "Represents a valid ACL [`Number`].",
"allOf": [
{
"$ref": "#/definitions/Number"
}
]
},
{
"description": "Represents a [`String`].",
"type": "string"
},
{
"description": "Represents a list of other [`Value`]s.",
"type": "array",
"items": {
"$ref": "#/definitions/Value"
}
},
{
"description": "Represents a map of [`String`] keys to [`Value`]s.",
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/Value"
}
}
]
},
"Number": {
"description": "A valid ACL number.",
"anyOf": [
{
"description": "Represents an [`i64`].",
"type": "integer",
"format": "int64"
},
{
"description": "Represents a [`f64`].",
"type": "number",
"format": "double"
}
]
},
"Target": {
"description": "Platform target.",
"oneOf": [
{
"description": "MacOS.",
"type": "string",
"enum": [
"macOS"
]
},
{
"description": "Windows.",
"type": "string",
"enum": [
"windows"
]
},
{
"description": "Linux.",
"type": "string",
"enum": [
"linux"
]
},
{
"description": "Android.",
"type": "string",
"enum": [
"android"
]
},
{
"description": "iOS.",
"type": "string",
"enum": [
"iOS"
]
}
]
},
"PermissionKind": {
"type": "string",
"oneOf": [
{
"description": "Enables the filename command without any pre-configured scope.",
"type": "string",
"const": "allow-filename",
"markdownDescription": "Enables the filename command without any pre-configured scope."
},
{
"description": "Denies the filename command without any pre-configured scope.",
"type": "string",
"const": "deny-filename",
"markdownDescription": "Denies the filename command without any pre-configured scope."
},
{
"description": "Enables the restore_state command without any pre-configured scope.",
"type": "string",
"const": "allow-restore-state",
"markdownDescription": "Enables the restore_state command without any pre-configured scope."
},
{
"description": "Denies the restore_state command without any pre-configured scope.",
"type": "string",
"const": "deny-restore-state",
"markdownDescription": "Denies the restore_state command without any pre-configured scope."
},
{
"description": "Enables the save_window_state command without any pre-configured scope.",
"type": "string",
"const": "allow-save-window-state",
"markdownDescription": "Enables the save_window_state command without any pre-configured scope."
},
{
"description": "Denies the save_window_state command without any pre-configured scope.",
"type": "string",
"const": "deny-save-window-state",
"markdownDescription": "Denies the save_window_state command without any pre-configured scope."
},
{
"description": "This permission set configures what kind of\noperations are available from the window state plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n\n#### This default permission set includes:\n\n- `allow-filename`\n- `allow-restore-state`\n- `allow-save-window-state`",
"type": "string",
"const": "default",
"markdownDescription": "This permission set configures what kind of\noperations are available from the window state plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n\n#### This default permission set includes:\n\n- `allow-filename`\n- `allow-restore-state`\n- `allow-save-window-state`"
}
]
}
}
}

View File

@@ -0,0 +1,7 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { createConfig } from '../../shared/rollup.config.js'
export default createConfig()

View File

@@ -0,0 +1,48 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{AppHandleExt, StateFlags, WindowExt};
use tauri::{command, AppHandle, Manager, Runtime};
fn get_state_flags<R: Runtime>(
app: &AppHandle<R>,
flags: Option<u32>,
) -> std::result::Result<StateFlags, String> {
let flags = if let Some(flags) = flags {
StateFlags::from_bits(flags).ok_or_else(|| format!("Invalid state flags bits: {flags}"))?
} else {
let plugin_state = app.state::<crate::PluginState>();
plugin_state.state_flags
};
Ok(flags)
}
#[command]
pub async fn save_window_state<R: Runtime>(
app: AppHandle<R>,
flags: Option<u32>,
) -> std::result::Result<(), String> {
let flags = get_state_flags(&app, flags)?;
app.save_window_state(flags).map_err(|e| e.to_string())?;
Ok(())
}
#[command]
pub async fn restore_state<R: Runtime>(
app: AppHandle<R>,
label: String,
flags: Option<u32>,
) -> std::result::Result<(), String> {
let flags = get_state_flags(&app, flags)?;
app.get_webview_window(&label)
.ok_or_else(|| format!("Couldn't find window with label: {label}"))?
.restore_state(flags)
.map_err(|e| e.to_string())?;
Ok(())
}
#[command]
pub fn filename<R: Runtime>(app: AppHandle<R>) -> String {
app.filename()
}

View File

@@ -0,0 +1,575 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Save window positions and sizes and restore them when the app is reopened.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
)]
#![cfg(not(any(target_os = "android", target_os = "ios")))]
use bitflags::bitflags;
use serde::{Deserialize, Serialize};
use tauri::{
plugin::{Builder as PluginBuilder, TauriPlugin},
AppHandle, Manager, Monitor, PhysicalPosition, PhysicalSize, RunEvent, Runtime, WebviewWindow,
Window, WindowEvent,
};
use std::{
collections::{HashMap, HashSet},
fs::create_dir_all,
io::BufReader,
sync::{Arc, Mutex},
};
mod cmd;
type LabelMapperFn = dyn Fn(&str) -> &str + Send + Sync;
type FilterCallbackFn = dyn Fn(&str) -> bool + Send + Sync;
/// Default filename used to store window state.
///
/// If using a custom filename, you should probably use [`AppHandleExt::filename`] instead.
pub const DEFAULT_FILENAME: &str = ".window-state.json";
/// The error type returned by this plugin's fallible functions.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// An I/O error occurred while reading or writing the window state file.
#[error(transparent)]
Io(#[from] std::io::Error),
/// An error occurred while calling into Tauri, e.g. while resolving the app config directory
/// or manipulating a window.
#[error(transparent)]
Tauri(#[from] tauri::Error),
/// An error occurred while serializing or deserializing the window state file.
#[error(transparent)]
SerdeJson(#[from] serde_json::Error),
}
/// Alias for a [`Result`](std::result::Result) with the error type [`Error`].
pub type Result<T> = std::result::Result<T, Error>;
bitflags! {
/// Flags controlling which parts of a window's state are saved and restored.
///
/// Flags can be combined with the bitwise OR operator (`|`), e.g. `StateFlags::SIZE | StateFlags::POSITION`.
#[derive(Clone, Copy, Debug)]
pub struct StateFlags: u32 {
/// Save and restore the window size.
const SIZE = 1 << 0;
/// Save and restore the window position.
const POSITION = 1 << 1;
/// Save and restore whether the window is maximized.
const MAXIMIZED = 1 << 2;
/// Save and restore whether the window is visible.
const VISIBLE = 1 << 3;
/// Save and restore whether the window has decorations.
const DECORATIONS = 1 << 4;
/// Save and restore whether the window is fullscreen.
const FULLSCREEN = 1 << 5;
}
}
impl Default for StateFlags {
/// Default to [`all`](Self::all)
fn default() -> Self {
Self::all()
}
}
struct PluginState {
pub(crate) state_flags: StateFlags,
filename: String,
map_label: Option<Box<LabelMapperFn>>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct WindowState {
width: u32,
height: u32,
x: i32,
y: i32,
// prev_x and prev_y are used to store position
// before maximization happened, because maximization
// will set x and y to the top-left corner of the monitor
prev_x: i32,
prev_y: i32,
maximized: bool,
visible: bool,
decorated: bool,
fullscreen: bool,
}
impl Default for WindowState {
fn default() -> Self {
Self {
width: Default::default(),
height: Default::default(),
x: Default::default(),
y: Default::default(),
prev_x: Default::default(),
prev_y: Default::default(),
maximized: Default::default(),
visible: true,
decorated: true,
fullscreen: Default::default(),
}
}
}
struct WindowStateCache(Arc<Mutex<HashMap<String, WindowState>>>);
/// Used to prevent deadlocks from resize and position event listeners setting the cached state on restoring states
struct RestoringWindowState(Mutex<()>);
/// Extension trait for [`AppHandle`] exposing window state APIs.
pub trait AppHandleExt {
/// Saves all open windows state to disk
fn save_window_state(&self, flags: StateFlags) -> Result<()>;
/// Get the name of the file used to store window state.
fn filename(&self) -> String;
}
impl<R: Runtime> AppHandleExt for tauri::AppHandle<R> {
fn save_window_state(&self, flags: StateFlags) -> Result<()> {
let app_dir = self.path().app_config_dir()?;
let plugin_state = self.state::<PluginState>();
let state_path = app_dir.join(&plugin_state.filename);
let windows = self.webview_windows();
let cache = self.state::<WindowStateCache>();
let mut state = cache.0.lock().unwrap();
for (label, s) in state.iter_mut() {
let window = if let Some(map) = &plugin_state.map_label {
windows
.iter()
.find_map(|(l, window)| (map(l) == label).then_some(window))
} else {
windows.get(label)
};
if let Some(window) = window {
window.update_state(s, flags)?;
}
}
create_dir_all(app_dir)?;
std::fs::write(state_path, serde_json::to_vec_pretty(&*state)?)?;
Ok(())
}
fn filename(&self) -> String {
self.state::<PluginState>().filename.clone()
}
}
/// Extension trait for [`Window`] and [`WebviewWindow`] exposing window state APIs.
pub trait WindowExt {
/// Restores this window state from disk
fn restore_state(&self, flags: StateFlags) -> tauri::Result<()>;
}
impl<R: Runtime> WindowExt for WebviewWindow<R> {
fn restore_state(&self, flags: StateFlags) -> tauri::Result<()> {
self.as_ref().window().restore_state(flags)
}
}
impl<R: Runtime> WindowExt for Window<R> {
fn restore_state(&self, flags: StateFlags) -> tauri::Result<()> {
let plugin_state = self.app_handle().state::<PluginState>();
let label = plugin_state
.map_label
.as_ref()
.map(|map| map(self.label()))
.unwrap_or_else(|| self.label());
let restoring_window_state = self.state::<RestoringWindowState>();
let _restoring_window_lock = restoring_window_state.0.lock().unwrap();
let cache = self.state::<WindowStateCache>();
let mut c = cache.0.lock().unwrap();
let mut should_show = true;
if let Some(state) = c
.get(label)
.filter(|state| state != &&WindowState::default())
{
if flags.contains(StateFlags::DECORATIONS) {
self.set_decorations(state.decorated)?;
}
if flags.contains(StateFlags::POSITION) {
let position = (state.x, state.y).into();
let size = (state.width, state.height).into();
// restore position to saved value if saved monitor exists
// otherwise, let the OS decide where to place the window
for m in self.available_monitors()? {
if m.intersects(position, size) {
self.set_position(PhysicalPosition {
x: if state.maximized {
state.prev_x
} else {
state.x
},
y: if state.maximized {
state.prev_y
} else {
state.y
},
})?;
}
}
}
if flags.contains(StateFlags::SIZE) {
self.set_size(PhysicalSize {
width: state.width,
height: state.height,
})?;
}
if flags.contains(StateFlags::MAXIMIZED) && state.maximized {
self.maximize()?;
}
if flags.contains(StateFlags::FULLSCREEN) {
self.set_fullscreen(state.fullscreen)?;
}
should_show = state.visible;
} else {
let mut metadata = WindowState::default();
if flags.contains(StateFlags::SIZE) {
let size = self.inner_size()?;
metadata.width = size.width;
metadata.height = size.height;
}
if flags.contains(StateFlags::POSITION) {
let pos = self.outer_position()?;
metadata.x = pos.x;
metadata.y = pos.y;
}
if flags.contains(StateFlags::MAXIMIZED) {
metadata.maximized = self.is_maximized()?;
}
if flags.contains(StateFlags::VISIBLE) {
metadata.visible = self.is_visible()?;
}
if flags.contains(StateFlags::DECORATIONS) {
metadata.decorated = self.is_decorated()?;
}
if flags.contains(StateFlags::FULLSCREEN) {
metadata.fullscreen = self.is_fullscreen()?;
}
c.insert(label.into(), metadata);
}
if flags.contains(StateFlags::VISIBLE) && should_show {
self.show()?;
self.set_focus()?;
}
Ok(())
}
}
trait WindowExtInternal {
fn update_state(&self, state: &mut WindowState, flags: StateFlags) -> tauri::Result<()>;
}
impl<R: Runtime> WindowExtInternal for WebviewWindow<R> {
fn update_state(&self, state: &mut WindowState, flags: StateFlags) -> tauri::Result<()> {
self.as_ref().window().update_state(state, flags)
}
}
impl<R: Runtime> WindowExtInternal for Window<R> {
fn update_state(&self, state: &mut WindowState, flags: StateFlags) -> tauri::Result<()> {
let is_maximized = flags
.intersects(StateFlags::MAXIMIZED | StateFlags::POSITION | StateFlags::SIZE)
&& self.is_maximized()?;
let is_minimized =
flags.intersects(StateFlags::POSITION | StateFlags::SIZE) && self.is_minimized()?;
if flags.contains(StateFlags::MAXIMIZED) {
state.maximized = is_maximized;
}
if flags.contains(StateFlags::FULLSCREEN) {
state.fullscreen = self.is_fullscreen()?;
}
if flags.contains(StateFlags::DECORATIONS) {
state.decorated = self.is_decorated()?;
}
if flags.contains(StateFlags::VISIBLE) {
state.visible = self.is_visible()?;
}
if flags.contains(StateFlags::SIZE) && !is_maximized && !is_minimized {
let size = self.inner_size()?;
// It doesn't make sense to save a window with 0 height or width
if size.width > 0 && size.height > 0 {
state.width = size.width;
state.height = size.height;
}
}
if flags.contains(StateFlags::POSITION) && !is_maximized && !is_minimized {
let position = self.outer_position()?;
state.x = position.x;
state.y = position.y;
}
Ok(())
}
}
/// Builder for the window-state [plugin](TauriPlugin).
#[derive(Default)]
pub struct Builder {
denylist: HashSet<String>,
filter_callback: Option<Box<FilterCallbackFn>>,
skip_initial_state: HashSet<String>,
state_flags: StateFlags,
map_label: Option<Box<LabelMapperFn>>,
filename: Option<String>,
}
impl Builder {
/// Creates a new [`Builder`] with the default configuration:
/// all [`StateFlags`] enabled, no denylist, no filter, and the [`DEFAULT_FILENAME`].
pub fn new() -> Self {
Self::default()
}
/// Sets the state flags to control what state gets restored and saved.
pub fn with_state_flags(mut self, flags: StateFlags) -> Self {
self.state_flags = flags;
self
}
/// Sets a custom filename to use when saving and restoring window states from disk.
pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
self.filename.replace(filename.into());
self
}
/// Sets a list of windows that shouldn't be tracked and managed by this plugin
/// For example, splash screen windows.
pub fn with_denylist(mut self, denylist: &[&str]) -> Self {
self.denylist = denylist.iter().map(|l| l.to_string()).collect();
self
}
/// Sets a filter callback to exclude specific windows from being tracked.
/// Return `true` to save the state, or `false` to skip and not save it.
pub fn with_filter<F>(mut self, filter_callback: F) -> Self
where
F: Fn(&str) -> bool + Send + Sync + 'static,
{
self.filter_callback = Some(Box::new(filter_callback));
self
}
/// Adds the given window label to a list of windows to skip initial state restore.
pub fn skip_initial_state(mut self, label: &str) -> Self {
self.skip_initial_state.insert(label.into());
self
}
/// Transforms the window label when saving the window state.
///
/// This can be used to group different windows to use the same state.
pub fn map_label<F>(mut self, map_fn: F) -> Self
where
F: Fn(&str) -> &str + Sync + Send + 'static,
{
self.map_label = Some(Box::new(map_fn));
self
}
/// Builds the [`TauriPlugin`].
///
/// The plugin loads the previously saved window state on setup, restores each window's
/// state when it becomes ready (unless denylisted, filtered out, or opted out with
/// [`Builder::skip_initial_state`]), tracks move/resize events to keep the state up to date,
/// and saves the state of all windows to disk when the app exits.
pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
let state_flags = self.state_flags;
let filename = self.filename.unwrap_or_else(|| DEFAULT_FILENAME.into());
let map_label = self.map_label;
PluginBuilder::new("window-state")
.invoke_handler(tauri::generate_handler![
cmd::save_window_state,
cmd::restore_state,
cmd::filename
])
.setup(move |app, _api| {
let cache = load_saved_window_states(app, &filename).unwrap_or_default();
app.manage(WindowStateCache(Arc::new(Mutex::new(cache))));
app.manage(RestoringWindowState(Mutex::new(())));
app.manage(PluginState {
state_flags,
filename,
map_label,
});
Ok(())
})
.on_window_ready(move |window| {
let plugin_state = window.app_handle().state::<PluginState>();
let label = plugin_state
.map_label
.as_ref()
.map(|map| map(window.label()))
.unwrap_or_else(|| window.label());
// Check deny list names
if self.denylist.contains(label) {
return;
}
// Check deny list callback
if let Some(filter_callback) = &self.filter_callback {
// Don't save the state if the callback returns false
if !filter_callback(label) {
return;
}
}
if !self.skip_initial_state.contains(label) {
let _ = window.restore_state(state_flags);
}
let cache = window.state::<WindowStateCache>();
let cache = cache.0.clone();
let label = label.to_string();
let window_clone = window.clone();
// insert a default state if this window should be tracked and
// the disk cache doesn't have a state for it
{
cache
.lock()
.unwrap()
.entry(label.clone())
.or_insert_with(WindowState::default);
}
window.on_window_event(move |e| match e {
WindowEvent::CloseRequested { .. } => {
let mut c = cache.lock().unwrap();
if let Some(state) = c.get_mut(&label) {
let _ = window_clone.update_state(state, state_flags);
}
}
WindowEvent::Moved(position)
if state_flags.contains(StateFlags::POSITION)
&& window_clone
.state::<RestoringWindowState>()
.0
.try_lock()
.is_ok()
&& !window_clone.is_minimized().unwrap_or_default() =>
{
let mut c = cache.lock().unwrap();
if let Some(state) = c.get_mut(&label) {
state.prev_x = state.x;
state.prev_y = state.y;
state.x = position.x;
state.y = position.y;
}
}
WindowEvent::Resized(size)
if state_flags.contains(StateFlags::SIZE)
&& window_clone
.state::<RestoringWindowState>()
.0
.try_lock()
.is_ok() =>
{
// TODO: Remove once https://github.com/tauri-apps/tauri/issues/5812 is resolved.
let is_maximized = if cfg!(target_os = "macos")
&& (!window_clone.is_decorated().unwrap_or_default()
|| !window_clone.is_resizable().unwrap_or_default())
{
false
} else {
window_clone.is_maximized().unwrap_or_default()
};
if !window_clone.is_minimized().unwrap_or_default() && !is_maximized {
let mut c = cache.lock().unwrap();
if let Some(state) = c.get_mut(&label) {
state.width = size.width;
state.height = size.height;
}
}
}
_ => {}
});
})
.on_event(move |app, event| {
if let RunEvent::Exit = event {
let _ = app.save_window_state(state_flags);
}
})
.build()
}
}
fn load_saved_window_states<R: Runtime>(
app: &AppHandle<R>,
filename: &String,
) -> Result<HashMap<String, WindowState>> {
let app_dir = app.path().app_config_dir()?;
let state_path = app_dir.join(filename);
let file = std::fs::File::open(state_path)?;
let reader = BufReader::new(file);
let states = serde_json::from_reader(reader)?;
Ok(states)
}
trait MonitorExt {
fn intersects(&self, position: PhysicalPosition<i32>, size: PhysicalSize<u32>) -> bool;
}
impl MonitorExt for Monitor {
fn intersects(&self, position: PhysicalPosition<i32>, size: PhysicalSize<u32>) -> bool {
let PhysicalPosition { x, y } = *self.position();
let PhysicalSize { width, height } = *self.size();
let left = x;
let right = x + width as i32;
let top = y;
let bottom = y + height as i32;
[
(position.x, position.y),
(position.x + size.width as i32, position.y),
(position.x, position.y + size.height as i32),
(
position.x + size.width as i32,
position.y + size.height as i32,
),
]
.into_iter()
.any(|(x, y)| x >= left && x < right && y >= top && y < bottom)
}
}

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "guest-js"
},
"include": ["guest-js/*.ts"]
}