Skip to content

Commit

Permalink
Merge pull request #34 from RyKilleen/custom-hot-keys
Browse files Browse the repository at this point in the history
Custom hot keys
  • Loading branch information
RyKilleen authored Mar 10, 2022
2 parents deacccd + 46ef5b7 commit b00e2e0
Show file tree
Hide file tree
Showing 10 changed files with 203 additions and 41 deletions.
26 changes: 24 additions & 2 deletions package-lock.json

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

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "brancato",
"version": "0.2.0",
"version": "0.3.0",
"private": true,
"dependencies": {
"@algolia/autocomplete-js": "^1.5.3",
Expand All @@ -13,6 +13,8 @@
"@types/node": "^16.11.26",
"@types/react": "^17.0.39",
"@types/react-dom": "^17.0.13",
"hotkeys-js": "^3.8.7",
"keycode": "^2.2.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hook-form": "^7.27.1",
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/Cargo.lock

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

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "brancato"
version = "0.2.0"
version = "0.3.0"
description = "A tool for stage-managing your life"
authors = ["Ryan Killeen"]
license = ""
Expand Down
24 changes: 18 additions & 6 deletions src-tauri/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,40 @@ use std::fs;

use super::workflows::Workflow;

#[derive(Default, Clone, Serialize, Deserialize, Debug)]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Config {
pub workflows: Vec<Workflow>,
#[serde(default = "default_shortcut")]
pub shortcut: String,
}

impl Default for Config {
fn default() -> Self {
Config {
workflows: Vec::new(),
shortcut: "alt + m".to_string(),
}
}
}

fn default_shortcut() -> String {
"alt + m".to_string()
}

pub fn get_config() -> Config {
let default = Config {
workflows: Vec::new(),
};
if let Some(proj_dirs) = ProjectDirs::from("", "", "Brancato") {
let config_dir = proj_dirs.config_dir();
let read_path = config_dir.join("config.json");

let config_file = fs::read_to_string(&read_path);
let config: Config = match config_file {
Ok(file) => serde_json::from_str(&file).unwrap(),
Err(_) => default,
Err(_) => Config::default(),
};

return config;
} else {
default
Config::default()
}
}

Expand Down
64 changes: 52 additions & 12 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,30 @@ fn _get_state(state: State<AppState>) -> Config {
config
}

#[tauri::command]
fn save_workflows(
fn update_config_and_state(
app: &AppHandle,
state: State<AppState>,
app: AppHandle,
config: Config,
new_config: Config,
) -> Result<(), tauri::Error> {
let mut app_state = state.0.lock().expect("Could not lock mutex");
// Save to file
config::set_config(&config);
// Update state
*app_state = config;
// Instruct client
config::set_config(&new_config);
let payload = new_config.clone();
*app_state = new_config;
app
.get_window("omnibar")
.unwrap()
.emit("state-updated", "")?;
.emit("state-updated", payload)?;
Ok(())
}

#[tauri::command]
fn save_workflows(
state: State<AppState>,
app: AppHandle,
config: Config,
) -> Result<(), tauri::Error> {
update_config_and_state(&app, state, config).ok();

Ok(())
}

Expand Down Expand Up @@ -74,6 +82,35 @@ async fn open_settings(app: AppHandle) -> Result<(), tauri::Error> {
Ok(())
}

#[tauri::command]
async fn set_shortcut(
app: AppHandle,
state: State<'_, AppState>,
shortcut: String,
) -> Result<(), tauri::Error> {
let config = _get_state(state.clone());

let new_config = Config {
shortcut: shortcut.to_owned(),
..config.to_owned()
};

let app_ref = &app.clone();
app
.global_shortcut_manager()
.unregister(&config.shortcut)
.ok();
app
.global_shortcut_manager()
.register(&new_config.shortcut, move || {
open_omnibar(&app).ok();
})
.ok();

update_config_and_state(app_ref, state, new_config).ok();
Ok(())
}

fn open_omnibar(app: &AppHandle) -> Result<(), tauri::Error> {
let label = "omnibar".to_owned();
focus_window(app, String::from(&label))?;
Expand Down Expand Up @@ -136,7 +173,8 @@ fn main() {
get_state,
save_workflows,
run_workflow,
open_settings
open_settings,
set_shortcut
])
.build(tauri::generate_context!())
.expect("error while running tauri application");
Expand All @@ -145,9 +183,11 @@ fn main() {
// Application is ready (triggered only once)
RunEvent::Ready => {
let app_handle = app_handle.clone();
let startup_shortcut = _get_state(app_handle.state::<AppState>()).shortcut;

app_handle
.global_shortcut_manager()
.register("Alt+m", move || {
.register(&startup_shortcut, move || {
open_omnibar(&app_handle).ok();
})
.expect("Couldn't create shortcut");
Expand Down
30 changes: 21 additions & 9 deletions src/Config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { invoke } from "@tauri-apps/api/tauri";
import { DevTool } from "@hookform/devtools";
import { useForm } from "react-hook-form";
import WorkflowArray from "./forms/workflow-array";
import { getConfig } from "./utils";
import { Commands, getConfig } from "./utils";
import Shortcut from "./components/Shortcut";

export type Workflow = {
name: string;
Expand All @@ -15,35 +16,40 @@ export type Workflow = {

export type Workflows = {
workflows: Workflow[];
shortcut: string;
};

export const defaultWorkflow = {
name: "",
steps: [{ value: "" }],
};
export async function getConfigAndSet(setData: (state: Workflows) => void) {
let state = await getConfig();
setData(state);
}

function Config() {
// const [pathFromFile, setPathFromFile] = useState<string | undefined>();
const [defaultValues, setDefaultValues] = useState<Workflows>({
workflows: [defaultWorkflow],
});
const [appConfig, setAppConfig] = useState<Workflows | undefined>();
const [defaultValues, setDefaultValues] = useState<Workflows | undefined>();
const { control, register, handleSubmit, getValues, setValue, reset } =
useForm<Workflows>({
defaultValues,
});

const onSubmit = (data: Workflows) => {
invoke("save_workflows", { config: data });
invoke(Commands.SaveWorkflows, { config: data });
};

useEffect(() => {
reset(defaultValues);
}, [defaultValues, reset]);

useEffect(() => {
async function setStoredConfigAsDefaults() {
let state = await getConfig();
setDefaultValues(state);
}
appConfig && setDefaultValues(appConfig);
}, [appConfig]);
const setStoredConfigAsDefaults = () => getConfigAndSet(setAppConfig);
useEffect(() => {
setStoredConfigAsDefaults();
}, []);

Expand Down Expand Up @@ -72,6 +78,12 @@ function Config() {
/>
<button type="submit">Save</button>
</form>
{appConfig && (
<Shortcut
onUpdate={setStoredConfigAsDefaults}
currentShortcut={appConfig.shortcut}
/>
)}
</header>
{/* <button type="button" onClick={addFilePath}>
Add file/program
Expand Down
11 changes: 3 additions & 8 deletions src/Omnibar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@ import { invoke } from "@tauri-apps/api/tauri";
import { appWindow } from "@tauri-apps/api/window";
import { useEffect, useState } from "react";
import { Action, Autocomplete } from "./components/Autocomplete";
import { getConfig } from "./utils";

enum AppEvents {
OmnibarFocused = "omnibar-focus",
AppStateUpdated = "state-updated",
}
import { AppEvents, Commands, getConfig } from "./utils";

const focusSearchBar = () => {
let input = document.querySelector(".aa-Input") as HTMLElement | null;
Expand Down Expand Up @@ -40,7 +35,7 @@ const Omnibar = () => {
}, []);

const handleRunWorkflow = async (label: string) => {
invoke("run_workflow", { label });
invoke(Commands.RunWorkflow, { label });
};

return (
Expand Down Expand Up @@ -85,7 +80,7 @@ const Omnibar = () => {
return item.label;
},
getItems({ state }: { state: any }) {
return [{ label: "Settings", action: "open_settings" }];
return [{ label: "Settings", action: Commands.OpenSettings }];
},
// Run this code when item is selected
onSelect(params: any) {
Expand Down
Loading

0 comments on commit b00e2e0

Please sign in to comment.