Skip to content

Commit

Permalink
Rework window management & config system
Browse files Browse the repository at this point in the history
  • Loading branch information
m1guelpf committed Aug 6, 2023
1 parent e06b3ad commit 2ee69e3
Show file tree
Hide file tree
Showing 9 changed files with 260 additions and 110 deletions.
55 changes: 38 additions & 17 deletions Cargo.lock

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

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ authors = ["Miguel Piedrafita <sup@miguel.build>"]
description = "Open-source Git client for minimalists"

[dependencies]
confy = "0.5.1"
rayon = "1.7.0"
walkdir = "2.3.3"
anyhow = "1.0.72"
Expand All @@ -17,7 +16,12 @@ priority-queue = "1.3.2"
window-vibrancy = "0.4.0"
serde = { version = "1.0", features = ["derive"] }
git2 = { version = "0.17.2", default-features = false }
tauri-plugin-spotlight = { git = "https://github.com/zzzze/tauri-plugin-spotlight" }
tauri-plugin-autostart = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
directories = "5.0.1"
toml = "0.7.6"
thiserror = "1.0.44"


[dependencies.tauri]
version = "1.4"
Expand Down
1 change: 1 addition & 0 deletions Tauri.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ iconPath = "icons/menubar.png"
[tauri.bundle]
active = true
targets = ["app", "dmg"]
category = "DeveloperTool"
identifier = "build.miguel.commit"
icon = [
"icons/32x32.png",
Expand Down
2 changes: 1 addition & 1 deletion src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn commit(
)
.map_err(|e| e.to_string())?;

window::toggle(&window).unwrap();
window::hide(&window).unwrap();
Notification::new(&app.config().tauri.bundle.identifier)
.title("Commit")
.body("Commit successful!")
Expand Down
54 changes: 46 additions & 8 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,61 @@
use std::{path::PathBuf, process::Command, sync::RwLock};
use std::{fs, io, path::PathBuf, process::Command, sync::RwLock};

use anyhow::Result;
use directories::ProjectDirs;

use crate::shortcuts;

pub type GetConfig = RwLock<Config>;

#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Encoding(#[from] toml::ser::Error),
#[error(transparent)]
Decoding(#[from] toml::de::Error),
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Config {
pub autostart: bool,
pub shortcut: String,
pub should_push: bool,
pub repo_paths: Vec<PathBuf>,
}

impl Config {
pub fn load() -> Result<Self, confy::ConfyError> {
let config: Self = confy::load("commit", Some("Settings"))?;
pub fn load() -> Result<Self, Error> {
let config_path = Self::config_path();
if config_path.exists() {
let config = toml::from_str(&fs::read_to_string(config_path)?)?;

return Ok(config);
}

let config = Self::default();
config.save()?;

Ok(config)
}

pub fn save(&self) -> Result<(), confy::ConfyError> {
confy::store("commit", Some("Settings"), self)
pub fn save(&self) -> Result<(), Error> {
let path = Self::config_path();
fs::create_dir_all(path.parent().unwrap())?;
fs::write(path, toml::to_string_pretty(self)?)?;

Ok(())
}

pub fn manage(self) -> RwLock<Self> {
RwLock::new(self)
}

pub fn config_path() -> Result<PathBuf, confy::ConfyError> {
confy::get_configuration_file_path("commit", Some("Settings"))
pub fn config_path() -> PathBuf {
let project_dirs = ProjectDirs::from("", "Miguel Piedrafita", "Commit").unwrap();

project_dirs.config_dir().join("Settings.toml")
}
}

Expand All @@ -38,12 +65,23 @@ impl Default for Config {
autostart: false,
should_push: true,
repo_paths: vec![],
shortcut: shortcuts::DEFAULT_SHORTCUT.to_string(),
}
}
}

pub fn edit() -> Result<()> {
Command::new("open").arg(Config::config_path()?).status()?;
Command::new("open").arg(Config::config_path()).status()?;

Ok(())
}

pub trait ConfigExt<R: tauri::Runtime> {
fn user_config(&self) -> tauri::State<'_, GetConfig>;
}

impl<R: tauri::Runtime, T: tauri::Manager<R>> ConfigExt<R> for T {
fn user_config(&self) -> tauri::State<'_, GetConfig> {
self.state::<GetConfig>()
}
}
36 changes: 22 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use anyhow::anyhow;
use config::Config;
use config::{Config, ConfigExt};
use std::error::Error;
use tauri::{generate_context, ActivationPolicy, Builder as Tauri, GlobalShortcutManager, Manager};
use tauri::{generate_context, ActivationPolicy, Builder as Tauri, Manager};
use tauri_plugin_autostart::{self as tauri_autostart, MacosLauncher};
use tauri_plugin_spotlight::WindowConfig;

mod commands;
mod config;
mod shortcuts;
mod tray;
mod utils;
mod window;
Expand All @@ -23,6 +25,16 @@ fn main() {
.invoke_handler(commands::handler())
.on_system_tray_event(tray::handle)
.plugin(tauri_autostart::init(MacosLauncher::LaunchAgent, None))
.plugin(tauri_plugin_spotlight::init(Some(
tauri_plugin_spotlight::PluginConfig {
windows: Some(vec![WindowConfig {
macos_window_level: Some(20),
label: String::from(window::NAME),
shortcut: String::from(shortcuts::DEFAULT_SHORTCUT),
}]),
global_close_shortcut: None,
},
)))
.build(generate_context!())
.expect("error while running tauri application");

Expand All @@ -33,25 +45,21 @@ fn setup_tauri(app: &mut tauri::App) -> Result<(), Box<(dyn Error + 'static)>> {
app.set_activation_policy(ActivationPolicy::Accessory);

let window = app
.get_window("main")
.get_window(window::NAME)
.ok_or_else(|| anyhow!("Window not found"))?;

window::make_transparent(&window).map_err(|_| {
anyhow!("Unsupported platform! 'apply_vibrancy' is only supported on macOS")
})?;

let mut shortcuts = app.global_shortcut_manager();
let config = app.user_config();
let config = config
.read()
.map_err(|_| anyhow!("Failed to read config"))?;

let window_handle = window.clone();
shortcuts.register("CmdOrControl+Alt+Shift+C", move || {
window::toggle(&window_handle).unwrap()
})?;

shortcuts.register("CmdOrControl+,", move || {
if window.is_focused().unwrap() {
config::edit().unwrap();
}
})?;
if config.shortcut != shortcuts::DEFAULT_SHORTCUT {
shortcuts::update_default(window, shortcuts::DEFAULT_SHORTCUT, &config.shortcut)?;
}

Ok(())
}
62 changes: 62 additions & 0 deletions src/shortcuts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use tauri::{AppHandle, GlobalShortcutManager, Manager, Window};

use crate::{config, window};

pub const DEFAULT_SHORTCUT: &str = "Cmd+Alt+Shift+C";

pub fn update_default(
window: Window,
old_shortcut: &str,
new_shortcut: &str,
) -> Result<(), tauri::Error> {
let app = window.app_handle();
let mut shortcuts = app.global_shortcut_manager();

shortcuts.unregister(old_shortcut)?;
shortcuts.register(new_shortcut, move || {
if window.is_visible().unwrap() {
window::hide(&window).unwrap();
} else {
window::show(&window).unwrap();
}
})?;

Ok(())
}

pub fn register_settings(app: &AppHandle) -> Result<(), anyhow::Error> {
let mut shortcuts = app.global_shortcut_manager();

shortcuts.register("Cmd+,", move || {
config::edit().unwrap();
})?;

Ok(())
}

pub fn unregister_settings(app: &AppHandle) -> Result<(), anyhow::Error> {
let mut shortcuts = app.global_shortcut_manager();

shortcuts.unregister("Cmd+,")?;

Ok(())
}

pub fn register_escape(window: Window) -> Result<(), tauri::Error> {
let app = window.app_handle();
let mut shortcuts = app.global_shortcut_manager();

shortcuts.register("Escape", move || {
window::hide(&window).unwrap();
})?;

Ok(())
}

pub fn unregister_escape(app: &AppHandle) -> Result<(), tauri::Error> {
let mut shortcuts = app.global_shortcut_manager();

shortcuts.unregister("Escape")?;

Ok(())
}
Loading

0 comments on commit 2ee69e3

Please sign in to comment.