moved initialization logic to rust backend

This commit is contained in:
Vomitblood 2024-08-08 19:56:46 +08:00
parent a379f74616
commit 205b0e593c
21 changed files with 166 additions and 216 deletions

View file

@ -0,0 +1,2 @@
pub const APP_NAME: &str = "stort";
pub const APP_TITLE: &str = "Stort";

View file

@ -104,3 +104,8 @@ pub fn delete_file(file_path: &std::path::Path) -> std::io::Result<()> {
))
}
}
pub fn create_directory(directory_path: &std::path::Path) -> std::io::Result<()> {
// attempt to create the directory
std::fs::create_dir_all(directory_path)
}

View file

@ -0,0 +1,11 @@
pub fn initialize_directories() {
// getting the directories will also create them if they dont exist
// get the app data directory
crate::paths::get_app_data_dir().expect("Failed to get or create app data directory");
// get the app cache directory
crate::paths::get_app_data_dir().expect("Failed to get or create app data directory");
// get the app config directory
crate::paths::get_app_data_dir().expect("Failed to get or create app data directory");
}

View file

@ -1,3 +1,6 @@
pub mod constants;
pub mod fs;
pub mod initialize;
pub mod paths;
pub mod tauri;
pub mod wallpaper;

View file

@ -2,11 +2,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
app::wallpaper::process_wallpaper_image,
app::wallpaper::delete_old_wallpaper_image,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
app::initialize::initialize_directories();
app::tauri::run_tauri_app();
}

View file

@ -2,7 +2,7 @@ pub fn get_app_data_dir() -> Result<std::path::PathBuf, String> {
// attempt to get the app data directory
match tauri::api::path::data_dir() {
Some(data_dir) => {
let app_data_dir = data_dir.join("stort/");
let app_data_dir = data_dir.join(crate::constants::APP_NAME);
// ensure the directory exists
if !app_data_dir.exists() {
// attempt to create the directory
@ -18,3 +18,45 @@ pub fn get_app_data_dir() -> Result<std::path::PathBuf, String> {
None => Err("Failed to get app data directory".to_string()),
}
}
pub fn get_app_cache_dir() -> Result<std::path::PathBuf, String> {
// attempt to get the app cache directory
match tauri::api::path::cache_dir() {
Some(cache_dir) => {
let app_cache_dir = cache_dir.join(crate::constants::APP_NAME);
// ensure the directory exists
if !app_cache_dir.exists() {
// attempt to create the directory
std::fs::create_dir_all(&app_cache_dir).map_err(|e| {
format!(
"Failed to create app cache directory {:?}: {}",
app_cache_dir, e
)
})?;
}
Ok(app_cache_dir)
}
None => Err("Failed to get app cache directory".to_string()),
}
}
pub fn get_app_config_dir() -> Result<std::path::PathBuf, String> {
// attempt to get the app config directory
match tauri::api::path::config_dir() {
Some(config_dir) => {
let app_config_dir = config_dir.join(crate::constants::APP_NAME);
// ensure the directory exists
if !app_config_dir.exists() {
// attempt to create the directory
std::fs::create_dir_all(&app_config_dir).map_err(|e| {
format!(
"Failed to create app config directory {:?}: {}",
app_config_dir, e
)
})?;
}
Ok(app_config_dir)
}
None => Err("Failed to get app config directory".to_string()),
}
}

9
src-tauri/src/tauri.rs Normal file
View file

@ -0,0 +1,9 @@
pub fn run_tauri_app() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
crate::wallpaper::process_wallpaper_image,
crate::wallpaper::delete_old_wallpaper_image,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View file

@ -22,7 +22,8 @@
"**/*",
"/**/*",
"$CONFIG/stort/",
"$CONFIG/stort/**"
"$CONFIG/stort/**",
"$HOME/.local/share/stort/*"
]
},
"notification": {
@ -38,9 +39,7 @@
"all": true,
"asset": true,
"assetScope": [
"**",
"**/*",
"/**/*"
"$APPDATA/*"
]
},
"window": {
@ -62,7 +61,7 @@
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "com.vomitblood.stort",
"identifier": "stort",
"longDescription": "Launcher for Steam Deck",
"resources": [],
"shortDescription": "Launcher for Steam Deck",

View file

@ -1,57 +0,0 @@
import { Settings } from "@mui/icons-material";
import { Box, Stack } from "@mui/material";
import { useRouter } from "next/router";
import { WindowButtons } from "./HeaderBar/WindowButtons";
export const FooterBar = () => {
return (
<Box
className="titlebar"
data-tauri-drag-region="true"
sx={{
alignItems: "center",
backdropFilter: "blur(10px)",
backgroundColor: "rgba(0, 0, 0, 0.5)",
display: "flex",
flexDirection: "row",
height: "48px",
justifyContent: "space-between",
p: 1,
}}
>
<Box
className="titlebar"
data-tauri-drag-region="true"
sx={{
alignItems: "center",
display: "flex",
flexDirection: "row",
}}
>
hello this is the left side
</Box>
<Box
className="titlebar"
data-tauri-drag-region="true"
sx={{
alignItems: "center",
display: "flex",
flexDirection: "row",
}}
>
<Stack
direction="row"
spacing={2}
sx={{
alignItems: "center",
display: "flex",
flexDirection: "row",
}}
>
<Settings />
<WindowButtons />
</Stack>
</Box>
</Box>
);
};

View file

@ -0,0 +1,56 @@
import { Settings } from "@mui/icons-material";
import { Box, Stack } from "@mui/material";
import { WindowButtons } from "../HeaderBar/WindowButtons";
export const FooterBar = () => {
return (
<Box
className="titlebar"
data-tauri-drag-region="true"
sx={{
alignItems: "center",
backdropFilter: "blur(10px)",
backgroundColor: "rgba(0, 0, 0, 0.5)",
display: "flex",
flexDirection: "row",
height: "48px",
justifyContent: "space-between",
p: 1,
}}
>
<Box
className="titlebar"
data-tauri-drag-region="true"
sx={{
alignItems: "center",
display: "flex",
flexDirection: "row",
}}
>
hello this is the left side
</Box>
<Box
className="titlebar"
data-tauri-drag-region="true"
sx={{
alignItems: "center",
display: "flex",
flexDirection: "row",
}}
>
<Stack
direction="row"
spacing={2}
sx={{
alignItems: "center",
display: "flex",
flexDirection: "row",
}}
>
<Settings />
<WindowButtons />
</Stack>
</Box>
</Box>
);
};

View file

@ -1,34 +0,0 @@
import { createDir, exists } from "@tauri-apps/api/fs";
import { useEffect } from "react";
import { useSettings } from "../../contexts/SettingsContext";
import Paths from "../../lib/path";
export const Initialization = () => {
const { settings, settingsLoading } = useSettings();
useEffect(() => {
const initializePaths = async () => {
try {
await Paths.initialize();
} catch (error) {
console.error(`Failed to initialize paths: ${error}`);
}
};
const createDirectories = async () => {
const configDirectoryExists = await exists(Paths.getPath("configDirectory"));
if (!configDirectoryExists) await createDir(Paths.getPath("configDirectory"));
};
const fullscreen = async () => {
const { appWindow } = await import("@tauri-apps/api/window");
await appWindow.setFullscreen(true);
};
initializePaths().then(() => createDirectories());
// TODO: race condition here, need to wait for settings to load
if (settings.window.start_fullscreen) fullscreen();
}, [settingsLoading]);
return null;
};

View file

@ -1,9 +1,9 @@
import { Box, Button } from "@mui/material";
import { convertFileSrc } from "@tauri-apps/api/tauri";
import { useState } from "react";
import { FooterBar } from "../FooterBar";
import { HeaderBar } from "../HeaderBar/HeaderBar";
import { useEffect, useState } from "react";
import { useSettings } from "../../contexts/SettingsContext";
import { FooterBar } from "../FooterBar/FooterBar";
import { HeaderBar } from "../HeaderBar/HeaderBar";
export const Layout = () => {
const { settings } = useSettings();
@ -11,15 +11,21 @@ export const Layout = () => {
const [imageUrl, setImageUrl] = useState<string | null>(null);
const setBackground = async () => {
const assetUrl = convertFileSrc("/home/vomitblood/Downloads/toothless-dance.gif");
const assetUrl = convertFileSrc("/home/vomitblood/.local/share/stort/wallpaper.jpeg");
setImageUrl(assetUrl);
};
// useEffect(() => {
// if (settings.background.background_image_path) {
// setBackground(settings.background.background_image_path);
// }
// }, [settings.background.background_image_path]);
return (
<Box
sx={{
// Use the URL function for background images
backgroundColor: settings.background.background_color,
// backgroundColor: settings.background.background_color,
backgroundImage: `url(${imageUrl})`,
backgroundSize: "cover", // Cover the entire area
backgroundPosition: "center", // Center the image
@ -41,6 +47,7 @@ export const Layout = () => {
<Button
onClick={() => {
setBackground();
console.log("set background");
}}
>
set background

View file

@ -7,9 +7,9 @@ import { useEffect, useState } from "react";
import { useSettings } from "../../../contexts/SettingsContext";
import { stagedSettingsAtom } from "../../../lib/store/jotai/settings";
import { FloatingDialog } from "../../Generic/FloatingDialog";
import { SettingsTabBackground } from "./SettingsTabs/SettingsTabBackground";
import { SettingsTabStyle } from "./SettingsTabs/SettingsTabStyle";
import { SettingsTabWindow } from "./SettingsTabs/SettingsTabWindow";
import { SettingsTabBackground } from "./SettingsTabs/SettingsTabBackground";
export const Settings = () => {
// contexts

View file

@ -8,7 +8,6 @@ import { FC } from "react";
import { stagedSettingsAtom } from "../../../../lib/store/jotai/settings";
import { CategoryTitle } from "../CategoryTitle";
import { SettingsItem } from "../SettingsItem";
import Path from "../../../../lib/path";
interface SettingsTabBackgroundProps {
sx?: any;

View file

@ -1,9 +1,9 @@
import { Close, CloseFullscreen, Minimize } from "@mui/icons-material";
import { Box, Button, ButtonGroup, IconButton, Stack, useTheme } from "@mui/material";
import { Box, IconButton, Stack, useTheme } from "@mui/material";
import { exit } from "@tauri-apps/api/process";
import { WebviewWindow } from "@tauri-apps/api/window";
import { useEffect, useState } from "react";
import { useSettings } from "../../contexts/SettingsContext";
import { exit } from "@tauri-apps/api/process";
export const WindowButtons = () => {
// contexts

View file

@ -9,9 +9,7 @@ export default function createEmotionCache() {
let insertionPoint;
if (isBrowser) {
const emotionInsertionPoint = document.querySelector<HTMLMetaElement>(
'meta[name="emotion-insertion-point"]',
);
const emotionInsertionPoint = document.querySelector<HTMLMetaElement>('meta[name="emotion-insertion-point"]');
insertionPoint = emotionInsertionPoint ?? undefined;
}

View file

@ -29,9 +29,7 @@ export class LogcatServiceClass {
log(message: string, level: LogLevel = "INFO"): void {
const currentTimestamp = new Date().getTime();
const timeSinceLastLog = this.lastLogTimestamp
? currentTimestamp - this.lastLogTimestamp
: 0;
const timeSinceLastLog = this.lastLogTimestamp ? currentTimestamp - this.lastLogTimestamp : 0;
const logEntry: LogEntry = { message, level, timestamp: timeSinceLastLog };
this.logs.push(logEntry);

View file

@ -1,88 +0,0 @@
type PathsType = {
audioDirectory: string;
cacheDirectory: string;
configDirectory: string;
dataDirectory: string;
desktopDirectory: string;
documentDirectory: string;
downloadDirectory: string;
executableDirectory: string;
fontDirectory: string;
homeDirectory: string;
logDirectory: string;
pictureDirectory: string;
templateDirectory: string;
videoDirectory: string;
};
const programTrailingPath = "stort/";
class Paths {
private static instance: Paths;
paths: PathsType | null = null;
private constructor() {}
static getInstance(): Paths {
if (!Paths.instance) {
Paths.instance = new Paths();
}
return Paths.instance;
}
async initialize(): Promise<void> {
// avoid reinitialization if already doen
if (this.paths) return;
const {
audioDir,
cacheDir,
configDir,
dataDir,
desktopDir,
documentDir,
downloadDir,
executableDir,
fontDir,
homeDir,
logDir,
pictureDir,
templateDir,
videoDir,
} = await import("@tauri-apps/api/path");
try {
this.paths = {
audioDirectory: await audioDir(),
cacheDirectory: (await cacheDir()) + programTrailingPath,
configDirectory: (await configDir()) + programTrailingPath,
dataDirectory: (await dataDir()) + programTrailingPath,
desktopDirectory: await desktopDir(),
documentDirectory: await documentDir(),
downloadDirectory: await downloadDir(),
executableDirectory: await executableDir(),
fontDirectory: await fontDir(),
homeDirectory: await homeDir(),
logDirectory: await logDir(),
pictureDirectory: await pictureDir(),
templateDirectory: await templateDir(),
videoDirectory: await videoDir(),
};
// make paths immutable
Object.freeze(this.paths);
} catch (error) {
console.error("Error initializing paths:", error);
throw error;
}
}
getPath(key: keyof PathsType): string {
if (!this.paths) {
throw new Error("Paths are not initialized. Call initialize() first.");
}
return this.paths[key];
}
}
export default Paths.getInstance();

View file

@ -1,5 +1,4 @@
import { merge } from "lodash";
import Paths from "./path";
import { readTomlFile, writeTomlFile } from "./utils/toml";
export const defaultSettings = {
@ -30,9 +29,8 @@ export const readConfigFile = async (): Promise<SettingsType> => {
let existingData: SettingsType = defaultSettings;
try {
// try to read the config file
await Paths.initialize();
const data = await readTomlFile<SettingsType>(Paths.getPath("configDirectory") + "config.toml");
const { appConfigDir } = await import("@tauri-apps/api/path");
const data = await readTomlFile<SettingsType>(appConfigDir() + "/config.toml");
if (data) {
existingData = data;
console.log("existing data");
@ -52,6 +50,7 @@ export const readConfigFile = async (): Promise<SettingsType> => {
};
export const writeConfigFile = async (settingsValues: SettingsType): Promise<void> => {
await writeTomlFile<SettingsType>(Paths.getPath("configDirectory") + "config.toml", settingsValues);
const { appConfigDir } = await import("@tauri-apps/api/path");
await writeTomlFile<SettingsType>(appConfigDir() + "/config.toml", settingsValues);
console.debug("Settings file written successfully.");
};

View file

@ -2,7 +2,6 @@ import { CacheProvider, EmotionCache } from "@emotion/react";
import { CssBaseline } from "@mui/material";
import { AppProps } from "next/app";
import Head from "next/head";
import { Initialization } from "../components/Generic/Initialization";
import { UserThemeProvider } from "../contexts/ThemeContext";
import createEmotionCache from "../lib/createEmotionCache";
import "../styles/global.css";
@ -22,14 +21,13 @@ export default function MyApp(props: MyAppProps) {
<Head>
<title>Stort</title>
<meta
name='viewport'
content='initial-scale=1, width=device-width'
name="viewport"
content="initial-scale=1, width=device-width"
/>
</Head>
<SettingsProvider>
<UserThemeProvider>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<Initialization />
<CssBaseline />
<Component {...pageProps} />
</UserThemeProvider>

View file

@ -1,5 +1,6 @@
import { BugReport } from "@mui/icons-material";
import { Box, IconButton, TextField, Typography } from "@mui/material";
import { appDataDir } from "@tauri-apps/api/path";
import { invoke } from "@tauri-apps/api/tauri";
import { useRouter } from "next/router";
import { useState } from "react";
@ -47,6 +48,13 @@ export default function Testing() {
>
testing
</button>
<button
onClick={async () => {
console.log(await appDataDir());
}}
>
log appdatadir
</button>
<button
onClick={async () => {
const bruh = settings.background.background_image_path;