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
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:
80
plugins/opener/CHANGELOG.md
Normal file
80
plugins/opener/CHANGELOG.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# Changelog
|
||||
|
||||
## [2.5.5]
|
||||
|
||||
- [`db9c5998`](https://github.com/tauri-apps/plugins-workspace/commit/db9c5998feff9384f9cbbefcbe0d45937c00a1fc) ([#3531](https://github.com/tauri-apps/plugins-workspace/pull/3531) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix missing `consumer-rules.pro` on Gradle v9.
|
||||
|
||||
## \[2.5.4]
|
||||
|
||||
- [`c1fd33b3`](https://github.com/tauri-apps/plugins-workspace/commit/c1fd33b3a2735f2e25c1d026dc524af932db3315) ([#3343](https://github.com/tauri-apps/plugins-workspace/pull/3343) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix `revealItemInDir`/`reveal_items_in_dir` can't reveal network paths like `\\wsl.localhost\Ubuntu\etc` on Windows
|
||||
|
||||
## \[2.5.3]
|
||||
|
||||
- [`3d0d2e04`](https://github.com/tauri-apps/plugins-workspace/commit/3d0d2e041bbad9766aebecaeba291a28d8d7bf5c) ([#3163](https://github.com/tauri-apps/plugins-workspace/pull/3163) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Properly ignore `with: inAppBrowser` on desktop. This prevents an issue were `open_url` seamingly did nothing on desktop.
|
||||
|
||||
## \[2.5.2]
|
||||
|
||||
- [`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.5.1]
|
||||
|
||||
- [`6c9b61fb`](https://github.com/tauri-apps/plugins-workspace/commit/6c9b61fb658145d13893626112fc489f7458aa17) ([#3039](https://github.com/tauri-apps/plugins-workspace/pull/3039) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) On Android, updated compileSdk to 36.
|
||||
- [`67a7bf80`](https://github.com/tauri-apps/plugins-workspace/commit/67a7bf80f8e6f3aec76ebaba0983f0cf0103d3ff) ([#3018](https://github.com/tauri-apps/plugins-workspace/pull/3018) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix opener doesn't open same origin links in the browser
|
||||
|
||||
## \[2.5.0]
|
||||
|
||||
### enhance
|
||||
|
||||
- [`b8056f48`](https://github.com/tauri-apps/plugins-workspace/commit/b8056f484c7144af095d4d6ded1e8adbb9b8a865) ([#2897](https://github.com/tauri-apps/plugins-workspace/pull/2897) by [@petersamokhin](https://github.com/tauri-apps/plugins-workspace/../../petersamokhin)) Allow reveal multiple items in the file explorer.
|
||||
|
||||
## \[2.4.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.3.1]
|
||||
|
||||
### feat
|
||||
|
||||
- [`2aec8ff4`](https://github.com/tauri-apps/plugins-workspace/commit/2aec8ff4c41d178ea9804f7b6eff343c726be015) ([#2803](https://github.com/tauri-apps/plugins-workspace/pull/2803) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Add `inAppBrowser` option to open URLs in an in-app browser on Android and iOS.
|
||||
|
||||
## \[2.3.0]
|
||||
|
||||
- [`ce9888a2`](https://github.com/tauri-apps/plugins-workspace/commit/ce9888a2d4c9b449bd2a306f0fa6c76507fd46d3) ([#2762](https://github.com/tauri-apps/plugins-workspace/pull/2762)) Similar to the `fs` plugin the `opener` plugin now supports a `requireLiteralLeadingDot` configuration in `tauri.conf.json`.
|
||||
|
||||
## \[2.2.7]
|
||||
|
||||
- [`6c9e08dc`](https://github.com/tauri-apps/plugins-workspace/commit/6c9e08dccb3ac99fccfce586fa2b69717ba81b52) ([#2695](https://github.com/tauri-apps/plugins-workspace/pull/2695) by [@ShaunSHamilton](https://github.com/tauri-apps/plugins-workspace/../../ShaunSHamilton)) Adjust `open_url` url type to allow `URL`
|
||||
- [`dde6f3c3`](https://github.com/tauri-apps/plugins-workspace/commit/dde6f3c31c1b79942abb556be31757dc583f509e) ([#2549](https://github.com/tauri-apps/plugins-workspace/pull/2549) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update `windows` crate to 0.61 to align with Tauri 2.5
|
||||
|
||||
## \[2.2.6]
|
||||
|
||||
- [`1a984659`](https://github.com/tauri-apps/plugins-workspace/commit/1a9846599b6a71faf330845847a30f6bf9735898) ([#2469](https://github.com/tauri-apps/plugins-workspace/pull/2469) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Update `objc2` crate to 0.6. No user facing changes.
|
||||
- [`71f95c9f`](https://github.com/tauri-apps/plugins-workspace/commit/71f95c9f05b29cf1be586849614c0b007757c15d) ([#2445](https://github.com/tauri-apps/plugins-workspace/pull/2445) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated `windows` crate to 0.60 to match Tauri 2.3.0. No user facing changes.
|
||||
|
||||
## \[2.2.5]
|
||||
|
||||
- [`5b821181`](https://github.com/tauri-apps/plugins-workspace/commit/5b8211815825ddae2dcc0c00520e0cfdff002763) ([#2332](https://github.com/tauri-apps/plugins-workspace/pull/2332) by [@betamos](https://github.com/tauri-apps/plugins-workspace/../../betamos)) Fix broken JS commands `opener.openPath` and `opener.openUrl` on mobile.
|
||||
|
||||
## \[2.2.4]
|
||||
|
||||
- [`da5c59e2`](https://github.com/tauri-apps/plugins-workspace/commit/da5c59e2fe879d177e3cfd52fcacce85440423cb) ([#2271](https://github.com/tauri-apps/plugins-workspace/pull/2271) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated `zbus` dependency to version 5. No API changes.
|
||||
|
||||
## \[2.2.3]
|
||||
|
||||
- [`a9ac1e3c`](https://github.com/tauri-apps/plugins-workspace/commit/a9ac1e3c939cec4338a9422ef02323c1d4dde6cd) ([#2253](https://github.com/tauri-apps/plugins-workspace/pull/2253) by [@betamos](https://github.com/tauri-apps/plugins-workspace/../../betamos)) Return an error in `open_path` if the file does not exist when opening with default application.
|
||||
|
||||
## \[2.2.2]
|
||||
|
||||
- [`ee0f65de`](https://github.com/tauri-apps/plugins-workspace/commit/ee0f65de5c645c244c5f0b638e0e0aab687cb9bf) ([#2207](https://github.com/tauri-apps/plugins-workspace/pull/2207) by [@universalappfactory](https://github.com/tauri-apps/plugins-workspace/../../universalappfactory)) Fixed OpenerPlugin packagename for android
|
||||
|
||||
## \[2.2.1]
|
||||
|
||||
- [`18dffc9d`](https://github.com/tauri-apps/plugins-workspace/commit/18dffc9dfecaf0c900e233e041d9ca36c92834b5) ([#2189](https://github.com/tauri-apps/plugins-workspace/pull/2189) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Fix usage on iOS.
|
||||
|
||||
## \[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.0]
|
||||
|
||||
- [`383e636a`](https://github.com/tauri-apps/plugins-workspace/commit/383e636a8e595aec1300999a8aeb7d9bf8c14632) ([#2019](https://github.com/tauri-apps/plugins-workspace/pull/2019) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Initial Release
|
||||
67
plugins/opener/Cargo.toml
Normal file
67
plugins/opener/Cargo.toml
Normal file
@@ -0,0 +1,67 @@
|
||||
[package]
|
||||
name = "tauri-plugin-opener"
|
||||
version = "2.5.5"
|
||||
description = "Open files and URLs using their default application."
|
||||
edition = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
license = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
links = "tauri-plugin-opener"
|
||||
|
||||
# Platforms supported by the plugin
|
||||
# Support levels are "full", "partial", "none", "unknown"
|
||||
# Details of the support level are left to plugin maintainer
|
||||
exclude = ["/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 = "partial", notes = "Only allows to open URLs via `open`" }
|
||||
ios = { level = "partial", notes = "Only allows to open URLs via `open`" }
|
||||
|
||||
|
||||
[build-dependencies]
|
||||
tauri-plugin = { workspace = true, features = ["build"] }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
open = { version = "5", features = ["shellexecute-on-windows"] }
|
||||
glob = { workspace = true }
|
||||
dunce = { workspace = true }
|
||||
|
||||
[target."cfg(windows)".dependencies.windows]
|
||||
version = "0.61"
|
||||
features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_UI_Shell_Common",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Registry",
|
||||
"Win32_Storage_FileSystem",
|
||||
]
|
||||
|
||||
[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"netbsd\", target_os = \"openbsd\"))".dependencies]
|
||||
zbus = { workspace = true }
|
||||
url = { workspace = true }
|
||||
|
||||
[target."cfg(target_os = \"macos\")".dependencies.objc2-app-kit]
|
||||
version = "0.3"
|
||||
default-features = false
|
||||
features = ["std", "NSWorkspace"]
|
||||
|
||||
[target."cfg(target_os = \"macos\")".dependencies.objc2-foundation]
|
||||
version = "0.3"
|
||||
default-features = false
|
||||
features = ["std", "NSURL", "NSArray", "NSString"]
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
20
plugins/opener/LICENSE.spdx
Normal file
20
plugins/opener/LICENSE.spdx
Normal 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
|
||||
177
plugins/opener/LICENSE_APACHE-2.0
Normal file
177
plugins/opener/LICENSE_APACHE-2.0
Normal 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
|
||||
21
plugins/opener/LICENSE_MIT
Normal file
21
plugins/opener/LICENSE_MIT
Normal 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.
|
||||
143
plugins/opener/README.md
Normal file
143
plugins/opener/README.md
Normal file
@@ -0,0 +1,143 @@
|
||||

|
||||
|
||||
<!-- description -->
|
||||
|
||||
| Platform | Supported |
|
||||
| -------- | --------- |
|
||||
| Linux | ✓ |
|
||||
| Windows | ✓ |
|
||||
| macOS | ✓ |
|
||||
| Android | ✓ |
|
||||
| iOS | ✓ |
|
||||
|
||||
## 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-opener = "2.0.0"
|
||||
# alternatively with Git:
|
||||
tauri-plugin-opener = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
<!-- Add the branch for installations using git! -->
|
||||
|
||||
```sh
|
||||
pnpm add @tauri-apps/plugin-opener
|
||||
# or
|
||||
npm add @tauri-apps/plugin-opener
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-opener
|
||||
```
|
||||
|
||||
## 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_opener::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import { openUrl, openPath, revealItemInDir } from '@tauri-apps/plugin-opener'
|
||||
|
||||
// Opens the URL in the default browser
|
||||
await openUrl('https://example.com')
|
||||
// Or with a specific browser/app
|
||||
await openUrl('https://example.com', 'firefox')
|
||||
|
||||
// Opens the path with the system's default app
|
||||
await openPath('/path/to/file')
|
||||
// Or with a specific app
|
||||
await openPath('/path/to/file', 'firefox')
|
||||
|
||||
// Reveal a path with the system's default explorer
|
||||
await revealItemInDir('/path/to/file')
|
||||
|
||||
// Reveal multiple paths with the system's default explorer
|
||||
// Note: will be renamed to `revealItemsInDir` in the next major version
|
||||
await revealItemInDir(['/path/to/file', '/path/to/another/file'])
|
||||
```
|
||||
|
||||
### Usage from Rust
|
||||
|
||||
You can also use those APIs from Rust:
|
||||
|
||||
```rust
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.setup(|app| {
|
||||
let opener = app.opener();
|
||||
|
||||
// Opens the URL in the default browser
|
||||
opener.open_url("https://example.com", None::<&str>)?;
|
||||
// Or with a specific browser/app
|
||||
opener.open_url("https://example.com", Some("firefox"))?;
|
||||
|
||||
// Opens the path with the system's default app
|
||||
opener.open_path("/path/to/file", None::<&str>)?;
|
||||
// Or with a specific app
|
||||
opener.open_path("/path/to/file", Some("firefox"))?;
|
||||
|
||||
// Reveal a path with the system's default explorer
|
||||
opener.reveal_item_in_dir("/path/to/file")?;
|
||||
|
||||
// Reveal multiple paths with the system's default explorer
|
||||
opener.reveal_items_in_dir(["/path/to/file"])?;
|
||||
Ok(())
|
||||
})
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
## 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.
|
||||
23
plugins/opener/SECURITY.md
Normal file
23
plugins/opener/SECURITY.md
Normal 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).
|
||||
2
plugins/opener/android/.gitignore
vendored
Normal file
2
plugins/opener/android/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/build
|
||||
/.tauri
|
||||
31
plugins/opener/android/build.gradle.kts
Normal file
31
plugins/opener/android/build.gradle.kts
Normal file
@@ -0,0 +1,31 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri.opener"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.core:core-ktx:1.9.0")
|
||||
implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
|
||||
implementation("androidx.browser:browser:1.8.0")
|
||||
implementation(project(":tauri-android"))
|
||||
}
|
||||
21
plugins/opener/android/consumer-rules.pro
Normal file
21
plugins/opener/android/consumer-rules.pro
Normal file
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
2
plugins/opener/android/settings.gradle
Normal file
2
plugins/opener/android/settings.gradle
Normal file
@@ -0,0 +1,2 @@
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
|
||||
3
plugins/opener/android/src/main/AndroidManifest.xml
Normal file
3
plugins/opener/android/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
</manifest>
|
||||
44
plugins/opener/android/src/main/java/OpenerPlugin.kt
Normal file
44
plugins/opener/android/src/main/java/OpenerPlugin.kt
Normal file
@@ -0,0 +1,44 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.opener
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import androidx.browser.customtabs.CustomTabsIntent
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.Plugin
|
||||
import androidx.core.net.toUri
|
||||
import app.tauri.annotation.InvokeArg
|
||||
|
||||
@InvokeArg
|
||||
class OpenArgs {
|
||||
lateinit var url: String
|
||||
var with: String? = null
|
||||
}
|
||||
|
||||
@TauriPlugin
|
||||
class OpenerPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
@Command
|
||||
fun open(invoke: Invoke) {
|
||||
try {
|
||||
val args = invoke.parseArgs(OpenArgs::class.java)
|
||||
|
||||
if (args.with == "inAppBrowser") {
|
||||
val builder = CustomTabsIntent.Builder()
|
||||
val intent = builder.build()
|
||||
intent.launchUrl(activity, args.url.toUri())
|
||||
} else {
|
||||
val intent = Intent(Intent.ACTION_VIEW, args.url.toUri())
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
activity.applicationContext?.startActivity(intent)
|
||||
}
|
||||
invoke.resolve()
|
||||
} catch (ex: Exception) {
|
||||
invoke.reject(ex.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
1
plugins/opener/api-iife.js
Normal file
1
plugins/opener/api-iife.js
Normal file
@@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_OPENER__=function(n,e){"use strict";return n.openPath=async function(n,_){await e.invoke("plugin:opener|open_path",{path:n,with:_})},n.openUrl=async function(n,_){await e.invoke("plugin:opener|open_url",{url:n,with:_})},n.revealItemInDir=async function(n){const _="string"==typeof n?[n]:n;return e.invoke("plugin:opener|reveal_item_in_dir",{paths:_})},n}({},window.__TAURI__.core);Object.defineProperty(window.__TAURI__,"opener",{value:__TAURI_PLUGIN_OPENER__})}
|
||||
132
plugins/opener/build.rs
Normal file
132
plugins/opener/build.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[path = "src/scope_entry.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod scope;
|
||||
|
||||
/// Opener scope application.
|
||||
#[derive(schemars::JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
#[allow(unused)]
|
||||
#[derive(Default)]
|
||||
enum Application {
|
||||
/// Open in default application.
|
||||
#[default]
|
||||
Default,
|
||||
/// If true, allow open with any application.
|
||||
Enable(bool),
|
||||
/// Allow specific application to open with.
|
||||
App(String),
|
||||
}
|
||||
|
||||
/// Opener scope entry.
|
||||
#[derive(schemars::JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
#[allow(unused)]
|
||||
enum OpenerScopeEntry {
|
||||
Url {
|
||||
/// A URL that can be opened by the webview when using the Opener APIs.
|
||||
///
|
||||
/// Wildcards can be used following the UNIX glob pattern.
|
||||
///
|
||||
/// Examples:
|
||||
///
|
||||
/// - "https://*" : allows all HTTPS origin
|
||||
///
|
||||
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
|
||||
///
|
||||
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
|
||||
url: String,
|
||||
/// An application to open this url with, for example: firefox.
|
||||
#[serde(default)]
|
||||
app: Application,
|
||||
},
|
||||
Path {
|
||||
/// A path that can be opened by the webview when using the Opener APIs.
|
||||
///
|
||||
/// The pattern can start with a variable that resolves to a system base directory.
|
||||
/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
|
||||
/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
|
||||
/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
|
||||
/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
|
||||
path: PathBuf,
|
||||
/// An application to open this path with, for example: xdg-open.
|
||||
#[serde(default)]
|
||||
app: Application,
|
||||
},
|
||||
}
|
||||
|
||||
// Ensure `OpenerScopeEntry` and `scope::EntryRaw` is kept in sync
|
||||
fn _f() {
|
||||
match (scope::EntryRaw::Url {
|
||||
url: String::new(),
|
||||
app: scope::Application::Enable(true),
|
||||
}) {
|
||||
scope::EntryRaw::Url { url, app } => OpenerScopeEntry::Url {
|
||||
url,
|
||||
app: match app {
|
||||
scope::Application::Enable(p) => Application::Enable(p),
|
||||
scope::Application::App(p) => Application::App(p),
|
||||
scope::Application::Default => Application::Default,
|
||||
},
|
||||
},
|
||||
scope::EntryRaw::Path { path, app } => OpenerScopeEntry::Path {
|
||||
path,
|
||||
app: match app {
|
||||
scope::Application::Enable(p) => Application::Enable(p),
|
||||
scope::Application::App(p) => Application::App(p),
|
||||
scope::Application::Default => Application::Default,
|
||||
},
|
||||
},
|
||||
};
|
||||
match (OpenerScopeEntry::Url {
|
||||
url: String::new(),
|
||||
app: Application::Enable(true),
|
||||
}) {
|
||||
OpenerScopeEntry::Url { url, app } => scope::EntryRaw::Url {
|
||||
url,
|
||||
app: match app {
|
||||
Application::Enable(p) => scope::Application::Enable(p),
|
||||
Application::App(p) => scope::Application::App(p),
|
||||
Application::Default => scope::Application::Default,
|
||||
},
|
||||
},
|
||||
OpenerScopeEntry::Path { path, app } => scope::EntryRaw::Path {
|
||||
path,
|
||||
app: match app {
|
||||
Application::Enable(p) => scope::Application::Enable(p),
|
||||
Application::App(p) => scope::Application::App(p),
|
||||
Application::Default => scope::Application::Default,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const COMMANDS: &[&str] = &["open_url", "open_path", "reveal_item_in_dir"];
|
||||
|
||||
fn main() {
|
||||
tauri_plugin::Builder::new(COMMANDS)
|
||||
.global_api_script_path("./api-iife.js")
|
||||
.android_path("android")
|
||||
.ios_path("ios")
|
||||
.global_scope_schema(schemars::schema_for!(OpenerScopeEntry))
|
||||
.build();
|
||||
|
||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
let mobile = target_os == "ios" || target_os == "android";
|
||||
alias("desktop", !mobile);
|
||||
alias("mobile", mobile);
|
||||
}
|
||||
|
||||
// creates a cfg alias if `has_feature` is true.
|
||||
// `alias` must be a snake case string.
|
||||
fn alias(alias: &str, has_feature: bool) {
|
||||
println!("cargo:rustc-check-cfg=cfg({alias})");
|
||||
if has_feature {
|
||||
println!("cargo:rustc-cfg={alias}");
|
||||
}
|
||||
}
|
||||
99
plugins/opener/guest-js/index.ts
Normal file
99
plugins/opener/guest-js/index.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Open files and URLs using their default application.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the files and urls to be opened.
|
||||
*
|
||||
* ### Restricting access to the {@link open | `open`} API
|
||||
*
|
||||
* On the configuration object, `open: true` means that the {@link open} API can be used with any URL,
|
||||
* as the argument is validated with the `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+` regex.
|
||||
* You can change that regex by changing the boolean value to a string, e.g. `open: ^https://github.com/`.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
|
||||
/**
|
||||
* Opens a url with the system's default app, or the one specified with {@linkcode openWith}.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { openUrl } from '@tauri-apps/plugin-opener';
|
||||
*
|
||||
* // opens the given URL on the default browser:
|
||||
* await openUrl('https://github.com/tauri-apps/tauri');
|
||||
* // opens the given URL using `firefox`:
|
||||
* await openUrl('https://github.com/tauri-apps/tauri', 'firefox');
|
||||
* ```
|
||||
*
|
||||
* @param url The URL to open.
|
||||
* @param openWith The app to open the URL with. If not specified, defaults to the system default application for the specified url type.
|
||||
* On mobile, `openWith` can be provided as `inAppBrowser` to open the URL in an in-app browser. Otherwise, it will open the URL in the system default browser.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function openUrl(
|
||||
url: string | URL,
|
||||
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
|
||||
openWith?: 'inAppBrowser' | string
|
||||
): Promise<void> {
|
||||
await invoke('plugin:opener|open_url', {
|
||||
url,
|
||||
with: openWith
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a path with the system's default app, or the one specified with {@linkcode openWith}.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { openPath } from '@tauri-apps/plugin-opener';
|
||||
*
|
||||
* // opens a file using the default program:
|
||||
* await openPath('/path/to/file');
|
||||
* // opens a file using `vlc` command on Windows.
|
||||
* await openPath('C:/path/to/file', 'vlc');
|
||||
* ```
|
||||
*
|
||||
* @param path The path to open.
|
||||
* @param openWith The app to open the path with. If not specified, defaults to the system default application for the specified path type.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function openPath(path: string, openWith?: string): Promise<void> {
|
||||
await invoke('plugin:opener|open_path', {
|
||||
path,
|
||||
with: openWith
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveal a path with the system's default explorer.
|
||||
*
|
||||
* #### Platform-specific:
|
||||
*
|
||||
* - **Android / iOS:** Unsupported.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { revealItemInDir } from '@tauri-apps/plugin-opener';
|
||||
* await revealItemInDir('/path/to/file');
|
||||
* await revealItemInDir([ '/path/to/file', '/path/to/another/file' ]);
|
||||
* ```
|
||||
*
|
||||
* @param path The path to reveal.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function revealItemInDir(path: string | string[]): Promise<void> {
|
||||
const paths = typeof path === 'string' ? [path] : path
|
||||
return invoke('plugin:opener|reveal_item_in_dir', { paths })
|
||||
}
|
||||
70
plugins/opener/guest-js/init.ts
Normal file
70
plugins/opener/guest-js/init.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Webview script injected by the opener plugin on every page load.
|
||||
*
|
||||
* It installs a `click` listener on `window` that intercepts clicks on `<a>` elements whose
|
||||
* `target` is `_blank` (or that are clicked while holding `Ctrl` or `Shift`) and whose `href`
|
||||
* uses the `http:`, `https:`, `mailto:` or `tel:` protocol, cancels the navigation and opens the
|
||||
* link with the system's default browser through the `plugin:opener|open_url` command instead.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
|
||||
// open <a href="..."> links with the API
|
||||
window.addEventListener('click', function (evt) {
|
||||
// return early if
|
||||
if (
|
||||
// event was prevented
|
||||
evt.defaultPrevented
|
||||
// or not a left click
|
||||
|| evt.button !== 0
|
||||
// or meta key pressed
|
||||
|| evt.metaKey
|
||||
// or al key pressed
|
||||
|| evt.altKey
|
||||
)
|
||||
return
|
||||
|
||||
const a = evt
|
||||
.composedPath()
|
||||
.find((el) => el instanceof Node && el.nodeName.toUpperCase() === 'A') as
|
||||
| HTMLAnchorElement
|
||||
| undefined
|
||||
|
||||
// return early if
|
||||
if (
|
||||
// not tirggered from <a> element
|
||||
!a
|
||||
// or doesn't have a href
|
||||
|| !a.href
|
||||
// or not supposed to be open in a new tab
|
||||
|| !(
|
||||
a.target === '_blank'
|
||||
// or ctrl key pressed
|
||||
|| evt.ctrlKey
|
||||
// or shift key pressed
|
||||
|| evt.shiftKey
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
const url = new URL(a.href)
|
||||
|
||||
// return early if
|
||||
if (
|
||||
// not default protocols
|
||||
['http:', 'https:', 'mailto:', 'tel:'].every((p) => url.protocol !== p)
|
||||
)
|
||||
return
|
||||
|
||||
evt.preventDefault()
|
||||
|
||||
void invoke('plugin:opener|open_url', {
|
||||
url
|
||||
})
|
||||
})
|
||||
16
plugins/opener/ios/Package.resolved
Normal file
16
plugins/opener/ios/Package.resolved
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "SwiftRs",
|
||||
"repositoryURL": "https://github.com/Brendonovich/swift-rs",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "b5ed223fcdab165bc21219c1925dc1e77e2bef5e",
|
||||
"version": "1.0.6"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
34
plugins/opener/ios/Package.swift
Normal file
34
plugins/opener/ios/Package.swift
Normal file
@@ -0,0 +1,34 @@
|
||||
// swift-tools-version:5.3
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "tauri-plugin-opener",
|
||||
platforms: [
|
||||
.macOS(.v10_13),
|
||||
.iOS(.v13),
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, and make them visible to other packages.
|
||||
.library(
|
||||
name: "tauri-plugin-opener",
|
||||
type: .static,
|
||||
targets: ["tauri-plugin-opener"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "Tauri", path: "../.tauri/tauri-api")
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
// Targets can depend on other targets in this package, and on products in packages this package depends on.
|
||||
.target(
|
||||
name: "tauri-plugin-opener",
|
||||
dependencies: [
|
||||
.byName(name: "Tauri")
|
||||
],
|
||||
path: "Sources")
|
||||
]
|
||||
)
|
||||
46
plugins/opener/ios/Sources/OpenerPlugin.swift
Normal file
46
plugins/opener/ios/Sources/OpenerPlugin.swift
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import SafariServices
|
||||
import SwiftRs
|
||||
import Tauri
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
struct OpenArgs: Decodable {
|
||||
let url: String
|
||||
let with: String?
|
||||
}
|
||||
|
||||
class OpenerPlugin: Plugin {
|
||||
@objc public func open(_ invoke: Invoke) throws {
|
||||
do {
|
||||
let args = try invoke.parseArgs(OpenArgs.self)
|
||||
if let url = URL(string: args.url) {
|
||||
if args.with == "inAppBrowser" {
|
||||
DispatchQueue.main.async {
|
||||
let safariVC = SFSafariViewController(url: url)
|
||||
self.manager.viewController?.present(safariVC, animated: true)
|
||||
}
|
||||
} else {
|
||||
if #available(iOS 10, *) {
|
||||
UIApplication.shared.open(url, options: [:])
|
||||
} else {
|
||||
UIApplication.shared.openURL(url)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
invoke.resolve()
|
||||
} catch {
|
||||
invoke.reject(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("init_plugin_opener")
|
||||
func initPlugin() -> Plugin {
|
||||
return OpenerPlugin()
|
||||
}
|
||||
30
plugins/opener/package.json
Normal file
30
plugins/opener/package.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-opener",
|
||||
"version": "2.5.5",
|
||||
"description": "Open files and URLs using their default application.",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
17
plugins/opener/permissions/allow-default-urls.toml
Normal file
17
plugins/opener/permissions/allow-default-urls.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
"$schema" = "schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-default-urls"
|
||||
description = "This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application."
|
||||
|
||||
[[permission.scope.allow]]
|
||||
url = "mailto:*"
|
||||
|
||||
[[permission.scope.allow]]
|
||||
url = "tel:*"
|
||||
|
||||
[[permission.scope.allow]]
|
||||
url = "http://*"
|
||||
|
||||
[[permission.scope.allow]]
|
||||
url = "https://*"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-open-path"
|
||||
description = "Enables the open_path command without any pre-configured scope."
|
||||
commands.allow = ["open_path"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-open-path"
|
||||
description = "Denies the open_path command without any pre-configured scope."
|
||||
commands.deny = ["open_path"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-open-url"
|
||||
description = "Enables the open_url command without any pre-configured scope."
|
||||
commands.allow = ["open_url"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-open-url"
|
||||
description = "Denies the open_url command without any pre-configured scope."
|
||||
commands.deny = ["open_url"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-reveal-item-in-dir"
|
||||
description = "Enables the reveal_item_in_dir command without any pre-configured scope."
|
||||
commands.allow = ["reveal_item_in_dir"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-reveal-item-in-dir"
|
||||
description = "Denies the reveal_item_in_dir command without any pre-configured scope."
|
||||
commands.deny = ["reveal_item_in_dir"]
|
||||
111
plugins/opener/permissions/autogenerated/reference.md
Normal file
111
plugins/opener/permissions/autogenerated/reference.md
Normal file
@@ -0,0 +1,111 @@
|
||||
## Default Permission
|
||||
|
||||
This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application
|
||||
as well as reveal file in directories using default file explorer
|
||||
|
||||
#### This default permission set includes the following:
|
||||
|
||||
- `allow-open-url`
|
||||
- `allow-reveal-item-in-dir`
|
||||
- `allow-default-urls`
|
||||
|
||||
## Permission Table
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Identifier</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`opener:allow-default-urls`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`opener:allow-open-path`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the open_path command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`opener:deny-open-path`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the open_path command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`opener:allow-open-url`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the open_url command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`opener:deny-open-url`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the open_url command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`opener:allow-reveal-item-in-dir`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the reveal_item_in_dir command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`opener:deny-reveal-item-in-dir`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the reveal_item_in_dir command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
10
plugins/opener/permissions/default.toml
Normal file
10
plugins/opener/permissions/default.toml
Normal file
@@ -0,0 +1,10 @@
|
||||
"$schema" = "schemas/schema.json"
|
||||
|
||||
[default]
|
||||
description = """This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application
|
||||
as well as reveal file in directories using default file explorer"""
|
||||
permissions = [
|
||||
"allow-open-url",
|
||||
"allow-reveal-item-in-dir",
|
||||
"allow-default-urls",
|
||||
]
|
||||
348
plugins/opener/permissions/schemas/schema.json
Normal file
348
plugins/opener/permissions/schemas/schema.json
Normal file
@@ -0,0 +1,348 @@
|
||||
{
|
||||
"$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": "This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.",
|
||||
"type": "string",
|
||||
"const": "allow-default-urls",
|
||||
"markdownDescription": "This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application."
|
||||
},
|
||||
{
|
||||
"description": "Enables the open_path command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-open-path",
|
||||
"markdownDescription": "Enables the open_path command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the open_path command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-open-path",
|
||||
"markdownDescription": "Denies the open_path command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the open_url command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-open-url",
|
||||
"markdownDescription": "Enables the open_url command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the open_url command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-open-url",
|
||||
"markdownDescription": "Denies the open_url command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the reveal_item_in_dir command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-reveal-item-in-dir",
|
||||
"markdownDescription": "Enables the reveal_item_in_dir command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the reveal_item_in_dir command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-reveal-item-in-dir",
|
||||
"markdownDescription": "Denies the reveal_item_in_dir command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer\n#### This default permission set includes:\n\n- `allow-open-url`\n- `allow-reveal-item-in-dir`\n- `allow-default-urls`",
|
||||
"type": "string",
|
||||
"const": "default",
|
||||
"markdownDescription": "This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer\n#### This default permission set includes:\n\n- `allow-open-url`\n- `allow-reveal-item-in-dir`\n- `allow-default-urls`"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
22
plugins/opener/rollup.config.js
Normal file
22
plugins/opener/rollup.config.js
Normal file
@@ -0,0 +1,22 @@
|
||||
// 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'
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve'
|
||||
import typescript from '@rollup/plugin-typescript'
|
||||
import terser from '@rollup/plugin-terser'
|
||||
|
||||
export default createConfig({
|
||||
additionalConfigs: {
|
||||
input: 'guest-js/init.ts',
|
||||
output: {
|
||||
file: 'src/init-iife.js',
|
||||
format: 'iife'
|
||||
},
|
||||
plugins: [typescript(), terser(), nodeResolve()],
|
||||
onwarn: (warning) => {
|
||||
throw Object.assign(new Error(), warning)
|
||||
}
|
||||
}
|
||||
})
|
||||
76
plugins/opener/src/commands.rs
Normal file
76
plugins/opener/src/commands.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use tauri::{
|
||||
ipc::{CommandScope, GlobalScope},
|
||||
AppHandle, Runtime,
|
||||
};
|
||||
|
||||
use crate::{scope::Scope, Error, OpenerExt};
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn open_url<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
command_scope: CommandScope<crate::scope::Entry>,
|
||||
global_scope: GlobalScope<crate::scope::Entry>,
|
||||
url: String,
|
||||
with: Option<String>,
|
||||
) -> crate::Result<()> {
|
||||
let scope = Scope::new(
|
||||
&app,
|
||||
command_scope
|
||||
.allows()
|
||||
.iter()
|
||||
.chain(global_scope.allows())
|
||||
.collect(),
|
||||
command_scope
|
||||
.denies()
|
||||
.iter()
|
||||
.chain(global_scope.denies())
|
||||
.collect(),
|
||||
);
|
||||
|
||||
if scope.is_url_allowed(&url, with.as_deref()) {
|
||||
app.opener().open_url(url, with)
|
||||
} else {
|
||||
Err(Error::ForbiddenUrl { url, with })
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn open_path<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
command_scope: CommandScope<crate::scope::Entry>,
|
||||
global_scope: GlobalScope<crate::scope::Entry>,
|
||||
path: String,
|
||||
with: Option<String>,
|
||||
) -> crate::Result<()> {
|
||||
let scope = Scope::new(
|
||||
&app,
|
||||
command_scope
|
||||
.allows()
|
||||
.iter()
|
||||
.chain(global_scope.allows())
|
||||
.collect(),
|
||||
command_scope
|
||||
.denies()
|
||||
.iter()
|
||||
.chain(global_scope.denies())
|
||||
.collect(),
|
||||
);
|
||||
|
||||
if scope.is_path_allowed(Path::new(&path), with.as_deref())? {
|
||||
app.opener().open_path(path, with)
|
||||
} else {
|
||||
Err(Error::ForbiddenPath { path, with })
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO: in the next major version, rename to `reveal_items_in_dir`
|
||||
#[tauri::command]
|
||||
pub async fn reveal_item_in_dir(paths: Vec<PathBuf>) -> crate::Result<()> {
|
||||
crate::reveal_items_in_dir(&paths)
|
||||
}
|
||||
19
plugins/opener/src/config.rs
Normal file
19
plugins/opener/src/config.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// Whether or not paths that contain components that start with a `.`
|
||||
/// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
|
||||
/// or `[...]` will not match. This is useful because such files are
|
||||
/// conventionally considered hidden on Unix systems and it might be
|
||||
/// desirable to skip them when listing files.
|
||||
///
|
||||
/// Defaults to `true` on Unix systems and `false` on Windows
|
||||
// dotfiles are not supposed to be exposed by default on unix
|
||||
pub require_literal_leading_dot: Option<bool>,
|
||||
}
|
||||
82
plugins/opener/src/error.rs
Normal file
82
plugins/opener/src/error.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
/// The error type returned by the opener plugin's commands and APIs.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// Forwarded from a failed call into the mobile plugin runtime.
|
||||
#[cfg(mobile)]
|
||||
#[error(transparent)]
|
||||
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
|
||||
/// Forwarded from a [`tauri::Error`], e.g. when resolving a scoped path fails.
|
||||
#[error(transparent)]
|
||||
Tauri(#[from] tauri::Error),
|
||||
/// Forwarded from an [`std::io::Error`] raised while opening or revealing a path.
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
/// Forwarded from a [`serde_json::Error`] raised while (de)serializing a mobile plugin payload.
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
/// The program passed as `with` is not a program name known by the underlying opener.
|
||||
#[error("unknown program {0}")]
|
||||
UnknownProgramName(String),
|
||||
/// The path is not allowed by the opener scope, optionally together with the program it was requested to be opened with.
|
||||
#[error("Not allowed to open path {}{}", .path, .with.as_ref().map(|w| format!(" with {w}")).unwrap_or_default())]
|
||||
ForbiddenPath {
|
||||
/// The path that was rejected by the scope.
|
||||
path: String,
|
||||
/// The program the path was requested to be opened with, if any.
|
||||
with: Option<String>,
|
||||
},
|
||||
/// The URL is not allowed by the opener scope, optionally together with the program it was requested to be opened with.
|
||||
#[error("Not allowed to open url {}{}", .url, .with.as_ref().map(|w| format!(" with {w}")).unwrap_or_default())]
|
||||
ForbiddenUrl {
|
||||
/// The URL that was rejected by the scope.
|
||||
url: String,
|
||||
/// The program the URL was requested to be opened with, if any.
|
||||
with: Option<String>,
|
||||
},
|
||||
/// The requested API is not supported on the current platform, e.g. [`crate::reveal_item_in_dir`] on Android and iOS.
|
||||
#[error("API not supported on the current platform")]
|
||||
UnsupportedPlatform,
|
||||
/// Forwarded from a Win32 API call, see [`windows::core::Error`].
|
||||
#[error(transparent)]
|
||||
#[cfg(windows)]
|
||||
Win32Error(#[from] windows::core::Error),
|
||||
/// The given path has no parent directory, so it cannot be revealed in its containing folder.
|
||||
#[error("Path doesn't have a parent: {0}")]
|
||||
NoParent(PathBuf),
|
||||
// TODO: Add the underlying io::Error to this variant
|
||||
/// Failed to convert the path to a Windows `ITEMIDLIST` while preparing it to be revealed in the file explorer.
|
||||
#[cfg(windows)]
|
||||
#[error("Failed to convert path '{0}' to ITEMIDLIST")]
|
||||
FailedToConvertPathToItemIdList(PathBuf),
|
||||
/// Failed to convert the path to a `file://` URL, which is required to reveal it via D-Bus on Linux and BSD.
|
||||
#[error("Failed to convert path to file:// url")]
|
||||
FailedToConvertPathToFileUrl,
|
||||
/// Forwarded from a [`zbus::Error`] raised while talking to the file manager or the desktop portal over D-Bus.
|
||||
#[error(transparent)]
|
||||
#[cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
Zbus(#[from] zbus::Error),
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
1
plugins/opener/src/init-iife.js
Normal file
1
plugins/opener/src/init-iife.js
Normal file
@@ -0,0 +1 @@
|
||||
!function(){"use strict";"function"==typeof SuppressedError&&SuppressedError,window.addEventListener("click",function(e){if(e.defaultPrevented||0!==e.button||e.metaKey||e.altKey)return;const t=e.composedPath().find(e=>e instanceof Node&&"A"===e.nodeName.toUpperCase());if(!t||!t.href||"_blank"!==t.target&&!e.ctrlKey&&!e.shiftKey)return;const n=new URL(t.href);["http:","https:","mailto:","tel:"].every(e=>n.protocol!==e)||(e.preventDefault(),async function(e,t={},n){window.__TAURI_INTERNALS__.invoke(e,t,n)}("plugin:opener|open_url",{url:n}))})}();
|
||||
269
plugins/opener/src/lib.rs
Normal file
269
plugins/opener/src/lib.rs
Normal file
@@ -0,0 +1,269 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Open files and URLs using their default application, and reveal files in the system's file explorer.
|
||||
//!
|
||||
//! Use the [`OpenerExt`] trait to access [`Opener::open_url`] and [`Opener::open_path`] from a
|
||||
//! running Tauri app; the plugin's `open_url` and `open_path` commands enforce the scope
|
||||
//! configured for the plugin before delegating to them. The [`open_url`] and [`open_path`] free
|
||||
//! functions and the [`Opener`] methods themselves do not perform any scope check.
|
||||
//! [`reveal_item_in_dir`] and [`reveal_items_in_dir`] return [`Error::UnsupportedPlatform`] on
|
||||
//! Android and iOS.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use tauri::{plugin::TauriPlugin, Manager, Runtime};
|
||||
|
||||
#[cfg(mobile)]
|
||||
use tauri::plugin::PluginHandle;
|
||||
#[cfg(target_os = "android")]
|
||||
const PLUGIN_IDENTIFIER: &str = "app.tauri.opener";
|
||||
#[cfg(target_os = "ios")]
|
||||
tauri::ios_plugin_binding!(init_plugin_opener);
|
||||
|
||||
mod commands;
|
||||
mod config;
|
||||
mod error;
|
||||
mod open;
|
||||
mod reveal_item_in_dir;
|
||||
mod scope;
|
||||
mod scope_entry;
|
||||
#[cfg(windows)]
|
||||
mod windows_shell_path;
|
||||
|
||||
pub use error::Error;
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
pub use open::{open_path, open_url};
|
||||
pub use reveal_item_in_dir::{reveal_item_in_dir, reveal_items_in_dir};
|
||||
|
||||
/// Access to the opener APIs, managed by the plugin as app state.
|
||||
///
|
||||
/// Obtain an instance via [`OpenerExt::opener`].
|
||||
pub struct Opener<R: Runtime> {
|
||||
// we use `fn() -> R` to silence the unused generic error
|
||||
// while keeping this struct `Send + Sync` without requiring `R` to be
|
||||
#[cfg(not(mobile))]
|
||||
_marker: std::marker::PhantomData<fn() -> R>,
|
||||
#[cfg(mobile)]
|
||||
mobile_plugin_handle: PluginHandle<R>,
|
||||
require_literal_leading_dot: Option<bool>,
|
||||
}
|
||||
|
||||
impl<R: Runtime> Opener<R> {
|
||||
/// Open a url with a default or specific program.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_opener::OpenerExt;
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given URL on the system default browser
|
||||
/// app.opener().open_url("https://github.com/tauri-apps/tauri", None::<&str>)?;
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS**: Always opens using default program, unless `with` is provided as "inAppBrowser".
|
||||
#[cfg(desktop)]
|
||||
pub fn open_url(&self, url: impl Into<String>, with: Option<impl Into<String>>) -> Result<()> {
|
||||
crate::open::open(
|
||||
url.into(),
|
||||
with.map(Into::into).filter(|with| with != "inAppBrowser"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Open a url with a default or specific program.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_opener::OpenerExt;
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given URL on the system default browser
|
||||
/// app.opener().open_url("https://github.com/tauri-apps/tauri", None::<&str>)?;
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS**: Always opens using default program, unless `with` is provided as "inAppBrowser".
|
||||
#[cfg(mobile)]
|
||||
pub fn open_url(&self, url: impl Into<String>, with: Option<impl Into<String>>) -> Result<()> {
|
||||
self.mobile_plugin_handle
|
||||
.run_mobile_plugin(
|
||||
"open",
|
||||
serde_json::json!({ "url": url.into(), "with": with.map(Into::into) }),
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Open a path with a default or specific program.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_opener::OpenerExt;
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given path on the system default explorer
|
||||
/// app.opener().open_path("/path/to/file", None::<&str>)?;
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS**: Always opens using default program.
|
||||
#[cfg(desktop)]
|
||||
pub fn open_path(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
with: Option<impl Into<String>>,
|
||||
) -> Result<()> {
|
||||
crate::open::open(
|
||||
path.into(),
|
||||
with.map(Into::into).filter(|with| with != "inAppBrowser"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Open a path with a default or specific program.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_opener::OpenerExt;
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given path on the system default explorer
|
||||
/// app.opener().open_path("/path/to/file", None::<&str>)?;
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS**: Always opens using default program.
|
||||
#[cfg(mobile)]
|
||||
pub fn open_path(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
_with: Option<impl Into<String>>,
|
||||
) -> Result<()> {
|
||||
self.mobile_plugin_handle
|
||||
.run_mobile_plugin("open", path.into())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Reveal a path in the system's default explorer. See [`reveal_item_in_dir`] for details.
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS:** Unsupported, returns [`Error::UnsupportedPlatform`].
|
||||
pub fn reveal_item_in_dir<P: AsRef<Path>>(&self, p: P) -> Result<()> {
|
||||
reveal_item_in_dir(p)
|
||||
}
|
||||
|
||||
/// Reveal multiple paths in the system's default explorer. See [`reveal_items_in_dir`] for details.
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS:** Unsupported, returns [`Error::UnsupportedPlatform`].
|
||||
pub fn reveal_items_in_dir<I, P>(&self, paths: I) -> Result<()>
|
||||
where
|
||||
I: IntoIterator<Item = P>,
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
reveal_items_in_dir(paths)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the opener APIs.
|
||||
pub trait OpenerExt<R: Runtime> {
|
||||
/// Returns the [`Opener`] instance managed by the plugin.
|
||||
fn opener(&self) -> &Opener<R>;
|
||||
}
|
||||
|
||||
impl<R: Runtime, T: Manager<R>> OpenerExt<R> for T {
|
||||
fn opener(&self) -> &Opener<R> {
|
||||
self.state::<Opener<R>>().inner()
|
||||
}
|
||||
}
|
||||
|
||||
/// The opener plugin Builder.
|
||||
pub struct Builder {
|
||||
open_js_links_on_click: bool,
|
||||
}
|
||||
|
||||
impl Default for Builder {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
open_js_links_on_click: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
/// Create a new opener plugin Builder.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Whether the plugin should inject a JS script to open URLs in default browser
|
||||
/// when clicking on `<a>` elements that has `_blank` target, or when pressing `Ctrl` or `Shift` while clicking it.
|
||||
///
|
||||
/// Enabled by default for `http:`, `https:`, `mailto:`, `tel:` links.
|
||||
pub fn open_js_links_on_click(mut self, open: bool) -> Self {
|
||||
self.open_js_links_on_click = open;
|
||||
self
|
||||
}
|
||||
|
||||
/// Build and Initializes the plugin.
|
||||
pub fn build<R: Runtime>(self) -> TauriPlugin<R, Option<config::Config>> {
|
||||
let mut builder = tauri::plugin::Builder::<R, Option<config::Config>>::new("opener")
|
||||
.setup(|app, api| {
|
||||
#[cfg(target_os = "android")]
|
||||
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "OpenerPlugin")?;
|
||||
#[cfg(target_os = "ios")]
|
||||
let handle = api.register_ios_plugin(init_plugin_opener)?;
|
||||
|
||||
app.manage(Opener {
|
||||
#[cfg(not(mobile))]
|
||||
_marker: std::marker::PhantomData::<fn() -> R>,
|
||||
#[cfg(mobile)]
|
||||
mobile_plugin_handle: handle,
|
||||
require_literal_leading_dot: api
|
||||
.config()
|
||||
.as_ref()
|
||||
.and_then(|c| c.require_literal_leading_dot),
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::open_url,
|
||||
commands::open_path,
|
||||
commands::reveal_item_in_dir,
|
||||
]);
|
||||
|
||||
if self.open_js_links_on_click {
|
||||
builder = builder.js_init_script(include_str!("init-iife.js").to_string());
|
||||
}
|
||||
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the plugin.
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
|
||||
Builder::default().build()
|
||||
}
|
||||
61
plugins/opener/src/open.rs
Normal file
61
plugins/opener/src/open.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Types and functions related to shell.
|
||||
|
||||
use std::{ffi::OsStr, path::Path};
|
||||
|
||||
pub(crate) fn open<P: AsRef<OsStr>, S: AsRef<str>>(path: P, with: Option<S>) -> crate::Result<()> {
|
||||
match with {
|
||||
Some(program) => ::open::with_detached(path, program.as_ref()),
|
||||
None => ::open::that_detached(path),
|
||||
}
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Opens URL with the program specified in `with`, or system default if `None`.
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS**: Always opens using default program.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given URL on the system default browser
|
||||
/// tauri_plugin_opener::open_url("https://github.com/tauri-apps/tauri", None::<&str>)?;
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn open_url<P: AsRef<str>, S: AsRef<str>>(url: P, with: Option<S>) -> crate::Result<()> {
|
||||
let url = url.as_ref();
|
||||
open(url, with)
|
||||
}
|
||||
|
||||
/// Opens path with the program specified in `with`, or system default if `None`.
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS**: Always opens using default program.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// // open the given URL on the system default explorer
|
||||
/// tauri_plugin_opener::open_path("/path/to/file", None::<&str>)?;
|
||||
/// Ok(())
|
||||
/// });
|
||||
/// ```
|
||||
pub fn open_path<P: AsRef<Path>, S: AsRef<str>>(path: P, with: Option<S>) -> crate::Result<()> {
|
||||
let path = path.as_ref();
|
||||
if with.is_none() {
|
||||
// Returns an IO error if not exists, and besides `exists()` is a shorthand for `metadata()`
|
||||
_ = path.metadata()?;
|
||||
}
|
||||
open(path, with)
|
||||
}
|
||||
311
plugins/opener/src/reveal_item_in_dir.rs
Normal file
311
plugins/opener/src/reveal_item_in_dir.rs
Normal file
@@ -0,0 +1,311 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Reveal a path in the system's default explorer.
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS:** Unsupported.
|
||||
pub fn reveal_item_in_dir<P: AsRef<Path>>(path: P) -> crate::Result<()> {
|
||||
let path = canonicalize(path.as_ref())?;
|
||||
|
||||
#[cfg(any(
|
||||
windows,
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
return imp::reveal_items_in_dir(&[path]);
|
||||
|
||||
#[cfg(not(any(
|
||||
windows,
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
Err(crate::Error::UnsupportedPlatform)
|
||||
}
|
||||
|
||||
/// Reveal multiple paths in the system's default explorer.
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Android / iOS:** Unsupported.
|
||||
pub fn reveal_items_in_dir<I, P>(paths: I) -> crate::Result<()>
|
||||
where
|
||||
I: IntoIterator<Item = P>,
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
let mut canonicalized = vec![];
|
||||
|
||||
for path in paths {
|
||||
let path = canonicalize(path.as_ref())?;
|
||||
canonicalized.push(path);
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
windows,
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
return imp::reveal_items_in_dir(&canonicalized);
|
||||
|
||||
#[cfg(not(any(
|
||||
windows,
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
Err(crate::Error::UnsupportedPlatform)
|
||||
}
|
||||
|
||||
fn canonicalize(path: &Path) -> crate::Result<PathBuf> {
|
||||
#[cfg(windows)]
|
||||
let path = crate::windows_shell_path::absolute_and_check_exists(dunce::simplified(path))?;
|
||||
#[cfg(not(windows))]
|
||||
let path = std::fs::canonicalize(path)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
|
||||
use windows::{
|
||||
core::{w, HSTRING, PCWSTR},
|
||||
Win32::{
|
||||
Foundation::ERROR_FILE_NOT_FOUND,
|
||||
System::Com::CoInitialize,
|
||||
UI::{
|
||||
Shell::{
|
||||
ILCreateFromPathW, ILFree, SHOpenFolderAndSelectItems, ShellExecuteExW,
|
||||
SHELLEXECUTEINFOW,
|
||||
},
|
||||
WindowsAndMessaging::SW_SHOWNORMAL,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
pub fn reveal_items_in_dir(paths: &[PathBuf]) -> crate::Result<()> {
|
||||
if paths.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut grouped_paths: HashMap<Cow<Path>, Vec<&Path>> = HashMap::new();
|
||||
for path in paths {
|
||||
let parent = crate::windows_shell_path::shell_parent_path(path)
|
||||
.ok_or_else(|| crate::Error::NoParent(path.to_path_buf()))?;
|
||||
grouped_paths.entry(parent).or_default().push(path);
|
||||
}
|
||||
|
||||
let _ = unsafe { CoInitialize(None) };
|
||||
|
||||
for (parent, to_reveals) in grouped_paths {
|
||||
let parent_item_id_list = OwnedItemIdList::new(&parent)?;
|
||||
let to_reveals_item_id_list = to_reveals
|
||||
.iter()
|
||||
.map(|to_reveal| OwnedItemIdList::new(to_reveal))
|
||||
.collect::<crate::Result<Vec<_>>>()?;
|
||||
if let Err(e) = unsafe {
|
||||
SHOpenFolderAndSelectItems(
|
||||
parent_item_id_list.item,
|
||||
Some(
|
||||
&to_reveals_item_id_list
|
||||
.iter()
|
||||
.map(|item| item.item)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
0,
|
||||
)
|
||||
} {
|
||||
// from https://github.com/electron/electron/blob/10d967028af2e72382d16b7e2025d243b9e204ae/shell/common/platform_util_win.cc#L302
|
||||
// On some systems, the above call mysteriously fails with "file not
|
||||
// found" even though the file is there. In these cases, ShellExecute()
|
||||
// seems to work as a fallback (although it won't select the file).
|
||||
//
|
||||
// Note: we only handle the first file here if multiple of are present
|
||||
if e.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
|
||||
let first_path = to_reveals[0];
|
||||
let is_dir = first_path.is_dir();
|
||||
let mut info = SHELLEXECUTEINFOW {
|
||||
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as _,
|
||||
nShow: SW_SHOWNORMAL.0,
|
||||
lpFile: PCWSTR(parent_item_id_list.hstring.as_ptr()),
|
||||
lpClass: if is_dir { w!("folder") } else { PCWSTR::null() },
|
||||
lpVerb: if is_dir {
|
||||
w!("explore")
|
||||
} else {
|
||||
PCWSTR::null()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
unsafe { ShellExecuteExW(&mut info) }?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct OwnedItemIdList {
|
||||
hstring: HSTRING,
|
||||
item: *const ITEMIDLIST,
|
||||
}
|
||||
|
||||
impl OwnedItemIdList {
|
||||
fn new(path: &Path) -> crate::Result<Self> {
|
||||
let path_hstring = HSTRING::from(path);
|
||||
let item_id_list = unsafe { ILCreateFromPathW(&path_hstring) };
|
||||
if item_id_list.is_null() {
|
||||
Err(crate::Error::FailedToConvertPathToItemIdList(
|
||||
path.to_owned(),
|
||||
))
|
||||
} else {
|
||||
Ok(Self {
|
||||
hstring: path_hstring,
|
||||
item: item_id_list,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OwnedItemIdList {
|
||||
fn drop(&mut self) {
|
||||
if !self.item.is_null() {
|
||||
unsafe { ILFree(Some(self.item)) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
mod imp {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn reveal_items_in_dir(paths: &[PathBuf]) -> crate::Result<()> {
|
||||
let connection = zbus::blocking::Connection::session()?;
|
||||
|
||||
reveal_with_filemanager1(paths, &connection).or_else(|e| {
|
||||
// Fallback to opening the directory of the first item if revealing multiple items fails.
|
||||
if let Some(first_path) = paths.first() {
|
||||
reveal_with_open_uri_portal(first_path, &connection)
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn reveal_with_filemanager1(
|
||||
paths: &[PathBuf],
|
||||
connection: &zbus::blocking::Connection,
|
||||
) -> crate::Result<()> {
|
||||
let uris: Result<Vec<_>, _> = paths
|
||||
.iter()
|
||||
.map(|path| {
|
||||
url::Url::from_file_path(path)
|
||||
.map_err(|_| crate::Error::FailedToConvertPathToFileUrl)
|
||||
})
|
||||
.collect();
|
||||
let uris = uris?;
|
||||
let uri_strs: Vec<&str> = uris.iter().map(|uri| uri.as_str()).collect();
|
||||
|
||||
#[zbus::proxy(
|
||||
interface = "org.freedesktop.FileManager1",
|
||||
default_service = "org.freedesktop.FileManager1",
|
||||
default_path = "/org/freedesktop/FileManager1"
|
||||
)]
|
||||
trait FileManager1 {
|
||||
async fn ShowItems(&self, name: Vec<&str>, arg2: &str) -> crate::Result<()>;
|
||||
}
|
||||
|
||||
let proxy = FileManager1ProxyBlocking::new(connection)?;
|
||||
|
||||
proxy.ShowItems(uri_strs, "")
|
||||
}
|
||||
|
||||
fn reveal_with_open_uri_portal(
|
||||
path: &Path,
|
||||
connection: &zbus::blocking::Connection,
|
||||
) -> crate::Result<()> {
|
||||
let uri = url::Url::from_file_path(path)
|
||||
.map_err(|_| crate::Error::FailedToConvertPathToFileUrl)?;
|
||||
|
||||
#[zbus::proxy(
|
||||
interface = "org.freedesktop.portal.Desktop",
|
||||
default_service = "org.freedesktop.portal.OpenURI",
|
||||
default_path = "/org/freedesktop/portal/desktop"
|
||||
)]
|
||||
trait PortalDesktop {
|
||||
async fn OpenDirectory(
|
||||
&self,
|
||||
arg1: &str,
|
||||
name: &str,
|
||||
arg3: HashMap<&str, &str>,
|
||||
) -> crate::Result<()>;
|
||||
}
|
||||
|
||||
let proxy = PortalDesktopProxyBlocking::new(connection)?;
|
||||
|
||||
proxy.OpenDirectory("", uri.as_str(), HashMap::new())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use objc2_app_kit::NSWorkspace;
|
||||
use objc2_foundation::{NSArray, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn reveal_items_in_dir(paths: &[PathBuf]) -> crate::Result<()> {
|
||||
// these AppKit calls are only `unsafe` before objc2-app-kit 0.3.2
|
||||
#[allow(unused_unsafe)]
|
||||
unsafe {
|
||||
let mut urls = Vec::new();
|
||||
|
||||
for path in paths {
|
||||
let path = path.to_string_lossy();
|
||||
let path = NSString::from_str(&path);
|
||||
let url = NSURL::fileURLWithPath(&path);
|
||||
|
||||
urls.push(url);
|
||||
}
|
||||
|
||||
let urls = NSArray::from_retained_slice(&urls);
|
||||
|
||||
let workspace = NSWorkspace::new();
|
||||
workspace.activateFileViewerSelectingURLs(&urls);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
141
plugins/opener/src/scope.rs
Normal file
141
plugins/opener/src/scope.rs
Normal file
@@ -0,0 +1,141 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{
|
||||
marker::PhantomData,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use tauri::{ipc::ScopeObject, utils::acl::Value, AppHandle, Manager, Runtime};
|
||||
|
||||
use crate::{scope_entry::EntryRaw, Error};
|
||||
|
||||
pub use crate::scope_entry::Application;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Entry {
|
||||
Url {
|
||||
url: glob::Pattern,
|
||||
app: Application,
|
||||
},
|
||||
Path {
|
||||
path: Option<PathBuf>,
|
||||
app: Application,
|
||||
},
|
||||
}
|
||||
|
||||
impl ScopeObject for Entry {
|
||||
type Error = Error;
|
||||
|
||||
fn deserialize<R: Runtime>(
|
||||
app_handle: &AppHandle<R>,
|
||||
raw: Value,
|
||||
) -> std::result::Result<Self, Self::Error> {
|
||||
serde_json::from_value(raw.into())
|
||||
.and_then(|raw| {
|
||||
let entry = match raw {
|
||||
EntryRaw::Url { url, app } => Entry::Url {
|
||||
url: glob::Pattern::new(&url)
|
||||
.map_err(|e| serde::de::Error::custom(e.to_string()))?,
|
||||
app,
|
||||
},
|
||||
EntryRaw::Path { path, app } => {
|
||||
let path = match app_handle.path().parse(path) {
|
||||
Ok(path) => Some(path),
|
||||
#[cfg(not(target_os = "android"))]
|
||||
Err(tauri::Error::UnknownPath) => None,
|
||||
Err(err) => return Err(serde::de::Error::custom(err.to_string())),
|
||||
};
|
||||
|
||||
Entry::Path { path, app }
|
||||
}
|
||||
};
|
||||
|
||||
Ok(entry)
|
||||
})
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
impl Application {
|
||||
fn matches(&self, a: Option<&str>) -> bool {
|
||||
match self {
|
||||
Self::Default => a.is_none(),
|
||||
Self::Enable(enable) => *enable,
|
||||
Self::App(program) => Some(program.as_str()) == a,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn path(&self) -> Option<PathBuf> {
|
||||
match self {
|
||||
Self::Url { .. } => None,
|
||||
Self::Path { path, .. } => path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_url(&self, u: &str, a: Option<&str>) -> bool {
|
||||
match self {
|
||||
Self::Url { url, app } => url.matches(u) && app.matches(a),
|
||||
Self::Path { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_path_program(&self, a: Option<&str>) -> bool {
|
||||
match self {
|
||||
Self::Url { .. } => false,
|
||||
Self::Path { app, .. } => app.matches(a),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Scope<'a, R: Runtime, M: Manager<R>> {
|
||||
allowed: Vec<&'a Arc<Entry>>,
|
||||
denied: Vec<&'a Arc<Entry>>,
|
||||
manager: &'a M,
|
||||
_marker: PhantomData<R>,
|
||||
}
|
||||
|
||||
impl<'a, R: Runtime, M: Manager<R>> Scope<'a, R, M> {
|
||||
pub(crate) fn new(
|
||||
manager: &'a M,
|
||||
allowed: Vec<&'a Arc<Entry>>,
|
||||
denied: Vec<&'a Arc<Entry>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
manager,
|
||||
allowed,
|
||||
denied,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_url_allowed(&self, url: &str, with: Option<&str>) -> bool {
|
||||
let denied = self.denied.iter().any(|e| e.matches_url(url, with));
|
||||
if denied {
|
||||
false
|
||||
} else {
|
||||
self.allowed.iter().any(|e| e.matches_url(url, with))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_path_allowed(&self, path: &Path, with: Option<&str>) -> crate::Result<bool> {
|
||||
let fs_scope = tauri::fs::Scope::new(
|
||||
self.manager,
|
||||
&tauri::utils::config::FsScope::Scope {
|
||||
allow: self.allowed.iter().filter_map(|e| e.path()).collect(),
|
||||
deny: self.denied.iter().filter_map(|e| e.path()).collect(),
|
||||
require_literal_leading_dot: self
|
||||
.manager
|
||||
.state::<crate::Opener<R>>()
|
||||
.require_literal_leading_dot,
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(fs_scope.is_allowed(path) && self.allowed.iter().any(|e| e.matches_path_program(with)))
|
||||
}
|
||||
}
|
||||
32
plugins/opener/src/scope_entry.rs
Normal file
32
plugins/opener/src/scope_entry.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(untagged)]
|
||||
#[derive(Default)]
|
||||
pub enum Application {
|
||||
#[default]
|
||||
Default,
|
||||
Enable(bool),
|
||||
App(String),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged, rename_all = "camelCase")]
|
||||
pub(crate) enum EntryRaw {
|
||||
Url {
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
app: Application,
|
||||
},
|
||||
Path {
|
||||
path: PathBuf,
|
||||
#[serde(default)]
|
||||
app: Application,
|
||||
},
|
||||
}
|
||||
255
plugins/opener/src/windows_shell_path.rs
Normal file
255
plugins/opener/src/windows_shell_path.rs
Normal file
@@ -0,0 +1,255 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
ffi::OsString,
|
||||
io,
|
||||
os::windows::ffi::OsStringExt,
|
||||
path::{Component, Path, PathBuf, Prefix, PrefixComponent},
|
||||
};
|
||||
|
||||
use windows::{core::HSTRING, Win32::Storage::FileSystem::GetFullPathNameW};
|
||||
|
||||
pub fn absolute_and_check_exists(path: &Path) -> io::Result<PathBuf> {
|
||||
let path = absolute(path)?;
|
||||
if path.exists() {
|
||||
Ok(path)
|
||||
} else {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"path doesn't exist",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Switch to use `std::path::absolute` once MSRV > 1.79
|
||||
// Modified from https://github.com/rust-lang/rust/blob/b49ecc9eb70a51e89f32a7358e790f7b3808ccb3/library/std/src/sys/path/windows.rs#L185
|
||||
// Note: this doesn't resolve symlinks
|
||||
fn absolute(path: &Path) -> io::Result<PathBuf> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"cannot make an empty path absolute",
|
||||
));
|
||||
}
|
||||
|
||||
let prefix = path.components().next();
|
||||
// Verbatim paths should not be modified.
|
||||
if prefix
|
||||
.map(|component| {
|
||||
let Component::Prefix(prefix) = component else {
|
||||
return false;
|
||||
};
|
||||
matches!(
|
||||
prefix.kind(),
|
||||
Prefix::Verbatim(..) | Prefix::VerbatimDisk(..) | Prefix::VerbatimUNC(..)
|
||||
)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
{
|
||||
// NULs in verbatim paths are rejected for consistency.
|
||||
if path.as_os_str().as_encoded_bytes().contains(&0) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"strings passed to WinAPI cannot contain NULs",
|
||||
));
|
||||
}
|
||||
return Ok(path.to_owned());
|
||||
}
|
||||
|
||||
// This is an additional check to make sure we don't pass in a single driver letter to GetFullPathNameW
|
||||
// which will resolves to the current working directory
|
||||
//
|
||||
// > https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew#:~:text=If%20you%20specify%20%22U%3A%22%20the%20path%20returned%20is%20the%20current%20directory%20on%20the%20%22U%3A%5C%22%20drive
|
||||
#[allow(clippy::collapsible_if)]
|
||||
if let Some(Component::Prefix(last_prefix)) = path.components().next_back() {
|
||||
if matches!(last_prefix.kind(), Prefix::Disk(..)) {
|
||||
return Ok(PathBuf::from(last_prefix.as_os_str()));
|
||||
}
|
||||
}
|
||||
|
||||
let path_hstring = HSTRING::from(path);
|
||||
|
||||
let size = unsafe { GetFullPathNameW(&path_hstring, None, None) };
|
||||
if size == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut buffer = vec![0; size as usize];
|
||||
let size = unsafe { GetFullPathNameW(&path_hstring, Some(&mut buffer), None) };
|
||||
if size == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
Ok(PathBuf::from(OsString::from_wide(&buffer[..size as usize])))
|
||||
}
|
||||
|
||||
/// Similar to [`Path::parent`] but resolves parent of `C:`/`C:\` to `""` and handles UNC host name (`\\wsl.localhost\Ubuntu\` to `\\wsl.localhost`)
|
||||
pub fn shell_parent_path(path: &Path) -> Option<Cow<'_, Path>> {
|
||||
fn handle_prefix(prefix: PrefixComponent<'_>) -> Option<Cow<'_, Path>> {
|
||||
match prefix.kind() {
|
||||
Prefix::UNC(host_name, _share_name) => {
|
||||
let mut path = OsString::from(r"\\");
|
||||
path.push(host_name);
|
||||
Some(PathBuf::from(path).into())
|
||||
}
|
||||
Prefix::Disk(_) => Some(PathBuf::from("").into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let mut components = path.components();
|
||||
let component = components.next_back()?;
|
||||
match component {
|
||||
Component::Normal(_) | Component::CurDir | Component::ParentDir => {
|
||||
Some(components.as_path().into())
|
||||
}
|
||||
Component::Prefix(prefix) => handle_prefix(prefix),
|
||||
// Handle cases like `C:\` and `\\wsl.localhost\Ubuntu\`
|
||||
Component::RootDir => {
|
||||
if let Component::Prefix(prefix) = components.next_back()? {
|
||||
handle_prefix(prefix)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
// absolute() tests
|
||||
|
||||
#[test]
|
||||
fn absolute_empty_error() {
|
||||
let err = absolute(Path::new("")).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_verbatim_passthrough() {
|
||||
let path = Path::new(r"\\?\C:\foo");
|
||||
assert_eq!(absolute(path).unwrap(), path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_verbatim_unc_passthrough() {
|
||||
let path = Path::new(r"\\?\UNC\server\share");
|
||||
assert_eq!(absolute(path).unwrap(), path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_bare_drive_letter() {
|
||||
let result = absolute(Path::new("C:")).unwrap();
|
||||
assert_eq!(result, Path::new("C:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_already_absolute() {
|
||||
let result = absolute(Path::new(r"C:\Windows")).unwrap();
|
||||
assert_eq!(result, Path::new(r"C:\Windows"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_unc_path() {
|
||||
let result = absolute(Path::new(r"\\server\share\folder")).unwrap();
|
||||
assert_eq!(result, Path::new(r"\\server\share\folder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_converts_forward_slashes() {
|
||||
let result = absolute(Path::new("C:/Windows/System32")).unwrap();
|
||||
assert_eq!(result, Path::new(r"C:\Windows\System32"));
|
||||
}
|
||||
|
||||
// absolute_and_check_exists() tests
|
||||
|
||||
#[test]
|
||||
fn absolute_and_check_exists_existing_path() {
|
||||
assert!(absolute_and_check_exists(Path::new(r"C:\Windows")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_and_check_exists_nonexistent_path() {
|
||||
let err = absolute_and_check_exists(Path::new(r"C:\nonexistent_xyz_12345")).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_and_check_exists_empty_propagates() {
|
||||
let err = absolute_and_check_exists(Path::new("")).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
// shell_parent_path() tests
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_local_path() {
|
||||
let result = shell_parent_path(Path::new(r"C:\Users\foo"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new(r"C:\Users")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_nested_path() {
|
||||
let result = shell_parent_path(Path::new(r"C:\a\b\c\d"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new(r"C:\a\b\c")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_drive_root_trailing() {
|
||||
let result = shell_parent_path(Path::new(r"C:\"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new("")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_bare_drive() {
|
||||
let result = shell_parent_path(Path::new("C:"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new("")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_unc_with_subfolder() {
|
||||
let result = shell_parent_path(Path::new(r"\\server\share\folder"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new(r"\\server\share")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_unc_share_trailing_slash() {
|
||||
let result = shell_parent_path(Path::new(r"\\server.local\share\"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new(r"\\server.local")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_unc_share_no_slash() {
|
||||
let result = shell_parent_path(Path::new(r"\\server\share"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new(r"\\server")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_relative() {
|
||||
let result = shell_parent_path(Path::new(r"foo\bar"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new("foo")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_single_component() {
|
||||
let result = shell_parent_path(Path::new("foo"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new("")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_empty() {
|
||||
let result = shell_parent_path(Path::new(""));
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_parent_path_verbatim() {
|
||||
let result = shell_parent_path(Path::new(r"\\?\C:\foo"));
|
||||
assert_eq!(result.as_deref(), Some(Path::new(r"\\?\C:\")));
|
||||
}
|
||||
}
|
||||
7
plugins/opener/tsconfig.json
Normal file
7
plugins/opener/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "guest-js"
|
||||
},
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user