├── .envrc ├── .npmrc ├── libs ├── share-picker │ ├── .bacon-locations │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ └── share.rs │ │ └── lib.rs │ ├── Cargo.toml │ └── README.md ├── color │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ └── color.rs │ │ └── lib.rs │ └── Cargo.toml ├── toast │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ └── toast.rs │ │ └── lib.rs │ ├── Cargo.toml │ └── README.md ├── popover │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ └── popover.rs │ │ └── lib.rs │ ├── Cargo.toml │ └── README.md ├── app-icon │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ ├── tests.rs │ │ │ └── request.rs │ │ ├── lib.rs │ │ └── windows │ │ │ ├── tests.rs │ │ │ └── mod.rs │ ├── Cargo.toml │ └── README.md ├── border │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ ├── tag.rs │ │ │ └── border.rs │ │ └── lib.rs │ ├── Cargo.toml │ └── README.md ├── example │ ├── src │ │ └── lib.rs │ └── Cargo.toml ├── menubar │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ ├── tests.rs │ │ │ └── menubar.rs │ │ └── lib.rs │ ├── Cargo.toml │ └── README.md ├── system-notification │ ├── src │ │ ├── macos │ │ │ ├── mod.rs │ │ │ └── app_handle.rs │ │ └── lib.rs │ ├── Cargo.toml │ └── README.md └── monitor │ ├── src │ ├── macos │ │ ├── mod.rs │ │ ├── tests.rs │ │ ├── utils.rs │ │ └── monitor.rs │ └── lib.rs │ ├── Cargo.toml │ └── README.md ├── assets ├── toast.gif ├── share-picker.gif ├── border-demo-01.png ├── border-demo-02.png └── border-demo-03.png ├── .gitignore ├── shared ├── tsconfig.json ├── template │ └── lib.md └── rollup.config.mjs ├── renovate.json ├── biome.json ├── tsconfig.base.json ├── package.json ├── LICENSE_MIT ├── README.md ├── flake.nix ├── flake.lock ├── Cargo.toml ├── bacon.toml ├── pnpm-lock.yaml └── LICENSE_APACHE-2.0 /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | auto-install-peers=true 2 | -------------------------------------------------------------------------------- /libs/share-picker/.bacon-locations: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /libs/color/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod color; 2 | -------------------------------------------------------------------------------- /libs/toast/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod toast; 2 | -------------------------------------------------------------------------------- /libs/popover/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod popover; 2 | -------------------------------------------------------------------------------- /libs/share-picker/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod share; 2 | -------------------------------------------------------------------------------- /libs/app-icon/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod request; 2 | mod tests; 3 | -------------------------------------------------------------------------------- /libs/border/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod border; 2 | pub mod tag; 3 | -------------------------------------------------------------------------------- /libs/example/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn foo() { 2 | todo!() 3 | } 4 | -------------------------------------------------------------------------------- /libs/menubar/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod menubar; 2 | mod tests; 3 | -------------------------------------------------------------------------------- /libs/system-notification/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod app_handle; 2 | -------------------------------------------------------------------------------- /libs/monitor/src/macos/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod monitor; 2 | mod tests; 3 | mod utils; 4 | -------------------------------------------------------------------------------- /assets/toast.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahkohd/tauri-toolkit/HEAD/assets/toast.gif -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | node_modules 3 | dist 4 | dist-js 5 | .direnv 6 | .bacon-locations 7 | -------------------------------------------------------------------------------- /assets/share-picker.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahkohd/tauri-toolkit/HEAD/assets/share-picker.gif -------------------------------------------------------------------------------- /assets/border-demo-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahkohd/tauri-toolkit/HEAD/assets/border-demo-01.png -------------------------------------------------------------------------------- /assets/border-demo-02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahkohd/tauri-toolkit/HEAD/assets/border-demo-02.png -------------------------------------------------------------------------------- /assets/border-demo-03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahkohd/tauri-toolkit/HEAD/assets/border-demo-03.png -------------------------------------------------------------------------------- /shared/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.base.json", 3 | "include": ["guest-js/*.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /libs/toast/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | pub mod macos; 3 | 4 | #[cfg(target_os = "macos")] 5 | pub use macos::toast::*; 6 | -------------------------------------------------------------------------------- /libs/share-picker/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | mod macos; 3 | 4 | #[cfg(target_os = "macos")] 5 | pub use macos::share::*; 6 | -------------------------------------------------------------------------------- /libs/color/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | pub mod macos; 3 | 4 | #[cfg(target_os = "macos")] 5 | pub use macos::color::ColorExt; 6 | -------------------------------------------------------------------------------- /libs/system-notification/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | mod macos; 3 | 4 | #[cfg(target_os = "macos")] 5 | pub use macos::app_handle::WorkspaceListener; 6 | -------------------------------------------------------------------------------- /libs/menubar/src/macos/tests.rs: -------------------------------------------------------------------------------- 1 | #![cfg(test)] 2 | 3 | #[test] 4 | fn it_gets_the_menubar_height() { 5 | let menubar_height = super::menubar::get_height(); 6 | 7 | assert!(menubar_height >= 22.0); 8 | } 9 | -------------------------------------------------------------------------------- /libs/example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "example" 3 | version = "0.1.0" 4 | description = "An example library" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | -------------------------------------------------------------------------------- /libs/border/src/macos/tag.rs: -------------------------------------------------------------------------------- 1 | use std::collections::hash_map::DefaultHasher; 2 | use std::hash::{Hash, Hasher}; 3 | 4 | use cocoa::foundation::NSInteger; 5 | 6 | pub fn from_str(s: &str) -> NSInteger { 7 | let mut hasher = DefaultHasher::new(); 8 | 9 | s.hash(&mut hasher); 10 | 11 | let hash = hasher.finish(); 12 | 13 | hash as NSInteger 14 | } 15 | -------------------------------------------------------------------------------- /libs/menubar/src/macos/menubar.rs: -------------------------------------------------------------------------------- 1 | use cocoa::{appkit::CGFloat, base::id}; 2 | use objc::{class, msg_send, sel, sel_impl}; 3 | 4 | pub fn get_height() -> CGFloat { 5 | let status_bar: id = unsafe { msg_send![class!(NSStatusBar), systemStatusBar] }; 6 | 7 | let menubar_height: CGFloat = unsafe { msg_send![status_bar, thickness] }; 8 | 9 | menubar_height 10 | } 11 | -------------------------------------------------------------------------------- /libs/color/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "color" 3 | version = "0.1.0" 4 | description = "color utils" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [target."cfg(target_os = \"macos\")".dependencies] 13 | tauri.workspace = true 14 | cocoa.workspace = true 15 | objc.workspace = true 16 | 17 | [features] 18 | cargo-clippy = [] 19 | -------------------------------------------------------------------------------- /libs/monitor/src/macos/tests.rs: -------------------------------------------------------------------------------- 1 | #![cfg(test)] 2 | 3 | use crate::get_monitor_with_cursor; 4 | 5 | use super::monitor::get_monitors; 6 | 7 | #[test] 8 | fn it_gets_monitor_with_cursor() { 9 | let monitor = get_monitor_with_cursor(); 10 | 11 | assert!(monitor.is_some()); 12 | 13 | let monitor = monitor.unwrap(); 14 | 15 | assert!(monitor.id() > 0); 16 | } 17 | 18 | #[test] 19 | fn it_gets_all_monitors() { 20 | let monitors = get_monitors(); 21 | 22 | assert!(!monitors.is_empty()); 23 | } 24 | -------------------------------------------------------------------------------- /libs/monitor/src/macos/utils.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{c_char, CStr}; 2 | 3 | use cocoa::base::id; 4 | use objc::{msg_send, sel, sel_impl}; 5 | 6 | pub fn nsstring_to_string(ns_string: id) -> Option { 7 | let utf8: id = unsafe { msg_send![ns_string, UTF8String] }; 8 | 9 | if !utf8.is_null() { 10 | Some(unsafe { 11 | { 12 | CStr::from_ptr(utf8 as *const c_char) 13 | .to_string_lossy() 14 | .into_owned() 15 | } 16 | }) 17 | } else { 18 | None 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["config:base"], 3 | "enabledManagers": ["cargo", "npm"], 4 | "semanticCommitType": "chore", 5 | "ignorePaths": [ 6 | "**/node_modules/**", 7 | "**/bower_components/**", 8 | "**/vendor/**", 9 | "**/__tests__/**", 10 | "**/test/**", 11 | "**/tests/**", 12 | "**/__fixtures__/**" 13 | ], 14 | "packageRules": [ 15 | { 16 | "description": "Disable node/pnpm version updates", 17 | "matchPackageNames": ["node", "pnpm"], 18 | "matchDepTypes": ["engines", "packageManager"], 19 | "enabled": false 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://biomejs.dev/schemas/1.3.3/schema.json", 3 | "organizeImports": { 4 | "enabled": true 5 | }, 6 | "linter": { 7 | "enabled": true, 8 | "rules": { 9 | "recommended": true 10 | } 11 | }, 12 | "formatter": { 13 | "enabled": true, 14 | "formatWithErrors": false, 15 | "indentStyle": "tab", 16 | "indentWidth": 2, 17 | "lineWidth": 80 18 | }, 19 | "files": { 20 | "ignoreUnknown": true, 21 | "ignore": [ 22 | "target", 23 | "node_modules", 24 | "dist", 25 | "dist-js", 26 | "pnpm-lock.yaml", 27 | "Cargo.lock" 28 | ] 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "esModuleInterop": true, 5 | "lib": ["ES2019", "ES2020.Promise", "ES2020.String", "DOM", "DOM.Iterable"], 6 | "module": "ESNext", 7 | "moduleResolution": "node", 8 | "noEmit": true, 9 | "noEmitOnError": false, 10 | "noUnusedLocals": true, 11 | "noUnusedParameters": true, 12 | "pretty": true, 13 | "sourceMap": true, 14 | "strict": true, 15 | "target": "ES2019", 16 | "declaration": true, 17 | "declarationDir": "./" 18 | }, 19 | "exclude": ["dist-js", "node_modules", "test/types"] 20 | } 21 | -------------------------------------------------------------------------------- /libs/share-picker/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "share-picker" 3 | version = "0.1.0" 4 | description = "A library to show the Share picker" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | 13 | [dependencies] 14 | tauri.workspace = true 15 | 16 | [target."cfg(target_os = \"macos\")".dependencies] 17 | objc2.workspace = true 18 | objc2-app-kit.workspace = true 19 | objc2-foundation.workspace = true 20 | 21 | [features] 22 | cargo-clippy = [] 23 | -------------------------------------------------------------------------------- /libs/system-notification/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "system-notification" 3 | version = "0.1.0" 4 | description = "Listen to System or Workspace notification" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | tauri.workspace = true 14 | 15 | [target."cfg(target_os = \"macos\")".dependencies] 16 | cocoa.workspace = true 17 | objc.workspace = true 18 | block.workspace = true 19 | 20 | [features] 21 | cargo-clippy = [] 22 | -------------------------------------------------------------------------------- /libs/menubar/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "menubar" 3 | version = "0.1.0" 4 | description = "A library to get information about menubar" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | thiserror.workspace = true 14 | 15 | [target."cfg(target_os = \"macos\")".dependencies] 16 | tauri.workspace = true 17 | serde.workspace = true 18 | cocoa.workspace = true 19 | objc.workspace = true 20 | 21 | [features] 22 | cargo-clippy = [] 23 | -------------------------------------------------------------------------------- /libs/border/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "border" 3 | version = "0.1.0" 4 | description = "A library to add border around your window" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [target."cfg(target_os = \"macos\")".dependencies] 13 | tauri.workspace = true 14 | cocoa.workspace = true 15 | objc.workspace = true 16 | objc-foundation.workspace = true 17 | objc_id.workspace = true 18 | color.workspace = true 19 | 20 | [features] 21 | cargo-clippy = [] 22 | -------------------------------------------------------------------------------- /libs/monitor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "monitor" 3 | version = "0.1.0" 4 | description = "A library to get information about monitors" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | thiserror.workspace = true 14 | 15 | [target."cfg(target_os = \"macos\")".dependencies] 16 | tauri.workspace = true 17 | serde.workspace = true 18 | cocoa.workspace = true 19 | objc.workspace = true 20 | core-foundation.workspace = true 21 | core-graphics.workspace = true 22 | 23 | 24 | [features] 25 | cargo-clippy = [] 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tauri-toolkit", 3 | "private": true, 4 | "license": "MIT or APACHE-2.0", 5 | "type": "module", 6 | "scripts": { 7 | "build": "pnpm run -r --parallel --filter !plugins-workspace --filter !\"./plugins/*/examples/**\" build", 8 | "lint": "biome check .", 9 | "format": "biome format --write .", 10 | "format-check": "biome format ." 11 | }, 12 | "devDependencies": { 13 | "@biomejs/biome": "^1.9.3", 14 | "@rollup/plugin-node-resolve": "^16.0.0", 15 | "@rollup/plugin-typescript": "^12.1.0" 16 | }, 17 | "engines": { 18 | "pnpm": ">=7.33.1" 19 | }, 20 | "pnpm": { 21 | "auditConfig": { 22 | "ignoreCves": [ 23 | "CVE-2023-46115" 24 | ] 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /libs/app-icon/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "app-icon" 3 | version = "0.1.0" 4 | description = "A library to retrieve an app's icon" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | thiserror.workspace = true 14 | 15 | [target."cfg(target_os = \"macos\")".dependencies] 16 | cocoa.workspace = true 17 | objc.workspace = true 18 | core-foundation.workspace = true 19 | 20 | [target."cfg(target_os = \"windows\")".dependencies] 21 | windows-sys.workspace = true 22 | image.workspace = true 23 | 24 | [features] 25 | cargo-clippy = [] 26 | -------------------------------------------------------------------------------- /libs/toast/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "toast" 3 | version = "0.1.0" 4 | description = "A library to show toast" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [target."cfg(target_os = \"macos\")".dependencies] 13 | tauri.workspace = true 14 | objc2.workspace = true 15 | objc2-app-kit.workspace = true 16 | objc2-foundation.workspace = true 17 | objc2-quartz-core.workspace = true 18 | block2.workspace = true 19 | monitor.workspace = true 20 | markdown.workspace = true 21 | 22 | cocoa.workspace = true 23 | objc.workspace = true 24 | 25 | [features] 26 | cargo-clippy = [] 27 | -------------------------------------------------------------------------------- /libs/popover/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "popover" 3 | version = "0.1.0" 4 | description = "A popover view to WebviewWindow" 5 | authors.workspace = true 6 | license.workspace = true 7 | edition.workspace = true 8 | rust-version.workspace = true 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | thiserror.workspace = true 14 | 15 | [target."cfg(target_os = \"macos\")".dependencies] 16 | tauri.workspace = true 17 | serde.workspace = true 18 | cocoa.workspace = true 19 | objc.workspace = true 20 | objc_id.workspace = true 21 | core-foundation.workspace = true 22 | core-graphics.workspace = true 23 | objc-foundation.workspace = true 24 | objc2-foundation.workspace = true 25 | objc2-app-kit.workspace = true 26 | 27 | [features] 28 | cargo-clippy = [] 29 | -------------------------------------------------------------------------------- /libs/menubar/src/lib.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[cfg(target_os = "macos")] 4 | mod macos; 5 | 6 | #[derive(Default, Serialize, Deserialize, Debug, Clone)] 7 | pub struct Menubar { 8 | height: f64, 9 | } 10 | 11 | impl Menubar { 12 | pub fn height(&self) -> f64 { 13 | #[cfg(target_os = "windows")] 14 | { 15 | unimplemented!() 16 | } 17 | 18 | #[cfg(target_os = "linux")] 19 | { 20 | unimplemented!() 21 | } 22 | 23 | #[cfg(target_os = "macos")] 24 | macos::menubar::get_height() 25 | } 26 | } 27 | 28 | /// Get info about the system-wide Menubar 29 | pub fn get_menubar() -> Menubar { 30 | #[cfg(target_os = "windows")] 31 | { 32 | unimplemented!() 33 | } 34 | 35 | #[cfg(target_os = "linux")] 36 | { 37 | unimplemented!() 38 | } 39 | 40 | #[cfg(target_os = "macos")] 41 | { 42 | Menubar::default() 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /shared/template/lib.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | ## Usage 20 | 21 | 22 | ## Contributing 23 | 24 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 25 | 26 | ## License 27 | MIT or MIT/Apache 2.0 where applicable 28 | -------------------------------------------------------------------------------- /LICENSE_MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 - Victor Aremu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /libs/app-icon/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use thiserror::Error; 3 | 4 | #[cfg(target_os = "macos")] 5 | mod macos; 6 | 7 | #[cfg(target_os = "windows")] 8 | mod windows; 9 | 10 | #[derive(Error, Debug)] 11 | #[error("get app icon error")] 12 | pub struct GetAppIconError { 13 | #[cfg(target_os = "macos")] 14 | #[from] 15 | source: macos::request::GetIconError, 16 | #[cfg(target_os = "windows")] 17 | #[from] 18 | source: windows::GetIconError, 19 | } 20 | 21 | #[cfg(target_os = "windows")] 22 | pub fn get_icon(app_path: &Path, save_path: &Path, size: f64) -> Result<(), GetAppIconError> { 23 | windows::get_icon(app_path, save_path, size)?; 24 | Ok(()) 25 | } 26 | 27 | #[cfg(target_os = "linux")] 28 | pub fn get_icon(app_path: &Path, save_path: &Path, size: f64) -> Result<(), GetAppIconError> { 29 | unimplemented!(); 30 | } 31 | 32 | /// Get app icon from app bundle. You specify the path to save the icon, and the desired icon size (like 16, 32, 48, 128, 256, 512) 33 | /// Saves the icon in PNG format. 34 | #[cfg(target_os = "macos")] 35 | pub fn get_icon(app_path: &Path, save_path: &Path, size: f64) -> Result<(), GetAppIconError> { 36 | macos::request::get_icon(app_path, save_path, size)?; 37 | Ok(()) 38 | } 39 | -------------------------------------------------------------------------------- /libs/app-icon/src/macos/tests.rs: -------------------------------------------------------------------------------- 1 | #![cfg(test)] 2 | use super::request::{get_icon, GetIconError}; 3 | use std::path::Path; 4 | 5 | #[test] 6 | fn app_path_does_not_exist() { 7 | let app_path = Path::new("/foo/bar"); 8 | let save_path = Path::new("/tmp"); 9 | assert_eq!( 10 | get_icon(app_path, save_path, 32.0).unwrap_err(), 11 | GetIconError::AppPathDoesNotExist 12 | ); 13 | } 14 | 15 | #[test] 16 | fn app_path_without_app_extension() { 17 | let app_path = Path::new("/System/Applications"); 18 | let save_path = Path::new("/tmp"); 19 | assert_eq!( 20 | get_icon(app_path, save_path, 32.0).unwrap_err(), 21 | GetIconError::AppPathDoesNotEndWithApp 22 | ); 23 | } 24 | 25 | #[test] 26 | fn save_path_parent_does_not_exist() { 27 | let app_path = Path::new("/System/Applications/Notes.app"); 28 | let save_path = Path::new("/foo/Notes.png"); 29 | assert_eq!( 30 | get_icon(app_path, save_path, 32.0).unwrap_err(), 31 | GetIconError::SavePathParentDirDoesNotExist 32 | ); 33 | } 34 | 35 | #[test] 36 | fn it_works() { 37 | let app_path = Path::new("/System/Applications/Notes.app"); 38 | let save_path = Path::new("/tmp/Notes.png"); 39 | assert!(get_icon(app_path, save_path, 32.0).is_ok()); 40 | } 41 | -------------------------------------------------------------------------------- /libs/app-icon/README.md: -------------------------------------------------------------------------------- 1 | A library to get the app icon from an app bundle. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | app-icon = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | ## Usage 20 | ```rust 21 | use app_icon::GetAppIconError; 22 | 23 | fn main() -> Result<(), GetAppIconError> { 24 | let app_path = Path::new("/System/Applications/Notes.app"); 25 | let save_path = Path::new("/tmp/Notes.png"); 26 | app_icon::get_icon(app_path, save_path, 32.0)?; 27 | Ok(()) 28 | } 29 | ``` 30 | 31 | ## Contributing 32 | 33 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 34 | 35 | ## License 36 | MIT or MIT/Apache 2.0 where applicable 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Libraries Found Here 2 | 3 | | | | Win | Mac | Lin | iOS | And | 4 | | ------------------------------------------ | --------------------------------------------------------- | --- | --- | --- | --- | --- | 5 | | [app-icon](libs/app-icon) | Get the app icon from an app bundle. | ✅ | ✅ | ? | ? | ? | 6 | | [monitor](libs/monitor) | Get information about monitors. | ? | ✅ | ? | ? | ? | 7 | | [menubar](libs/menubar) | Get information about menubar. | ? | ✅ | ? | ? | ? | 8 | | [popover](libs/popover) | Add popover view to `WebviewWindow`. | ? | ✅ | ? | ? | ? | 9 | | [border](libs/border) | Add border to `WebviewWindow`. | ? | ✅ | ? | ? | ? | 10 | | [system-notification](libs/system-notification) | Listen to System or Workspace notification. | ? | ✅ | ? | ? | ? | 11 | | [share-picker](libs/share-picker) | Show a share picker. | ? | ✅ | ? | ? | ? | 12 | | [toast](libs/toast) | Show a toast. | ? | ✅ | ? | ? | ? | 13 | 14 | 15 | _This repo and all plugins require a Rust version of at least __1.64___ 16 | -------------------------------------------------------------------------------- /shared/rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import { builtinModules } from "module"; 2 | 3 | import resolve from "@rollup/plugin-node-resolve"; 4 | import typescript from "@rollup/plugin-typescript"; 5 | 6 | /** 7 | * Create a base rollup config 8 | * @param {Record} pkg Imported package.json 9 | * @param {string[]} external Imported package.json 10 | * @returns {import('rollup').RollupOptions} 11 | */ 12 | export function createConfig({ input = "index.ts", pkg, external = [] }) { 13 | return [ 14 | { 15 | input, 16 | external: Object.keys(pkg.dependencies || {}) 17 | .concat(Object.keys(pkg.peerDependencies || {})) 18 | .concat(builtinModules) 19 | .concat(external), 20 | onwarn: (warning) => { 21 | throw Object.assign(new Error(), warning); 22 | }, 23 | strictDeprecations: true, 24 | output: { 25 | file: pkg.module, 26 | format: "es", 27 | sourcemap: true, 28 | }, 29 | plugins: [typescript({ sourceMap: true })], 30 | }, 31 | { 32 | input, 33 | onwarn: (warning) => { 34 | throw Object.assign(new Error(), warning); 35 | }, 36 | strictDeprecations: true, 37 | output: { 38 | file: pkg.browser, 39 | format: "es", 40 | sourcemap: true, 41 | entryFileNames: "[name].min.js", 42 | }, 43 | plugins: [resolve(), typescript({ sourceMap: true })], 44 | }, 45 | ]; 46 | } 47 | -------------------------------------------------------------------------------- /libs/app-icon/src/windows/tests.rs: -------------------------------------------------------------------------------- 1 | #![cfg(test)] 2 | use std::path::Path; 3 | 4 | use super::{get_icon, GetIconError}; 5 | 6 | #[test] 7 | fn app_path_does_not_exist() { 8 | let app_path = Path::new(r"C:\foo\bar"); 9 | let save_path = Path::new(r"C:\foo\temp"); 10 | assert_eq!( 11 | get_icon(app_path, save_path, 32.0).unwrap_err(), 12 | GetIconError::AppPathDoesNotExist 13 | ); 14 | } 15 | 16 | #[test] 17 | fn save_path_parent_does_not_exist() { 18 | let app_path = Path::new(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"); 19 | let save_path = Path::new(r"Windows\Temp\edge.png"); 20 | assert_eq!( 21 | get_icon(app_path, save_path, 32.0).unwrap_err(), 22 | GetIconError::SavePathParentDirDoesNotExist 23 | ); 24 | } 25 | 26 | #[test] 27 | fn image_save_failure() { 28 | let app_path = Path::new(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"); 29 | // eleveted access required to write to this folder 30 | let save_path = Path::new(r"C:\Windows\System32\forbidden_icon.png"); 31 | let result = get_icon(app_path, save_path, 32.0); 32 | assert!(result.is_err()); 33 | assert_eq!(result.unwrap_err(), GetIconError::ImageSaveError); 34 | } 35 | 36 | #[test] 37 | fn it_works() { 38 | let app_path = Path::new(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"); 39 | let save_path = Path::new(r"C:\Windows\Temp\edge.png"); 40 | assert!(get_icon(app_path, save_path, 32.0).is_ok()); 41 | } 42 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | inputs = { 3 | nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable-small"; 4 | rust-overlay.url = "github:oxalica/rust-overlay"; 5 | }; 6 | 7 | outputs = { self, nixpkgs, rust-overlay }: 8 | let 9 | overlays = [ rust-overlay.overlays.default ]; 10 | 11 | pkgs = import nixpkgs { 12 | system = "aarch64-darwin"; 13 | inherit overlays; 14 | }; 15 | pkgsX86 = import nixpkgs { 16 | system = "x86_64-darwin"; 17 | inherit overlays; 18 | }; 19 | 20 | rustToolchainExtensions = [ "rust-src" "rust-analyzer" "clippy" ]; 21 | rustToolchain = pkgs.rust-bin.stable.latest.default.override { 22 | targets = [ "aarch64-apple-darwin" ]; 23 | extensions = rustToolchainExtensions; 24 | }; 25 | rustToolchainX86 = pkgsX86.rust-bin.stable.latest.default.override { 26 | targets = [ "x86_64-apple-darwin" ]; 27 | extensions = rustToolchainExtensions; 28 | }; 29 | 30 | commonPackages = p: with p; [ bacon ]; 31 | 32 | in { 33 | devShells = { 34 | aarch64-darwin.default = pkgs.mkShellNoCC { 35 | packages = [ rustToolchain ] ++ (commonPackages pkgs); 36 | shellHook = '' 37 | echo "=== 🛠️ DEV SHELL (APPLE SILICON) ===" 38 | ''; 39 | }; 40 | x86_64-darwin.default = pkgsX86.mkShellNoCC { 41 | packages = [ rustToolchainX86 ] ++ (commonPackages pkgsX86); 42 | shellHook = '' 43 | echo "=== 🛠️ DEV SHELL (APPLE ROSETTA) ===" 44 | ''; 45 | }; 46 | }; 47 | }; 48 | } 49 | -------------------------------------------------------------------------------- /libs/color/src/macos/color.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Div; 2 | 3 | use cocoa::{ 4 | appkit::{CGFloat, NSColor}, 5 | base::{id, nil}, 6 | }; 7 | use objc::{class, msg_send, sel, sel_impl}; 8 | use tauri::window::Color; 9 | 10 | pub trait ColorExt { 11 | fn to_nscolor(&self) -> id; 12 | 13 | fn normalize(x: impl Into) -> T 14 | where 15 | T: From + Div + From; 16 | 17 | #[allow(clippy::missing_safety_doc)] 18 | unsafe fn from_nscolor(color: id) -> Color; 19 | } 20 | 21 | impl ColorExt for Color { 22 | fn normalize(x: impl Into) -> T 23 | where 24 | T: From + Div + From, 25 | { 26 | let clamped = x.into().min(255) as u8; 27 | T::from(clamped) / T::from(255u8) 28 | } 29 | 30 | fn to_nscolor(&self) -> id { 31 | unsafe { 32 | NSColor::colorWithSRGBRed_green_blue_alpha_( 33 | nil, 34 | Color::normalize::(self.0), 35 | Color::normalize::(self.1), 36 | Color::normalize::(self.2), 37 | Color::normalize::(self.3), 38 | ) 39 | } 40 | } 41 | 42 | unsafe fn from_nscolor(color: id) -> Self { 43 | let color_space: id = unsafe { msg_send![class!(NSColorSpace), sRGBColorSpace] }; 44 | 45 | let color: id = color.colorUsingColorSpace_(color_space); 46 | 47 | unsafe { 48 | Self( 49 | (color.redComponent() * 255.0) as u8, 50 | (color.greenComponent() * 255.0) as u8, 51 | (color.blueComponent() * 255.0) as u8, 52 | (color.alphaComponent() * 255.0) as u8, 53 | ) 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "nixpkgs": { 4 | "locked": { 5 | "lastModified": 1742700815, 6 | "narHash": "sha256-tNc+2n53oQMgvx7w/NuxoJwOE4hhrZMqhToQsu0tsy4=", 7 | "owner": "nixos", 8 | "repo": "nixpkgs", 9 | "rev": "a90d8216fdce578320153f91d399fa517e3ba782", 10 | "type": "github" 11 | }, 12 | "original": { 13 | "owner": "nixos", 14 | "ref": "nixos-unstable-small", 15 | "repo": "nixpkgs", 16 | "type": "github" 17 | } 18 | }, 19 | "nixpkgs_2": { 20 | "locked": { 21 | "lastModified": 1736320768, 22 | "narHash": "sha256-nIYdTAiKIGnFNugbomgBJR+Xv5F1ZQU+HfaBqJKroC0=", 23 | "owner": "NixOS", 24 | "repo": "nixpkgs", 25 | "rev": "4bc9c909d9ac828a039f288cf872d16d38185db8", 26 | "type": "github" 27 | }, 28 | "original": { 29 | "owner": "NixOS", 30 | "ref": "nixpkgs-unstable", 31 | "repo": "nixpkgs", 32 | "type": "github" 33 | } 34 | }, 35 | "root": { 36 | "inputs": { 37 | "nixpkgs": "nixpkgs", 38 | "rust-overlay": "rust-overlay" 39 | } 40 | }, 41 | "rust-overlay": { 42 | "inputs": { 43 | "nixpkgs": "nixpkgs_2" 44 | }, 45 | "locked": { 46 | "lastModified": 1742697269, 47 | "narHash": "sha256-Lpp0XyAtIl1oGJzNmTiTGLhTkcUjwSkEb0gOiNzYFGM=", 48 | "owner": "oxalica", 49 | "repo": "rust-overlay", 50 | "rev": "01973c84732f9275c50c5f075dd1f54cc04b3316", 51 | "type": "github" 52 | }, 53 | "original": { 54 | "owner": "oxalica", 55 | "repo": "rust-overlay", 56 | "type": "github" 57 | } 58 | } 59 | }, 60 | "root": "root", 61 | "version": 7 62 | } 63 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["libs/*"] 3 | resolver = "2" 4 | 5 | [workspace.dependencies] 6 | serde = { version = "1.0.200", features = ["derive"] } 7 | tauri = "2.0.0-beta.22" 8 | tauri-build = "2.0.0-beta.17" 9 | serde_json = "1" 10 | thiserror = "2.0.3" 11 | 12 | cocoa = "0.26.0" 13 | objc = "0.2.7" 14 | core-foundation = "0.10.0" 15 | core-graphics = "0.24.0" 16 | objc_id = "0.1.1" 17 | objc-foundation = "0.1.1" 18 | objc2-core-foundation = "0.3.0" 19 | objc2-quartz-core = { version = "0.3.0", features = ["CALayer"] } 20 | objc2 = "0.6.0" 21 | objc2-foundation = { version = "0.3.0", features = [ 22 | "NSGeometry", 23 | "NSString", 24 | "NSTimer", 25 | "NSThread", 26 | ] } 27 | objc2-app-kit = { version = "0.3.0", features = [ 28 | "block2", 29 | "objc2-quartz-core", 30 | "objc2-core-foundation", 31 | "NSBezierPath", 32 | "NSSharingService", 33 | "NSResponder", 34 | "NSWindow", 35 | "NSPanel", 36 | "NSView", 37 | "NSText", 38 | "NSTextField", 39 | "NSControl", 40 | "NSParagraphStyle", 41 | "NSVisualEffectView", 42 | "NSGraphics", 43 | "NSAnimation", 44 | "NSAnimationContext", 45 | "NSColor", 46 | "NSMenuItem", 47 | ] } 48 | 49 | block = "0.1.6" 50 | block2 = "0.6.0" 51 | 52 | windows-sys = { version = "0.59.0", features = [ 53 | "Win32_UI", 54 | "Win32_UI_Shell", 55 | "Win32_UI_WindowsAndMessaging", 56 | "Win32_Graphics", 57 | "Win32_Foundation", 58 | "Win32_Graphics_Gdi", 59 | "Win32_UI_HiDpi", 60 | "Win32_System", 61 | "Win32_System_Com", 62 | "Win32_System_Com_StructuredStorage", 63 | ] } 64 | 65 | image = "0.25.1" 66 | markdown = "1.0.0" 67 | 68 | color = { path = "libs/color" } 69 | monitor = { path = "libs/monitor" } 70 | 71 | [workspace.package] 72 | edition = "2021" 73 | authors = ["Victor Aremu "] 74 | license = "Apache-2.0 OR MIT" 75 | rust-version = "1.64" 76 | -------------------------------------------------------------------------------- /libs/menubar/README.md: -------------------------------------------------------------------------------- 1 | A library to get information about menubar. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | menubar = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | 20 | ## Usage 21 | ```rust 22 | use menubar::get_menubar; 23 | 24 | fn main() { 25 | let menubar = get_menubar(); 26 | } 27 | ``` 28 | 29 | ## Functions 30 | 31 | - `get_menubar() -> Menubar`: 32 | Get info about the system-wide Menubar. 33 | 34 | 35 | ### Menubar 36 | The struct Menubar provides properties are defined as follows: 37 | ```rust 38 | #[derive(Serialize, Deserialize, Debug, Clone)] 39 | pub struct Menubar { 40 | height: f64, 41 | } 42 | ``` 43 | It includes the following fields: 44 | - `height`: the height of the menubar 45 | 46 | #### Menubar Methods 47 | 48 | `Menubar` struct provides the following methods to fetch its attributes: 49 | 50 | - `height(&self) -> f64`: This method returns the height. 51 | 52 | To use any of these methods, you need to have an instance of a `Menubar`. 53 | 54 | For example: 55 | ```rust 56 | let menubar_height = menubar.height(); 57 | ``` 58 | 59 | ## Contributing 60 | 61 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 62 | 63 | ## License 64 | MIT or MIT/Apache 2.0 where applicable 65 | -------------------------------------------------------------------------------- /libs/border/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | use cocoa::foundation::NSRect; 3 | 4 | #[cfg(target_os = "macos")] 5 | use cocoa::{ 6 | base::id, 7 | foundation::{NSPoint, NSSize}, 8 | }; 9 | 10 | #[cfg(target_os = "macos")] 11 | use macos::border::{BorderView, BorderViewConfig}; 12 | 13 | #[cfg(target_os = "macos")] 14 | use objc::{msg_send, sel, sel_impl}; 15 | 16 | #[cfg(target_os = "macos")] 17 | use objc_id::ShareId; 18 | use tauri::{Runtime, WebviewWindow}; 19 | 20 | #[cfg(target_os = "macos")] 21 | pub mod macos; 22 | 23 | #[cfg(target_os = "macos")] 24 | pub type BorderConfig = macos::border::BorderViewConfig; 25 | 26 | #[cfg(target_os = "macos")] 27 | pub trait WebviewWindowExt { 28 | fn add_border(&self, config: Option); 29 | 30 | fn border(&self) -> Option>; 31 | } 32 | 33 | #[cfg(target_os = "macos")] 34 | impl WebviewWindowExt for WebviewWindow { 35 | fn add_border(&self, config: Option) { 36 | let handle: id = self.ns_window().unwrap() as _; 37 | 38 | let content_frame: NSRect = unsafe { msg_send![handle, frame] }; 39 | 40 | let content_view: id = unsafe { msg_send![handle, contentView] }; 41 | 42 | let view = self 43 | .border() 44 | .unwrap_or(BorderView::new(config, self.label().to_string())); 45 | 46 | let frame = NSRect::new( 47 | NSPoint::new(0.0, 0.0), 48 | NSSize::new(content_frame.size.width, content_frame.size.height), 49 | ); 50 | 51 | view.set_frame(frame); 52 | 53 | view.set_parent(content_view); 54 | 55 | view.set_auto_resizing(); 56 | } 57 | 58 | fn border(&self) -> Option> { 59 | let handle: id = self.ns_window().unwrap() as _; 60 | 61 | let content_view: id = unsafe { msg_send![handle, contentView] }; 62 | 63 | BorderView::find_with_tag(content_view, self.label().to_string()) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /libs/popover/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | pub mod macos; 3 | 4 | #[cfg(target_os = "macos")] 5 | use crate::macos::popover::PopoverConfig; 6 | 7 | #[cfg(target_os = "windows")] 8 | pub fn add_view(window: &tauri::WebviewWindow) { 9 | unimplemented!(); 10 | } 11 | 12 | #[cfg(target_os = "linux")] 13 | pub fn add_view(window: &tauri::WebviewWindow) { 14 | unimplemented!(); 15 | } 16 | 17 | #[cfg(target_os = "macos")] 18 | pub fn add_view(window: &tauri::WebviewWindow, options: Option) { 19 | use cocoa::{ 20 | base::id, 21 | foundation::{NSInteger, NSPoint, NSRect, NSSize}, 22 | }; 23 | use objc::{msg_send, sel, sel_impl}; 24 | use tauri::Manager; 25 | 26 | use crate::macos::popover::PopoverView; 27 | 28 | #[allow(non_upper_case_globals)] 29 | const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4; 30 | 31 | let win = window.clone(); 32 | 33 | window 34 | .app_handle() 35 | .run_on_main_thread(move || { 36 | let handle: id = win.ns_window().unwrap() as _; 37 | 38 | let content_frame: NSRect = unsafe { msg_send![handle, frame] }; 39 | 40 | let content_view: id = unsafe { msg_send![handle, contentView] }; 41 | 42 | let mut config = options.unwrap_or_default(); 43 | 44 | if options.is_none() { 45 | config.arrow_position = content_frame.size.width / 2.0; 46 | } 47 | 48 | let view = PopoverView::new(config); 49 | 50 | let _frame = NSRect::new( 51 | NSPoint::new(0.0, 0.0), 52 | NSSize::new(content_frame.size.width, content_frame.size.height), 53 | ); 54 | 55 | view.set_frame(_frame); 56 | 57 | view.set_parent(content_view); 58 | 59 | view.set_autoresizing(); 60 | 61 | let () = unsafe { 62 | msg_send![handle, setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow] 63 | }; 64 | }) 65 | .unwrap(); 66 | } 67 | -------------------------------------------------------------------------------- /libs/share-picker/README.md: -------------------------------------------------------------------------------- 1 | Show the Share picker over a `WebviewWindow`. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | share-picker = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | 20 | ### Demo 21 | ![A demo of the share picker](https://github.com/ahkohd/tauri-toolkit/blob/v2/assets/share-picker.gif) 22 | 23 | ## Usage 24 | ```rust 25 | use share_picker::{SharePicker, PreferredEdge}; 26 | use tauri::PhysicalPosition; 27 | 28 | fn main() { 29 | let window = app_handle.get_webview_window("window_name"); 30 | 31 | let item = Path::from("/foo/bar.pdf"); 32 | 33 | window.share(vec![item.to_path_buf()], PhysicalPosition { 34 | x: 0.0, 35 | y: 0.0 36 | }, PreferredEdge::BottomLeft); 37 | } 38 | ``` 39 | 40 | ## Functions 41 | 42 | - `share(window: &tauri::WebviewWindow, items: Vec, position: PhysicalPosition, preferred_edge: PreferredEdge)`: 43 | Displays the Share picker at the cursor position within a WebviewWindow. 44 | - `items: Vec`: A list of paths to items to share. 45 | - `position: PhysicalPosition`: Set the position to display the share picker. The origin is the top left corner of the window. 46 | - `preferred_edge: PreferredEdge`: The preferred edge for displaying the share picker at the cursor position's rectangle. 47 | 48 | 49 | ## PreferredEdge Enum 50 | - `TopLeft`: Place at the top left edge. 51 | - `TopRight`: Place at the top right edge. 52 | - `BottomLeft`: Place at the bottom left edge. 53 | - `BottomRight`: Place at the bottom right edge. 54 | 55 | ## Contributing 56 | 57 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 58 | 59 | ## License 60 | MIT or MIT/Apache 2.0 where applicable 61 | -------------------------------------------------------------------------------- /libs/system-notification/README.md: -------------------------------------------------------------------------------- 1 | Listen to System or Workspace notification. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | system-notification = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | 20 | ### Usage 21 | 22 | ```rust 23 | use system_notification::WorkspaceListener; 24 | 25 | fn main() { 26 | // ... 27 | 28 | // listen to a workspace notification 29 | app_handle.listen_workspace("NSWorkspaceDidActivateApplicationNotification", |app_handle| { 30 | // An app was activated, do something here... 31 | }); 32 | 33 | // listen to a notification sent by the system to the application 34 | app_handle.listen_notification("NSSystemColorsDidChangeNotification", |app_handle| { 35 | // System colors have changed, do something here... 36 | }); 37 | 38 | // ... 39 | } 40 | ``` 41 | 42 | ## Functions 43 | The `WorkspaceListener` trait from the `system-notification` crate when in scope adds the following methods to the `AppHandle`. 44 | 45 | - `listen_workspace(&str, notification_name: &str, callback: fn(AppHandle))`: 46 | Listen to a workspace notification. 47 | 48 | - `listen_notification(&str, notification_name: &str, callback: fn(AppHandle))`: 49 | Listen to a system notification sent to the application's default notification center. 50 | 51 | **Prameters:** 52 | - `notification_name` _&str_ The notification name. See https://developer.apple.com/documentation/foundation/nsnotificationname for an exhaustive list of notification names. 53 | - `callback` _fn(AppHandle)_ A callback function. 54 | 55 | ## Contributing 56 | 57 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 58 | 59 | ## License 60 | MIT or MIT/Apache 2.0 where applicable 61 | -------------------------------------------------------------------------------- /libs/monitor/src/lib.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use tauri::{PhysicalPosition, PhysicalSize}; 3 | 4 | #[cfg(target_os = "macos")] 5 | mod macos; 6 | 7 | #[derive(Serialize, Deserialize, Debug, Clone)] 8 | pub struct VisibleArea { 9 | size: PhysicalSize, 10 | position: PhysicalPosition, 11 | } 12 | 13 | impl VisibleArea { 14 | pub fn size(&self) -> PhysicalSize { 15 | self.size 16 | } 17 | 18 | pub fn position(&self) -> PhysicalPosition { 19 | self.position 20 | } 21 | } 22 | 23 | #[derive(Serialize, Deserialize, Debug, Clone)] 24 | pub struct Monitor { 25 | id: u32, 26 | uuid: Option, 27 | name: Option, 28 | size: PhysicalSize, 29 | position: PhysicalPosition, 30 | scale_factor: f64, 31 | has_cursor: bool, 32 | is_primary: bool, 33 | visible_area: VisibleArea, 34 | } 35 | 36 | impl Monitor { 37 | pub fn id(&self) -> u32 { 38 | self.id 39 | } 40 | 41 | pub fn uuid(&self) -> Option<&String> { 42 | self.uuid.as_ref() 43 | } 44 | 45 | pub fn name(&self) -> Option<&String> { 46 | self.name.as_ref() 47 | } 48 | 49 | pub fn size(&self) -> PhysicalSize { 50 | self.size 51 | } 52 | 53 | pub fn visible_area(&self) -> VisibleArea { 54 | self.visible_area.clone() 55 | } 56 | 57 | pub fn position(&self) -> PhysicalPosition { 58 | self.position 59 | } 60 | 61 | pub fn scale_factor(&self) -> f64 { 62 | self.scale_factor 63 | } 64 | 65 | pub fn has_cursor(&self) -> bool { 66 | self.has_cursor 67 | } 68 | 69 | pub fn is_primary(&self) -> bool { 70 | self.is_primary 71 | } 72 | } 73 | 74 | pub fn get_monitor_with_cursor() -> Option { 75 | #[cfg(target_os = "windows")] 76 | { 77 | unimplemented!() 78 | } 79 | 80 | #[cfg(target_os = "linux")] 81 | { 82 | unimplemented!() 83 | } 84 | 85 | #[cfg(target_os = "macos")] 86 | { 87 | macos::monitor::get_monitor_with_cursor() 88 | } 89 | } 90 | 91 | pub fn get_monitors() -> Vec { 92 | #[cfg(target_os = "windows")] 93 | { 94 | unimplemented!() 95 | } 96 | 97 | #[cfg(target_os = "linux")] 98 | { 99 | unimplemented!() 100 | } 101 | 102 | #[cfg(target_os = "macos")] 103 | { 104 | macos::monitor::get_monitors() 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /libs/toast/README.md: -------------------------------------------------------------------------------- 1 | Show a toast. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | toast = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | 20 | ### Demo 21 | ![A demo of toast](https://github.com/ahkohd/tauri-toolkit/blob/v2/assets/toast.gif) 22 | 23 | ## Usage 24 | ```rust 25 | use toast::{Toast, ToastExt}; 26 | 27 | fn main() { 28 | // setup the toast with default configuration 29 | app_handle.manage(Toast::default()); 30 | 31 | // show a toast 32 | // `message` can be formatted in markdown 33 | app_handle.toast("Hello, **World!** 🎉", None); 34 | } 35 | ``` 36 | 37 | ## Functions 38 | 39 | - `app_handle.toast(message: &str, options: Option)`: 40 | Shows a toast 41 | - `message: &str`: The toast message. It supports markdown. 42 | - `options: Option`: Options for the toast. 43 | 44 | ## ToastConfig 45 | Configure the toast 46 | - `font_size: f64`: The font size of the toast text label 47 | - `padding: (f64, f64)`: The padding of the toast 48 | - `position: ToastPosition`: Where to place the toast 49 | - `offset: f64`: Offset the toast position 50 | - `duration: f64`: The duration of the toast 51 | - `fade_duration: f64`: The duration of the enter and exit fade animation 52 | - `shadow: bool`: The toast panel has shadow 53 | 54 | ## ToastPosition 55 | - `Top`: The toast will be position at the top center of the monitor with cursor 56 | - `Bottom`: The toast will be position at the bottom center of the monitor with cursor 57 | - `At(x, y)`: Position the toast at a specific point. The origin is located at the top left corner 58 | 59 | To configure your toast, use `Toast::new(...)` instead of `Toast::default()`. For example: 60 | ```rust 61 | use toast::{Toast, ToastConfig, ToastPosition}; 62 | 63 | app_handle.manage(Toast::new(ToastConfig { 64 | position: ToastPosition::Top, 65 | offset: 20.0, 66 | ..Default::default() 67 | })); 68 | ``` 69 | 70 | ## Contributing 71 | 72 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 73 | 74 | ## License 75 | MIT or MIT/Apache 2.0 where applicable 76 | -------------------------------------------------------------------------------- /libs/system-notification/src/macos/app_handle.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CString; 2 | 3 | use block::ConcreteBlock; 4 | use cocoa::base::{id, nil}; 5 | use objc::{class, msg_send, sel, sel_impl}; 6 | use tauri::{AppHandle, Runtime}; 7 | 8 | pub trait WorkspaceListener { 9 | fn register_application_notification_listener(name: &str, callback: Box); 10 | 11 | fn register_workspace_notification_listener(name: &str, callback: Box); 12 | 13 | fn listen_notification(&self, name: &str, callback: fn(AppHandle)); 14 | 15 | fn listen_workspace(&self, name: &str, callback: fn(AppHandle)); 16 | } 17 | 18 | impl WorkspaceListener for AppHandle { 19 | fn register_application_notification_listener(name: &str, callback: Box) { 20 | let notification_center: id = 21 | unsafe { msg_send![class!(NSNotificationCenter), defaultCenter] }; 22 | 23 | let block = ConcreteBlock::new(move |_notif: id| { 24 | callback(); 25 | }); 26 | 27 | let block = block.copy(); 28 | 29 | let name: id = 30 | unsafe { msg_send![class!(NSString), stringWithCString: CString::new(name).unwrap()] }; 31 | 32 | unsafe { 33 | let _: () = msg_send![ 34 | notification_center, 35 | addObserverForName: name object: nil queue: nil usingBlock: block 36 | ]; 37 | } 38 | } 39 | 40 | fn listen_notification(&self, name: &str, callback: fn(AppHandle)) { 41 | let app_handle = self.clone(); 42 | 43 | AppHandle::::register_application_notification_listener( 44 | name, 45 | Box::new(move || callback(app_handle.clone())), 46 | ); 47 | } 48 | 49 | fn register_workspace_notification_listener(name: &str, callback: Box) { 50 | let workspace: id = unsafe { msg_send![class!(NSWorkspace), sharedWorkspace] }; 51 | 52 | let notification_center: id = unsafe { msg_send![workspace, notificationCenter] }; 53 | 54 | let block = ConcreteBlock::new(move |_notif: id| { 55 | callback(); 56 | }); 57 | 58 | let block = block.copy(); 59 | 60 | let name: id = 61 | unsafe { msg_send![class!(NSString), stringWithCString: CString::new(name).unwrap()] }; 62 | 63 | unsafe { 64 | let _: () = msg_send![ 65 | notification_center, 66 | addObserverForName: name object: nil queue: nil usingBlock: block 67 | ]; 68 | } 69 | } 70 | 71 | fn listen_workspace(&self, name: &str, callback: fn(AppHandle)) { 72 | let app_handle = self.clone(); 73 | 74 | AppHandle::::register_workspace_notification_listener( 75 | name, 76 | Box::new(move || callback(app_handle.clone())), 77 | ); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /libs/share-picker/src/macos/share.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | 3 | use objc2::{msg_send, rc::Retained, ClassType}; 4 | use objc2_app_kit::{NSSharingServicePicker, NSView, NSWindow}; 5 | use objc2_foundation::{ 6 | MainThreadMarker, NSArray, NSPoint, NSRect, NSRectEdge, NSSize, NSString, NSURL, 7 | }; 8 | use tauri::{PhysicalPosition, Runtime, WebviewWindow}; 9 | 10 | pub enum PreferredEdge { 11 | TopLeft, 12 | TopRight, 13 | BottomLeft, 14 | BottomRight, 15 | } 16 | 17 | impl PreferredEdge { 18 | fn to_ns_rect_edge(&self) -> NSRectEdge { 19 | match self { 20 | Self::TopLeft => NSRectEdge::NSMinXEdge, 21 | Self::TopRight => NSRectEdge::NSMaxXEdge, 22 | Self::BottomLeft => NSRectEdge::NSMinYEdge, 23 | Self::BottomRight => NSRectEdge::NSMaxYEdge, 24 | } 25 | } 26 | } 27 | 28 | pub trait SharePicker { 29 | fn share( 30 | &self, 31 | items: Vec, 32 | position: PhysicalPosition, 33 | preferred_edge: PreferredEdge, 34 | ); 35 | } 36 | 37 | impl SharePicker for WebviewWindow { 38 | fn share( 39 | &self, 40 | items: Vec, 41 | position: PhysicalPosition, 42 | preferred_edge: PreferredEdge, 43 | ) { 44 | let items = items 45 | .iter() 46 | .map(|url| NSString::from_str(url.to_str().unwrap())) 47 | .collect::>>(); 48 | 49 | let urls = items 50 | .iter() 51 | .map(|url| unsafe { NSURL::fileURLWithPath(url) }) 52 | .collect::>>(); 53 | 54 | let picker: Retained = unsafe { 55 | let items = NSArray::from_retained_slice(urls.as_slice()) 56 | .downcast() 57 | .unwrap(); 58 | 59 | let obj = msg_send![NSSharingServicePicker::class(), alloc]; 60 | 61 | NSSharingServicePicker::initWithItems(obj, &items) 62 | }; 63 | 64 | let window = self.ns_window().unwrap(); 65 | 66 | let window = unsafe { (window.cast() as *mut NSWindow).as_ref().unwrap() }; 67 | 68 | let content_view = window.contentView().unwrap(); 69 | 70 | let position = PhysicalPosition { 71 | x: position.x, 72 | y: window.frame().size.height - position.y, 73 | }; 74 | 75 | let point_in_window = NSPoint::new(position.x, position.y); 76 | 77 | let point_in_content_view = content_view.convertPoint_fromView(point_in_window, None); 78 | 79 | let mtm = MainThreadMarker::new().unwrap(); 80 | 81 | let view = unsafe { NSView::new(mtm) }; 82 | 83 | unsafe { 84 | view.setFrame(NSRect::new(point_in_content_view, NSSize::new(1.0, 1.0))); 85 | 86 | content_view.addSubview(&view); 87 | } 88 | 89 | unsafe { 90 | picker.standardShareMenuItem(mtm); 91 | 92 | picker.showRelativeToRect_ofView_preferredEdge( 93 | NSRect::ZERO, 94 | view.as_ref(), 95 | preferred_edge.to_ns_rect_edge(), 96 | ) 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /libs/popover/README.md: -------------------------------------------------------------------------------- 1 | A popover view to `WebviewWindow`. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | popover = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | 20 | ### Demo 21 | See an [example project](https://github.com/ahkohd/tauri-macos-menubar-app-example/tree/popover) that uses this `popover` lib. 22 | 23 | image 24 | 25 | ## Usage 26 | ```rust 27 | use popover; 28 | 29 | fn main() { 30 | let window = app_handle.get_webview_window("window_name"); 31 | 32 | popover::add_view(&window, None); 33 | } 34 | ``` 35 | 36 | ## Functions 37 | 38 | - `add_view(window: &tauri::WebviewWindow, options: PopoverConfig)`: 39 | Adds a popover view to the `WebviewWindow`. If options is `None`, the default options are used. 40 | 41 | 42 | ## PopoverConfig Struct 43 | Here is the description of the fields in this struct: 44 | 45 | - `arrow_height`: CGFloat representing the height of popover arrow. 46 | - `arrow_position`: CGFloat representing the horizontal position of arrow. 47 | - `arrow_width`: CGFloat describing the width of the arrow. 48 | - `background_color`: An instance of NSColor determining the background color of the popover. 49 | - `border_color`: NSColor instance representing the border color of the popover. 50 | - `border_width`: CGFloat representing the width of the popover's border. 51 | - `content_edge_insets`: NSEdgeInsets defining the content edge insets of the popover. This typically influences the padding around the content inside the popover. 52 | - `corner_radius`: CGFloat representing the radius of the popover's corners. 53 | - `popover_to_status_item_margin`: CGFloat indicating the margin or distance between the popover and the status item. 54 | - `right_edge_margin`: CGFloat representing the margin or spacing to the right edge of the popover. 55 | 56 | To create a new `PopoverConfig`, you can use the following example: 57 | 58 | ```rust 59 | use obj2_app_kit::{ NSEdgeInsetsZero }; 60 | 61 | use objc::{ msg_send, class, sel, sel_impl }; 62 | 63 | use cocoa::base::id; 64 | 65 | let background_color: id = unsafe { msg_send![class!(NSColor), windowBackgroundColor] }; 66 | 67 | let border_color: id = unsafe { msg_send![class!(NSColor), whiteColor] }; 68 | 69 | let config = PopoverConfig { 70 | arrow_height: 10.0, 71 | arrow_position: 100.0, 72 | arrow_width: 20.0, 73 | background_color, 74 | border_color, 75 | border_width: 2.0, 76 | content_edge_insets: unsafe { NSEdgeInsetsZero }, 77 | corner_radius: 10.0, 78 | popover_to_status_item_margin: 10.0, 79 | right_edge_margin: 12.0, 80 | }; 81 | ``` 82 | 83 | This will create a popover with specified configurations in the above example. 84 | 85 | 86 | ## Contributing 87 | 88 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 89 | 90 | ## License 91 | MIT or MIT/Apache 2.0 where applicable 92 | -------------------------------------------------------------------------------- /bacon.toml: -------------------------------------------------------------------------------- 1 | # This is a configuration file for the bacon tool 2 | # 3 | # Bacon repository: https://github.com/Canop/bacon 4 | # Complete help on configuration: https://dystroy.org/bacon/config/ 5 | # You can also check bacon's own bacon.toml file 6 | # as an example: https://github.com/Canop/bacon/blob/main/bacon.toml 7 | 8 | default_job = "clippy" 9 | 10 | [jobs.check] 11 | command = ["cargo", "check", "--color", "always"] 12 | need_stdout = false 13 | 14 | [jobs.check-all] 15 | command = ["cargo", "check", "--all-targets", "--color", "always"] 16 | need_stdout = false 17 | 18 | # Run clippy on the default target 19 | [jobs.clippy] 20 | command = ["cargo", "clippy", "--color", "always"] 21 | need_stdout = false 22 | 23 | 24 | # Run clippy on the default target for share-picker 25 | [jobs.clippy-share-menu] 26 | command = [ 27 | "cargo", 28 | "clippy", 29 | "--color", 30 | "always", 31 | "--manifest-path", 32 | "./libs/share-picker/Cargo.toml", 33 | ] 34 | need_stdout = false 35 | 36 | 37 | # Run clippy on the default target for popover 38 | [jobs.clippy-popover] 39 | command = [ 40 | "cargo", 41 | "clippy", 42 | "--color", 43 | "always", 44 | "--manifest-path", 45 | "./libs/popover/Cargo.toml", 46 | ] 47 | need_stdout = false 48 | 49 | 50 | # Run clippy on all targets 51 | # To disable some lints, you may change the job this way: 52 | # [jobs.clippy-all] 53 | # command = [ 54 | # "cargo", "clippy", 55 | # "--all-targets", 56 | # "--color", "always", 57 | # "--", 58 | # "-A", "clippy::bool_to_int_with_if", 59 | # "-A", "clippy::collapsible_if", 60 | # "-A", "clippy::derive_partial_eq_without_eq", 61 | # ] 62 | # need_stdout = false 63 | [jobs.clippy-all] 64 | command = ["cargo", "clippy", "--all-targets", "--color", "always"] 65 | need_stdout = false 66 | 67 | # This job lets you run 68 | # - all tests: bacon test 69 | # - a specific test: bacon test -- config::test_default_files 70 | # - the tests of a package: bacon test -- -- -p config 71 | [jobs.test] 72 | command = [ 73 | "cargo", 74 | "test", 75 | "--color", 76 | "always", 77 | "--", 78 | "--color", 79 | "always", # see https://github.com/Canop/bacon/issues/124 80 | ] 81 | need_stdout = true 82 | 83 | [jobs.doc] 84 | command = ["cargo", "doc", "--color", "always", "--no-deps"] 85 | need_stdout = false 86 | 87 | # If the doc compiles, then it opens in your browser and bacon switches 88 | # to the previous job 89 | [jobs.doc-open] 90 | command = ["cargo", "doc", "--color", "always", "--no-deps", "--open"] 91 | need_stdout = false 92 | on_success = "back" # so that we don't open the browser at each change 93 | 94 | # You can run your application and have the result displayed in bacon, 95 | # *if* it makes sense for this crate. 96 | # Don't forget the `--color always` part or the errors won't be 97 | # properly parsed. 98 | # If your program never stops (eg a server), you may set `background` 99 | # to false to have the cargo run output immediately displayed instead 100 | # of waiting for program's end. 101 | [jobs.run] 102 | command = [ 103 | "cargo", 104 | "run", 105 | "--color", 106 | "always", 107 | # put launch parameters for your program behind a `--` separator 108 | ] 109 | need_stdout = true 110 | allow_warnings = true 111 | background = true 112 | 113 | # This parameterized job runs the example of your choice, as soon 114 | # as the code compiles. 115 | # Call it as 116 | # bacon ex -- my-example 117 | [jobs.ex] 118 | command = ["cargo", "run", "--color", "always", "--example"] 119 | need_stdout = true 120 | allow_warnings = true 121 | 122 | # You may define here keybindings that would be specific to 123 | # a project, for example a shortcut to launch a specific job. 124 | # Shortcuts to internal functions (scrolling, toggling, etc.) 125 | # should go in your personal global prefs.toml file instead. 126 | [keybindings] 127 | # alt-m = "job:my-job" 128 | c = "job:clippy" 129 | s = "job:clippy-share-menu" 130 | p = "job:clippy-popover" 131 | 132 | esc = "back" 133 | g = "scroll-to-top" 134 | shift-g = "scroll-to-bottom" 135 | k = "scroll-lines(-1)" 136 | j = "scroll-lines(1)" 137 | ctrl-u = "scroll-page(-1)" 138 | ctrl-d = "scroll-page(1)" 139 | -------------------------------------------------------------------------------- /libs/app-icon/src/macos/request.rs: -------------------------------------------------------------------------------- 1 | use std::{ffi::CString, path::Path}; 2 | 3 | use cocoa::{ 4 | base::{id, nil, NO, YES}, 5 | foundation::{NSInteger, NSPoint, NSRect, NSSize}, 6 | }; 7 | use objc::{class, msg_send, rc::autoreleasepool, sel, sel_impl}; 8 | use thiserror::Error; 9 | 10 | #[repr(u64)] 11 | #[derive(Clone, Copy, Debug, PartialEq)] 12 | enum NSBitmapImageFileType { 13 | NSBitmapImageFileTypePNG = 4, 14 | } 15 | 16 | #[link(name = "AppKit", kind = "framework")] 17 | extern "C" { 18 | pub static NSDeviceRGBColorSpace: id; 19 | } 20 | 21 | #[derive(Error, Debug, PartialEq)] 22 | pub enum GetIconError { 23 | #[error("app path does not exist")] 24 | AppPathDoesNotExist, 25 | #[error("app path does not have '.app' extension")] 26 | AppPathDoesNotEndWithApp, 27 | #[error("save path parent directory does not exist")] 28 | SavePathParentDirDoesNotExist, 29 | #[error("failed to convert {0} to &str")] 30 | PathConversionError(&'static str), 31 | #[error("Failed to create a CString from the path")] 32 | CStringCreationError(#[from] std::ffi::NulError), 33 | } 34 | 35 | pub fn get_icon(app_path: &Path, save_path: &Path, icon_size: f64) -> Result<(), GetIconError> { 36 | if !app_path.exists() { 37 | return Err(GetIconError::AppPathDoesNotExist); 38 | } 39 | 40 | if !app_path.extension().map_or(false, |ext| ext == "app") { 41 | return Err(GetIconError::AppPathDoesNotEndWithApp); 42 | } 43 | 44 | let parent = save_path 45 | .parent() 46 | .ok_or(GetIconError::SavePathParentDirDoesNotExist)?; 47 | 48 | if !parent.exists() { 49 | return Err(GetIconError::SavePathParentDirDoesNotExist); 50 | } 51 | 52 | autoreleasepool(|| unsafe { 53 | let app_path = app_path 54 | .to_str() 55 | .ok_or(GetIconError::PathConversionError("app_path")) 56 | .map(CString::new)? 57 | .map_err(GetIconError::CStringCreationError)?; 58 | let save_path = save_path 59 | .to_str() 60 | .ok_or(GetIconError::PathConversionError("save_path")) 61 | .map(CString::new)? 62 | .map_err(GetIconError::CStringCreationError)?; 63 | let nsstring_app_path: id = msg_send![class!(NSString), stringWithCString: app_path]; 64 | let nsstring_save_path: id = msg_send![class!(NSString), stringWithCString: save_path]; 65 | 66 | let nsworkspace: id = msg_send![class!(NSWorkspace), sharedWorkspace]; 67 | let nsimage: id = msg_send![nsworkspace, iconForFile: nsstring_app_path]; 68 | let () = msg_send![nsimage, setSize: NSSize::new(icon_size, icon_size)]; 69 | 70 | let bits_per_sample: NSInteger = 8; 71 | let samples_per_pixel: NSInteger = 4; 72 | let zero: NSInteger = 0; 73 | 74 | let bitmap_ref: id = msg_send![class!(NSBitmapImageRep), alloc]; 75 | let image_rep: id = msg_send![bitmap_ref, initWithBitmapDataPlanes:nil pixelsWide:icon_size as NSInteger pixelsHigh:icon_size as NSInteger bitsPerSample:bits_per_sample samplesPerPixel:samples_per_pixel hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:zero bitsPerPixel:zero]; 76 | let () = msg_send![image_rep, setSize: NSSize::new(icon_size, icon_size)]; 77 | 78 | let () = msg_send![class!(NSGraphicsContext), saveGraphicsState]; 79 | let context: id = msg_send![ 80 | class!(NSGraphicsContext), 81 | graphicsContextWithBitmapImageRep: image_rep 82 | ]; 83 | let () = msg_send![class!(NSGraphicsContext), setCurrentContext: context]; 84 | let () = msg_send![nsimage, drawInRect: NSRect { 85 | origin: NSPoint { 86 | x: 0.0, 87 | y: 0.0, 88 | }, 89 | size: NSSize { 90 | width: icon_size, 91 | height: icon_size, 92 | }, 93 | } fromRect:NSRect { 94 | origin: NSPoint { 95 | x: 0.0, 96 | y: 0.0, 97 | }, 98 | size: NSSize { 99 | width: 0.0, 100 | height: 0.0, 101 | }, 102 | } operation:cocoa::appkit::NSCompositingOperation::NSCompositeCopy fraction:1.0]; 103 | 104 | let () = msg_send![class!(NSGraphicsContext), restoreGraphicsState]; 105 | let png_data: id = msg_send![image_rep, representationUsingType:NSBitmapImageFileType::NSBitmapImageFileTypePNG properties:nil]; 106 | let () = msg_send![png_data, writeToFile:nsstring_save_path atomically:YES]; 107 | let () = msg_send![image_rep, autorelease]; 108 | 109 | Ok(()) 110 | }) 111 | } 112 | -------------------------------------------------------------------------------- /libs/border/README.md: -------------------------------------------------------------------------------- 1 | Add border around `WebviewWindow`. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | border = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | ### Demo 20 | 21 | > By default add a standard looking macOS border: 22 | 23 | ![Border view demo](../../assets/border-demo-01.png) 24 | 25 | > Customise the color, thickness and corner radius: 26 | 27 | ![Border view demo](../../assets/border-demo-02.png) 28 | 29 | > You can inset if need be: 30 | 31 | ![Border view demo](../../assets/border-demo-03.png) 32 | 33 | > See an example project of a window with a border [here](https://github.com/ahkohd/tauri-macos-window-border-example) 34 | 35 | ## Usage 36 | A basic usage: 37 | ```rust 38 | use border::WebviewWindowExt as BorderWebviewWindowExt; 39 | 40 | fn main() { 41 | let window = app_handle.get_webview_window("window_name"); 42 | 43 | // Add border around the WebviewWindow. 44 | // You can pass your Some(BorderConfig), otherwise leave as None 45 | // to use default options. 46 | 47 | window.add_border(None); 48 | 49 | // Get access to the border 50 | // Useful if you want to update the border appearance dynamically 51 | 52 | let border = window.border().expect("Have you added a border?!"); 53 | 54 | // For example, update the border color 55 | 56 | use tauri::window::Color; 57 | 58 | border.set_line_color(Color(255, 0, 0, 255)); 59 | 60 | // Want to remove the border? 61 | 62 | border.remove(); 63 | } 64 | ``` 65 | 66 | With your config: 67 | 68 | ```rust 69 | use tauri::window::Color; 70 | use border::{BorderConfig, WebviewWindowExt as BorderWebviewWindowExt}; 71 | 72 | fn main() { 73 | let window = app_handle.get_webview_window("window_name"); 74 | 75 | window.add_border(Some(BorderConfig { 76 | line_width: 1.0, 77 | line_color: Color(255, 0, 0, 255), 78 | inset: 0.5, 79 | corner_radius: 10.0, 80 | })); 81 | } 82 | ``` 83 | 84 | ## BorderConfig Struct 85 | Here is the description of the fields in this struct: 86 | 87 | - `line_width`: _CGFloat_ representing the thickness of the border. 88 | - `line_color`: _Color_ representing the color of the border. 89 | - `inset`: _CGFloat_ defining the inset between the border and the window frame. 90 | - `corner_radius`: _CGFloat_ defining the corner radius of the border. 91 | 92 | ## Functions 93 | The `WebviewWindowExt` trait from the `border` crate when in scope adds the following methods to the `WebviewWindow`. 94 | 95 | - `add_border(&self, config: Option)`: 96 | Adds a border view around the `WebviewWindow`. If options is `None`, the default options are used. 97 | - `border(&self) -> Option>`: 98 | Get the border view added around the `WebviewWindow`. 99 | 100 | ## BorderView 101 | The view that adds border around the `WebviewWindow`. 102 | 103 | ### Functions 104 | - `set_line_color(&self, color: Color)`: 105 | Update the border's line color. 106 | - `set_line_width(&self, width: CGFloat)`: 107 | Update the border line width. 108 | - `set_inset(&self, inset: CGFloat)`: 109 | Update the inset. 110 | - `set_corner_radius(&self, inset: CGFloat)`: 111 | Update the corner radius of the border. 112 | - `set_accepts_first_mouse(&self, value: bool)`: 113 | Sets whether the border view should accept the first mouse click. 114 | - `remove(&self)`: 115 | Remove the border view from the parent view. 116 | 117 | You probably will not need to use the following methods, _they are used internally to setup the border view_: 118 | - `set_frame(&self, frame: NSRect)`: 119 | Update the frame of the border. 120 | - `set_parent(&self, ns_view: id)`: 121 | Update the parent of the border view. 122 | - `set_auto_resizing(&self)`: 123 | Make the border view auto-resize along with the window's frame. 124 | _For convince, by default this is already called during the setup of the border view when you use the `window.add_border` API._ 125 | 126 | 127 | ## Contributing 128 | 129 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 130 | 131 | ## License 132 | MIT or MIT/Apache 2.0 where applicable 133 | 134 | -------------------------------------------------------------------------------- /libs/monitor/README.md: -------------------------------------------------------------------------------- 1 | A library to get information about monitors. 2 | 3 | ### Install 4 | _This lib requires a Rust version of at least **1.64**_ 5 | 6 | There are three general methods of installation that we can recommend. 7 | 8 | 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked) 9 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 10 | 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) 11 | 12 | Install the Core plugin by adding the following to your `Cargo.toml` file: 13 | 14 | `src-tauri/Cargo.toml` 15 | ```toml 16 | [dependencies] 17 | monitor = { git = "https://github.com/ahkohd/tauri-toolkit", branch = "v2" } 18 | ``` 19 | 20 | ## Usage 21 | ```rust 22 | use monitor::{get_monitors, get_monitor_with_cursor}; 23 | 24 | fn main() { 25 | let monitors = get_monitors(); 26 | 27 | let monitor_with_cursor = get_monitor_with_cursor(); 28 | } 29 | ``` 30 | 31 | ## Functions 32 | 33 | - `get_monitor_with_cursor() -> Option`: 34 | Returns the monitor which currently hosts the system pointer, if any. 35 | 36 | - `get_monitors() -> Vec`: 37 | Returns a vector of all connected monitors. 38 | 39 | ### Monitor 40 | The struct Monitor provides properties of a single display monitor, defined as follows: 41 | ```rust 42 | #[derive(Serialize, Deserialize, Debug, Clone)] 43 | pub struct Monitor { 44 | id: u32, 45 | uuid: Option, 46 | name: Option, 47 | size: PhysicalSize, 48 | position: PhysicalPosition, 49 | scale_factor: f64, 50 | has_cursor: bool, 51 | is_primary: bool, 52 | visible_area: VisibleArea, 53 | } 54 | ``` 55 | It includes the following fields: 56 | - `id`: a unique identifier for the monitor 57 | - `uuid`: the UUID of the monitor, if any 58 | - `name`: the name of the monitor, if available 59 | - `size`: the size of the monitor, specified as a PhysicalSize struct 60 | - `position`: the position of the monitor, specified as a PhysicalPosition struct 61 | - `scale_factor`: the scaling factor of the monitor's resolution 62 | - `has_cursor`: a Boolean flag indicating if the monitor currently has a cursor 63 | - `is_primary`: a Boolean flag indicating if the monitor is the primary monitor 64 | - `visible_area`: the visible area of the monitor 65 | 66 | #### Monitor Methods 67 | 68 | `Monitor` struct provides the following methods to fetch its attributes: 69 | 70 | - `id(&self) -> u32`: This method returns the identifier of the monitor which is of type `u32`. 71 | 72 | - `uuid(&self) -> Option<&String>`: This method returns an `Option` containing a reference to the UUID of the monitor, if it is assigned one. 73 | 74 | - `name(&self) -> Option<&String>`: This method returns an `Option` containing a reference to the name of the monitor, if it is assigned one. 75 | 76 | - `size(&self) -> PhysicalSize`: This method returns the size of the monitor as an instance of `PhysicalSize`. 77 | 78 | - `visible_area(&self) -> VisibleArea`: This method returns the visible area of the monitor as a `VisibleArea` struct. 79 | 80 | - `position(&self) -> PhysicalPosition`: This method returns the position of the monitor as an instance of `PhysicalPosition`. 81 | 82 | - `scale_factor(&self) -> f64`: This method returns the scale factor of the monitor. 83 | 84 | - `has_cursor(&self) -> bool`: This method returns a boolean value indicating whether the monitor currently has a cursor. 85 | 86 | - `is_primary(&self) -> bool`: This method returns a boolean value indicating whether or not the monitor is the primary monitor. 87 | 88 | To use any of these methods, you need to have an instance of a `Monitor`. 89 | 90 | For example: 91 | ```rust 92 | let monitor_id = monitor.id(); 93 | let monitor_uuid = monitor.uuid(); 94 | ``` 95 | 96 | ### VisibleArea 97 | 98 | This visible area is represented by the struct `VisibleArea` defined as follows: 99 | 100 | ```rust 101 | #[derive(Serialize, Deserialize, Debug, Clone)] 102 | pub struct VisibleArea { 103 | size: PhysicalSize, 104 | position: PhysicalPosition, 105 | } 106 | ``` 107 | It includes fields: 108 | - `size`: the size of the visible area specified as a PhysicalSize struct containing width and height as f64. 109 | - `position`: the position of the visible area on screen specified as a PhysicalPosition struct containing x and y as f64. 110 | 111 | #### VisibleArea Methods 112 | 113 | `VisibleArea` struct provides the following methods: 114 | 115 | - `size(&self) -> PhysicalSize`: This method returns the size of the visible area as an instance of `PhysicalSize`. 116 | 117 | - `position(&self) -> PhysicalPosition`: This method returns the position of the visible area on the screen as an instance of `PhysicalPosition`. 118 | 119 | Each of these methods allow you to access specific attributes of the `VisibleArea`. 120 | 121 | For example: 122 | ```rust 123 | let visible_area_size = visible_area.size(); 124 | let visible_area_position = visible_area.position(); 125 | ``` 126 | 127 | These methods are particularly useful when you need to query or manipulate the visible area of a screen. Just instantiate a `VisibleArea` and call the appropriate methods. 128 | 129 | ## Contributing 130 | 131 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 132 | 133 | ## License 134 | MIT or MIT/Apache 2.0 where applicable 135 | -------------------------------------------------------------------------------- /libs/app-icon/src/windows/mod.rs: -------------------------------------------------------------------------------- 1 | use std::num::TryFromIntError; 2 | use std::os::windows::ffi::OsStrExt; 3 | use std::path::Path; 4 | use std::{ 5 | mem::{self, MaybeUninit}, 6 | ptr::addr_of_mut, 7 | }; 8 | 9 | use image::RgbaImage; 10 | use thiserror::Error; 11 | use windows_sys::Win32::Graphics::Gdi::{ 12 | DeleteObject, GetDC, GetDIBits, GetObjectW, ReleaseDC, BITMAP, BITMAPINFOHEADER, BI_RGB, 13 | DIB_RGB_COLORS, 14 | }; 15 | use windows_sys::Win32::System::Com::CoUninitialize; 16 | use windows_sys::Win32::UI::Shell::ExtractIconExW; 17 | use windows_sys::Win32::UI::WindowsAndMessaging::{DestroyIcon, GetIconInfo, HICON}; 18 | 19 | mod tests; 20 | 21 | #[derive(Error, Debug, PartialEq)] 22 | pub enum GetIconError { 23 | #[error("app path does not exist")] 24 | AppPathDoesNotExist, 25 | #[error("save path parent directory does not exist")] 26 | SavePathParentDirDoesNotExist, 27 | #[error("failed to extract icon")] 28 | IconExtractionError, 29 | #[error("failed to get icon info")] 30 | IconInfoError, 31 | #[error("failed to convert icon info")] 32 | IconInfoConversionError, 33 | #[error("failed to save image")] 34 | ImageSaveError, 35 | #[error("Failed to convert one of the bitmap data to valid integer: {0}")] 36 | BitmapConversionError(#[from] TryFromIntError), 37 | } 38 | 39 | unsafe fn icon_to_image(icon: HICON) -> Result { 40 | let mut icon_info = MaybeUninit::uninit(); 41 | if GetIconInfo(icon, icon_info.as_mut_ptr()) == 0 { 42 | return Err(GetIconError::IconInfoError); 43 | } 44 | let icon_info = icon_info.assume_init(); 45 | 46 | DeleteObject(icon_info.hbmMask); 47 | 48 | // rough way to get bitmap structure for icon 49 | let bitmap_size_i32 = i32::try_from(mem::size_of::())?; 50 | let mut bitmap: MaybeUninit = MaybeUninit::uninit(); 51 | let result = GetObjectW( 52 | icon_info.hbmColor, 53 | bitmap_size_i32, 54 | bitmap.as_mut_ptr().cast(), 55 | ); 56 | if result == 0 { 57 | DeleteObject(icon_info.hbmColor); 58 | return Err(GetIconError::IconInfoConversionError); 59 | } 60 | let bitmap = bitmap.assume_init(); 61 | 62 | let width_u32 = u32::try_from(bitmap.bmWidth)?; 63 | let height_u32 = u32::try_from(bitmap.bmHeight)?; 64 | let width_usize = usize::try_from(bitmap.bmWidth)?; 65 | let height_usize = usize::try_from(bitmap.bmHeight)?; 66 | let buf_size = width_usize 67 | .checked_mul(height_usize) 68 | .and_then(|size| size.checked_mul(4)) 69 | .ok_or(GetIconError::IconInfoConversionError)?; 70 | let mut buf: Vec = Vec::with_capacity(buf_size); 71 | 72 | // device context 73 | let dc = GetDC(0); 74 | if dc == 0 { 75 | DeleteObject(icon_info.hbmColor); 76 | return Err(GetIconError::IconInfoError); 77 | } 78 | 79 | let biheader_size_u32 = u32::try_from(mem::size_of::())?; 80 | let mut bitmap_info = BITMAPINFOHEADER { 81 | biSize: biheader_size_u32, 82 | biWidth: bitmap.bmWidth, 83 | // i'm using negative sign here to indicate that DIB should from top to bottom (i.e top down) 84 | biHeight: -bitmap.bmHeight, 85 | biPlanes: 1, 86 | biBitCount: 32, 87 | biCompression: BI_RGB, 88 | biSizeImage: 0, 89 | biXPelsPerMeter: 0, 90 | biYPelsPerMeter: 0, 91 | biClrUsed: 0, 92 | biClrImportant: 0, 93 | }; 94 | 95 | let result = GetDIBits( 96 | dc, 97 | icon_info.hbmColor, 98 | 0, 99 | height_u32, 100 | buf.as_mut_ptr().cast(), 101 | addr_of_mut!(bitmap_info).cast(), 102 | DIB_RGB_COLORS, 103 | ); 104 | if result == 0 { 105 | DeleteObject(icon_info.hbmColor); 106 | ReleaseDC(0, dc); 107 | return Err(GetIconError::IconInfoConversionError); 108 | } 109 | buf.set_len(buf.capacity()); 110 | 111 | ReleaseDC(0, dc); 112 | DeleteObject(icon_info.hbmColor); 113 | 114 | // swap the red and blue channels 115 | for chunk in buf.chunks_exact_mut(4) { 116 | let [b, _, r, _] = chunk else { unreachable!() }; 117 | mem::swap(b, r); 118 | } 119 | 120 | RgbaImage::from_vec(width_u32, height_u32, buf).ok_or(GetIconError::ImageSaveError) 121 | } 122 | 123 | pub fn get_icon(app_path: &Path, save_path: &Path, _icon_size: f64) -> Result<(), GetIconError> { 124 | if !app_path.exists() { 125 | return Err(GetIconError::AppPathDoesNotExist); 126 | } 127 | 128 | let parent = save_path 129 | .parent() 130 | .ok_or(GetIconError::SavePathParentDirDoesNotExist)?; 131 | 132 | if !parent.exists() { 133 | return Err(GetIconError::SavePathParentDirDoesNotExist); 134 | } 135 | 136 | let path: Vec = app_path.as_os_str().encode_wide().chain(Some(0)).collect(); 137 | 138 | let mut large_icon: isize = 0; 139 | let mut small_icon: isize = 0; 140 | 141 | unsafe { 142 | let count = ExtractIconExW(path.as_ptr(), 0, &mut large_icon, &mut small_icon, 1); 143 | if count == 0 { 144 | CoUninitialize(); 145 | return Err(GetIconError::IconExtractionError); 146 | } 147 | 148 | let image = icon_to_image(large_icon).map_err(|e| { 149 | DestroyIcon(large_icon); 150 | CoUninitialize(); 151 | e 152 | })?; 153 | 154 | DestroyIcon(large_icon); 155 | image 156 | .save(save_path) 157 | .map_err(|_| GetIconError::ImageSaveError)?; 158 | CoUninitialize(); 159 | } 160 | 161 | Ok(()) 162 | } 163 | -------------------------------------------------------------------------------- /libs/monitor/src/macos/monitor.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CString; 2 | 3 | use cocoa::{ 4 | appkit::CGFloat, 5 | base::{id, nil}, 6 | foundation::{NSPoint, NSRect}, 7 | }; 8 | use core_foundation::{ 9 | base::{kCFAllocatorDefault, CFRelease}, 10 | mach_port::CFAllocatorRef, 11 | string::CFStringRef, 12 | uuid::CFUUIDRef, 13 | }; 14 | use core_graphics::display::{CGDirectDisplayID, CGMainDisplayID}; 15 | use objc::{ 16 | class, msg_send, 17 | runtime::{BOOL, NO, YES}, 18 | sel, sel_impl, 19 | }; 20 | use tauri::{PhysicalPosition, PhysicalSize}; 21 | 22 | use crate::{Monitor, VisibleArea}; 23 | 24 | use super::utils::nsstring_to_string; 25 | 26 | #[link(name = "Foundation", kind = "framework")] 27 | extern "C" { 28 | pub fn NSMouseInRect(aPoint: NSPoint, aRect: NSRect, flipped: BOOL) -> BOOL; 29 | } 30 | 31 | #[link(name = "ApplicationServices", kind = "framework")] 32 | extern "C" { 33 | fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef; 34 | 35 | fn CFUUIDCreateString(allocator: CFAllocatorRef, uuid: CFUUIDRef) -> CFStringRef; 36 | } 37 | 38 | pub fn get_monitor_with_cursor() -> Option { 39 | objc::rc::autoreleasepool(|| { 40 | let main_display_id: CGDirectDisplayID = unsafe { CGMainDisplayID() }; 41 | 42 | let mouse_location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] }; 43 | 44 | let screens: id = unsafe { msg_send![class!(NSScreen), screens] }; 45 | 46 | let screens_iter: id = unsafe { msg_send![screens, objectEnumerator] }; 47 | 48 | let mut next_screen: id; 49 | 50 | let frames: Option<(NSRect, NSRect)> = loop { 51 | next_screen = unsafe { msg_send![screens_iter, nextObject] }; 52 | 53 | if next_screen == nil { 54 | break None; 55 | } 56 | 57 | let frame: NSRect = unsafe { msg_send![next_screen, frame] }; 58 | 59 | let visible_frame: NSRect = unsafe { msg_send![next_screen, visibleFrame] }; 60 | 61 | let is_mouse_in_screen_frame: BOOL = 62 | unsafe { NSMouseInRect(mouse_location, frame, NO) }; 63 | 64 | if is_mouse_in_screen_frame == YES { 65 | break Some((frame, visible_frame)); 66 | } 67 | }; 68 | 69 | if let Some((frame, visible_frame)) = frames { 70 | let screen_name = nsstring_to_string(unsafe { msg_send![next_screen, localizedName] }); 71 | 72 | let scale_factor: CGFloat = unsafe { msg_send![next_screen, backingScaleFactor] }; 73 | 74 | let scale_factor: f64 = scale_factor; 75 | 76 | let device_description_dict: id = unsafe { msg_send![next_screen, deviceDescription] }; 77 | 78 | let nsscreen_number: id = unsafe { 79 | msg_send![class!(NSString), stringWithCString: CString::new("NSScreenNumber").unwrap()] 80 | }; 81 | 82 | let monitor_id: id = 83 | unsafe { msg_send![device_description_dict, objectForKey: nsscreen_number] }; 84 | 85 | let monitor_id: CGDirectDisplayID = unsafe { msg_send![monitor_id, unsignedIntValue] }; 86 | 87 | let uuid: Option = { 88 | let uuid_ref: CFUUIDRef = unsafe { CGDisplayCreateUUIDFromDisplayID(monitor_id) }; 89 | 90 | if uuid_ref.is_null() { 91 | None 92 | } else { 93 | let uuid_string_ref: CFStringRef = 94 | unsafe { CFUUIDCreateString(kCFAllocatorDefault, uuid_ref) }; 95 | 96 | let uuid = nsstring_to_string(uuid_string_ref as _); 97 | 98 | unsafe { 99 | CFRelease(uuid_string_ref.cast()); 100 | 101 | CFRelease(uuid_ref.cast()) 102 | }; 103 | 104 | uuid 105 | } 106 | }; 107 | 108 | return Some(Monitor { 109 | id: monitor_id, 110 | uuid, 111 | name: screen_name, 112 | position: PhysicalPosition { 113 | x: frame.origin.x * scale_factor, 114 | y: frame.origin.y * scale_factor, 115 | }, 116 | size: PhysicalSize { 117 | width: frame.size.width * scale_factor, 118 | height: frame.size.height * scale_factor, 119 | }, 120 | visible_area: VisibleArea { 121 | size: PhysicalSize { 122 | width: visible_frame.size.width * scale_factor, 123 | height: visible_frame.size.height * scale_factor, 124 | }, 125 | position: PhysicalPosition { 126 | x: visible_frame.origin.x * scale_factor, 127 | y: visible_frame.origin.y * scale_factor, 128 | }, 129 | }, 130 | scale_factor, 131 | has_cursor: true, 132 | is_primary: monitor_id == main_display_id, 133 | }); 134 | } 135 | 136 | None 137 | }) 138 | } 139 | 140 | pub fn get_monitors() -> Vec { 141 | objc::rc::autoreleasepool(|| { 142 | let main_display_id: CGDirectDisplayID = unsafe { CGMainDisplayID() }; 143 | 144 | let mouse_location: NSPoint = unsafe { msg_send![class!(NSEvent), mouseLocation] }; 145 | 146 | let screens: id = unsafe { msg_send![class!(NSScreen), screens] }; 147 | 148 | let screens_iter: id = unsafe { msg_send![screens, objectEnumerator] }; 149 | 150 | let mut next_screen: id; 151 | 152 | let mut monitors = vec![]; 153 | 154 | loop { 155 | next_screen = unsafe { msg_send![screens_iter, nextObject] }; 156 | 157 | if next_screen == nil { 158 | break; 159 | } 160 | 161 | let frame: NSRect = unsafe { msg_send![next_screen, frame] }; 162 | 163 | let visible_frame: NSRect = unsafe { msg_send![next_screen, visibleFrame] }; 164 | 165 | let is_mouse_in_screen_frame: BOOL = 166 | unsafe { NSMouseInRect(mouse_location, frame, NO) }; 167 | 168 | let screen_name = nsstring_to_string(unsafe { msg_send![next_screen, localizedName] }); 169 | 170 | let scale_factor: CGFloat = unsafe { msg_send![next_screen, backingScaleFactor] }; 171 | 172 | let scale_factor: f64 = scale_factor; 173 | 174 | let device_description_dict: id = unsafe { msg_send![next_screen, deviceDescription] }; 175 | 176 | let nsscreen_number: id = unsafe { 177 | msg_send![class!(NSString), stringWithCString: CString::new("NSScreenNumber").unwrap()] 178 | }; 179 | 180 | let monitor_id: id = 181 | unsafe { msg_send![device_description_dict, objectForKey: nsscreen_number] }; 182 | 183 | let monitor_id: CGDirectDisplayID = unsafe { msg_send![monitor_id, unsignedIntValue] }; 184 | 185 | let uuid: Option = { 186 | let uuid_ref: CFUUIDRef = unsafe { CGDisplayCreateUUIDFromDisplayID(monitor_id) }; 187 | 188 | if uuid_ref.is_null() { 189 | None 190 | } else { 191 | let uuid_string_ref: CFStringRef = 192 | unsafe { CFUUIDCreateString(kCFAllocatorDefault, uuid_ref) }; 193 | 194 | let uuid = nsstring_to_string(uuid_string_ref as _); 195 | 196 | unsafe { 197 | CFRelease(uuid_string_ref.cast()); 198 | 199 | CFRelease(uuid_ref.cast()) 200 | }; 201 | 202 | uuid 203 | } 204 | }; 205 | 206 | monitors.push(Monitor { 207 | id: monitor_id, 208 | uuid, 209 | name: screen_name, 210 | position: PhysicalPosition { 211 | x: frame.origin.x * scale_factor, 212 | y: frame.origin.y * scale_factor, 213 | }, 214 | size: PhysicalSize { 215 | width: frame.size.width * scale_factor, 216 | height: frame.size.height * scale_factor, 217 | }, 218 | visible_area: VisibleArea { 219 | size: PhysicalSize { 220 | width: visible_frame.size.width * scale_factor, 221 | height: visible_frame.size.height * scale_factor, 222 | }, 223 | position: PhysicalPosition { 224 | x: visible_frame.origin.x * scale_factor, 225 | y: visible_frame.origin.y * scale_factor, 226 | }, 227 | }, 228 | scale_factor, 229 | has_cursor: is_mouse_in_screen_frame == YES, 230 | is_primary: monitor_id == main_display_id, 231 | }); 232 | } 233 | 234 | monitors 235 | }) 236 | } 237 | -------------------------------------------------------------------------------- /pnpm-lock.yaml: -------------------------------------------------------------------------------- 1 | lockfileVersion: '9.0' 2 | 3 | settings: 4 | autoInstallPeers: true 5 | excludeLinksFromLockfile: false 6 | 7 | importers: 8 | 9 | .: 10 | devDependencies: 11 | '@biomejs/biome': 12 | specifier: ^1.9.3 13 | version: 1.9.4 14 | '@rollup/plugin-node-resolve': 15 | specifier: ^16.0.0 16 | version: 16.0.1 17 | '@rollup/plugin-typescript': 18 | specifier: ^12.1.0 19 | version: 12.1.2(typescript@5.4.3) 20 | 21 | packages: 22 | 23 | '@biomejs/biome@1.9.4': 24 | resolution: {integrity: sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog==} 25 | engines: {node: '>=14.21.3'} 26 | hasBin: true 27 | 28 | '@biomejs/cli-darwin-arm64@1.9.4': 29 | resolution: {integrity: sha512-bFBsPWrNvkdKrNCYeAp+xo2HecOGPAy9WyNyB/jKnnedgzl4W4Hb9ZMzYNbf8dMCGmUdSavlYHiR01QaYR58cw==} 30 | engines: {node: '>=14.21.3'} 31 | cpu: [arm64] 32 | os: [darwin] 33 | 34 | '@biomejs/cli-darwin-x64@1.9.4': 35 | resolution: {integrity: sha512-ngYBh/+bEedqkSevPVhLP4QfVPCpb+4BBe2p7Xs32dBgs7rh9nY2AIYUL6BgLw1JVXV8GlpKmb/hNiuIxfPfZg==} 36 | engines: {node: '>=14.21.3'} 37 | cpu: [x64] 38 | os: [darwin] 39 | 40 | '@biomejs/cli-linux-arm64-musl@1.9.4': 41 | resolution: {integrity: sha512-v665Ct9WCRjGa8+kTr0CzApU0+XXtRgwmzIf1SeKSGAv+2scAlW6JR5PMFo6FzqqZ64Po79cKODKf3/AAmECqA==} 42 | engines: {node: '>=14.21.3'} 43 | cpu: [arm64] 44 | os: [linux] 45 | 46 | '@biomejs/cli-linux-arm64@1.9.4': 47 | resolution: {integrity: sha512-fJIW0+LYujdjUgJJuwesP4EjIBl/N/TcOX3IvIHJQNsAqvV2CHIogsmA94BPG6jZATS4Hi+xv4SkBBQSt1N4/g==} 48 | engines: {node: '>=14.21.3'} 49 | cpu: [arm64] 50 | os: [linux] 51 | 52 | '@biomejs/cli-linux-x64-musl@1.9.4': 53 | resolution: {integrity: sha512-gEhi/jSBhZ2m6wjV530Yy8+fNqG8PAinM3oV7CyO+6c3CEh16Eizm21uHVsyVBEB6RIM8JHIl6AGYCv6Q6Q9Tg==} 54 | engines: {node: '>=14.21.3'} 55 | cpu: [x64] 56 | os: [linux] 57 | 58 | '@biomejs/cli-linux-x64@1.9.4': 59 | resolution: {integrity: sha512-lRCJv/Vi3Vlwmbd6K+oQ0KhLHMAysN8lXoCI7XeHlxaajk06u7G+UsFSO01NAs5iYuWKmVZjmiOzJ0OJmGsMwg==} 60 | engines: {node: '>=14.21.3'} 61 | cpu: [x64] 62 | os: [linux] 63 | 64 | '@biomejs/cli-win32-arm64@1.9.4': 65 | resolution: {integrity: sha512-tlbhLk+WXZmgwoIKwHIHEBZUwxml7bRJgk0X2sPyNR3S93cdRq6XulAZRQJ17FYGGzWne0fgrXBKpl7l4M87Hg==} 66 | engines: {node: '>=14.21.3'} 67 | cpu: [arm64] 68 | os: [win32] 69 | 70 | '@biomejs/cli-win32-x64@1.9.4': 71 | resolution: {integrity: sha512-8Y5wMhVIPaWe6jw2H+KlEm4wP/f7EW3810ZLmDlrEEy5KvBsb9ECEfu/kMWD484ijfQ8+nIi0giMgu9g1UAuuA==} 72 | engines: {node: '>=14.21.3'} 73 | cpu: [x64] 74 | os: [win32] 75 | 76 | '@rollup/plugin-node-resolve@16.0.1': 77 | resolution: {integrity: sha512-tk5YCxJWIG81umIvNkSod2qK5KyQW19qcBF/B78n1bjtOON6gzKoVeSzAE8yHCZEDmqkHKkxplExA8KzdJLJpA==} 78 | engines: {node: '>=14.0.0'} 79 | peerDependencies: 80 | rollup: ^2.78.0||^3.0.0||^4.0.0 81 | peerDependenciesMeta: 82 | rollup: 83 | optional: true 84 | 85 | '@rollup/plugin-typescript@12.1.2': 86 | resolution: {integrity: sha512-cdtSp154H5sv637uMr1a8OTWB0L1SWDSm1rDGiyfcGcvQ6cuTs4MDk2BVEBGysUWago4OJN4EQZqOTl/QY3Jgg==} 87 | engines: {node: '>=14.0.0'} 88 | peerDependencies: 89 | rollup: ^2.14.0||^3.0.0||^4.0.0 90 | tslib: '*' 91 | typescript: '>=3.7.0' 92 | peerDependenciesMeta: 93 | rollup: 94 | optional: true 95 | tslib: 96 | optional: true 97 | 98 | '@rollup/pluginutils@5.1.4': 99 | resolution: {integrity: sha512-USm05zrsFxYLPdWWq+K3STlWiT/3ELn3RcV5hJMghpeAIhxfsUIg6mt12CBJBInWMV4VneoV7SfGv8xIwo2qNQ==} 100 | engines: {node: '>=14.0.0'} 101 | peerDependencies: 102 | rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0 103 | peerDependenciesMeta: 104 | rollup: 105 | optional: true 106 | 107 | '@types/estree@1.0.6': 108 | resolution: {integrity: sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==} 109 | 110 | '@types/resolve@1.20.2': 111 | resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==} 112 | 113 | deepmerge@4.3.1: 114 | resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} 115 | engines: {node: '>=0.10.0'} 116 | 117 | estree-walker@2.0.2: 118 | resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} 119 | 120 | function-bind@1.1.2: 121 | resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} 122 | 123 | hasown@2.0.2: 124 | resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} 125 | engines: {node: '>= 0.4'} 126 | 127 | is-core-module@2.16.0: 128 | resolution: {integrity: sha512-urTSINYfAYgcbLb0yDQ6egFm6h3Mo1DcF9EkyXSRjjzdHbsulg01qhwWuXdOoUBuTkbQ80KDboXa0vFJ+BDH+g==} 129 | engines: {node: '>= 0.4'} 130 | 131 | is-core-module@2.16.1: 132 | resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} 133 | engines: {node: '>= 0.4'} 134 | 135 | is-module@1.0.0: 136 | resolution: {integrity: sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==} 137 | 138 | path-parse@1.0.7: 139 | resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} 140 | 141 | picomatch@4.0.2: 142 | resolution: {integrity: sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==} 143 | engines: {node: '>=12'} 144 | 145 | resolve@1.22.10: 146 | resolution: {integrity: sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==} 147 | engines: {node: '>= 0.4'} 148 | hasBin: true 149 | 150 | resolve@1.22.9: 151 | resolution: {integrity: sha512-QxrmX1DzraFIi9PxdG5VkRfRwIgjwyud+z/iBwfRRrVmHc+P9Q7u2lSSpQ6bjr2gy5lrqIiU9vb6iAeGf2400A==} 152 | hasBin: true 153 | 154 | supports-preserve-symlinks-flag@1.0.0: 155 | resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} 156 | engines: {node: '>= 0.4'} 157 | 158 | typescript@5.4.3: 159 | resolution: {integrity: sha512-KrPd3PKaCLr78MalgiwJnA25Nm8HAmdwN3mYUYZgG/wizIo9EainNVQI9/yDavtVFRN2h3k8uf3GLHuhDMgEHg==} 160 | engines: {node: '>=14.17'} 161 | hasBin: true 162 | 163 | snapshots: 164 | 165 | '@biomejs/biome@1.9.4': 166 | optionalDependencies: 167 | '@biomejs/cli-darwin-arm64': 1.9.4 168 | '@biomejs/cli-darwin-x64': 1.9.4 169 | '@biomejs/cli-linux-arm64': 1.9.4 170 | '@biomejs/cli-linux-arm64-musl': 1.9.4 171 | '@biomejs/cli-linux-x64': 1.9.4 172 | '@biomejs/cli-linux-x64-musl': 1.9.4 173 | '@biomejs/cli-win32-arm64': 1.9.4 174 | '@biomejs/cli-win32-x64': 1.9.4 175 | 176 | '@biomejs/cli-darwin-arm64@1.9.4': 177 | optional: true 178 | 179 | '@biomejs/cli-darwin-x64@1.9.4': 180 | optional: true 181 | 182 | '@biomejs/cli-linux-arm64-musl@1.9.4': 183 | optional: true 184 | 185 | '@biomejs/cli-linux-arm64@1.9.4': 186 | optional: true 187 | 188 | '@biomejs/cli-linux-x64-musl@1.9.4': 189 | optional: true 190 | 191 | '@biomejs/cli-linux-x64@1.9.4': 192 | optional: true 193 | 194 | '@biomejs/cli-win32-arm64@1.9.4': 195 | optional: true 196 | 197 | '@biomejs/cli-win32-x64@1.9.4': 198 | optional: true 199 | 200 | '@rollup/plugin-node-resolve@16.0.1': 201 | dependencies: 202 | '@rollup/pluginutils': 5.1.4 203 | '@types/resolve': 1.20.2 204 | deepmerge: 4.3.1 205 | is-module: 1.0.0 206 | resolve: 1.22.10 207 | 208 | '@rollup/plugin-typescript@12.1.2(typescript@5.4.3)': 209 | dependencies: 210 | '@rollup/pluginutils': 5.1.4 211 | resolve: 1.22.9 212 | typescript: 5.4.3 213 | 214 | '@rollup/pluginutils@5.1.4': 215 | dependencies: 216 | '@types/estree': 1.0.6 217 | estree-walker: 2.0.2 218 | picomatch: 4.0.2 219 | 220 | '@types/estree@1.0.6': {} 221 | 222 | '@types/resolve@1.20.2': {} 223 | 224 | deepmerge@4.3.1: {} 225 | 226 | estree-walker@2.0.2: {} 227 | 228 | function-bind@1.1.2: {} 229 | 230 | hasown@2.0.2: 231 | dependencies: 232 | function-bind: 1.1.2 233 | 234 | is-core-module@2.16.0: 235 | dependencies: 236 | hasown: 2.0.2 237 | 238 | is-core-module@2.16.1: 239 | dependencies: 240 | hasown: 2.0.2 241 | 242 | is-module@1.0.0: {} 243 | 244 | path-parse@1.0.7: {} 245 | 246 | picomatch@4.0.2: {} 247 | 248 | resolve@1.22.10: 249 | dependencies: 250 | is-core-module: 2.16.1 251 | path-parse: 1.0.7 252 | supports-preserve-symlinks-flag: 1.0.0 253 | 254 | resolve@1.22.9: 255 | dependencies: 256 | is-core-module: 2.16.0 257 | path-parse: 1.0.7 258 | supports-preserve-symlinks-flag: 1.0.0 259 | 260 | supports-preserve-symlinks-flag@1.0.0: {} 261 | 262 | typescript@5.4.3: {} 263 | -------------------------------------------------------------------------------- /libs/border/src/macos/border.rs: -------------------------------------------------------------------------------- 1 | use cocoa::{ 2 | appkit::{CGFloat, NSViewHeightSizable, NSViewWidthSizable}, 3 | base::{id, BOOL, NO, YES}, 4 | foundation::{NSInteger, NSPoint, NSRect, NSSize}, 5 | }; 6 | use objc::{ 7 | class, 8 | declare::ClassDecl, 9 | msg_send, 10 | runtime::{Class, Object, Sel}, 11 | sel, sel_impl, Message, 12 | }; 13 | use objc_foundation::INSObject; 14 | use objc_id::{Id, ShareId}; 15 | use tauri::window::Color; 16 | 17 | use color::ColorExt; 18 | 19 | use crate::macos::tag; 20 | 21 | static CLS_NAME: &str = "BorderView"; 22 | 23 | pub struct BorderView; 24 | 25 | unsafe impl Sync for BorderView {} 26 | 27 | unsafe impl Send for BorderView {} 28 | 29 | pub struct BorderViewConfig { 30 | pub line_width: CGFloat, 31 | pub line_color: Color, 32 | pub inset: CGFloat, 33 | pub corner_radius: CGFloat, 34 | } 35 | 36 | impl Default for BorderViewConfig { 37 | fn default() -> Self { 38 | BorderViewConfig { 39 | line_width: 1.0, 40 | line_color: Color(255, 255, 255, 38), 41 | inset: 0.5, 42 | corner_radius: 10.0, 43 | } 44 | } 45 | } 46 | 47 | impl BorderView { 48 | fn define_class() -> &'static Class { 49 | let mut decl = ClassDecl::new(CLS_NAME, class!(NSView)) 50 | .unwrap_or_else(|| panic!("Unable to register {} class", CLS_NAME)); 51 | 52 | decl.add_ivar::("line_width"); 53 | 54 | decl.add_ivar::("line_color"); 55 | 56 | decl.add_ivar::("inset"); 57 | 58 | decl.add_ivar::("corner_radius"); 59 | 60 | decl.add_ivar::("accepts_first_mouse"); 61 | 62 | decl.add_ivar::("_tag"); 63 | 64 | unsafe { 65 | decl.add_method( 66 | sel!(setLineWidth:), 67 | Self::handle_set_line_width as extern "C" fn(&mut Object, Sel, CGFloat), 68 | ); 69 | 70 | decl.add_method( 71 | sel!(setLineColor:), 72 | Self::handle_set_line_color as extern "C" fn(&mut Object, Sel, id), 73 | ); 74 | 75 | decl.add_method( 76 | sel!(setInset:), 77 | Self::handle_set_inset as extern "C" fn(&mut Object, Sel, CGFloat), 78 | ); 79 | 80 | decl.add_method( 81 | sel!(setCornerRadius:), 82 | Self::handle_set_corner_radius as extern "C" fn(&mut Object, Sel, CGFloat), 83 | ); 84 | 85 | decl.add_method( 86 | sel!(setAcceptsFirstMouse:), 87 | Self::handle_set_accepts_first_mouse as extern "C" fn(&mut Object, Sel, BOOL), 88 | ); 89 | 90 | decl.add_method( 91 | sel!(tag), 92 | Self::handle_get_tag as extern "C" fn(&mut Object, Sel) -> NSInteger, 93 | ); 94 | 95 | decl.add_method( 96 | sel!(setTag:), 97 | Self::handle_set_tag as extern "C" fn(&mut Object, Sel, NSInteger), 98 | ); 99 | 100 | decl.add_method( 101 | sel!(drawRect:), 102 | Self::draw_rect as extern "C" fn(&Object, _, NSRect), 103 | ); 104 | 105 | decl.add_method( 106 | sel!(acceptsFirstMouse:), 107 | Self::accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL, 108 | ); 109 | } 110 | 111 | decl.register() 112 | } 113 | 114 | extern "C" fn handle_set_line_width(this: &mut Object, _: Sel, width: CGFloat) { 115 | unsafe { this.set_ivar::("line_width", width) }; 116 | } 117 | 118 | extern "C" fn handle_set_line_color(this: &mut Object, _: Sel, color: id) { 119 | unsafe { this.set_ivar::("line_color", color) }; 120 | } 121 | 122 | extern "C" fn handle_set_inset(this: &mut Object, _: Sel, inset: CGFloat) { 123 | unsafe { this.set_ivar::("inset", inset) }; 124 | } 125 | 126 | extern "C" fn handle_set_corner_radius(this: &mut Object, _: Sel, radius: CGFloat) { 127 | unsafe { this.set_ivar::("corner_radius", radius) }; 128 | } 129 | 130 | extern "C" fn handle_set_accepts_first_mouse(this: &mut Object, _: Sel, value: BOOL) { 131 | unsafe { this.set_ivar::("accepts_first_mouse", value) }; 132 | } 133 | 134 | extern "C" fn handle_get_tag(this: &mut Object, _: Sel) -> NSInteger { 135 | unsafe { *this.get_ivar::("_tag") } 136 | } 137 | 138 | extern "C" fn handle_set_tag(this: &mut Object, _: Sel, tag: NSInteger) { 139 | unsafe { this.set_ivar::("_tag", tag) }; 140 | } 141 | 142 | extern "C" fn draw_rect(this: &Object, _: Sel, rect: NSRect) { 143 | let () = unsafe { msg_send![this, setWantsLayer: true] }; 144 | 145 | let inset: CGFloat = unsafe { *this.get_ivar::("inset") }; 146 | 147 | let inset_rect = NSRect { 148 | origin: NSPoint { 149 | x: rect.origin.x + inset, 150 | y: rect.origin.y + inset, 151 | }, 152 | size: NSSize { 153 | width: rect.size.width - 2.0 * inset, 154 | height: rect.size.height - 2.0 * inset, 155 | }, 156 | }; 157 | 158 | let line_color: id = unsafe { *this.get_ivar::("line_color") }; 159 | 160 | let line_width = unsafe { *this.get_ivar::("line_width") }; 161 | 162 | let corner_radius = unsafe { *this.get_ivar::("corner_radius") }; 163 | 164 | let rounded_rect_class = class!(NSBezierPath); 165 | 166 | let rounded_rect: *mut Object = unsafe { 167 | msg_send![rounded_rect_class, bezierPathWithRoundedRect:inset_rect xRadius:corner_radius yRadius:corner_radius] 168 | }; 169 | 170 | let () = unsafe { msg_send![line_color, setStroke] }; 171 | 172 | let () = unsafe { msg_send![rounded_rect, setLineWidth: line_width] }; 173 | 174 | let () = unsafe { msg_send![rounded_rect, stroke] }; 175 | } 176 | 177 | extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL { 178 | unsafe { *this.get_ivar::("accepts_first_mouse") } 179 | } 180 | 181 | pub fn new(config: Option, tag: String) -> ShareId { 182 | let config = config.unwrap_or_default(); 183 | 184 | let border_view: id = unsafe { msg_send![Self::class(), alloc] }; 185 | 186 | let border_view: id = unsafe { msg_send![border_view, init] }; 187 | 188 | let () = unsafe { msg_send![border_view, setLineWidth: config.line_width] }; 189 | 190 | let () = unsafe { msg_send![border_view, setLineColor: config.line_color.to_nscolor()] }; 191 | 192 | let () = unsafe { msg_send![border_view, setInset: config.inset] }; 193 | 194 | let () = unsafe { msg_send![border_view, setCornerRadius: config.corner_radius] }; 195 | 196 | let () = unsafe { msg_send![border_view, setTag: tag::from_str(&tag)] }; 197 | 198 | unsafe { Id::from_retained_ptr(border_view as *mut BorderView) } 199 | } 200 | 201 | #[allow(clippy::not_unsafe_ptr_arg_deref)] 202 | pub fn set_parent(&self, parent_view: id) { 203 | let () = unsafe { msg_send![parent_view, addSubview: self] }; 204 | } 205 | 206 | pub fn set_frame(&self, frame: NSRect) { 207 | unsafe { 208 | let () = msg_send![self, setFrame: frame]; 209 | } 210 | } 211 | 212 | pub fn set_auto_resizing(&self) { 213 | let autoresizing_mask = NSViewWidthSizable | NSViewHeightSizable; 214 | 215 | let _: () = unsafe { msg_send![self, setAutoresizingMask: autoresizing_mask] }; 216 | } 217 | 218 | #[allow(dead_code)] 219 | pub fn set_line_width(&self, width: CGFloat) { 220 | let () = unsafe { msg_send![self, setLineWidth: width] }; 221 | 222 | let () = unsafe { msg_send![self, display] }; 223 | } 224 | 225 | #[allow(dead_code)] 226 | pub fn set_line_color(&self, color: Color) { 227 | let () = unsafe { msg_send![self, setLineColor: color.to_nscolor()] }; 228 | 229 | let () = unsafe { msg_send![self, display] }; 230 | } 231 | 232 | #[allow(dead_code)] 233 | pub fn set_inset(&self, inset: CGFloat) { 234 | let () = unsafe { msg_send![self, setInset: inset] }; 235 | 236 | let () = unsafe { msg_send![self, display] }; 237 | } 238 | 239 | #[allow(dead_code)] 240 | pub fn set_corner_radius(&self, radius: CGFloat) { 241 | let () = unsafe { msg_send![self, setWantsLayer: true] }; 242 | 243 | let layer: id = unsafe { msg_send![self, layer] }; 244 | 245 | let () = unsafe { msg_send![layer, setCornerRadius: radius] }; 246 | 247 | let () = unsafe { msg_send![self, display] }; 248 | } 249 | 250 | #[allow(dead_code)] 251 | pub fn set_accepts_first_mouse(&self, value: bool) { 252 | let () = unsafe { msg_send![self, setAcceptsFirstMouse: if value { YES } else { NO } ] }; 253 | } 254 | 255 | #[allow(dead_code)] 256 | #[allow(clippy::not_unsafe_ptr_arg_deref)] 257 | pub fn find_with_tag(content_view: id, name: String) -> Option> { 258 | let border_view: id = unsafe { msg_send![content_view, viewWithTag: tag::from_str(&name)] }; 259 | 260 | if border_view.is_null() { 261 | None 262 | } else { 263 | Some(unsafe { Id::from_ptr(border_view as *mut BorderView) }) 264 | } 265 | } 266 | 267 | pub fn remove(&self) { 268 | let () = unsafe { msg_send![self, removeFromSuperview] }; 269 | } 270 | } 271 | 272 | unsafe impl Message for BorderView {} 273 | 274 | impl INSObject for BorderView { 275 | fn class() -> &'static Class { 276 | Class::get(CLS_NAME).unwrap_or_else(Self::define_class) 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /LICENSE_APACHE-2.0: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /libs/popover/src/macos/popover.rs: -------------------------------------------------------------------------------- 1 | use objc2_foundation::{NSPoint as CGPoint, NSRect as CGRect, NSSize as CGSize}; 2 | 3 | use cocoa::{ 4 | appkit::{CGFloat, NSViewHeightSizable, NSViewWidthSizable, NSWindowOrderingMode}, 5 | base::id, 6 | foundation::NSRect, 7 | }; 8 | use objc::{ 9 | class, 10 | declare::ClassDecl, 11 | msg_send, 12 | runtime::{Class, Object, Sel}, 13 | sel, sel_impl, Message, 14 | }; 15 | 16 | use objc2_app_kit::NSBezierPath; 17 | 18 | use objc_id::Id; 19 | 20 | use objc2_foundation::{NSEdgeInsets, NSEdgeInsetsZero}; 21 | 22 | use objc_foundation::INSObject; 23 | 24 | const CLS_NAME: &str = "PopoverView"; 25 | 26 | #[derive(Copy, Clone)] 27 | pub struct PopoverConfig { 28 | pub arrow_height: CGFloat, 29 | pub arrow_position: CGFloat, 30 | pub arrow_width: CGFloat, 31 | pub background_color: id, 32 | pub border_color: id, 33 | pub border_width: CGFloat, 34 | pub content_edge_insets: NSEdgeInsets, 35 | pub corner_radius: CGFloat, 36 | pub popover_to_status_item_margin: CGFloat, 37 | pub right_edge_margin: CGFloat, 38 | } 39 | 40 | impl Default for PopoverConfig { 41 | fn default() -> Self { 42 | let background_color: id = unsafe { msg_send![class!(NSColor), windowBackgroundColor] }; 43 | 44 | let border_color: id = unsafe { msg_send![class!(NSColor), whiteColor] }; 45 | 46 | let border_color: id = unsafe { msg_send![border_color, colorWithAlphaComponent: 0.1] }; 47 | 48 | Self { 49 | popover_to_status_item_margin: 2.0, 50 | background_color, 51 | border_color, 52 | border_width: 2.0, 53 | arrow_width: 62.0, 54 | arrow_height: 12.0, 55 | arrow_position: 0.0, 56 | corner_radius: 12.0, 57 | content_edge_insets: unsafe { NSEdgeInsetsZero }, 58 | right_edge_margin: 12.0, 59 | } 60 | } 61 | } 62 | 63 | unsafe impl Sync for PopoverConfig {} 64 | 65 | unsafe impl Send for PopoverConfig {} 66 | 67 | pub struct PopoverView; 68 | 69 | unsafe impl Sync for PopoverView {} 70 | 71 | unsafe impl Send for PopoverView {} 72 | 73 | impl PopoverView { 74 | fn define_class() -> &'static Class { 75 | let mut decl = ClassDecl::new(CLS_NAME, class!(NSView)) 76 | .unwrap_or_else(|| panic!("Unable to register {} class", CLS_NAME)); 77 | 78 | decl.add_ivar::("popover_to_status_item_margin"); 79 | 80 | decl.add_ivar::("background_color"); 81 | 82 | decl.add_ivar::("border_color"); 83 | 84 | decl.add_ivar::("border_width"); 85 | 86 | decl.add_ivar::("arrow_height"); 87 | 88 | decl.add_ivar::("arrow_width"); 89 | 90 | decl.add_ivar::("arrow_position"); 91 | 92 | decl.add_ivar::("corner_radius"); 93 | 94 | decl.add_ivar::("content_edge_insets"); 95 | 96 | decl.add_ivar::("right_edge_margin"); 97 | 98 | unsafe { 99 | decl.add_method( 100 | sel!(drawRect:), 101 | Self::draw_rect as extern "C" fn(&Object, _, NSRect), 102 | ); 103 | 104 | decl.add_method( 105 | sel!(setPopoverToStatusItemMargin:), 106 | Self::handle_set_popover_to_status_item_margin 107 | as extern "C" fn(&mut Object, Sel, CGFloat), 108 | ); 109 | 110 | decl.add_method( 111 | sel!(setBackgroundColor:), 112 | Self::handle_set_background_color as extern "C" fn(&mut Object, Sel, id), 113 | ); 114 | 115 | decl.add_method( 116 | sel!(setBorderColor:), 117 | Self::handle_set_border_color as extern "C" fn(&mut Object, Sel, id), 118 | ); 119 | 120 | decl.add_method( 121 | sel!(setBorderWidth:), 122 | Self::handle_set_border_width as extern "C" fn(&mut Object, Sel, CGFloat), 123 | ); 124 | 125 | decl.add_method( 126 | sel!(setArrowHeight:), 127 | Self::handle_set_arrow_height as extern "C" fn(&mut Object, Sel, CGFloat), 128 | ); 129 | 130 | decl.add_method( 131 | sel!(setArrowWidth:), 132 | Self::handle_set_arrow_width as extern "C" fn(&mut Object, Sel, CGFloat), 133 | ); 134 | 135 | decl.add_method( 136 | sel!(setArrowPosition:), 137 | Self::handle_set_arrow_position as extern "C" fn(&mut Object, Sel, CGFloat), 138 | ); 139 | 140 | decl.add_method( 141 | sel!(setCornerRadius:), 142 | Self::handle_set_corner_radius as extern "C" fn(&mut Object, Sel, CGFloat), 143 | ); 144 | 145 | decl.add_method( 146 | sel!(setContentEdgeInsets:), 147 | Self::handle_set_content_edge_insets as extern "C" fn(&mut Object, Sel, id), 148 | ); 149 | 150 | decl.add_method( 151 | sel!(setRightEdgeMargin:), 152 | Self::handle_set_right_edge_margin as extern "C" fn(&mut Object, Sel, CGFloat), 153 | ); 154 | } 155 | 156 | decl.register() 157 | } 158 | 159 | extern "C" fn handle_set_popover_to_status_item_margin( 160 | this: &mut Object, 161 | _: Sel, 162 | value: CGFloat, 163 | ) { 164 | unsafe { this.set_ivar::("popover_to_status_item_margin", value) }; 165 | } 166 | 167 | extern "C" fn handle_set_background_color(this: &mut Object, _: Sel, ns_color: id) { 168 | unsafe { this.set_ivar::("background_color", ns_color) }; 169 | } 170 | 171 | extern "C" fn handle_set_border_color(this: &mut Object, _: Sel, ns_color: id) { 172 | unsafe { this.set_ivar::("border_color", ns_color) }; 173 | } 174 | 175 | extern "C" fn handle_set_border_width(this: &mut Object, _: Sel, value: CGFloat) { 176 | unsafe { this.set_ivar::("border_width", value) }; 177 | } 178 | 179 | extern "C" fn handle_set_arrow_height(this: &mut Object, _: Sel, value: CGFloat) { 180 | unsafe { this.set_ivar::("arrow_height", value) }; 181 | } 182 | 183 | extern "C" fn handle_set_arrow_width(this: &mut Object, _: Sel, value: CGFloat) { 184 | unsafe { this.set_ivar::("arrow_width", value) }; 185 | } 186 | 187 | extern "C" fn handle_set_arrow_position(this: &mut Object, _: Sel, value: CGFloat) { 188 | unsafe { this.set_ivar::("arrow_position", value) }; 189 | } 190 | 191 | extern "C" fn handle_set_corner_radius(this: &mut Object, _: Sel, value: CGFloat) { 192 | unsafe { this.set_ivar::("corner_radius", value) }; 193 | } 194 | 195 | extern "C" fn handle_set_content_edge_insets(this: &mut Object, _: Sel, ns_edge_insets: id) { 196 | unsafe { this.set_ivar::("content_edge_insets", ns_edge_insets) }; 197 | } 198 | 199 | extern "C" fn handle_set_right_edge_margin(this: &mut Object, _: Sel, value: CGFloat) { 200 | unsafe { this.set_ivar::("right_edge_margin", value) }; 201 | } 202 | 203 | extern "C" fn draw_rect(this: &Object, _: Sel, rect: NSRect) { 204 | let arrow_height = unsafe { this.get_ivar::("arrow_height") }; 205 | 206 | let arrow_width = unsafe { this.get_ivar::("arrow_width") }; 207 | 208 | let arrow_position = unsafe { this.get_ivar::("arrow_position") }; 209 | 210 | let border_width = unsafe { this.get_ivar::("border_width") }; 211 | 212 | let corner_radius = unsafe { this.get_ivar::("corner_radius") }; 213 | 214 | let border_color = unsafe { this.get_ivar::("border_color") }; 215 | 216 | let bg_color = unsafe { this.get_ivar::("background_color") }; 217 | 218 | let bg_rect = CGRect::new( 219 | CGPoint::new(rect.origin.x, rect.origin.y), 220 | CGSize::new(rect.size.width, rect.size.height - arrow_height), 221 | ); 222 | 223 | let bg_rect = CGRect::new( 224 | CGPoint::new( 225 | bg_rect.origin.x + border_width, 226 | bg_rect.origin.y + border_width, 227 | ), 228 | CGSize::new( 229 | bg_rect.size.width - 2.0 * border_width, 230 | bg_rect.size.height - 2.0 * border_width, 231 | ), 232 | ); 233 | 234 | let control_points = unsafe { NSBezierPath::new() }; 235 | 236 | let window_path = unsafe { NSBezierPath::new() }; 237 | 238 | let arrow_path = unsafe { NSBezierPath::new() }; 239 | 240 | let bg_path = unsafe { NSBezierPath::new() }; 241 | 242 | unsafe { 243 | bg_path.appendBezierPathWithRoundedRect_xRadius_yRadius( 244 | CGRect::new( 245 | CGPoint::new(bg_rect.origin.x, bg_rect.origin.y), 246 | CGSize::new(bg_rect.size.width, bg_rect.size.height), 247 | ), 248 | *corner_radius, 249 | *corner_radius, 250 | ) 251 | }; 252 | 253 | let x = *arrow_position; 254 | 255 | let y_max = bg_rect.origin.y + bg_rect.size.height; 256 | 257 | let left_point = CGPoint::new(x - arrow_width / 2.0, y_max); 258 | 259 | let to_point = CGPoint::new(x, y_max + arrow_height); 260 | 261 | let right_point = CGPoint::new(x + arrow_width / 2.0, y_max); 262 | 263 | let cp11 = CGPoint::new(x - arrow_width / 6.0, y_max); 264 | 265 | let cp12 = CGPoint::new(x - arrow_width / 9.0, y_max + arrow_height); 266 | 267 | let cp21 = CGPoint::new(x + arrow_width / 9.0, y_max + arrow_height); 268 | 269 | let cp22 = CGPoint::new(x + arrow_width / 6.0, y_max); 270 | 271 | unsafe { 272 | control_points.appendBezierPathWithOvalInRect(CGRect::new( 273 | CGPoint::new(left_point.x - 2.0, left_point.y - 2.0), 274 | CGSize::new(4.0, 4.0), 275 | )); 276 | } 277 | 278 | unsafe { 279 | control_points.appendBezierPathWithOvalInRect(CGRect::new( 280 | CGPoint::new(to_point.x - 2.0, to_point.y - 2.0), 281 | CGSize::new(4.0, 4.0), 282 | )); 283 | } 284 | 285 | unsafe { 286 | control_points.appendBezierPathWithOvalInRect(CGRect::new( 287 | CGPoint::new(right_point.x - 2.0, right_point.y - 2.0), 288 | CGSize::new(4.0, 4.0), 289 | )); 290 | } 291 | 292 | unsafe { 293 | control_points.appendBezierPathWithOvalInRect(CGRect::new( 294 | CGPoint::new(cp11.x - 2.0, cp11.y - 2.0), 295 | CGSize::new(4.0, 4.0), 296 | )); 297 | } 298 | 299 | unsafe { 300 | control_points.appendBezierPathWithOvalInRect(CGRect::new( 301 | CGPoint::new(cp12.x - 2.0, cp12.y - 2.0), 302 | CGSize::new(4.0, 4.0), 303 | )); 304 | } 305 | 306 | unsafe { 307 | control_points.appendBezierPathWithOvalInRect(CGRect::new( 308 | CGPoint::new(cp21.x - 2.0, cp21.y - 2.0), 309 | CGSize::new(4.0, 4.0), 310 | )); 311 | } 312 | 313 | unsafe { 314 | control_points.appendBezierPathWithOvalInRect(CGRect::new( 315 | CGPoint::new(cp22.x - 2.0, cp22.y - 2.0), 316 | CGSize::new(4.0, 4.0), 317 | )); 318 | } 319 | 320 | unsafe { 321 | arrow_path.moveToPoint(CGPoint::new(left_point.x, left_point.y)); 322 | } 323 | 324 | unsafe { 325 | arrow_path.curveToPoint_controlPoint1_controlPoint2( 326 | CGPoint::new(to_point.x, to_point.y), 327 | CGPoint::new(cp11.x, cp11.y), 328 | CGPoint::new(cp12.x, cp12.y), 329 | ); 330 | } 331 | 332 | unsafe { 333 | arrow_path.curveToPoint_controlPoint1_controlPoint2( 334 | CGPoint::new(right_point.x, right_point.y), 335 | CGPoint::new(cp21.x, cp21.y), 336 | CGPoint::new(cp22.x, cp22.y), 337 | ); 338 | } 339 | 340 | unsafe { 341 | arrow_path.lineToPoint(CGPoint::new(left_point.x, left_point.y)); 342 | } 343 | 344 | unsafe { 345 | arrow_path.closePath(); 346 | } 347 | 348 | unsafe { 349 | window_path.appendBezierPath(&arrow_path); 350 | window_path.appendBezierPath(&bg_path); 351 | } 352 | 353 | if !border_color.is_null() { 354 | let () = unsafe { msg_send![*border_color, setStroke] }; 355 | 356 | unsafe { 357 | window_path.setLineWidth(*border_width); 358 | 359 | window_path.stroke(); 360 | }; 361 | } 362 | 363 | let () = unsafe { msg_send![*bg_color, setFill] }; 364 | 365 | unsafe { 366 | window_path.fill(); 367 | } 368 | } 369 | 370 | pub fn new(config: PopoverConfig) -> Id { 371 | let popover_view: id = unsafe { msg_send![Self::class(), alloc] }; 372 | 373 | let popover_view: id = unsafe { msg_send![popover_view, init] }; 374 | 375 | let () = unsafe { 376 | msg_send![popover_view, setPopoverToStatusItemMargin: config.popover_to_status_item_margin ] 377 | }; 378 | 379 | let () = unsafe { msg_send![popover_view, setBackgroundColor: config.background_color] }; 380 | 381 | let () = unsafe { msg_send![popover_view, setBorderColor: config.border_color] }; 382 | 383 | let () = unsafe { msg_send![popover_view, setBorderWidth: config.border_width ] }; 384 | 385 | let () = unsafe { msg_send![popover_view, setArrowHeight: config.arrow_height ] }; 386 | 387 | let () = unsafe { msg_send![popover_view, setArrowWidth: config.arrow_width ] }; 388 | 389 | let () = unsafe { msg_send![popover_view, setArrowPosition: config.arrow_position ] }; 390 | 391 | let () = unsafe { msg_send![popover_view, setCornerRadius: config.corner_radius] }; 392 | 393 | let () = 394 | unsafe { msg_send![popover_view, setContentEdgeInsets: config.content_edge_insets ] }; 395 | 396 | let () = unsafe { msg_send![popover_view, setRightEdgeMargin: config.right_edge_margin ] }; 397 | 398 | unsafe { Id::from_retained_ptr(popover_view as *mut PopoverView) } 399 | } 400 | 401 | pub fn set_frame(&self, frame: NSRect) { 402 | unsafe { 403 | let () = msg_send![self, setFrame: frame]; 404 | } 405 | } 406 | 407 | #[allow(clippy::not_unsafe_ptr_arg_deref)] 408 | pub fn set_parent(&self, parent_view: id) { 409 | let () = unsafe { 410 | msg_send![parent_view, addSubview: self positioned: NSWindowOrderingMode::NSWindowBelow relativeTo: 0] 411 | }; 412 | } 413 | 414 | pub fn set_autoresizing(&self) { 415 | let autoresizing_mask = NSViewWidthSizable | NSViewHeightSizable; 416 | 417 | let () = unsafe { msg_send![self, setAutoresizingMask: autoresizing_mask] }; 418 | } 419 | } 420 | 421 | unsafe impl Message for PopoverView {} 422 | 423 | impl INSObject for PopoverView { 424 | fn class() -> &'static Class { 425 | Class::get(CLS_NAME).unwrap_or_else(Self::define_class) 426 | } 427 | } 428 | -------------------------------------------------------------------------------- /libs/toast/src/macos/toast.rs: -------------------------------------------------------------------------------- 1 | extern crate markdown; 2 | 3 | use std::{ 4 | ptr::NonNull, 5 | sync::{Arc, Mutex}, 6 | }; 7 | 8 | use block2::RcBlock; 9 | use monitor::get_monitor_with_cursor; 10 | use objc2::{ 11 | define_class, extern_methods, msg_send, rc::Retained, AllocAnyThread, MainThreadOnly, Message, 12 | }; 13 | use objc2_app_kit::{ 14 | NSAnimatablePropertyContainer, NSAnimationContext, NSAutoresizingMaskOptions, 15 | NSBackingStoreType, NSColor, NSLineBreakMode, NSMutableParagraphStyle, NSPanel, NSTextField, 16 | NSVisualEffectBlendingMode, NSVisualEffectMaterial, NSVisualEffectState, NSVisualEffectView, 17 | NSWindowCollectionBehavior, NSWindowOrderingMode, NSWindowStyleMask, 18 | }; 19 | use objc2_foundation::{ 20 | MainThreadMarker, NSAttributedString, NSAttributedStringKey, NSMutableAttributedString, 21 | NSObjectProtocol, NSPoint as CGPoint, NSRange, NSRect, NSSize as CGSize, NSString, NSTimer, 22 | NSUTF8StringEncoding, 23 | }; 24 | use tauri::{AppHandle, Manager, Runtime}; 25 | 26 | #[derive(Clone)] 27 | struct Ivars; 28 | 29 | define_class!( 30 | #[unsafe(super = NSPanel)] 31 | #[name = "ToastPanel"] 32 | #[thread_kind = MainThreadOnly] 33 | #[ivars = Ivars] 34 | struct ToastPanel; 35 | 36 | unsafe impl NSObjectProtocol for ToastPanel {} 37 | 38 | unsafe impl NSAnimatablePropertyContainer for ToastPanel {} 39 | 40 | impl ToastPanel { 41 | #[unsafe(method(canBecomeKeyWindow))] 42 | fn __can_become_key_window() -> bool { 43 | false 44 | } 45 | 46 | #[unsafe(method(show:))] 47 | fn __show(&self, fade_duration: f64) { 48 | unsafe { 49 | self.setAlphaValue(0.0); 50 | 51 | self.orderFrontRegardless(); 52 | 53 | NSAnimationContext::currentContext().setDuration(fade_duration); 54 | 55 | self.animator().setAlphaValue(1.0); 56 | }; 57 | } 58 | 59 | #[unsafe(method(hide:))] 60 | fn __hide(&self, fade_duration: f64) { 61 | unsafe { self.setAlphaValue(1.0) }; 62 | 63 | let group: Box)> = Box::new(|ctx| { 64 | let context = unsafe { ctx.as_ref() }; 65 | 66 | unsafe { context.setDuration(fade_duration) }; 67 | 68 | let panel = self.retain(); 69 | 70 | let cb: Box = Box::new(move ||{ 71 | panel.orderOut(None); 72 | }); 73 | 74 | let cb = RcBlock::new(cb); 75 | 76 | unsafe { context.setCompletionHandler(Some(&cb)) }; 77 | 78 | unsafe { self.animator().setAlphaValue(0.0) }; 79 | }); 80 | 81 | let group = RcBlock::new(group); 82 | 83 | unsafe { 84 | NSAnimationContext::runAnimationGroup(&group) 85 | }; 86 | } 87 | 88 | 89 | } 90 | ); 91 | 92 | impl ToastPanel { 93 | extern_methods!( 94 | #[unsafe(method(new))] 95 | pub unsafe fn new(mtm: MainThreadMarker) -> Retained; 96 | 97 | #[allow(non_snake_case)] 98 | #[unsafe(method(setFrame:display:))] 99 | pub fn setFrame_display(&self, frame_rect: NSRect, flag: bool); 100 | ); 101 | } 102 | 103 | impl ToastPanel { 104 | fn default() -> Retained { 105 | let mtm = MainThreadMarker::new().unwrap(); 106 | 107 | let panel = unsafe { ToastPanel::new(mtm) }; 108 | 109 | panel.setFrame_display(NSRect::ZERO, false); 110 | 111 | panel.setStyleMask(NSWindowStyleMask::NonactivatingPanel | NSWindowStyleMask::Borderless); 112 | 113 | unsafe { panel.setBackingType(NSBackingStoreType::Buffered) }; 114 | 115 | unsafe { 116 | panel.setFloatingPanel(true); 117 | 118 | panel.setHidesOnDeactivate(false); 119 | }; 120 | 121 | #[allow(non_snake_case)] 122 | let NSModalPanelWindowLevel = 8; 123 | 124 | panel.setLevel(NSModalPanelWindowLevel); 125 | 126 | unsafe { 127 | panel.setBackgroundColor(Some(&NSColor::clearColor())); 128 | }; 129 | 130 | panel.setOpaque(false); 131 | 132 | unsafe { panel.setAlphaValue(0.0) }; 133 | 134 | let content_view = panel.contentView().unwrap(); 135 | 136 | let bounds = content_view.bounds(); 137 | 138 | unsafe { 139 | panel.setCollectionBehavior( 140 | NSWindowCollectionBehavior::CanJoinAllSpaces 141 | | NSWindowCollectionBehavior::Stationary, 142 | ) 143 | }; 144 | 145 | let visual_effect_view = unsafe { NSVisualEffectView::new(mtm) }; 146 | 147 | unsafe { 148 | visual_effect_view.setFrame(bounds); 149 | 150 | visual_effect_view.setBlendingMode(NSVisualEffectBlendingMode::BehindWindow); 151 | 152 | visual_effect_view.setState(NSVisualEffectState::Active); 153 | 154 | visual_effect_view.setMaterial(NSVisualEffectMaterial::Popover); 155 | 156 | visual_effect_view.setAutoresizingMask( 157 | NSAutoresizingMaskOptions::ViewWidthSizable 158 | | NSAutoresizingMaskOptions::ViewHeightSizable, 159 | ); 160 | 161 | content_view.setWantsLayer(true); 162 | 163 | content_view.addSubview_positioned_relativeTo( 164 | &visual_effect_view, 165 | NSWindowOrderingMode::Below, 166 | None, 167 | ); 168 | } 169 | 170 | panel.orderOut(None); 171 | 172 | panel 173 | } 174 | 175 | fn show(&self, fade_duration: f64) { 176 | let () = unsafe { msg_send![self, show: fade_duration] }; 177 | } 178 | 179 | fn hide(&self, fade_duration: f64) { 180 | let () = unsafe { msg_send![self, hide: fade_duration] }; 181 | } 182 | } 183 | 184 | struct Panel(Retained); 185 | 186 | unsafe impl Sync for Panel {} 187 | 188 | unsafe impl Send for Panel {} 189 | 190 | struct ToastTimer(Retained); 191 | 192 | unsafe impl Sync for ToastTimer {} 193 | 194 | unsafe impl Send for ToastTimer {} 195 | 196 | #[derive(Debug, Clone)] 197 | pub enum ToastPosition { 198 | #[allow(dead_code)] 199 | Top, 200 | Bottom, 201 | At(f64, f64), 202 | } 203 | 204 | #[derive(Debug, Clone)] 205 | pub struct ToastConfig { 206 | pub font_size: f64, 207 | pub padding: (f64, f64), 208 | pub position: ToastPosition, 209 | pub offset: f64, 210 | pub duration: f64, 211 | pub fade_duration: f64, 212 | pub shadow: bool, 213 | } 214 | 215 | impl Default for ToastConfig { 216 | fn default() -> Self { 217 | ToastConfig { 218 | font_size: 16.0, 219 | padding: (15.0, 10.0), 220 | position: ToastPosition::Bottom, 221 | offset: 150.0, 222 | duration: 3.0, 223 | fade_duration: 0.3, 224 | shadow: false, 225 | } 226 | } 227 | } 228 | 229 | pub struct Toast { 230 | panel: Panel, 231 | timer: Arc>>, 232 | options: ToastConfig, 233 | } 234 | 235 | impl Default for Toast { 236 | fn default() -> Self { 237 | Self { 238 | panel: Panel(ToastPanel::default()), 239 | timer: Arc::new(Mutex::new(None)), 240 | options: Default::default(), 241 | } 242 | } 243 | } 244 | 245 | impl Toast { 246 | pub fn new(options: ToastConfig) -> Self { 247 | Self { 248 | panel: Panel(ToastPanel::default()), 249 | options, 250 | ..Default::default() 251 | } 252 | } 253 | 254 | fn message( 255 | &self, 256 | message: &str, 257 | options: Option<&ToastConfig>, 258 | ) -> Retained { 259 | let font_size = { 260 | if let Some(opt) = options { 261 | opt.font_size 262 | } else { 263 | self.options.font_size 264 | } 265 | }; 266 | 267 | let html = format!( 268 | "{}", 269 | font_size, 270 | markdown::to_html(message) 271 | ); 272 | 273 | let html = NSString::from_str(&html); 274 | 275 | let data = unsafe { html.dataUsingEncoding(NSUTF8StringEncoding) }.unwrap(); 276 | 277 | use cocoa::base::{id, nil}; 278 | use objc::{class, msg_send, sel, sel_impl}; 279 | 280 | let data = Retained::into_raw(data); 281 | 282 | let attributed_string: id = unsafe { msg_send![class!(NSAttributedString), alloc] }; 283 | 284 | let attributed_string: id = 285 | unsafe { msg_send![attributed_string, initWithHTML:data documentAttributes:nil] }; 286 | 287 | let attributed_string: Retained = 288 | unsafe { Retained::from_raw(attributed_string.cast()) }.unwrap(); 289 | 290 | let paragraph_style = unsafe { NSMutableParagraphStyle::new() }; 291 | 292 | unsafe { 293 | paragraph_style.setLineBreakMode(NSLineBreakMode::ByTruncatingTail); 294 | } 295 | 296 | let final_attributed_string = NSMutableAttributedString::alloc(); 297 | 298 | let final_attributed_string = NSMutableAttributedString::initWithAttributedString( 299 | final_attributed_string, 300 | &attributed_string, 301 | ); 302 | 303 | let length = final_attributed_string.length(); 304 | 305 | unsafe { 306 | final_attributed_string.addAttribute_value_range( 307 | &NSAttributedStringKey::from_str("NSParagraphStyleAtrributeName"), 308 | ¶graph_style, 309 | NSRange { 310 | location: 0, 311 | length, 312 | }, 313 | ) 314 | } 315 | 316 | final_attributed_string 317 | } 318 | 319 | fn message_frame( 320 | &self, 321 | attributed_string: Retained, 322 | options: Option<&ToastConfig>, 323 | ) -> NSRect { 324 | let attributed_string = Retained::into_raw(attributed_string); 325 | 326 | let size: CGSize = unsafe { objc2::msg_send![attributed_string, size] }; 327 | 328 | let origin = { 329 | if let Some(opts) = &options { 330 | CGPoint { 331 | x: opts.padding.0, 332 | y: -opts.padding.1, 333 | } 334 | } else { 335 | CGPoint { 336 | x: self.options.padding.0, 337 | y: -self.options.padding.1, 338 | } 339 | } 340 | }; 341 | 342 | let size = { 343 | if let Some(opts) = options { 344 | CGSize { 345 | width: size.width.ceil() + opts.padding.0 * 2.0, 346 | height: size.height.ceil() + opts.padding.1 * 2.0, 347 | } 348 | } else { 349 | CGSize { 350 | width: size.width.ceil() + self.options.padding.0 * 2.0, 351 | height: size.height.ceil() + self.options.padding.1 * 2.0, 352 | } 353 | } 354 | }; 355 | 356 | NSRect { origin, size } 357 | } 358 | 359 | fn window_frame(&self, msg_frame: NSRect, options: Option<&ToastConfig>) -> NSRect { 360 | let monitor = get_monitor_with_cursor().unwrap(); 361 | 362 | let scale_factor = monitor.scale_factor(); 363 | 364 | let monitor_size = monitor.size().to_logical::(scale_factor); 365 | 366 | let monitor_position = monitor.position().to_logical::(scale_factor); 367 | 368 | let width = msg_frame.size.width; 369 | 370 | let height = msg_frame.size.height; 371 | 372 | let offset = { 373 | if let Some(opts) = options.cloned() { 374 | opts.offset 375 | } else { 376 | self.options.offset 377 | } 378 | }; 379 | 380 | let position = { 381 | if let Some(opts) = options.cloned() { 382 | opts.position 383 | } else { 384 | self.options.position.clone() 385 | } 386 | }; 387 | 388 | NSRect { 389 | origin: CGPoint { 390 | x: match position { 391 | ToastPosition::At(x, _) => monitor_position.x + x, 392 | _ => monitor_position.x + monitor_size.width / 2.0 - width / 2.0, 393 | }, 394 | y: match position { 395 | ToastPosition::Top => monitor_position.y + monitor_size.height - offset, 396 | ToastPosition::Bottom => monitor_position.y + offset, 397 | ToastPosition::At(_, y) => (monitor_position.y + monitor_size.height) - y, 398 | }, 399 | }, 400 | size: CGSize { width, height }, 401 | } 402 | } 403 | 404 | fn label( 405 | &self, 406 | attributed_string: Retained, 407 | frame: NSRect, 408 | ) -> Retained { 409 | let mtn = MainThreadMarker::new().expect("run on the main thread"); 410 | 411 | let label = unsafe { NSTextField::new(mtn) }; 412 | 413 | unsafe { 414 | label.setFrame(frame); 415 | 416 | label.setEditable(false); 417 | 418 | let attributed_string = Retained::into_super(attributed_string); 419 | 420 | label.setAttributedStringValue(&attributed_string); 421 | 422 | label.setTextColor(Some(&NSColor::labelColor())); 423 | 424 | label.setDrawsBackground(false); 425 | 426 | label.setBordered(false); 427 | 428 | label.setTag(1); 429 | } 430 | 431 | label 432 | } 433 | 434 | fn resize(&self, message_frame: NSRect, options: Option<&ToastConfig>) { 435 | let panel_frame = self.window_frame(message_frame, options); 436 | 437 | self.panel.0.setFrame_display(panel_frame, true); 438 | 439 | let content_view = self.panel.0.contentView().unwrap(); 440 | 441 | let layer = unsafe { content_view.layer().unwrap() }; 442 | 443 | let frame = content_view.frame(); 444 | 445 | layer.setCornerRadius(frame.size.height / 2.0); 446 | } 447 | 448 | fn update_label(&self, message: Retained, frame: NSRect) { 449 | let content_view = self.panel.0.contentView().unwrap(); 450 | 451 | let label = self.label(message, frame); 452 | 453 | if let Some(view) = unsafe { content_view.viewWithTag(1) } { 454 | unsafe { content_view.replaceSubview_with(&view, &label) }; 455 | } else { 456 | unsafe { content_view.addSubview(&label) }; 457 | } 458 | } 459 | 460 | pub fn toast(&self, text: &str, options: Option) { 461 | let is_timer = self.timer.lock().unwrap().is_some(); 462 | 463 | if is_timer { 464 | unsafe { self.timer.lock().unwrap().as_ref().unwrap().0.invalidate() }; 465 | } 466 | 467 | let message = self.message(text, options.as_ref()); 468 | 469 | let frame = self.message_frame( 470 | NSMutableAttributedString::from_attributed_nsstring(&message), 471 | options.as_ref(), 472 | ); 473 | 474 | self.resize(frame, options.as_ref()); 475 | 476 | self.update_label(message, frame); 477 | 478 | let fade_duration = { 479 | if let Some(opts) = &options { 480 | opts.fade_duration 481 | } else { 482 | self.options.fade_duration 483 | } 484 | }; 485 | 486 | let shadow = { 487 | if let Some(opts) = &options { 488 | opts.shadow 489 | } else { 490 | self.options.shadow 491 | } 492 | }; 493 | 494 | self.panel.0.setHasShadow(shadow); 495 | 496 | self.panel.0.show(fade_duration); 497 | 498 | let panel = self.panel.0.retain(); 499 | 500 | let callback: Box)> = Box::new(move |_| { 501 | panel.hide(fade_duration); 502 | }); 503 | 504 | let duration = { 505 | if let Some(opts) = &options { 506 | opts.duration 507 | } else { 508 | self.options.duration 509 | } 510 | }; 511 | 512 | let timer = unsafe { 513 | NSTimer::scheduledTimerWithTimeInterval_repeats_block( 514 | duration, 515 | false, 516 | &RcBlock::new(callback), 517 | ) 518 | }; 519 | 520 | *self.timer.lock().unwrap() = Some(ToastTimer(timer)); 521 | } 522 | } 523 | 524 | pub trait ToastExt { 525 | fn toast(&self, message: &str, options: Option); 526 | } 527 | 528 | impl ToastExt for AppHandle { 529 | fn toast(&self, message: &str, options: Option) { 530 | let message = message.to_owned(); 531 | 532 | let app_handle = self.clone(); 533 | 534 | self.run_on_main_thread(move || { 535 | app_handle.state::().toast(&message, options); 536 | }) 537 | .unwrap(); 538 | } 539 | } 540 | --------------------------------------------------------------------------------