Merge branch 'dev' into renovate/notify-5.x

pull/71/head
FabianLars 2 years ago
commit 96fc592649
No known key found for this signature in database
GPG Key ID: 3B12BC1DEBF61125

562
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -6,6 +6,7 @@ resolver = "2"
serde = { version = "1", features = ["derive"] }
log = "0.4"
tauri = "1"
tauri-build = "1"
serde_json = "1"
thiserror = "1"

@ -17,7 +17,7 @@
"@typescript-eslint/parser": "^5.46.1",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.5.0",
"eslint-config-standard-with-typescript": "^26.0.0",
"eslint-config-standard-with-typescript": "^27.0.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-promise": "^6.0.0",

@ -38,6 +38,8 @@ First you need to register the core plugin with Tauri:
`src-tauri/src/main.rs`
```rust
use tauri_plugin_autostart::MacosLauncher;
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, Some(vec!["--flag1", "--flag2"]) /* arbitrary number of args to pass to your app */))

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -0,0 +1,33 @@
[package]
name = "tauri-plugin-single-instance"
version = "0.1.0"
description = "Ensure a single instance of your tauri app is running."
authors.workspace = true
license.workspace = true
edition.workspace = true
rust-version.workspace = true
exclude = ["/examples"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde.workspace = true
serde_json.workspace = true
tauri.workspace = true
log.workspace = true
thiserror.workspace = true
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
version = "0.42"
features = [
"Win32_System_Threading",
"Win32_System_DataExchange",
"Win32_Foundation",
"Win32_UI_WindowsAndMessaging",
"Win32_Security",
"Win32_System_LibraryLoader",
"Win32_Graphics_Gdi",
]
[target.'cfg(target_os = "linux")'.dependencies]
zbus = "3"

@ -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

@ -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

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 - Present The Tauri Programme in the Commons Conservancy
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.

@ -0,0 +1,57 @@
![tauri-plugin-single-instance](banner.jpg)
Ensure a single instance of your tauri app is running.
## Install
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-single-instance = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "dev" }
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/main.rs`
```rust
use tauri::{Manager};
#[derive(Clone, serde::Serialize)]
struct Payload {
args: Vec<String>,
cwd: String,
}
fn main() {
tauri::Builder::default()
.plugin(auri_plugin_single_instance::init(|app, argv, cwd| {
println!("{}, {argv:?}, {cwd}", app.package_info().name);
app.emit_all("single-instance", Payload { args: argv, cwd }).unwrap();
}))
.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.
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

@ -0,0 +1,14 @@
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"dependencies": {
"@tauri-apps/cli": "^1.0.0"
}
}

@ -0,0 +1,106 @@
lockfileVersion: 5.4
specifiers:
'@tauri-apps/cli': ^1.0.0
dependencies:
'@tauri-apps/cli': 1.0.2
packages:
/@tauri-apps/cli-darwin-arm64/1.0.2:
resolution: {integrity: sha512-Ahd951yoYon1+WLNBg6xsx6Bb7+GJt7WwC1FllHZ2/iLCbrtWCS2qfeLS0L4ngBqCuWyL35JC/M2LIr9mcUzrg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-darwin-x64/1.0.2:
resolution: {integrity: sha512-8wo+SN1zWoXFQVa/iyEt3Cs0vNMjxDXqVe3Srm4UNpgKboFN5mIgbugwqvM+aJKnEZAH8h8n+ZJUHzc4wtPGHA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-linux-arm-gnueabihf/1.0.2:
resolution: {integrity: sha512-PGQghMn0adt9PTnyi2K2o/CLG3tWbOyZvwQjam5cfQbK757WmMgPErC1VqsxiQc+PItWYvqoE9gjANiFc2MpAQ==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-linux-arm64-gnu/1.0.2:
resolution: {integrity: sha512-Uc+XNlWelrnRh7DYrdxBi8Oam9JAQM1GzgEwjupF6Pv7BwlODN7s0HImGPQOKrEkqzpfmYw7KpfgWiiEjS5/3Q==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-linux-arm64-musl/1.0.2:
resolution: {integrity: sha512-lVwCG1QzQs2zWP32H4+Dw8NKgJ6hBox2X+bmawGfV9Ce+K4P84bnqfNgpdaSAncjeiTjrO+g7yT9gJFQCOrjlQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-linux-x64-gnu/1.0.2:
resolution: {integrity: sha512-G2XmGxvufW9sgGhA3rx+HehcifVTUo8zyISd8DpvGwtpp6Z4WakbivzKFyGiNnnok0nvj/WUrLgBxtUbfdSY+A==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-linux-x64-musl/1.0.2:
resolution: {integrity: sha512-/eX536p+KXSmkFuINGeU6EQmYiQEXj6JXbmetmJmkXN0297HbtH3rS3wlyVDCnobRzh1hMeOJEnV+XA20GghMA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-win32-ia32-msvc/1.0.2:
resolution: {integrity: sha512-ZvnaKkCABqUbyUKlNk4RdxKyfOte30D5BxN1pj6iZNeKAwXEuTcgP6iPzOovdeaDirkIjcWCEZymwtZDXN4Rvg==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli-win32-x64-msvc/1.0.2:
resolution: {integrity: sha512-uMcQyQQD7nyxps34HyYBYUYzFwH26lP58/qdT/GZWvBL1Sv2rqkQXuxHT7xtp4g7nTs0fGRWOtfcnvYIr/1wDw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@tauri-apps/cli/1.0.2:
resolution: {integrity: sha512-OJdQJVwtKnTAuv2a9JQlOd0gHbbGsXwT+N6M6YQiXZ3/5WdlXey1zhnD78GXwZsf8Cz0R7QIGTBECO4ur4fnKg==}
engines: {node: '>= 10'}
hasBin: true
optionalDependencies:
'@tauri-apps/cli-darwin-arm64': 1.0.2
'@tauri-apps/cli-darwin-x64': 1.0.2
'@tauri-apps/cli-linux-arm-gnueabihf': 1.0.2
'@tauri-apps/cli-linux-arm64-gnu': 1.0.2
'@tauri-apps/cli-linux-arm64-musl': 1.0.2
'@tauri-apps/cli-linux-x64-gnu': 1.0.2
'@tauri-apps/cli-linux-x64-musl': 1.0.2
'@tauri-apps/cli-win32-ia32-msvc': 1.0.2
'@tauri-apps/cli-win32-x64-msvc': 1.0.2
dev: false

@ -0,0 +1,5 @@
<html>
<body>
<div>Plugin example</div>
</body>
</html>

@ -0,0 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
/target/
WixTools

File diff suppressed because it is too large Load Diff

@ -0,0 +1,23 @@
[workspace]
[package]
name = "single-instance-example"
version = "0.1.0"
description = "A Tauri App"
authors = [ "You" ]
repository = ""
edition = "2021"
rust-version = "1.57"
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = [ "derive" ] }
tauri = { version = "1", features = ["api-all"] }
tauri-plugin-single-instance = { path = "../../../" }
[build-dependencies]
tauri-build = { version = "1", features = [] }
[features]
default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ]

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@ -0,0 +1,14 @@
max_width = 100
hard_tabs = false
tab_spaces = 2
newline_style = "Auto"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = true
edition = "2021"
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = true
imports_granularity = "Crate"

@ -0,0 +1,13 @@
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
println!("{}, {argv:?}, {cwd}", app.package_info().name);
}))
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

@ -0,0 +1,62 @@
{
"package": {
"productName": "app",
"version": "0.1.0"
},
"build": {
"distDir": "../public",
"devPath": "../public"
},
"tauri": {
"bundle": {
"active": true,
"targets": "all",
"identifier": "com.tauri.single-instance",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"resources": [],
"externalBin": [],
"copyright": "",
"category": "DeveloperTool",
"shortDescription": "",
"longDescription": "",
"deb": {
"depends": []
},
"macOS": {
"frameworks": [],
"exceptionDomain": "",
"signingIdentity": null,
"entitlements": null
},
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
},
"updater": {
"active": false
},
"allowlist": {
"all": true
},
"windows": [
{
"title": "app",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false
}
],
"security": {
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
}
}
}

@ -0,0 +1,24 @@
use tauri::{plugin::TauriPlugin, AppHandle, Manager, Runtime};
#[cfg(target_os = "windows")]
#[path = "platform_impl/windows.rs"]
mod platform_impl;
#[cfg(target_os = "linux")]
#[path = "platform_impl/linux.rs"]
mod platform_impl;
#[cfg(target_os = "macos")]
#[path = "platform_impl/macos.rs"]
mod platform_impl;
pub(crate) type SingleInstanceCallback<R> =
dyn FnMut(&AppHandle<R>, Vec<String>, String) + Send + Sync + 'static;
pub fn init<R: Runtime, F: FnMut(&AppHandle<R>, Vec<String>, String) + Send + Sync + 'static>(
f: F,
) -> TauriPlugin<R> {
platform_impl::init(Box::new(f))
}
pub fn destroy<R: Runtime, M: Manager<R>>(manager: &M) {
platform_impl::destroy(manager)
}

@ -0,0 +1,91 @@
#![cfg(target_os = "linux")]
use std::sync::Arc;
use crate::SingleInstanceCallback;
use tauri::{
plugin::{self, TauriPlugin},
AppHandle, Config, Manager, RunEvent, Runtime,
};
use zbus::{
blocking::{Connection, ConnectionBuilder},
dbus_interface,
};
struct ConnectionHandle(Connection);
struct SingleInstanceDBus<R: Runtime> {
callback: Box<SingleInstanceCallback<R>>,
app_handle: AppHandle<R>,
}
#[dbus_interface(name = "org.SingleInstance.DBus")]
impl<R: Runtime> SingleInstanceDBus<R> {
fn execute_callback(&mut self, argv: Vec<String>, cwd: String) {
(self.callback)(&self.app_handle, argv, cwd);
}
}
fn dbus_id(config: Arc<Config>) -> String {
config.tauri.bundle.identifier.replace(['.', '-'], "_")
}
pub fn init<R: Runtime>(f: Box<SingleInstanceCallback<R>>) -> TauriPlugin<R> {
plugin::Builder::new("single-instance")
.setup(|app| {
let id = dbus_id(app.config());
let single_instance_dbus = SingleInstanceDBus {
callback: f,
app_handle: app.clone(),
};
let dbus_name = format!("org.{}.SingleInstance", id);
let dbus_path = format!("/org/{}/SingleInstance", id);
match ConnectionBuilder::session()
.unwrap()
.name(dbus_name.as_str())
.unwrap()
.serve_at(dbus_path.as_str(), single_instance_dbus)
.unwrap()
.build()
{
Ok(connection) => {
app.manage(ConnectionHandle(connection));
}
Err(zbus::Error::NameTaken) => {
if let Ok(connection) = Connection::session() {
let _ = connection.call_method(
Some(dbus_name.as_str()),
dbus_path.as_str(),
Some("org.SingleInstance.DBus"),
"ExecuteCallback",
&(
std::env::args().collect::<Vec<String>>(),
std::env::current_dir()
.unwrap_or_default()
.to_str()
.unwrap_or_default(),
),
);
}
std::process::exit(0)
}
_ => {}
}
Ok(())
})
.on_event(|app, event| {
if let RunEvent::Exit = event {
destroy(app);
}
})
.build()
}
pub fn destroy<R: Runtime, M: Manager<R>>(manager: &M) {
if let Some(connection) = manager.try_state::<ConnectionHandle>() {
let dbus_name = format!("org.{}.SingleInstance", dbus_id(manager.config()));
let _ = connection.0.release_name(dbus_name);
}
}

@ -0,0 +1,12 @@
#![cfg(target_os = "macos")]
use crate::SingleInstanceCallback;
use tauri::{
plugin::{self, TauriPlugin},
Manager, Runtime,
};
pub fn init<R: Runtime>(_f: Box<SingleInstanceCallback<R>>) -> TauriPlugin<R> {
plugin::Builder::new("single-instance").build()
}
pub fn destroy<R: Runtime, M: Manager<R>>(_manager: &M) {}

@ -0,0 +1,215 @@
#![cfg(target_os = "windows")]
use crate::SingleInstanceCallback;
use std::ffi::CStr;
use tauri::{
plugin::{self, TauriPlugin},
AppHandle, Manager, RunEvent, Runtime,
};
use windows_sys::Win32::{
Foundation::{CloseHandle, GetLastError, ERROR_ALREADY_EXISTS, HWND, LPARAM, LRESULT, WPARAM},
System::{
DataExchange::COPYDATASTRUCT,
LibraryLoader::GetModuleHandleW,
Threading::{CreateMutexW, ReleaseMutex},
},
UI::WindowsAndMessaging::{
self as w32wm, CreateWindowExW, DefWindowProcW, DestroyWindow, FindWindowW,
RegisterClassExW, SendMessageW, GWL_STYLE, GWL_USERDATA, WINDOW_LONG_PTR_INDEX,
WM_COPYDATA, WM_DESTROY, WNDCLASSEXW, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
WS_EX_TRANSPARENT, WS_OVERLAPPED, WS_POPUP, WS_VISIBLE,
},
};
struct MutexHandle(isize);
struct TargetWindowHandle(isize);
const WMCOPYDATA_SINGLE_INSTANCE_DATA: usize = 1542;
pub fn init<R: Runtime>(f: Box<SingleInstanceCallback<R>>) -> TauriPlugin<R> {
plugin::Builder::new("single-instance")
.setup(|app| {
let id = &app.config().tauri.bundle.identifier;
let class_name = encode_wide(format!("{}-sic", id));
let window_name = encode_wide(format!("{}-siw", id));
let mutex_name = encode_wide(format!("{}-sim", id));
let hmutex =
unsafe { CreateMutexW(std::ptr::null(), true.into(), mutex_name.as_ptr()) };
if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {
unsafe {
let hwnd = FindWindowW(class_name.as_ptr(), window_name.as_ptr());
if hwnd != 0 {
let data = format!(
"{}|{}\0",
std::env::current_dir()
.unwrap_or_default()
.to_str()
.unwrap_or_default(),
std::env::args().collect::<Vec<String>>().join("|")
);
let bytes = data.as_bytes();
let cds = COPYDATASTRUCT {
dwData: WMCOPYDATA_SINGLE_INSTANCE_DATA,
cbData: bytes.len() as _,
lpData: bytes.as_ptr() as _,
};
SendMessageW(hwnd, WM_COPYDATA, 0, &cds as *const _ as _);
app.exit(0);
}
}
} else {
app.manage(MutexHandle(hmutex));
let hwnd = create_event_target_window::<R>(&class_name, &window_name);
unsafe {
SetWindowLongPtrW(
hwnd,
GWL_USERDATA,
Box::into_raw(Box::new((app.clone(), f))) as _,
)
};
app.manage(TargetWindowHandle(hwnd));
}
Ok(())
})
.on_event(|app, event| {
if let RunEvent::Exit = event {
destroy(app);
}
})
.build()
}
pub fn destroy<R: Runtime, M: Manager<R>>(manager: &M) {
if let Some(hmutex) = manager.try_state::<MutexHandle>() {
unsafe {
ReleaseMutex(hmutex.0);
CloseHandle(hmutex.0);
}
}
if let Some(hwnd) = manager.try_state::<TargetWindowHandle>() {
unsafe { DestroyWindow(hwnd.0) };
}
}
unsafe extern "system" fn single_instance_window_proc<R: Runtime>(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
let data_ptr = GetWindowLongPtrW(hwnd, GWL_USERDATA)
as *mut (AppHandle<R>, Box<SingleInstanceCallback<R>>);
let (app_handle, callback) = &mut *data_ptr;
match msg {
WM_COPYDATA => {
let cds_ptr = lparam as *const COPYDATASTRUCT;
if (*cds_ptr).dwData == WMCOPYDATA_SINGLE_INSTANCE_DATA {
let data = CStr::from_ptr((*cds_ptr).lpData as _).to_string_lossy();
let mut s = data.split("|");
let cwd = s.next().unwrap();
let args = s.into_iter().map(|s| s.to_string()).collect();
callback(&app_handle, args, cwd.to_string());
}
1
}
WM_DESTROY => {
let _ = Box::from_raw(data_ptr);
0
}
_ => DefWindowProcW(hwnd, msg, wparam, lparam),
}
}
fn create_event_target_window<R: Runtime>(class_name: &[u16], window_name: &[u16]) -> HWND {
unsafe {
let class = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: 0,
lpfnWndProc: Some(single_instance_window_proc::<R>),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: GetModuleHandleW(std::ptr::null()),
hIcon: 0,
hCursor: 0,
hbrBackground: 0,
lpszMenuName: std::ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: 0,
};
RegisterClassExW(&class);
let hwnd = CreateWindowExW(
WS_EX_NOACTIVATE
| WS_EX_TRANSPARENT
| WS_EX_LAYERED
// WS_EX_TOOLWINDOW prevents this window from ever showing up in the taskbar, which
// we want to avoid. If you remove this style, this window won't show up in the
// taskbar *initially*, but it can show up at some later point. This can sometimes
// happen on its own after several hours have passed, although this has proven
// difficult to reproduce. Alternatively, it can be manually triggered by killing
// `explorer.exe` and then starting the process back up.
// It is unclear why the bug is triggered by waiting for several hours.
| WS_EX_TOOLWINDOW,
class_name.as_ptr(),
window_name.as_ptr(),
WS_OVERLAPPED,
0,
0,
0,
0,
0,
0,
GetModuleHandleW(std::ptr::null()),
std::ptr::null(),
);
SetWindowLongPtrW(
hwnd,
GWL_STYLE,
// The window technically has to be visible to receive WM_PAINT messages (which are used
// for delivering events during resizes), but it isn't displayed to the user because of
// the LAYERED style.
(WS_VISIBLE | WS_POPUP) as isize,
);
hwnd
}
}
pub fn encode_wide(string: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
std::os::windows::prelude::OsStrExt::encode_wide(string.as_ref())
.chain(std::iter::once(0))
.collect()
}
#[cfg(target_pointer_width = "32")]
#[allow(non_snake_case)]
unsafe fn SetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize {
w32wm::SetWindowLongW(hwnd, index, value as _) as _
}
#[cfg(target_pointer_width = "64")]
#[allow(non_snake_case)]
unsafe fn SetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize {
w32wm::SetWindowLongPtrW(hwnd, index, value)
}
#[cfg(target_pointer_width = "32")]
#[allow(non_snake_case)]
unsafe fn GetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize {
w32wm::GetWindowLongW(hwnd, index) as _
}
#[cfg(target_pointer_width = "64")]
#[allow(non_snake_case)]
unsafe fn GetWindowLongPtrW(hwnd: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize {
w32wm::GetWindowLongPtrW(hwnd, index)
}

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -301,6 +301,7 @@ async fn select(
}
/// Tauri SQL plugin builder.
#[derive(Default)]
pub struct Builder {
migrations: Option<HashMap<String, MigrationList>>,
}
@ -347,7 +348,9 @@ impl Builder {
drop(lock);
app.manage(instances);
app.manage(Migrations(Mutex::new(self.migrations.take().unwrap())));
app.manage(Migrations(Mutex::new(
self.migrations.take().unwrap_or_default(),
)));
Ok(())
})

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -19,8 +19,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -1 +1 @@
node_modules
node_modules

@ -5,6 +5,7 @@ authors.workspace = true
license.workspace = true
edition.workspace = true
rust-version.workspace = true
exclude = ["/examples"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -17,4 +18,4 @@ thiserror.workspace = true
rand = "0.8"
futures-util = "0.3"
tokio = { version = "1", features = ["net", "sync"] }
tokio-tungstenite = { version = "0.18", features = ["native-tls"] }
tokio-tungstenite = { version = "0.18", features = ["native-tls"] }

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

@ -0,0 +1,27 @@
{
"name": "svelte-app",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^1.0.0",
"@sveltejs/kit": "^1.0.0",
"svelte": "^3.54.0",
"svelte-check": "^2.9.2",
"tslib": "^2.4.1",
"typescript": "^4.9.3",
"vite": "^4.0.0"
},
"dependencies": {
"@tauri-apps/cli": "^1.0.0",
"tauri-plugin-websocket-api": "link:../../"
},
"type": "module"
}

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
WixTools
# These are backup files generated by rustfmt
**/*.rs.bk

File diff suppressed because it is too large Load Diff

@ -0,0 +1,23 @@
[workspace]
[package]
name = "app"
version = "0.1.0"
description = "A Tauri App"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = { version = "1", features = [] }
tokio = { version = "1.11", features = ["net"] }
futures-util = "0.3"
tauri-plugin-websocket = { path = "../../../" }
tokio-tungstenite = "0.15"
[build-dependencies]
tauri-build = { version = "1", features = [] }
[features]
default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ]

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

@ -0,0 +1,13 @@
max_width = 100
hard_tabs = false
tab_spaces = 2
newline_style = "Auto"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = true
edition = "2018"
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = true

@ -0,0 +1,38 @@
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use futures_util::StreamExt;
use tokio::net::{TcpListener, TcpStream};
async fn start_server() {
let addr = "127.0.0.1:8080".to_string();
// Create the event loop and TCP listener we'll accept connections on.
let try_socket = TcpListener::bind(&addr).await;
let listener = try_socket.expect("Failed to bind");
while let Ok((stream, _)) = listener.accept().await {
tokio::spawn(accept_connection(stream));
}
}
async fn accept_connection(stream: TcpStream) {
let ws_stream = tokio_tungstenite::accept_async(stream)
.await
.expect("Error during the websocket handshake occurred");
let (write, read) = ws_stream.split();
if let Err(e) = read.forward(write).await {
eprintln!("Error: {}", e);
}
}
fn main() {
tauri::async_runtime::spawn(start_server());
tauri::Builder::default()
.plugin(tauri_plugin_websocket::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

@ -0,0 +1,52 @@
{
"build": {
"distDir": "../dist",
"devPath": "http://localhost:5173/",
"beforeDevCommand": "pnpm dev",
"beforeBuildCommand": "pnpm build",
"withGlobalTauri": false
},
"tauri": {
"bundle": {
"active": true,
"targets": "all",
"identifier": "com.tauri.dev",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"resources": [],
"externalBin": [],
"copyright": "",
"category": "DeveloperTool",
"shortDescription": "",
"longDescription": "",
"deb": {
"depends": []
},
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"exceptionDomain": ""
}
},
"allowlist": {
"all": false
},
"windows": [
{
"title": "Tauri App",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false
}
],
"security": {
"csp": null
}
}
}

@ -0,0 +1,9 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
declare namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface Platform {}
}

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="/global.css" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

@ -0,0 +1,35 @@
<script lang="ts">
import WebSocket from 'tauri-plugin-websocket-api'
import { onMount } from 'svelte'
let ws
let response = ''
let message = ''
onMount(async () => {
ws = await WebSocket.connect('ws://127.0.0.1:8080').then(r => {
_updateResponse('Connected')
return r
}).catch(_updateResponse)
ws.addListener(_updateResponse)
})
function _updateResponse(returnValue) {
response += (typeof returnValue === 'string' ? returnValue : JSON.stringify(returnValue)) + '<br>'
}
function send() {
ws.send(message).then(() => _updateResponse('Message sent')).catch(_updateResponse)
}
function disconnect() {
ws.disconnect().then(() => _updateResponse('Disconnected')).catch(_updateResponse)
}
</script>
<div>
<input bind:value={message}>
<button on:click={send}>Send</button>
<button on:click={disconnect}>Disconnect</button>
</div>
<div>{@html response}</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

@ -0,0 +1,68 @@
html,
body {
position: relative;
width: 100%;
height: 100%;
}
body {
color: #333;
margin: 0;
padding: 8px;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
a {
color: rgb(0, 100, 200);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:visited {
color: rgb(0, 80, 160);
}
label {
display: block;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
-webkit-padding: 0.4em 0;
padding: 0.4em;
margin: 0 0 0.5em 0;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 2px;
}
input:disabled {
color: #ccc;
}
button {
color: #333;
background-color: #f4f4f4;
outline: none;
}
button:disabled {
color: #999;
}
button:not(:disabled):active {
background-color: #ddd;
}
button:focus {
border-color: #666;
}

@ -0,0 +1,15 @@
import adapter from "@sveltejs/adapter-auto";
import { vitePreprocess } from "@sveltejs/kit/vite";
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
adapter: adapter(),
},
};
export default config;

@ -0,0 +1,17 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

@ -0,0 +1,8 @@
import { sveltekit } from "@sveltejs/kit/vite";
import type { UserConfig } from "vite";
const config: UserConfig = {
plugins: [sveltekit()],
};
export default config;

@ -5,7 +5,8 @@
use serde::{Deserialize, Serialize};
use tauri::{
plugin::{Builder as PluginBuilder, TauriPlugin},
LogicalSize, Manager, PhysicalPosition, RunEvent, Runtime, Window, WindowEvent,
LogicalSize, Manager, Monitor, PhysicalPosition, PhysicalSize, RunEvent, Runtime, Window,
WindowEvent,
};
use std::{
@ -58,7 +59,6 @@ struct WindowMetadata {
visible: bool,
decorated: bool,
fullscreen: bool,
monitor: String,
}
struct WindowStateCache(Arc<Mutex<HashMap<String, WindowMetadata>>>);
@ -105,12 +105,11 @@ impl<R: Runtime> WindowExt for Window<R> {
// restore position to saved value if saved monitor exists
// otherwise, let the OS decide where to place the window
for m in self.available_monitors()? {
if m.name().map(ToString::to_string).unwrap_or_default() == state.monitor {
if m.contains((state.x, state.y).into()) {
self.set_position(PhysicalPosition {
x: state.x,
y: state.y,
})?;
break;
}
}
@ -131,12 +130,6 @@ impl<R: Runtime> WindowExt for Window<R> {
let visible = self.is_visible().unwrap_or(true);
let decorated = self.is_decorated().unwrap_or(true);
let fullscreen = self.is_fullscreen().unwrap_or(false);
let monitor = self
.current_monitor()?
.unwrap()
.name()
.map(ToString::to_string)
.unwrap_or_default();
c.insert(
self.label().into(),
WindowMetadata {
@ -148,7 +141,6 @@ impl<R: Runtime> WindowExt for Window<R> {
visible,
decorated,
fullscreen,
monitor,
},
);
}
@ -235,8 +227,6 @@ impl Builder {
state.maximized = is_maximized;
if let Some(monitor) = window_clone.current_monitor().unwrap() {
state.monitor =
monitor.name().map(ToString::to_string).unwrap_or_default();
let monitor_position = monitor.position();
// save only window positions that are inside the current monitor
if position.x > monitor_position.x
@ -288,3 +278,19 @@ impl Builder {
.build()
}
}
trait MonitorExt {
fn contains(&self, position: PhysicalPosition<i32>) -> bool;
}
impl MonitorExt for Monitor {
fn contains(&self, position: PhysicalPosition<i32>) -> bool {
let PhysicalPosition { x, y } = *self.position();
let PhysicalSize { width, height } = *self.size();
x < position.x as _
&& position.x < (x + width as i32)
&& y < position.y as _
&& position.y < (y + height as i32)
}
}

File diff suppressed because it is too large Load Diff

@ -1,2 +1,3 @@
packages:
- plugins/*
- plugins/*/examples/*

@ -18,8 +18,8 @@
"build": "rollup -c"
},
"files": [
"dist",
"!dist/**/*.map",
"guest-js/dist",
"!guest-js/dist/**/*.map",
"README.md",
"LICENSE"
],

@ -16,5 +16,5 @@
"declaration": true,
"declarationDir": "dist"
},
"exclude": ["dist", "node_modules", "test/types"]
"exclude": ["guest-js/dist", "node_modules", "test/types"]
}

Loading…
Cancel
Save