feat: Switch to tauri_specta events and statics

This commit is contained in:
LynithDev 2024-07-29 13:51:53 +02:00
parent 95f6bf9d87
commit ca636e65c0
13 changed files with 167 additions and 141 deletions

View file

@ -31,8 +31,6 @@ fn main() {
"random_mods",
"get_mod",
"download_mod",
// Other
"get_program_info",
]),
),
)

View file

@ -32,7 +32,4 @@ permissions = [
"allow-random-mods",
"allow-get-mod",
"allow-download-mod",
# Other
"allow-get-program-info",
]

View file

@ -15,12 +15,7 @@ use uuid::Uuid;
macro_rules! collect_commands {
() => {{
use $crate::api::commands::*;
tauri_specta::ts::builder()
.config(
specta::ts::ExportConfig::default()
.bigint(specta::ts::BigIntExportBehavior::BigInt),
)
.commands(tauri_specta::collect_commands![
tauri_specta::collect_commands![
// User
auth_login,
get_users,
@ -47,9 +42,7 @@ macro_rules! collect_commands {
random_mods,
get_mod,
download_mod,
// Other
get_program_info,
])
]
}};
}
@ -175,33 +168,6 @@ pub async fn set_settings(settings: Settings) -> Result<(), String> {
Ok(settings::set(settings).await?)
}
#[derive(Serialize, Deserialize, Type)]
pub struct ProgramInfo {
launcher_version: String,
webview_version: String,
tauri_version: String,
dev_build: bool,
platform: String,
arch: String,
}
#[specta::specta]
#[tauri::command]
pub fn get_program_info() -> ProgramInfo {
let webview_version = tauri::webview_version().unwrap_or("UNKNOWN".into());
let tauri_version = tauri::VERSION;
let dev_build = tauri::is_dev();
ProgramInfo {
launcher_version: VERSION.into(),
webview_version,
tauri_version: tauri_version.into(),
dev_build,
platform: TARGET_OS.into(),
arch: NATIVE_ARCH.into(),
}
}
#[specta::specta]
#[tauri::command]
pub async fn get_users() -> Result<Vec<MinecraftCredentials>, String> {

View file

@ -0,0 +1,14 @@
#[macro_export]
macro_rules! collect_events {
() => {{
use onelauncher::api::proxy::*;
tauri_specta::collect_events![
ClusterPayload,
IngressPayload,
MessagePayload,
ProcessPayload,
InternetPayload,
OfflinePayload,
]
}}
}

View file

@ -5,6 +5,8 @@ use tauri::Manager;
use tokio::sync::Mutex;
pub mod commands;
pub mod events;
pub mod statics;
pub fn init<R: tauri::Runtime>() -> TauriPlugin<R> {
tauri::plugin::Builder::new("onelauncher")

View file

@ -0,0 +1,35 @@
use serde::Serialize;
use specta::Type;
use tauri_specta::StaticCollection;
use onelauncher::constants::*;
pub fn get_static_collection() -> StaticCollection {
StaticCollection::default()
.register("PROGRAM_INFO", get_program_info())
.to_owned()
}
#[derive(Serialize, Type)]
pub struct ProgramInfo {
launcher_version: String,
webview_version: String,
tauri_version: String,
dev_build: bool,
platform: String,
arch: String,
}
fn get_program_info() -> ProgramInfo {
let webview_version = tauri::webview_version().unwrap_or("UNKNOWN".into());
let tauri_version = tauri::VERSION;
let dev_build = tauri::is_dev();
ProgramInfo {
launcher_version: VERSION.into(),
webview_version,
tauri_version: tauri_version.into(),
dev_build,
platform: TARGET_OS.into(),
arch: NATIVE_ARCH.into(),
}
}

View file

@ -1,3 +1,4 @@
use api::statics::get_static_collection;
use tauri::Manager;
pub mod api;
@ -36,6 +37,23 @@ pub async fn run() {
}
pub async fn run_app<F: FnOnce(&mut tauri::App) + Send + 'static>(setup: F) {
let (invoke_handler, register_events) = {
let builder = tauri_specta::ts::builder()
.config(
specta::ts::ExportConfig::default()
.bigint(specta::ts::BigIntExportBehavior::BigInt)
)
.header("// @ts-ignore")
.statics(get_static_collection())
.commands(collect_commands!())
.events(collect_events!());
#[cfg(debug_assertions)]
let builder = builder.path("../frontend/src/bindings.ts");
builder.build().unwrap()
};
let builder = tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
@ -48,21 +66,15 @@ pub async fn run_app<F: FnOnce(&mut tauri::App) + Send + 'static>(setup: F) {
.plugin(ext::updater::plugin())
.manage(ext::updater::State::default())
// .plugin(tauri_plugin_window_state::Builder::default().build())
.plugin(api::init())
.menu(tauri::menu::Menu::new)
.invoke_handler(invoke_handler)
.setup(move |app| {
register_events(app);
setup(app);
Ok(())
});
let builder = builder.plugin(api::init()).invoke_handler({
let builder = collect_commands!();
#[cfg(debug_assertions)]
let builder = builder.path("../frontend/src/bindings.ts");
builder.build().unwrap()
});
let app = builder
.build(tauri::tauri_build_context!())
.expect("failed to build tauri application");

View file

@ -10,17 +10,13 @@ import UpdatesPage from './ui/pages/Updates';
import ClusterRoot from '~ui/pages/cluster/ClusterRoot';
import SettingsRoot from '~ui/pages/settings/SettingsRoot';
import BrowserRoot from '~ui/pages/browser/BrowserRoot';
import { initAppInfo } from '~utils/program-info';
(async () => {
await initAppInfo();
render(() => (
<Router root={App}>
<Route path="/" component={HomePage} />
<Route path="/updates" component={UpdatesPage} />
<Route path="/clusters" component={ClusterRoot} children={<ClusterRoot.Routes />} />
<Route path="/settings" component={SettingsRoot} children={<SettingsRoot.Routes />} />
<Route path="/browser" component={BrowserRoot} children={<BrowserRoot.Routes />} />
</Router>
), document.getElementById('root') as HTMLElement);
})();
render(() => (
<Router root={App}>
<Route path="/" component={HomePage} />
<Route path="/updates" component={UpdatesPage} />
<Route path="/clusters" component={ClusterRoot} children={<ClusterRoot.Routes />} />
<Route path="/settings" component={SettingsRoot} children={<SettingsRoot.Routes />} />
<Route path="/browser" component={BrowserRoot} children={<BrowserRoot.Routes />} />
</Router>
), document.getElementById('root') as HTMLElement);

View file

@ -9,10 +9,10 @@ import { SettingsProvider } from './hooks/useSettings';
import { ClusterModalController } from './components/overlay/cluster/ClusterCreationModal';
import { MultiProvider } from './components/MultiProvider';
import { AccountControllerProvider } from './components/overlay/account/AddAccountModal';
import { AppInfo } from '~utils/program-info';
import { PROGRAM_INFO } from '~bindings';
function App(props: ParentProps) {
if (AppInfo.dev_build !== true)
if (PROGRAM_INFO.dev_build !== true)
document.addEventListener('contextmenu', (event) => {
event.preventDefault();
});

View file

@ -13,7 +13,7 @@ import SettingsChangelog from './about/SettingsChangelog';
import AnimatedRoutes from '~ui/components/AnimatedRoutes';
import ErrorBoundary from '~ui/components/ErrorBoundary';
import Tooltip from '~ui/components/base/Tooltip';
import { AppInfo } from '~utils/program-info';
import { PROGRAM_INFO } from '~bindings';
function SettingsRoutes() {
return (
@ -91,11 +91,11 @@ function Info() {
}}
>
{`
Launcher Version: ${AppInfo.launcher_version}
Tauri Version: ${AppInfo.tauri_version}
Webview Version: ${AppInfo.webview_version}
Platform: ${AppInfo.platform} ${AppInfo.arch} bit
Build: ${AppInfo.dev_build ? 'dev' : 'release'}
Launcher Version: ${PROGRAM_INFO.launcher_version}
Tauri Version: ${PROGRAM_INFO.tauri_version}
Webview Version: ${PROGRAM_INFO.webview_version}
Platform: ${PROGRAM_INFO.platform} ${PROGRAM_INFO.arch} bit
Build: ${PROGRAM_INFO.dev_build ? 'dev' : 'release'}
`.trim()}
</div>
</Tooltip>

View file

@ -1,23 +0,0 @@
import type { ProgramInfo } from '~bindings';
import { bridge } from '~imports';
// eslint-disable-next-line import/no-mutable-exports -- because yes
export let AppInfo: ProgramInfo = {
launcher_version: 'err',
tauri_version: 'err',
webview_version: 'err',
platform: 'err',
arch: 'err',
dev_build: false,
};
export default AppInfo;
export async function initAppInfo() {
try {
AppInfo = await bridge.commands.getProgramInfo();
}
catch (err) {
console.error(err);
}
}

View file

@ -142,6 +142,7 @@ impl ProxyState {
}
}
#[cfg_attr(feature = "specta", derive(specta::Type))]
#[derive(Serialize, Deserialize, Clone, Debug, Hash, PartialEq, Eq)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
@ -184,6 +185,7 @@ pub enum IngressType {
},
}
#[cfg_attr(feature = "tauri", derive(specta::Type, tauri_specta::Event))]
#[derive(Serialize, Clone)]
pub struct IngressPayload {
pub event: IngressType,
@ -192,16 +194,19 @@ pub struct IngressPayload {
pub message: String,
}
#[cfg_attr(feature = "tauri", derive(specta::Type, tauri_specta::Event))]
#[derive(Serialize, Clone)]
pub struct OfflinePayload {
pub offline: bool,
}
#[cfg_attr(feature = "tauri", derive(specta::Type, tauri_specta::Event))]
#[derive(Serialize, Clone)]
pub struct MessagePayload {
pub message: String,
}
#[cfg_attr(feature = "tauri", derive(specta::Type, tauri_specta::Event))]
#[derive(Serialize, Clone)]
#[serde(tag = "event")]
pub enum InternetPayload {
@ -210,6 +215,7 @@ pub enum InternetPayload {
InstallPath { path: PathBuf },
}
#[cfg_attr(feature = "tauri", derive(specta::Type, tauri_specta::Event))]
#[derive(Serialize, Clone)]
pub struct ProcessPayload {
pub uuid: Uuid,
@ -218,6 +224,7 @@ pub struct ProcessPayload {
pub message: String,
}
#[cfg_attr(feature = "specta", derive(specta::Type))]
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ProcessPayloadType {
@ -226,6 +233,7 @@ pub enum ProcessPayloadType {
Finished,
}
#[cfg_attr(feature = "tauri", derive(specta::Type, tauri_specta::Event))]
#[derive(Serialize, Clone)]
pub struct ClusterPayload {
pub uuid: Uuid,
@ -235,6 +243,7 @@ pub struct ClusterPayload {
pub event: ClusterPayloadType,
}
#[cfg_attr(feature = "specta", derive(specta::Type))]
#[derive(Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ClusterPayloadType {

View file

@ -1,12 +1,16 @@
use super::IngressId;
use crate::api::proxy::{
use crate::{api::proxy::{
ClusterPayloadType, Ingress, IngressType, InternetPayload, ProcessPayloadType, ProxyError,
};
#[cfg(feature = "cli")]
use crate::constants::CLI_TOTAL_INGRESS;
}, proxy::OfflinePayload};
use crate::store::{ClusterPath, IngressProcessType, IngressProcessor};
use uuid::Uuid;
#[cfg(feature = "cli")]
use crate::constants::CLI_TOTAL_INGRESS;
#[cfg(feature = "tauri")]
use tauri_specta::Event;
#[cfg(feature = "tauri")]
use crate::api::proxy::{ClusterPayload, IngressPayload, MessagePayload, ProcessPayload};
@ -131,11 +135,12 @@ pub async fn send_ingress(
.set_position((display * CLI_TOTAL_INGRESS as f64).round() as u64);
}
#[cfg(feature = "tauri")]
proxy_state
.app
.emit(
"ingress",
IngressPayload::NAME,
IngressPayload {
fraction: display_conv,
message: message.unwrap_or(&ingress.message).to_string(),
@ -144,6 +149,12 @@ pub async fn send_ingress(
},
)
.map_err(ProxyError::from)?;
// let _ = IngressPayload {
// fraction: display_conv,
// message: message.unwrap_or(&ingress.message).to_string(),
// event: ingress.ingress_type.clone(),
// ingress_uuid: ingress.ingress_uuid,
// }.emit(proxy_state.app.app_handle());
ingress.last_sent = display;
}
@ -155,15 +166,9 @@ pub async fn send_message(message: &str) -> crate::Result<()> {
#[cfg(feature = "tauri")]
{
let proxy_state = crate::ProxyState::get().await?;
proxy_state
.app
.emit(
"message",
MessagePayload {
message: message.to_string(),
},
)
.map_err(ProxyError::from)?;
MessagePayload {
message: message.to_string(),
}.emit(proxy_state.app.app_handle())?;
}
tracing::warn!("{}", message);
@ -174,10 +179,11 @@ pub async fn send_offline(offline: bool) -> crate::Result<()> {
#[cfg(feature = "tauri")]
{
let proxy_state = crate::ProxyState::get().await?;
proxy_state
.app
.emit("offline", offline)
.map_err(ProxyError::from)?;
// proxy_state
// .app
// .emit("offline", offline)
// .map_err(ProxyError::from)?;
OfflinePayload { offline }.emit(proxy_state.app.app_handle())?;
}
Ok(())
@ -188,10 +194,11 @@ pub async fn send_internet(internet: InternetPayload) -> crate::Result<()> {
#[cfg(feature = "tauri")]
{
let proxy_state = crate::ProxyState::get().await?;
proxy_state
.app
.emit("internet", internet)
.map_err(ProxyError::from)?;
// proxy_state
// .app
// .emit("internet", internet)
// .map_err(ProxyError::from)?;
internet.emit(proxy_state.app.app_handle())?;
}
Ok(())
@ -206,18 +213,24 @@ pub async fn send_process(
#[cfg(feature = "tauri")]
{
let proxy_state = crate::ProxyState::get().await?;
proxy_state
.app
.emit(
"process",
ProcessPayload {
uuid,
pid,
event,
message: message.to_string(),
},
)
.map_err(ProxyError::from)?;
// proxy_state
// .app
// .emit(
// "process",
// ProcessPayload {
// uuid,
// pid,
// event,
// message: message.to_string(),
// },
// )
// .map_err(ProxyError::from)?;
ProcessPayload {
uuid,
pid,
event,
message: message.to_string(),
}.emit(proxy_state.app.app_handle())?;
}
Ok(())
@ -233,19 +246,26 @@ pub async fn send_cluster(
{
let path = cluster_path.full_path().await?;
let proxy_state = crate::ProxyState::get().await?;
proxy_state
.app
.emit(
"cluster",
ClusterPayload {
uuid,
cluster_path: cluster_path.clone(),
path,
name: name.to_string(),
event,
},
)
.map_err(ProxyError::from)?;
// proxy_state
// .app
// .emit(
// "cluster",
// ClusterPayload {
// uuid,
// cluster_path: cluster_path.clone(),
// path,
// name: name.to_string(),
// event,
// },
// )
// .map_err(ProxyError::from)?;
ClusterPayload {
uuid,
cluster_path: cluster_path.clone(),
path,
name: name.to_string(),
event,
}.emit(proxy_state.app.app_handle())?;
}
Ok(())