Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop): stop the target picker overlay crashing and Esc freezing on macOS

Richie McIlroy50203110c3d8
diff --git a/Cargo.lock b/Cargo.lock
index a47836d48..3dce4a298 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -10607,7 +10607,6 @@ dependencies = [
[[package]]
name = "tauri-nspanel"
version = "2.0.1"
-source = "git+https://github.com/ahkohd/tauri-nspanel?branch=v2#18ffb9a201fbf6fedfaa382fd4b92315ea30ab1a"
dependencies = [
"bitflags 2.13.1",
"block",
@@ -10616,6 +10615,7 @@ dependencies = [
"core-graphics 0.25.0",
"objc",
"objc-foundation",
+ "objc_exception",
"objc_id",
"tauri",
]
diff --git a/Cargo.toml b/Cargo.toml
index 0aa206efb..4cc80ceb6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -127,3 +127,11 @@ tao = { path = "vendor/tao" }
# https://github.com/CapSoftware/reqwest/commit/9b5ecbd5210a9510fde766015cabb724c1e70d2e
reqwest = { git = "https://github.com/CapSoftware/reqwest", rev = "9b5ecbd5210a9510fde766015cabb724c1e70d2e" }
+
+# tauri-nspanel v2 @ 18ffb9a with ownership fixes: `to_panel()` no longer steals
+# tao's NSWindow retain (every repeat call was an over-release), converting the
+# same window twice is a no-op, the store forgets destroyed windows, and the
+# broken `dealloc` override (NSObject dealloc + jump through a garbage pointer)
+# is gone. See vendor/tauri-nspanel/CAP-CHANGES.md.
+[patch."https://github.com/ahkohd/tauri-nspanel"]
+tauri-nspanel = { path = "vendor/tauri-nspanel" }
diff --git a/apps/desktop/scripts/desktop-picker-performance.md b/apps/desktop/scripts/desktop-picker-performance.md
index d3e87c8a3..a8a7f2af9 100644
--- a/apps/desktop/scripts/desktop-picker-performance.md
+++ b/apps/desktop/scripts/desktop-picker-performance.md
@@ -13,6 +13,12 @@ CAP_PICKER_BENCH_CAMERA_ID=<device-id> cargo test -p cap-desktop-gpui --bin cap-
Both debug apps also support `CAP_PICKER_BENCHMARK_OUTPUT=<absolute-json-path>` and `CAP_PICKER_BENCHMARK_DELAY_MS=0`. They open and dismiss six alternating display/window pickers, write timings, and exit. The default delay is 2000 ms. Run them sequentially after compilation has finished.
+The Tauri app also takes `CAP_PICKER_BENCHMARK_SAMPLES=<n>` to run more than six picker cycles and `CAP_PICKER_BENCHMARK_CAMERA_CYCLES=<n>` to follow them with camera-window close/reopen cycles (written to `<output>.camera.json`), and `CAP_PICKER_BENCHMARK_ESCAPE=direct` (or `wait:<ms>`, for an external driver sending a real Escape keypress) to check the picker is dismissed through the Escape path (written to `<output>.escape.json`). Together with `NSZombieEnabled=YES` this is the overlay soak that guards the vendored `tauri-nspanel` ownership fix: the picker reveal converts its overlay windows to NSPanels on every open, and the camera window is destroyed and recreated under one label, so an over-release in either path shows up as a `message sent to deallocated instance` line or a crash within a few cycles instead of in a user's session.
+
+```sh
+NSZombieEnabled=YES CAP_PICKER_BENCHMARK_OUTPUT=/tmp/picker.json CAP_PICKER_BENCHMARK_SAMPLES=200 CAP_PICKER_BENCHMARK_CAMERA_CYCLES=30 target/debug/cap-desktop
+```
+
- Tauri measures from the target-mode request through native window creation, frontend initialization, input restoration, and two animation frames with the recording button enabled.
- GPUI includes pending device discovery and selected-input readiness, then waits for two rendered overlay frames.
- Sample zero measures the first picker in a fresh process. Later samples measure reopening. These are picker timings, not total process launch times. They are not directly interchangeable across UI implementations.
diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rs
index 5d6623b46..a260f89ce 100644
--- a/apps/desktop/src-tauri/src/hotkeys.rs
+++ b/apps/desktop/src-tauri/src/hotkeys.rs
@@ -292,7 +292,15 @@ pub fn init(app: &AppHandle) {
}
if shortcut.key == Code::Escape {
- crate::target_select_overlay::dismiss_picker_from_escape(app);
+ // This handler runs on the main thread while the plugin
+ // holds its shortcut registry lock. Dismissing the picker
+ // ends the picker session, which unregisters Escape through
+ // that same lock, so doing it inline deadlocks the main
+ // thread (overlay stuck on screen, app frozen). Defer it.
+ let dismiss_app = app.clone();
+ spawn_shortcut_task(async move {
+ crate::target_select_overlay::dismiss_picker_from_escape(&dismiss_app);
+ });
OnEscapePress.emit(app).ok();
}
diff --git a/apps/desktop/src-tauri/src/picker_benchmark.rs b/apps/desktop/src-tauri/src/picker_benchmark.rs
index 7ec14003c..bd2abbf64 100644
--- a/apps/desktop/src-tauri/src/picker_benchmark.rs
+++ b/apps/desktop/src-tauri/src/picker_benchmark.rs
@@ -3,7 +3,10 @@ use std::time::{Duration, Instant};
use tauri::{Listener, Manager};
use tauri_specta::Event;
-use crate::{RequestSetTargetMode, recording_settings::RecordingTargetMode};
+use crate::{
+ RequestSetTargetMode, recording_settings::RecordingTargetMode,
+ target_select_overlay::WindowFocusManager,
+};
pub const SCRIPT: &str = include_str!("picker-benchmark.js");
@@ -25,8 +28,15 @@ pub fn run(app: tauri::AppHandle) {
let listener = app.listen_any("cap-picker-benchmark-ready", move |event| {
let _ = sender.send(event.payload().to_owned());
});
+ // Six alternating Display/Window cycles by default; the overlay
+ // soak (see CAP-CHANGES in vendor/tauri-nspanel) runs hundreds.
+ let sample_count = std::env::var("CAP_PICKER_BENCHMARK_SAMPLES")
+ .ok()
+ .and_then(|count| count.parse::<usize>().ok())
+ .filter(|count| *count > 0)
+ .unwrap_or(6);
let mut samples = Vec::new();
- for sample in 0..6 {
+ for sample in 0..sample_count {
let mode = if sample % 2 == 0 {
RecordingTargetMode::Display
} else {
@@ -58,10 +68,122 @@ pub fn run(app: tauri::AppHandle) {
.emit(&app);
tokio::time::sleep(Duration::from_millis(300)).await;
}
- app.unlisten(listener);
- if let Err(error) = std::fs::write(output, serde_json::json!(samples).to_string()) {
+ if let Err(error) = std::fs::write(&output, serde_json::json!(samples).to_string()) {
tracing::error!(%error, "Could not write picker benchmark results");
}
+
+ // Optional Escape phase: open the Display picker and confirm it is
+ // dismissed through the Escape path. `CAP_PICKER_BENCHMARK_ESCAPE=direct`
+ // calls the same dismissal the global-shortcut handler runs;
+ // `CAP_PICKER_BENCHMARK_ESCAPE=wait:<ms>` instead holds the picker open
+ // for that long while an external driver sends a real Escape keypress,
+ // and records whether the picker session ended on its own.
+ if let Ok(mode) = std::env::var("CAP_PICKER_BENCHMARK_ESCAPE") {
+ let hold_ms = mode
+ .strip_prefix("wait:")
+ .and_then(|value| value.parse::<u64>().ok());
+ let mut escape_samples = Vec::new();
+ for cycle in 0..3 {
+ for (label, window) in app.webview_windows() {
+ if label.starts_with("target-select-overlay") {
+ let _ = window.eval("globalThis.__capArmPickerBenchmark?.()");
+ }
+ }
+ let _ = RequestSetTargetMode {
+ target_mode: Some(RecordingTargetMode::Display),
+ display_id: None,
+ }
+ .emit(&app);
+ let ready = tokio::time::timeout(Duration::from_secs(20), receiver.recv())
+ .await
+ .is_ok();
+ let started = Instant::now();
+ let picker_open = || app.state::<WindowFocusManager>().picker_session().is_some();
+ let dismissed = if let Some(hold_ms) = hold_ms {
+ // Tell the external driver the picker is up so it sends
+ // exactly one Escape per cycle.
+ let marker = std::path::PathBuf::from(&output).with_extension("escape.ready");
+ let _ = std::fs::write(&marker, b"ready");
+ let deadline = Instant::now() + Duration::from_millis(hold_ms);
+ let mut dismissed = false;
+ while Instant::now() < deadline {
+ if !picker_open() {
+ dismissed = true;
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ let _ = std::fs::remove_file(&marker);
+ dismissed
+ } else {
+ tokio::time::sleep(Duration::from_millis(400)).await;
+ crate::target_select_overlay::dismiss_picker_from_escape(&app);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ !picker_open()
+ };
+ escape_samples.push(serde_json::json!({
+ "cycle": cycle,
+ "ready": ready,
+ "dismissed": dismissed,
+ "dismissMs": started.elapsed().as_secs_f64() * 1000.0,
+ }));
+ if !dismissed {
+ let _ = RequestSetTargetMode {
+ target_mode: None,
+ display_id: None,
+ }
+ .emit(&app);
+ }
+ tokio::time::sleep(Duration::from_millis(600)).await;
+ }
+ let escape_output = std::path::PathBuf::from(&output).with_extension("escape.json");
+ if let Err(error) =
+ std::fs::write(escape_output, serde_json::json!(escape_samples).to_string())
+ {
+ tracing::error!(%error, "Could not write escape benchmark results");
+ }
+ }
+ app.unlisten(listener);
+
+ // Optional second phase: close and reopen the camera window, which is
+ // destroyed and recreated under the same label. This exercises the
+ // NSPanel store's stale-entry replacement and its Destroyed cleanup
+ // (the paths that free a converted window for real), so an ownership
+ // bug in the vendored tauri-nspanel surfaces here instead of in a
+ // user's recording session. Results land next to the picker output.
+ let camera_cycles = std::env::var("CAP_PICKER_BENCHMARK_CAMERA_CYCLES")
+ .ok()
+ .and_then(|count| count.parse::<usize>().ok())
+ .unwrap_or(0);
+ if camera_cycles > 0 {
+ let mut camera_samples = Vec::new();
+ for cycle in 0..camera_cycles {
+ let started = Instant::now();
+ let removed = crate::windows::cleanup_camera_window(&app, None, true, true).await;
+ let close_ms = started.elapsed().as_secs_f64() * 1000.0;
+ tokio::time::sleep(Duration::from_millis(400)).await;
+ let started = Instant::now();
+ let shown = (crate::windows::ShowCapWindow::Camera { centered: true })
+ .show(&app)
+ .await
+ .is_ok();
+ camera_samples.push(serde_json::json!({
+ "cycle": cycle,
+ "removed": removed,
+ "closeMs": close_ms,
+ "shown": shown,
+ "showMs": started.elapsed().as_secs_f64() * 1000.0,
+ }));
+ tokio::time::sleep(Duration::from_millis(900)).await;
+ }
+ let camera_output = std::path::PathBuf::from(&output).with_extension("camera.json");
+ if let Err(error) =
+ std::fs::write(camera_output, serde_json::json!(camera_samples).to_string())
+ {
+ tracing::error!(%error, "Could not write camera benchmark results");
+ }
+ }
+ tracing::info!("Picker benchmark complete; requesting app exit");
app.exit(0);
});
}
diff --git a/vendor/tao/Cargo.toml b/vendor/tao/Cargo.toml
index 13c0c01c6..d0f849002 100644
--- a/vendor/tao/Cargo.toml
+++ b/vendor/tao/Cargo.toml
@@ -252,6 +252,7 @@ version = "1"
version = "0.6"
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies.objc2]
+features = ["exception"]
version = "0.6"
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies.dlopen2]
diff --git a/vendor/tao/src/platform_impl/macos/event_loop.rs b/vendor/tao/src/platform_impl/macos/event_loop.rs
index c3d4f61d2..ee0379dcd 100644
--- a/vendor/tao/src/platform_impl/macos/event_loop.rs
+++ b/vendor/tao/src/platform_impl/macos/event_loop.rs
@@ -276,7 +276,17 @@ pub fn stop_app_on_panic<F: FnOnce() -> R + UnwindSafe, R>(
panic_info: Weak<PanicInfo>,
f: F,
) -> Option<R> {
- match catch_unwind(f) {
+ // An Objective-C exception raised inside the callback would otherwise
+ // unwind through Rust frames, which aborts the process with no message.
+ // Catch it, log what AppKit actually complained about, and route it through
+ // the regular panic path so the crash is diagnosable.
+ match catch_unwind(move || match objc2::exception::catch(f) {
+ Ok(r) => r,
+ Err(exception) => {
+ eprintln!("tao: Objective-C exception in run loop callback: {exception:?}");
+ panic!("Objective-C exception in tao callback");
+ }
+ }) {
Ok(r) => Some(r),
Err(e) => {
// It's important that we set the panic before requesting a `stop`
diff --git a/vendor/tauri-nspanel/CAP-CHANGES.md b/vendor/tauri-nspanel/CAP-CHANGES.md
new file mode 100644
index 000000000..2f3798a0f
--- /dev/null
+++ b/vendor/tauri-nspanel/CAP-CHANGES.md
@@ -0,0 +1,67 @@
+# Cap changes to tauri-nspanel
+
+Vendored from https://github.com/ahkohd/tauri-nspanel branch `v2` at
+commit `18ffb9a201fbf6fedfaa382fd4b92315ea30ab1a` (crate version 2.0.1),
+wired in through `[patch."https://github.com/ahkohd/tauri-nspanel"]` in the
+workspace `Cargo.toml`. Only `src/` is patched; `macros.rs` is untouched.
+
+## Why
+
+Cap's target-select overlay crashed with `EXC_BAD_ACCESS` inside
+`objc_autoreleasePoolPop` after a few open/close cycles. Two upstream bugs
+combined:
+
+1. `RawNSPanel::from_window` built its handle with `Id::from_retained_ptr`,
+ claiming a +1 retain it never took. Tao still owned that retain, so every
+ time the plugin dropped a handle it sent a real `release` to a window it did
+ not own. `to_panel()` inserted a fresh handle into the label store on every
+ call, dropping the previous one, so each repeat conversion of the same
+ window stripped one retain. The overlay reveal path converts on every
+ reveal, which reached zero within a handful of cycles.
+2. The `dealloc` override sent `dealloc` to `NSObject`'s implementation
+ (skipping `NSWindow`'s teardown) and then called the leftover x0 register
+ as a function pointer. Any converted window that was ever freed jumped into
+ malloc metadata, which is the bus error in the crash reports.
+
+## Second bug found while soaking the fix: KVO vs `object_setClass`
+
+Destroying any converted window that hosts a webview aborted the process with
+`fatal runtime error: Rust cannot catch foreign exceptions`. The exception
+(captured by the vendored tao's run-loop guard) is Foundation's
+`NSRangeException: Cannot remove an observer <WKWindowVisibilityObserver> for
+the key path "contentLayoutRect" from <RawNSPanel> because it is not
+registered as an observer`. WebKit observes the window with KVO as soon as the
+webview is attached; KVO does that by giving the window a dynamic
+`NSKVONotifying_*` subclass; `object_setClass` to `RawNSPanel` discards that
+subclass, so the observer removal at teardown throws. This is upstream
+behaviour too (reproduced with the unpatched crate); it only needs a panel
+window to be destroyed, e.g. the camera window when the camera is removed.
+
+## What changed
+
+- `RawNSPanel::from_window` / `from_ns_window` now take a real retain with
+ `Id::from_ptr`. Tao's ownership is untouched; the store's handle is a +1 of
+ its own.
+- Conversion is idempotent. A window already re-classed to `RawNSPanel` skips
+ the class swap, tracking area and autoresize setup, so repeat calls add no
+ duplicate tracking areas.
+- `WebviewWindowExt::to_panel` returns the stored handle when the same live
+ window is converted again, replaces a stale entry left by an earlier window
+ with the same label, and registers a `Destroyed` listener that drops the
+ store entry so a closed window (and its webview) is not kept alive.
+- `ManagerExt::remove_webview_panel` exposes explicit removal.
+- The `dealloc` override is removed; `NSPanel`'s inherited chain is correct.
+- `add_tracking_area` releases the `NSTrackingArea` it allocated once the view
+ owns it.
+- The class swap runs with the content subviews (the webview) detached and
+ re-attached afterwards, so WebKit unregisters its observers against the old
+ class and re-registers against the panel. `is_raw_panel` uses
+ `isKindOfClass:` so a KVO-subclassed panel is never re-swapped.
+- Store handle releases go through `objc_exception::try` and log the reason if
+ AppKit throws, instead of unwinding through Rust.
+- The vendored tao (`vendor/tao`) now catches Objective-C exceptions in its
+ run-loop observer callback, logs them, and routes them through the normal
+ panic path, so this class of failure is diagnosable from logs.
+
+`NSPanel` and `NSWindow` have identical instance sizes (528 bytes, no extra
+ivars on `NSPanel`), which is what makes the `object_setClass` swap safe.
diff --git a/vendor/tauri-nspanel/Cargo.toml b/vendor/tauri-nspanel/Cargo.toml
new file mode 100644
index 000000000..eb6d2e474
--- /dev/null
+++ b/vendor/tauri-nspanel/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "tauri-nspanel"
+version = "2.0.1"
+authors = ["Victor Aremu <[email protected]>"]
+description = "A plugin for subclassing Tauri's NSWindow to NSPanel"
+edition = "2021"
+rust-version = "1.75"
+exclude = ["/examples"]
+
+[dependencies]
+tauri = { version = "2.0.6" }
+bitflags = "2.6.0"
+
+[target."cfg(target_os = \"macos\")".dependencies]
+block = "0.1.6"
+core-graphics = { version = "0.25.0" }
+core-foundation = { version = "0.10.0" }
+cocoa = { version = "0.26.0" }
+objc = { version = "0.2.7" }
+objc_exception = "0.1.2"
+objc_id = { version = "0.1.1" }
+objc-foundation = { version = "0.1.1" }
+
+[features]
+cargo-clippy = []
diff --git a/vendor/tauri-nspanel/LICENSE_APACHE-2.0 b/vendor/tauri-nspanel/LICENSE_APACHE-2.0
new file mode 100644
index 000000000..f433b1a53
--- /dev/null
+++ b/vendor/tauri-nspanel/LICENSE_APACHE-2.0
@@ -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
diff --git a/vendor/tauri-nspanel/LICENSE_MIT b/vendor/tauri-nspanel/LICENSE_MIT
new file mode 100644
index 000000000..986a7aa52
--- /dev/null
+++ b/vendor/tauri-nspanel/LICENSE_MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 - Present Victor Aremu
+
+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.
diff --git a/vendor/tauri-nspanel/README.md b/vendor/tauri-nspanel/README.md
new file mode 100644
index 000000000..f74b56d38
--- /dev/null
+++ b/vendor/tauri-nspanel/README.md
@@ -0,0 +1,123 @@
+Convert a Tauri `WebviewWindow` ([`NSWindow`](https://developer.apple.com/documentation/appkit/nswindow)) to panel ([`NSPanel`](https://developer.apple.com/documentation/appkit/nspanel))
+
+# Install
+Install the plugin by adding the following to your `Cargo.toml` file:
+
+```toml
+[dependencies]
+tauri-nspanel = { git = "https://github.com/ahkohd/tauri-nspanel", branch = "v2" }
+
+[features]
+cargo-clippy = []
+```
+
+# Usage
+
+1. First you need to register the core plugin with Tauri:
+
+`src-tauri/src/main.rs`
+
+```rust
+fn main() {
+ tauri::Builder::default()
+ .plugin(tauri_nspanel::init())
+ .run(tauri::generate_context!())
+ .expect("error while running tauri application");
+}
+```
+
+2. To swizzle a window's `NSWindow` to `NSPanel`, use the `to_panel()` method:
+
+```rust
+use tauri_nspanel::WebviewWindowExt;
+
+// ...
+let panel = window.to_panel().unwrap();
+```
+
+The window will be swizzled to `NSPanel`.
+
+> Only call the `to_panel()` method once on a webview window.
+
+3. To access your panels, use the `app_handle.get_webview_panel("label")`:
+
+```rust
+use tauri_nspanel::ManagerExt;
+
+// ...
+
+let my_panel = app_handle.get_webview_panel("main");
+```
+
+4. To respond to panel events, such as resizing, moving, exposing, and minimizing ([See the exhaustive list](https://developer.apple.com/documentation/appkit/nswindowdelegate?language=objc)), you need to setup a `NSWindowDelegate` for your panel.
+
+Use the `panel_delegate!()` macro to do this:
+
+```rust
+use tauri::Wry;
+use tauri_nspanel::{objc_id::Id, panel_delegate, ManagerExt, Panel, WindowExt};
+
+// ...
+// Use the `panel_delegate!()` macro to create your custom delegate
+
+// Specify your handlers
+// See, https://developer.apple.com/documentation/appkit/nswindowdelegate?language=objc
+// for an exhaustive list of handlers.
+//
+// Example: to respond to windowDidBecomeKey:
+// specify in snake case: window_did_become_key
+
+let delegate = panel_delegate!(MyPanelDelegate {
+ window_did_become_key,
+ window_did_resign_key
+});
+
+// Listen to when a delegate is called
+delegate.set_listener(Box::new(|delegate_name: String| {
+ println!("{} was called!", delegate_name);
+}));
+
+// Set your panel's delegate
+panel.set_delegate(delegate);
+```
+
+5. Simply calling the `.close()` method on your NSPanel instance may not be sufficient to fully release its resources. This is because, by default,
+ `NSPanels` are not released when they are closed. This is because NSPanels are often lightweight and designed for reuse.
+
+To ensure that your NSPanel is fully released:
+
+```rust
+// ...
+
+panel.set_released_when_closed(true);
+panel.close();
+```
+
+6. See the [examples](/examples) to learn how to use `tauri-nspanel`. For more information on panel methods, please refer to the [documentation page](https://ahkohd.github.io/tauri-nspanel/tauri_nspanel/raw_nspanel/struct.RawNSPanel.html).
+
+# Related
+
+The following are projects related to this plugin:
+
+- [tauri-plugin-spotlight](https://github.com/zzzze/tauri-plugin-spotlight)
+- [tauri-macos-spotlight-example](https://github.com/ahkohd/tauri-macos-spotlight-example)
+- [tauri-macos-menubar-example](https://github.com/ahkohd/tauri-macos-menubar-app-example)
+
+# Showcase
+
+Here are some projects using `tauri-nspanel`
+
+- [Cap](https://github.com/CapSoftware/Cap)
+- [EcoPaste](https://github.com/EcoPasteHub/EcoPaste)
+- [Overlayed](https://github.com/overlayeddev/overlayed)
+- [Lume](https://github.com/lumehq/lume)
+- [Verve](https://github.com/ParthJadhav/verve)
+- [Buffer](https://buffer.md)
+
+# Contributing
+
+PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
+
+# License
+
+MIT or MIT/Apache 2.0 where applicable.
diff --git a/vendor/tauri-nspanel/src/lib.rs b/vendor/tauri-nspanel/src/lib.rs
new file mode 100644
index 000000000..d406c4b24
--- /dev/null
+++ b/vendor/tauri-nspanel/src/lib.rs
@@ -0,0 +1,191 @@
+#![allow(deprecated)]
+
+mod macros;
+pub mod raw_nspanel;
+
+use std::{collections::HashMap, sync::Mutex};
+
+use cocoa::base::id;
+use objc_id::ShareId;
+use raw_nspanel::RawNSPanel;
+use tauri::{
+ plugin::{Builder, TauriPlugin},
+ Manager, Runtime, WebviewWindow,
+};
+
+pub extern crate block;
+pub extern crate cocoa;
+pub extern crate objc;
+pub extern crate objc_foundation;
+pub extern crate objc_id;
+pub extern crate tauri;
+
+pub type Panel = ShareId<RawNSPanel>;
+
+#[derive(Default)]
+pub struct Store {
+ panels: HashMap<String, ShareId<RawNSPanel>>,
+}
+
+pub struct WebviewPanelManager(pub Mutex<Store>);
+
+impl Default for WebviewPanelManager {
+ fn default() -> Self {
+ Self(Mutex::new(Store::default()))
+ }
+}
+
+pub trait ManagerExt<R: Runtime> {
+ fn get_webview_panel(&self, label: &str) -> Result<ShareId<RawNSPanel>, Error>;
+
+ /// Drops the store's handle for `label`, releasing the retain the plugin
+ /// took when the window was converted. Returns the handle so the caller
+ /// can decide where it is dropped (the final release of an NSWindow must
+ /// happen on the main thread).
+ fn remove_webview_panel(&self, label: &str) -> Option<ShareId<RawNSPanel>>;
+}
+
+#[derive(Debug)]
+pub enum Error {
+ PanelNotFound,
+}
+
+impl<R: Runtime, T: Manager<R>> ManagerExt<R> for T {
+ fn get_webview_panel(&self, label: &str) -> Result<ShareId<RawNSPanel>, Error> {
+ let manager = self.state::<self::WebviewPanelManager>();
+ let manager = manager.0.lock().unwrap();
+
+ match manager.panels.get(label) {
+ Some(panel) => Ok(panel.clone()),
+ None => Err(Error::PanelNotFound),
+ }
+ }
+
+ fn remove_webview_panel(&self, label: &str) -> Option<ShareId<RawNSPanel>> {
+ let manager = self.state::<self::WebviewPanelManager>();
+ let mut manager = manager.0.lock().unwrap();
+ manager.panels.remove(label)
+ }
+}
+
+#[derive(Default)]
+pub struct WebviewPanelConfig {
+ pub delegate: Option<id>,
+}
+
+pub trait WebviewWindowExt<R: Runtime> {
+ fn to_panel(&self) -> tauri::Result<ShareId<RawNSPanel>>;
+}
+
+/// Releases a store handle on the main thread, turning an Objective-C
+/// exception raised during the release (which would otherwise unwind through
+/// tao's run-loop observer and abort the process) into a logged error.
+fn release_panel_handle(context: &str, panel: ShareId<RawNSPanel>) {
+ use objc::{msg_send, sel, sel_impl};
+
+ let outcome = unsafe { objc_exception::r#try(move || drop(panel)) };
+ if let Err(exception) = outcome {
+ let exception = exception as id;
+ let description = unsafe {
+ let describe = |object: id| -> String {
+ if object.is_null() {
+ return String::from("<nil>");
+ }
+ let utf8: *const std::os::raw::c_char = msg_send![object, UTF8String];
+ if utf8.is_null() {
+ String::from("<non-utf8>")
+ } else {
+ std::ffi::CStr::from_ptr(utf8)
+ .to_string_lossy()
+ .into_owned()
+ }
+ };
+ if exception.is_null() {
+ String::from("<unknown exception>")
+ } else {
+ let name: id = msg_send![exception, name];
+ let reason: id = msg_send![exception, reason];
+ format!("{}: {}", describe(name), describe(reason))
+ }
+ };
+ eprintln!("tauri-nspanel: releasing panel handle ({context}) threw {description}");
+ }
+}
+
+fn panel_ptr(panel: &ShareId<RawNSPanel>) -> usize {
+ &**panel as *const RawNSPanel as usize
+}
+
+impl<R: Runtime> WebviewWindowExt<R> for WebviewWindow<R> {
+ /// Converts the window's NSWindow into a `RawNSPanel` and stores a handle
+ /// for it under the window label.
+ ///
+ /// Calling this again for the same live window returns the stored handle
+ /// without touching the window: no second class swap, no duplicate
+ /// tracking areas, and no change to the NSWindow's retain count. A stale
+ /// entry left by a previous window with the same label is replaced, and
+ /// the store forgets a window as soon as tao reports it destroyed, so the
+ /// plugin never keeps a closed window (or its webview) alive.
+ fn to_panel(&self) -> tauri::Result<ShareId<RawNSPanel>> {
+ let nswindow = self.ns_window()? as id;
+ let raw = nswindow as usize;
+ let label = self.label().to_string();
+ let manager = self.state::<self::WebviewPanelManager>();
+
+ if let Some(existing) = manager.0.lock().unwrap().panels.get(&label) {
+ if panel_ptr(existing) == raw {
+ return Ok(existing.clone());
+ }
+ }
+
+ // SAFETY: `ns_window()` handed us tao's live NSWindow, and tauri only
+ // exposes it from the main thread context this is called in.
+ let shared_panel = unsafe { RawNSPanel::from_ns_window(nswindow) }.share();
+
+ let previous = manager
+ .0
+ .lock()
+ .unwrap()
+ .panels
+ .insert(label.clone(), shared_panel.clone());
+ // A different window that used this label before. Its handle holds a
+ // real retain, so dropping it here (on the main thread) is the release
+ // that lets AppKit finally free the old window.
+ if let Some(previous) = previous {
+ release_panel_handle("replacing stale label entry", previous);
+ }
+
+ let app = self.app_handle().clone();
+ self.on_window_event(move |event| {
+ if !matches!(event, tauri::WindowEvent::Destroyed) {
+ return;
+ }
+ let manager = app.state::<self::WebviewPanelManager>();
+ let mut store = manager.0.lock().unwrap();
+ let stale = match store.panels.get(&label) {
+ Some(panel) if panel_ptr(panel) == raw => store.panels.remove(&label),
+ _ => None,
+ };
+ drop(store);
+ // Tao emits `Destroyed` from `windowWillClose:` on the main thread
+ // while it still holds its own reference, so releasing ours here
+ // never frees the window out from under AppKit.
+ if let Some(stale) = stale {
+ release_panel_handle("window destroyed", stale);
+ }
+ });
+
+ Ok(shared_panel)
+ }
+}
+
+/// Initializes the plugin.
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ Builder::new("nspanel")
+ .setup(|app, _api| {
+ app.manage(self::WebviewPanelManager::default());
+
+ Ok(())
+ })
+ .build()
+}
diff --git a/vendor/tauri-nspanel/src/macros.rs b/vendor/tauri-nspanel/src/macros.rs
new file mode 100644
index 000000000..9d9cfa26c
--- /dev/null
+++ b/vendor/tauri-nspanel/src/macros.rs
@@ -0,0 +1,139 @@
+#[macro_export]
+macro_rules! panel_delegate {
+ ($delegate_name:ident { $($fn_name:ident),* $(,)* }) => {{
+ use $crate::objc::{
+ class,
+ declare::ClassDecl,
+ msg_send,
+ runtime::{self, Class, Object, Protocol, Sel},
+ sel, sel_impl, Message,
+ };
+ use $crate::cocoa::base::{id, nil, BOOL, NO};
+ use $crate::objc_foundation::INSObject;
+ use $crate::objc_id::{Id, ShareId};
+ use $crate::raw_nspanel::RawNSPanel;
+ use $crate::tauri::Runtime;
+ use $crate::block::ConcreteBlock;
+ use std::ffi::{c_void, c_char};
+
+ macro_rules! snake_to_camel {
+ ($input:ident) => {{
+ let mut camel_case = String::new();
+ let mut chars = $input.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '_' {
+ if let Some(next) = chars.peek() {
+ camel_case.push(next.to_ascii_uppercase());
+ chars.next();
+ }
+ } else {
+ camel_case.push(c);
+ }
+ }
+ camel_case
+ }};
+ }
+
+ macro_rules! sel_from_func {
+ ($func:ident) => ({
+ let func_str = stringify!($func);
+ let sel_str = snake_to_camel!(func_str);
+ sel_impl!(format!("{}:{}", sel_str, '\0').as_str())
+ });
+ }
+
+ #[allow(dead_code)]
+ const DELEGATE_CLS_NAME: &str = stringify!($delegate_name);
+
+ #[allow(dead_code)]
+ struct $delegate_name;
+
+ impl $delegate_name {
+ #[allow(dead_code)]
+ fn get_class() -> &'static Class {
+ Class::get(DELEGATE_CLS_NAME).unwrap_or_else(Self::define_class)
+ }
+
+ #[allow(dead_code)]
+ fn define_class() -> &'static Class {
+ let mut cls = ClassDecl::new(DELEGATE_CLS_NAME, class!(NSObject))
+ .unwrap_or_else(|| panic!("Unable to register {} class", DELEGATE_CLS_NAME));
+
+ cls.add_protocol(
+ Protocol::get("NSWindowDelegate").expect("Failed to get NSWindowDelegate protocol"),
+ );
+
+ unsafe {
+ cls.add_ivar::<*mut c_void>("_listener");
+
+ cls.add_method(
+ sel!(setListener:),
+ Self::handle_set_listener as extern "C" fn(&mut Object, Sel, *mut c_void),
+ );
+
+ $(
+ cls.add_method(
+ sel_from_func!($fn_name),
+ Self::$fn_name as extern "C" fn(&Object, Sel, id),
+ );
+ )*
+
+ cls.add_method(
+ sel!(dealloc),
+ Self::dealloc as extern "C" fn(&mut Object, Sel),
+ );
+ }
+
+ cls.register()
+ }
+
+ extern "C" fn handle_set_listener(this: &mut Object, _: Sel, listener: *mut c_void) {
+ unsafe { this.set_ivar::<*mut c_void>("_listener", listener) };
+ }
+
+ $(
+ extern "C" fn $fn_name(this: &Object, _: Sel, _: id) {
+ let delegate_name = std::ffi::CString::new(stringify!($fn_name)).unwrap();
+ let delegate_name_ptr = delegate_name.as_ptr();
+
+ let listener: *mut c_void = unsafe { *this.get_ivar("_listener") };
+ let listener = listener as *const ConcreteBlock<(*const c_char, BOOL, *mut Object, *mut Sel, *mut c_void), (), ()>;
+
+ unsafe {
+ (*listener).call((delegate_name_ptr, NO, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()));
+ }
+ }
+ )*
+
+ extern "C" fn dealloc(this: &mut Object, _cmd: Sel) {
+ unsafe {
+ let superclass = class!(NSObject);
+ let dealloc: extern "C" fn(&mut Object, Sel) =
+ msg_send![super(this, superclass), dealloc];
+ dealloc(this, _cmd);
+ }
+ }
+ }
+
+ unsafe impl Message for $delegate_name {}
+
+ impl INSObject for $delegate_name {
+ fn class() -> &'static runtime::Class {
+ Self::get_class()
+ }
+ }
+
+ impl $delegate_name {
+ pub fn set_listener(&self, callback: Box<dyn Fn(String)>) {
+ let block = ConcreteBlock::new(move |_delegate_name: *const c_char| {
+ let delegate_name = unsafe { std::ffi::CStr::from_ptr(_delegate_name).to_string_lossy().into_owned() };
+ callback(delegate_name);
+ });
+ let block = block.copy();
+ let _: () = unsafe { msg_send![self, setListener: block] };
+ }
+ }
+
+ $delegate_name::new()
+ }};
+}
diff --git a/vendor/tauri-nspanel/src/raw_nspanel.rs b/vendor/tauri-nspanel/src/raw_nspanel.rs
new file mode 100644
index 000000000..31f13bbf7
--- /dev/null
+++ b/vendor/tauri-nspanel/src/raw_nspanel.rs
@@ -0,0 +1,351 @@
+#![allow(deprecated)]
+
+use bitflags::bitflags;
+use cocoa::{
+ appkit::{NSView, NSViewHeightSizable, NSViewWidthSizable, NSWindowCollectionBehavior},
+ base::{id, nil, BOOL, YES},
+ foundation::{NSRect, NSUInteger},
+};
+use objc::{
+ class,
+ declare::ClassDecl,
+ msg_send,
+ runtime::{self, Class, Object, Sel},
+ sel, sel_impl, Message,
+};
+use objc_foundation::INSObject;
+use objc_id::{Id, ShareId};
+use tauri::{Runtime, WebviewWindow};
+
+bitflags! {
+ struct NSTrackingAreaOptions: u32 {
+ const NSTrackingActiveAlways = 0x80;
+ const NSTrackingMouseEnteredAndExited = 0x01;
+ const NSTrackingMouseMoved = 0x02;
+ const NSTrackingCursorUpdate = 0x04;
+ }
+}
+
+extern "C" {
+ pub fn object_setClass(obj: id, cls: id) -> id;
+}
+
+const CLS_NAME: &str = "RawNSPanel";
+
+pub struct RawNSPanel;
+
+unsafe impl Sync for RawNSPanel {}
+unsafe impl Send for RawNSPanel {}
+
+impl INSObject for RawNSPanel {
+ fn class() -> &'static runtime::Class {
+ Class::get(CLS_NAME).unwrap_or_else(Self::define_class)
+ }
+}
+
+impl RawNSPanel {
+ /// Returns YES to ensure that RawNSPanel can become a key window
+ extern "C" fn can_become_key_window(_: &Object, _: Sel) -> BOOL {
+ YES
+ }
+
+ // No `dealloc` override. The upstream plugin installed one that sent
+ // `dealloc` straight to NSObject's implementation (skipping NSWindow's
+ // teardown) and then jumped through the leftover return register as if it
+ // were a function pointer, which is a bus error the moment a converted
+ // window is ever freed. NSPanel's inherited dealloc chain is the correct
+ // one; there is nothing panel-specific to clean up here.
+ fn define_class() -> &'static Class {
+ let mut cls = ClassDecl::new(CLS_NAME, class!(NSPanel))
+ .unwrap_or_else(|| panic!("Unable to register {} class", CLS_NAME));
+
+ unsafe {
+ cls.add_method(
+ sel!(canBecomeKeyWindow),
+ Self::can_become_key_window as extern "C" fn(&Object, Sel) -> BOOL,
+ );
+ }
+
+ cls.register()
+ }
+
+ /// Whether `object` has already been re-classed into a `RawNSPanel`.
+ ///
+ /// # Safety
+ /// `object` must point to a live Objective-C object.
+ pub unsafe fn is_raw_panel(object: id) -> bool {
+ if object.is_null() {
+ return false;
+ }
+ // `isKindOfClass:` rather than a pointer compare: once anything
+ // observes the window with KVO, its class becomes a dynamic
+ // `NSKVONotifying_RawNSPanel` subclass, and swapping the class again
+ // from under KVO is exactly what breaks observer removal later.
+ let is_kind: BOOL = msg_send![object, isKindOfClass: Self::class()];
+ is_kind == YES
+ }
+
+ /// Runs `swap` with the window's content subviews (the webview) detached.
+ ///
+ /// WebKit observes its window with KVO from the moment the webview is
+ /// added to it, and KVO implements that by giving the window a dynamic
+ /// notifying subclass. Re-classing the window while those observers are
+ /// registered discards that subclass, so when WebKit later removes its
+ /// observers (window teardown) Foundation throws `NSRangeException`
+ /// ("not registered as an observer"), which unwinds through tao's run-loop
+ /// observer and aborts the process. Detaching the views first makes WebKit
+ /// unregister against the old class and re-register against the panel.
+ unsafe fn with_content_subviews_detached(nswindow: id, swap: impl FnOnce()) {
+ let content_view: id = msg_send![nswindow, contentView];
+ if content_view.is_null() {
+ swap();
+ return;
+ }
+ let subviews: id = msg_send![content_view, subviews];
+ // Own a snapshot: removing views mutates the live array and would
+ // otherwise drop the only references to them.
+ let subviews: id = msg_send![subviews, copy];
+ let count: NSUInteger = msg_send![subviews, count];
+ let first_responder: id = msg_send![nswindow, firstResponder];
+ for index in 0..count {
+ let view: id = msg_send![subviews, objectAtIndex: index];
+ let _: () = msg_send![view, removeFromSuperview];
+ }
+
+ swap();
+
+ for index in 0..count {
+ let view: id = msg_send![subviews, objectAtIndex: index];
+ let _: () = msg_send![content_view, addSubview: view];
+ }
+ if !first_responder.is_null() {
+ let is_view: BOOL = msg_send![first_responder, isKindOfClass: class!(NSView)];
+ if is_view == YES {
+ let in_window: id = msg_send![first_responder, window];
+ if in_window == nswindow {
+ let _: BOOL = msg_send![nswindow, makeFirstResponder: first_responder];
+ }
+ }
+ }
+ let _: () = msg_send![subviews, release];
+ }
+
+ pub fn show(&self) {
+ self.make_first_responder(Some(self.content_view()));
+ self.order_front_regardless();
+ self.make_key_window();
+ }
+
+ pub fn is_visible(&self) -> bool {
+ let flag: BOOL = unsafe { msg_send![self, isVisible] };
+ flag == YES
+ }
+
+ pub fn is_floating_panel(&self) -> bool {
+ let flag: BOOL = unsafe { msg_send![self, isFloatingPanel] };
+ flag == YES
+ }
+
+ pub fn make_key_window(&self) {
+ let _: () = unsafe { msg_send![self, makeKeyWindow] };
+ }
+
+ pub fn resign_key_window(&self) {
+ let _: () = unsafe { msg_send![self, resignKeyWindow] };
+ }
+
+ pub fn make_key_and_order_front(&self, sender: Option<id>) {
+ let _: () = unsafe { msg_send![self, makeKeyAndOrderFront: sender.unwrap_or(nil)] };
+ }
+
+ pub fn order_front_regardless(&self) {
+ let _: () = unsafe { msg_send![self, orderFrontRegardless] };
+ }
+
+ pub fn order_out(&self, sender: Option<id>) {
+ let _: () = unsafe { msg_send![self, orderOut: sender.unwrap_or(nil)] };
+ }
+
+ pub fn content_view(&self) -> id {
+ unsafe { msg_send![self, contentView] }
+ }
+
+ pub fn make_first_responder(&self, sender: Option<id>) {
+ if let Some(responder) = sender {
+ let _: () = unsafe { msg_send![self, makeFirstResponder: responder] };
+ } else {
+ let _: () = unsafe { msg_send![self, makeFirstResponder: self] };
+ }
+ }
+
+ pub fn set_level(&self, level: i32) {
+ let _: () = unsafe { msg_send![self, setLevel: level] };
+ }
+
+ pub fn set_alpha_value(&self, value: f64) {
+ let _: () = unsafe { msg_send![self, setAlphaValue: value] };
+ }
+
+ pub fn set_content_size(&self, width: f64, height: f64) {
+ let _: () = unsafe { msg_send![self, setContentSize: (width, height)] };
+ }
+
+ pub fn set_style_mask(&self, style_mask: i32) {
+ let _: () = unsafe { msg_send![self, setStyleMask: style_mask] };
+ }
+
+ pub fn set_collection_behaviour(&self, behaviour: NSWindowCollectionBehavior) {
+ let _: () = unsafe { msg_send![self, setCollectionBehavior: behaviour] };
+ }
+
+ pub fn set_delegate<T>(&self, delegate: Id<T>) {
+ let _: () = unsafe { msg_send![self, setDelegate: delegate] };
+ }
+
+ pub fn set_floating_panel(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setFloatingPanel: value] };
+ }
+
+ pub fn set_accepts_mouse_moved_events(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setAcceptsMouseMovedEvents: value] };
+ }
+
+ pub fn set_ignore_mouse_events(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setIgnoresMouseEvents: value] };
+ }
+
+ pub fn set_hides_on_deactivate(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setHidesOnDeactivate: value] };
+ }
+
+ pub fn set_moveable_by_window_background(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setMovableByWindowBackground: value] };
+ }
+
+ pub fn set_becomes_key_only_if_needed(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setBecomesKeyOnlyIfNeeded: value] };
+ }
+
+ pub fn set_works_when_modal(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setWorksWhenModal: value] };
+ }
+
+ pub fn set_opaque(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setOpaque: value] };
+ }
+
+ pub fn set_has_shadow(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setHasShadow: value] };
+ }
+
+ pub fn set_released_when_closed(&self, value: bool) {
+ let _: () = unsafe { msg_send![self, setReleasedWhenClosed: value] };
+ }
+
+ #[deprecated(
+ since = "2.0.1",
+ note = "Use set_released_when_closed(bool) instead. This method will be removed in a future version."
+ )]
+ pub fn released_when_closed(&self, value: bool) {
+ self.set_released_when_closed(value);
+ }
+
+ pub fn close(&self) {
+ let _: () = unsafe { msg_send![self, close] };
+ }
+
+ pub fn handle(&mut self) -> ShareId<Self> {
+ unsafe { ShareId::from_ptr(self as *mut Self) }
+ }
+
+ fn add_tracking_area(&self) {
+ let view: id = self.content_view();
+ let bounds: NSRect = unsafe { NSView::bounds(view) };
+ let track_view: id = unsafe { msg_send![class!(NSTrackingArea), alloc] };
+ let track_view: id = unsafe {
+ msg_send![
+ track_view,
+ initWithRect: bounds
+ options: NSTrackingAreaOptions::NSTrackingActiveAlways
+ | NSTrackingAreaOptions::NSTrackingMouseEnteredAndExited
+ | NSTrackingAreaOptions::NSTrackingMouseMoved
+ | NSTrackingAreaOptions::NSTrackingCursorUpdate
+ owner: view
+ userInfo: nil
+ ]
+ };
+ let autoresizing_mask = NSViewWidthSizable | NSViewHeightSizable;
+ let () = unsafe { msg_send![view, setAutoresizingMask: autoresizing_mask] };
+ let () = unsafe { msg_send![view, addTrackingArea: track_view] };
+ // `alloc`/`init` handed us a +1 reference and the view now holds its
+ // own; drop ours so the tracking area is released with the view.
+ let () = unsafe { msg_send![track_view, release] };
+ }
+
+ /// Enables the webview (and any other subviews) to automatically resize with its parent window.
+ pub fn auto_resize(&self) {
+ let content_view: id = self.content_view();
+
+ let subviews: id = unsafe { msg_send![content_view, subviews] };
+
+ let count: NSUInteger = unsafe { msg_send![subviews, count] };
+
+ for i in 0..count {
+ let view: id = unsafe { msg_send![subviews, objectAtIndex: i] };
+
+ if view.is_null() {
+ continue;
+ }
+
+ let _: () = unsafe {
+ msg_send![view, setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable]
+ };
+ }
+ }
+
+ /// Create an NSPanel from a Tauri Webview Window.
+ ///
+ /// The returned handle owns a retain of its own. Tao keeps its reference to
+ /// the NSWindow untouched, so dropping this handle (or any clone of it) can
+ /// never strip the runtime's ownership. Converting a window that is already
+ /// a `RawNSPanel` is a no-op apart from taking that retain: the class swap,
+ /// tracking area and autoresize setup only happen on the first conversion.
+ pub fn from_window<R: Runtime>(window: WebviewWindow<R>) -> Id<Self> {
+ let nswindow: id = window.ns_window().unwrap() as _;
+ unsafe { Self::from_ns_window(nswindow) }
+ }
+
+ /// Re-class a live NSWindow into a `RawNSPanel` and take a retained handle
+ /// to it. See [`RawNSPanel::from_window`] for the ownership contract.
+ ///
+ /// # Safety
+ /// `nswindow` must point to a live NSWindow, and this must run on the main
+ /// thread (AppKit requires it for the class swap and view mutations).
+ pub unsafe fn from_ns_window(nswindow: id) -> Id<Self> {
+ let already_panel = Self::is_raw_panel(nswindow);
+ if !already_panel {
+ Self::with_content_subviews_detached(nswindow, || {
+ let nspanel_class: id = msg_send![Self::class(), class];
+ object_setClass(nswindow, nspanel_class);
+ });
+ }
+
+ // `from_ptr` retains: the plugin's handle is a real +1, not a claim on
+ // the retain tao already holds (which is what `from_retained_ptr` did,
+ // and what made every extra `to_panel()` an over-release).
+ let panel = Id::from_ptr(nswindow as *mut RawNSPanel);
+
+ if !already_panel {
+ // Add a tracking area to the panel's content view,
+ // so that we can receive mouse events such as mouseEntered and mouseExited
+ panel.add_tracking_area();
+
+ // Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
+ panel.auto_resize();
+ }
+
+ panel
+ }
+}
+
+unsafe impl Message for RawNSPanel {}