Skip to content

Commit

Permalink
refactor(tauri): split system_tray to another file
Browse files Browse the repository at this point in the history
  • Loading branch information
sekwah41 committed Oct 19, 2023
1 parent 10885a4 commit 1713c1a
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 77 deletions.
1 change: 1 addition & 0 deletions app/renderer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@pomatez/shareables": "*",
"@tauri-apps/api": "2.0.0-alpha.8",
"@tauri-apps/plugin-autostart": "^2.0.0-alpha.1",
"@tauri-apps/plugin-global-shortcut": "^2.0.0-alpha.1",
"@tauri-apps/plugin-window": "^2.0.0-alpha.1",
"@types/autosize": "^3.0.7",
"@types/jest": "^26.0.24",
Expand Down
29 changes: 29 additions & 0 deletions app/tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions app/tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ tauri-plugin-window = "2.0.0-alpha"
tauri-plugin-autostart = "2.0.0-alpha"
base64 = { version = "0.21.4", features = [] }

[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]
tauri-plugin-global-shortcut = "2.0.0-alpha"

[features]
# by default Tauri runs in production mode
# when `tauri dev` runs it is executed with `cargo run --no-default-features` if `devPath` is an URL
Expand Down
80 changes: 6 additions & 74 deletions app/tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,13 @@

use std::sync::Mutex;
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
use tauri::{Builder, Icon, PhysicalSize, Runtime, Wry};
use tauri::{
menu::{MenuBuilder, MenuItemBuilder},
tray::{ClickType, TrayIconBuilder},
};

use tauri::Manager;
use base64;
use base64::Engine;
use base64::engine::general_purpose;
use tauri::{Builder, PhysicalSize, Runtime, Wry};

#[non_exhaustive]
struct WindowSize;

use crate::system_tray;

impl WindowSize {

// Not sure why, if its due to UI scaling or what though these values seem to size smaller than the same values on electron
Expand Down Expand Up @@ -159,32 +152,9 @@ fn set_native_titlebar<R: Runtime>(use_native_titlebar: bool, window: tauri::Win
Ok(_) => (),
Err(e) => println!("There was a problem setting the window decorations! {:?}", e),
}
window.start_dragging();
println!("set_native_titlebar! {}", use_native_titlebar);
}

#[tauri::command]
fn tray_icon_update<R: Runtime>(data_url: String, window: tauri::Window<R>) {
println!("tray_icon_update!");
let base64_str = data_url.trim_start_matches("data:image/png;base64,");

let decoded_vec = match general_purpose::STANDARD.decode(base64_str) {
Ok(vec) => vec,
Err(e) => {
eprintln!("Error decoding Base64 string: {}", e);
return;
}
};

let icon: Icon = Icon::Raw(decoded_vec);
let tray = window.app_handle().tray();

if let Some(tray) = tray {
if let Err(e) = tray.set_icon(Some(icon)) {
eprintln!("Error setting tray icon: {}", e);
}
}
}

/**
* We could do this by passing the object into a custom function that adds the commands but I wanted
Expand All @@ -193,52 +163,14 @@ fn tray_icon_update<R: Runtime>(data_url: String, window: tauri::Window<R>) {
* Switch to a function that takes and returns tauri::Builder<Wry> or uses a reference if we need to
* switch it.
*/
pub trait PomatezExtras {
pub trait PomatezCommands {
fn register_pomatez_commands(self) -> tauri::Builder<Wry>;
fn set_pomatez_system_tray(self) -> tauri::Builder<Wry>;
}

impl PomatezExtras for Builder<Wry> {
impl PomatezCommands for Builder<Wry> {
fn register_pomatez_commands(self) -> tauri::Builder<Wry> {
self.invoke_handler(tauri::generate_handler![set_show, set_always_on_top,
set_fullscreen_break, set_compact_mode, set_ui_theme, set_native_titlebar,
tray_icon_update, set_close, set_minimize])
}

fn set_pomatez_system_tray(self) -> tauri::Builder<Wry> {
println!("Setting system tray");
self.setup(|app| {
// Was defined in tauri.config.json to start in v1
// That was created with an id of 1 though this gives more control

let show = MenuItemBuilder::with_id("show", "Show").build(app);
let quit = MenuItemBuilder::with_id("quit", "Quit").build(app);
let menu = MenuBuilder::new(app).items(&[&show, &quit]).build()?;
let tray = TrayIconBuilder::new()
.menu(&menu)
.tooltip("Pomatez")
.on_menu_event(move |app, event| match event.id().as_ref() {
"show" => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
"quit" => {
app.exit(0);
}
_ => {}
})
.on_tray_event(|tray, event| {
if event.click_type == ClickType::Left {
let app = tray.app_handle();
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
})
.icon(Icon::File("./icons/icon.png".into()))
.build(app)?;
Ok(())
})
system_tray::tray_icon_update, set_close, set_minimize])
}
}
Empty file.
6 changes: 5 additions & 1 deletion app/tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ use tauri_plugin_window;
#[macro_use]
mod commands;

use commands::PomatezExtras;
mod system_tray;
mod global_shortcuts;

use commands::PomatezCommands;
use system_tray::PomatezTray;

fn main() {
tauri::Builder::default()
Expand Down
94 changes: 94 additions & 0 deletions app/tauri/src/system_tray.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use std::path::PathBuf;
use tauri::{Builder, Icon, Manager, Runtime, Wry};
use tauri::{
menu::{MenuBuilder, MenuItemBuilder},
tray::{ClickType, TrayIconBuilder},
};
use tauri::path::BaseDirectory;

use base64;
use base64::Engine;
use base64::engine::general_purpose;

#[tauri::command]
pub fn tray_icon_update<R: Runtime>(data_url: String, window: tauri::Window<R>) {
println!("tray_icon_update!");
let base64_str = data_url.trim_start_matches("data:image/png;base64,");

let decoded_vec = match general_purpose::STANDARD.decode(base64_str) {
Ok(vec) => vec,
Err(e) => {
eprintln!("Error decoding Base64 string: {}", e);
return;
}
};

let icon: Icon = Icon::Raw(decoded_vec);
let tray = window.app_handle().tray();

if let Some(tray) = tray {
if let Err(e) = tray.set_icon(Some(icon)) {
eprintln!("Error setting tray icon: {}", e);
}
}
}


/**
* We could do this by passing the object into a custom function that adds the commands but I wanted
* to practice more with rust. Plus it makes the setup cleaner.
* Switch to a function that takes and returns tauri::Builder<Wry> or uses a reference if we need to
* switch it.
*/
pub trait PomatezTray {
fn set_pomatez_system_tray(self) -> tauri::Builder<Wry>;
}

impl PomatezTray for Builder<Wry> {

/*
* The icon is updated after rendering on the frontend so that is handled in the commands file.
* However the initial setup and behavior is handled here.
*/
fn set_pomatez_system_tray(self) -> tauri::Builder<Wry> {
println!("Setting system tray");
self.setup(|app| {
// Was defined in tauri.config.json to start in v1
// That was created with an id of 1 though this gives more control

let show = MenuItemBuilder::with_id("show", "Show").build(app);
let quit = MenuItemBuilder::with_id("quit", "Quit").build(app);
let menu = MenuBuilder::new(app).items(&[&show, &quit]).build()?;

let icon_path = app.path().resolve::<PathBuf>("icons/icon.png".into(), BaseDirectory::Resource)
.expect("failed to resolve icon path, this should not happen as it is an internal file");

let _ = TrayIconBuilder::new()
.menu(&menu)
.tooltip("Pomatez")
.on_menu_event(move |app, event| match event.id().as_ref() {
"show" => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
"quit" => {
app.exit(0);
}
_ => {}
})
.on_tray_event(|tray, event| {
if event.click_type == ClickType::Left {
let app = tray.app_handle();
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
})
.icon(Icon::File(icon_path))
.build(app)?;
Ok(())
})
}
}
4 changes: 2 additions & 2 deletions app/tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@
"signingIdentity": null
},
"publisher": "Roldan Montilla Jr",
"resources": [],
"resources": ["icons/icon.png"],
"shortDescription": "",
"targets": "all",
"targets": ["deb", "appimage", "msi", "dmg", "updater"],
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"suppressImplicitAnyIndexErrors": true,
"ignoreDeprecations": "5.0",

Check failure on line 12 in tsconfig.json

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, linux, build:linux-all)

Unknown compiler option 'ignoreDeprecations'.

Check failure on line 12 in tsconfig.json

View workflow job for this annotation

GitHub Actions / Test Build (ubuntu-20.04, linux)

Unknown compiler option 'ignoreDeprecations'.

Check failure on line 12 in tsconfig.json

View workflow job for this annotation

GitHub Actions / Test Build (macos-latest, mac)

Unknown compiler option 'ignoreDeprecations'.
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3732,6 +3732,13 @@
dependencies:
"@tauri-apps/api" "2.0.0-alpha.6"

"@tauri-apps/plugin-global-shortcut@^2.0.0-alpha.1":
version "2.0.0-alpha.1"
resolved "https://registry.yarnpkg.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.0.0-alpha.1.tgz#d5abec71d7b731b3530712fb21c05bf6d11fd9c4"
integrity sha512-86pqnvoylSZV7R/SjK1WlLhTWydIhRS5qjHl6IqIcY4sYRuBMovMNj8fMLhFt2Ppq4dRiSx5jbrlQDY82HJtaQ==
dependencies:
"@tauri-apps/api" "2.0.0-alpha.6"

"@tauri-apps/plugin-window@^2.0.0-alpha.1":
version "2.0.0-alpha.1"
resolved "https://registry.yarnpkg.com/@tauri-apps/plugin-window/-/plugin-window-2.0.0-alpha.1.tgz#28a0217100fc5a34fb2a6d76103ba056b2348286"
Expand Down

0 comments on commit 1713c1a

Please sign in to comment.