Skip to content

Commit

Permalink
feature: use setup hook and event handler to process app startup
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed Jun 16, 2024
1 parent f6f95b8 commit 6fcb85c
Show file tree
Hide file tree
Showing 8 changed files with 784 additions and 20 deletions.
634 changes: 632 additions & 2 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ unlicensed = "allow"
# [possible values: any SPDX 3.7 short identifier (+ optional exception)].
allow = [
"MIT",
"BSL-1.0", # Boost Software License 1.0, used by clipboard-win v5.3.1
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"Unicode-DFS-2016",
Expand Down
10 changes: 8 additions & 2 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ edition = "2021"
tauri-build = { version = "2.0.0-beta", features = [] }

[dependencies]
tauri = { version = "2.0.0-beta", features = [] }
tauri-plugin-shell = "2.0.0-beta"
anyhow = "1.0.86"
dirs = "5.0.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = { version = "2.0.0-beta", features = [] }
tauri-plugin-clipboard-manager = "2.1.0-beta"
tauri-plugin-log = { version = "2.0.0-beta", features = ["colored"] }
tauri-plugin-shell = "2.0.0-beta"
tauri-plugin-window-state = "2.0.0-beta"
tracing = { version = "0.1.40", features = ["log"] }
12 changes: 12 additions & 0 deletions src-tauri/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use crate::utils::app_dir;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
pub(crate) fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
pub(crate) fn get_app_dir() -> String {
app_dir().display().to_string()
}
86 changes: 86 additions & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
mod commands;
mod utils;

use commands::{get_app_dir, greet};
use tauri::{
webview::PageLoadPayload, App, Builder, Webview, WebviewUrl, WebviewWindowBuilder, Window,
WindowEvent, Wry,
};
use tauri_plugin_log::{Target, TargetKind};
use tracing::{debug, info};
use utils::log_dir;

pub fn app() -> anyhow::Result<Builder<Wry>> {
let builder = tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(logger().build())
.invoke_handler(tauri::generate_handler![greet, get_app_dir])
.setup(setup)
.on_page_load(page_load_handler)
.on_window_event(window_event_handler);
Ok(builder)
}

fn setup(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
info!("Setting up the app");

let handle = app.handle();

#[cfg(desktop)]
{
handle.plugin(tauri_plugin_window_state::Builder::default().build())?;
}

let mut builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::default());

#[cfg(desktop)]
{
builder = builder
.user_agent(&format!("Hn app - {}", std::env::consts::OS))
.title("Hacker News")
.inner_size(1200., 800.)
.min_inner_size(800., 600.)
.resizable(true)
.content_protected(true);
}

let webiview = builder.build()?;

#[cfg(debug_assertions)]
webiview.open_devtools();

// initialize updater..

Ok(())
}

// on_page_load is called when the webview is created.
fn page_load_handler(webview: &Webview, _payload: &PageLoadPayload<'_>) {
info!("Page loaded on {:?}", webview.label());
}

// signature: Fn(&Window<R>, &WindowEvent)
fn window_event_handler(window: &Window, event: &WindowEvent) {
debug!("Window event {:?} on {:?}", event, window.label());

if let WindowEvent::CloseRequested { api, .. } = event {
info!("Close requested on {:?}", window.label());
if window.label() == "main" {
api.prevent_close();
window.hide().unwrap()
}
}
}

fn logger() -> tauri_plugin_log::Builder {
tauri_plugin_log::Builder::default()
.targets([
Target::new(TargetKind::Webview),
Target::new(TargetKind::Folder {
path: log_dir(),
file_name: None,
}),
Target::new(TargetKind::Stdout),
])
.level(tracing::log::LevelFilter::Info)
}
15 changes: 6 additions & 9 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
use anyhow::Result;
use hn::app;

fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![greet])
fn main() -> Result<()> {
app()?
.run(tauri::generate_context!())
.expect("error while running tauri application");

Ok(())
}
38 changes: 38 additions & 0 deletions src-tauri/src/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use std::path::PathBuf;

const APP_DIR: &str = ".hn";
const LOG_DIR: &str = "log";
const CACHE_DIR: &str = "cache";
const DB_DIR: &str = "db";
const CONFIG_DIR: &str = "config";

#[allow(unused)]
#[inline]
pub(crate) fn app_dir() -> PathBuf {
dirs::home_dir()
.expect("failed to get home directory")
.join(APP_DIR)
}

#[inline]
pub(crate) fn log_dir() -> PathBuf {
app_dir().join(LOG_DIR)
}

#[allow(unused)]
#[inline]
pub(crate) fn cache_dir() -> PathBuf {
app_dir().join(CACHE_DIR)
}

#[allow(unused)]
#[inline]
pub(crate) fn db_dir() -> PathBuf {
app_dir().join(DB_DIR)
}

#[allow(unused)]
#[inline]
pub(crate) fn config_dir() -> PathBuf {
app_dir().join(CONFIG_DIR)
}
8 changes: 1 addition & 7 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"title": "hackernews",
"width": 1200,
"height": 800
}
],
"windows": [],
"security": {
"csp": null
}
Expand Down

0 comments on commit 6fcb85c

Please sign in to comment.