improvements to background setting logic

This commit is contained in:
Vomitblood 2024-08-09 18:58:19 +08:00
parent 205b0e593c
commit 2337661fed
8 changed files with 126 additions and 72 deletions

View file

@ -11,11 +11,13 @@ enum ImageType {
/// function to interface with the tauri api on the javascript side /// function to interface with the tauri api on the javascript side
#[tauri::command] #[tauri::command]
pub fn process_wallpaper_image(file_path_string: String) -> Result<String, String> { pub fn process_wallpaper_image(file_path_string: String) -> Result<String, String> {
println!("{file_path_string}");
// convert the string to a path // convert the string to a path
let file_path = std::path::Path::new(&file_path_string); let file_path = std::path::Path::new(&file_path_string);
// determine the image type and get the file extension // determine the image type and get the file extension
let file_extension = match determine_image_type(file_path) { match determine_image_type(file_path) {
Ok(image_type) => match image_type { Ok(image_type) => match image_type {
ImageType::Jpeg => "jpeg".to_string(), ImageType::Jpeg => "jpeg".to_string(),
ImageType::Png => "png".to_string(), ImageType::Png => "png".to_string(),
@ -33,7 +35,7 @@ pub fn process_wallpaper_image(file_path_string: String) -> Result<String, Strin
.map_err(|e| format!("Failed to get app data directory: {e}"))?; .map_err(|e| format!("Failed to get app data directory: {e}"))?;
// construct the destination path // construct the destination path
let destination_path = app_data_dir.join(format!("wallpaper.{}", file_extension)); let destination_path = app_data_dir.join(file_path.file_name().unwrap());
// move the file to the destination // move the file to the destination
crate::fs::copy_file(file_path, &destination_path, true) crate::fs::copy_file(file_path, &destination_path, true)

View file

@ -10,26 +10,25 @@ export const Layout = () => {
const [imageUrl, setImageUrl] = useState<string | null>(null); const [imageUrl, setImageUrl] = useState<string | null>(null);
const setBackground = async () => { const setBackground = async (filePath: string) => {
const assetUrl = convertFileSrc("/home/vomitblood/.local/share/stort/wallpaper.jpeg"); const assetUrl = convertFileSrc(filePath);
setImageUrl(assetUrl); setImageUrl(assetUrl);
}; };
// useEffect(() => { useEffect(() => {
// if (settings.background.background_image_path) { setBackground(settings.background.background_image_path);
// setBackground(settings.background.background_image_path); }, [settings.background.background_image_path]);
// }
// }, [settings.background.background_image_path]);
return ( return (
<Box <Box
key={imageUrl}
sx={{ sx={{
// Use the URL function for background images // Use the URL function for background images
// backgroundColor: settings.background.background_color, backgroundColor: settings.background.background_color,
backgroundImage: `url(${imageUrl})`, backgroundImage: settings.background.background_image_path ? `url(${imageUrl})` : "",
backgroundSize: "cover", // Cover the entire area backgroundSize: "cover",
backgroundPosition: "center", // Center the image backgroundPosition: "center",
backgroundRepeat: "no-repeat", // Do not repeat the image backgroundRepeat: "no-repeat",
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
height: "100vh", height: "100vh",
@ -46,8 +45,7 @@ export const Layout = () => {
<Box> <Box>
<Button <Button
onClick={() => { onClick={() => {
setBackground(); console.log(imageUrl);
console.log("set background");
}} }}
> >
set background set background

View file

@ -40,6 +40,12 @@ export const Settings = () => {
setSubTabValue(newTabValue); setSubTabValue(newTabValue);
}; };
// set staged settings back to current settings on cancel
const cancelClickEvent = () => {
setStagedSettings(settings);
setSettingsOpenState(false);
};
const applyClickEvent = () => { const applyClickEvent = () => {
setApplyLoading(true); setApplyLoading(true);
@ -57,9 +63,10 @@ export const Settings = () => {
closeSettings(); closeSettings();
}; };
// set staged settings back to current settings on close
useEffect(() => { useEffect(() => {
setStagedSettings(settings); if (!settingsOpenState) setStagedSettings(settings);
}, [setStagedSettings, settings]); }, [settingsOpenState]);
return ( return (
<FloatingDialog <FloatingDialog
@ -152,7 +159,7 @@ export const Settings = () => {
}} }}
> >
<Button <Button
onClick={() => setSettingsOpenState(false)} onClick={cancelClickEvent}
size="small" size="small"
sx={{ sx={{
mr: 1, mr: 1,

View file

@ -1,10 +1,11 @@
import { DeleteOutline, FileOpenOutlined } from "@mui/icons-material"; import { DeleteOutline, FileOpenOutlined } from "@mui/icons-material";
import { Box, Button, Stack, TextField } from "@mui/material"; import { Box, Button, Stack, TextField } from "@mui/material";
import { open } from "@tauri-apps/api/dialog"; import { open } from "@tauri-apps/api/dialog";
import { invoke } from "@tauri-apps/api/tauri"; import { convertFileSrc, invoke } from "@tauri-apps/api/tauri";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import Image from "next/image"; import Image from "next/image";
import { FC } from "react"; import { FC, useEffect, useState } from "react";
import { useSettings } from "../../../../contexts/SettingsContext";
import { stagedSettingsAtom } from "../../../../lib/store/jotai/settings"; import { stagedSettingsAtom } from "../../../../lib/store/jotai/settings";
import { CategoryTitle } from "../CategoryTitle"; import { CategoryTitle } from "../CategoryTitle";
import { SettingsItem } from "../SettingsItem"; import { SettingsItem } from "../SettingsItem";
@ -14,9 +15,17 @@ interface SettingsTabBackgroundProps {
} }
export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) => { export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) => {
// contexts
const { settings, updateSettings } = useSettings();
// atoms // atoms
const [stagedSettings, setStagedSettings] = useAtom(stagedSettingsAtom); const [stagedSettings, setStagedSettings] = useAtom(stagedSettingsAtom);
// states
const [oldWallpaperPath, setOldWallpaperPath] = useState<string | null>(null);
const [targetWallpaperPath, setTargetWallpaperPath] = useState<string | null>(null);
const [imageUrl, setImageUrl] = useState<string | null>(null);
const handleSettingsBackgroundValueChange = ( const handleSettingsBackgroundValueChange = (
settingKey: string, settingKey: string,
settingValue: boolean | number | string | number[], settingValue: boolean | number | string | number[],
@ -29,10 +38,17 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
}, },
}; };
setStagedSettings(newSettings); setStagedSettings(newSettings);
return newSettings;
};
const setImageSrc = async (filePath: string) => {
const assetUrl = convertFileSrc(filePath);
setImageUrl(assetUrl);
}; };
const selectImage = async () => { const selectImage = async () => {
const { basename } = await import("@tauri-apps/api/path"); const { appLocalDataDir, basename } = await import("@tauri-apps/api/path");
let selectedFilePath = await open({ let selectedFilePath = await open({
multiple: false, multiple: false,
@ -50,52 +66,95 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
} }
if (selectedFilePath) { if (selectedFilePath) {
setTargetWallpaperPath(selectedFilePath);
// construct the destination file path
const appLocalDataDirPath = await appLocalDataDir();
const filename = await basename(selectedFilePath);
const destinationFilePath = appLocalDataDirPath + filename;
handleSettingsBackgroundValueChange("background_image_path", destinationFilePath);
}
};
const clearImage = async () => {
if (stagedSettings.background.background_image_path) {
try { try {
// get the last filename from the path await invoke("delete_old_wallpaper_image", {
const filename = await basename(selectedFilePath); filePathString: stagedSettings.background.background_image_path,
});
} catch (error) {
console.error("Failed to delete old wallpaper image", error);
}
}
console.log(filename); const newSettings = handleSettingsBackgroundValueChange("background_image_path", "");
console.log(selectedFilePath);
updateSettings(newSettings);
};
// if settings.background.background_image_path changes, update the image
useEffect(() => {
const applyWallpaper = async () => {
try {
await invoke("process_wallpaper_image", {
filePathString: targetWallpaperPath,
});
// if there is already a wallpaper file, delete it // if there is already a wallpaper file, delete it
if (stagedSettings.background.background_image_path) { if (settings.background.background_image_path) {
try { try {
await invoke("delete_old_wallpaper_image", { await invoke("delete_old_wallpaper_image", {
filePathString: stagedSettings.background.background_image_path, filePathString: oldWallpaperPath,
}); });
} catch (error) { } catch (error) {
console.error("Failed to delete old wallpaper image", error); console.error("Failed to delete old wallpaper image", error);
} }
} }
const destinationFilePath = (await invoke("process_wallpaper_image", {
filePathString: selectedFilePath,
})) as string;
handleSettingsBackgroundValueChange("background_image_path", destinationFilePath);
} catch (error) { } catch (error) {
console.error("deec nuts", error); console.error(error);
} }
} };
};
// TODO: implement applyWallpaper();
const clearImage = async () => {};
setOldWallpaperPath(settings.background.background_image_path);
}, [settings.background.background_image_path]);
// update the preview image when stagedSettings.background.background_image_path changes
// useEffect(() => {
// if (stagedSettings.background.background_image_path) {
// setImageSrc(stagedSettings.background.background_image_path);
// } else {
// setImageUrl(null);
// }
// }, [stagedSettings.background.background_image_path]);
return ( return (
<Box sx={{ sx }}> <Box sx={{ sx }}>
<CategoryTitle title="Wallpaper" /> <CategoryTitle title="Wallpaper" />
<Box> <Box
sx={{
position: "relative",
// dynamic width based on the parent container
width: "100%",
// 3:2 aspect ratio (2/3 = 66.67%) qwuik mafs
paddingBottom: "66.67%",
// Hide overflow to maintain aspect ratio
overflow: "hidden",
borderRadius: "8px", // Optional: rounded corners
}}
>
<Image <Image
src="/wallpaper.jpg" src={imageUrl || "oh no"}
alt="Image not found" alt="Image not found"
width={200} // fill the box r/catsareliquid
height={200} layout="fill"
objectFit="cover"
/> />
</Box> </Box>
<Box <Box
sx={{ sx={{
mb: 2, mb: 2,
mt: 1,
}} }}
> >
<Stack <Stack
@ -104,7 +163,9 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
> >
<Button <Button
color="primary" color="primary"
onClick={selectImage} onClick={() => {
selectImage().then(() => updateSettings(stagedSettings));
}}
startIcon={<FileOpenOutlined />} startIcon={<FileOpenOutlined />}
size="small" size="small"
variant="outlined" variant="outlined"
@ -142,6 +203,13 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
/> />
} }
/> />
<button
onClick={() => {
updateSettings(stagedSettings);
}}
>
apply
</button>
</Box> </Box>
); );
}; };

View file

@ -24,6 +24,8 @@ export const SettingsTabStyle: FC<SettingsTabStyleProps> = ({ sx }) => {
}, },
}; };
setStagedSettings(newSettings); setStagedSettings(newSettings);
return newSettings;
}; };
return ( return (

View file

@ -22,6 +22,8 @@ export const SettingsTabWindow: FC<SettingsTabWindowProps> = ({ sx }) => {
}, },
}; };
setStagedSettings(newSettings); setStagedSettings(newSettings);
return newSettings;
}; };
return ( return (

View file

@ -30,7 +30,7 @@ export const readConfigFile = async (): Promise<SettingsType> => {
try { try {
const { appConfigDir } = await import("@tauri-apps/api/path"); const { appConfigDir } = await import("@tauri-apps/api/path");
const data = await readTomlFile<SettingsType>(appConfigDir() + "/config.toml"); const data = await readTomlFile<SettingsType>((await appConfigDir()) + "/config.toml");
if (data) { if (data) {
existingData = data; existingData = data;
console.log("existing data"); console.log("existing data");
@ -51,6 +51,6 @@ export const readConfigFile = async (): Promise<SettingsType> => {
export const writeConfigFile = async (settingsValues: SettingsType): Promise<void> => { export const writeConfigFile = async (settingsValues: SettingsType): Promise<void> => {
const { appConfigDir } = await import("@tauri-apps/api/path"); const { appConfigDir } = await import("@tauri-apps/api/path");
await writeTomlFile<SettingsType>(appConfigDir() + "/config.toml", settingsValues); await writeTomlFile<SettingsType>((await appConfigDir()) + "/config.toml", settingsValues);
console.debug("Settings file written successfully."); console.debug("Settings file written successfully.");
}; };

View file

@ -1,12 +1,9 @@
import { BugReport } from "@mui/icons-material"; import { BugReport } from "@mui/icons-material";
import { Box, IconButton, TextField, Typography } from "@mui/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 { useRouter } from "next/router";
import { useState } from "react"; import { useState } from "react";
import { SettingsItem } from "../components/HeaderBar/Settings/SettingsItem"; import { SettingsItem } from "../components/HeaderBar/Settings/SettingsItem";
import { useSettings } from "../contexts/SettingsContext"; import { useSettings } from "../contexts/SettingsContext";
import { testing } from "../lib/testing";
export default function Testing() { export default function Testing() {
// contexts // contexts
@ -43,34 +40,12 @@ export default function Testing() {
</button> </button>
<button <button
onClick={() => { onClick={() => {
console.log(testing()); console.log(settings.background.background_image_path);
}} }}
> >
testing testing
</button> </button>
<button
onClick={async () => {
console.log(await appDataDir());
}}
>
log appdatadir
</button>
<button
onClick={async () => {
const bruh = settings.background.background_image_path;
console.log(bruh);
try {
await invoke("delete_old_wallpaper_image", {
filePathString: "/home/vomitblood/.local/share/stort/wallpaper.jpeg",
});
} catch (error) {
console.error("deec nuts", error);
}
}}
>
invoke tauri shit
</button>
<Typography>{text}</Typography> <Typography>{text}</Typography>
<SettingsItem <SettingsItem
defaultText="#8ab4f8" defaultText="#8ab4f8"