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
#[tauri::command]
pub fn process_wallpaper_image(file_path_string: String) -> Result<String, String> {
println!("{file_path_string}");
// convert the string to a path
let file_path = std::path::Path::new(&file_path_string);
// 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 {
ImageType::Jpeg => "jpeg".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}"))?;
// 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
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 setBackground = async () => {
const assetUrl = convertFileSrc("/home/vomitblood/.local/share/stort/wallpaper.jpeg");
const setBackground = async (filePath: string) => {
const assetUrl = convertFileSrc(filePath);
setImageUrl(assetUrl);
};
// useEffect(() => {
// if (settings.background.background_image_path) {
// setBackground(settings.background.background_image_path);
// }
// }, [settings.background.background_image_path]);
useEffect(() => {
setBackground(settings.background.background_image_path);
}, [settings.background.background_image_path]);
return (
<Box
key={imageUrl}
sx={{
// Use the URL function for background images
// backgroundColor: settings.background.background_color,
backgroundImage: `url(${imageUrl})`,
backgroundSize: "cover", // Cover the entire area
backgroundPosition: "center", // Center the image
backgroundRepeat: "no-repeat", // Do not repeat the image
backgroundColor: settings.background.background_color,
backgroundImage: settings.background.background_image_path ? `url(${imageUrl})` : "",
backgroundSize: "cover",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
display: "flex",
flexDirection: "column",
height: "100vh",
@ -46,8 +45,7 @@ export const Layout = () => {
<Box>
<Button
onClick={() => {
setBackground();
console.log("set background");
console.log(imageUrl);
}}
>
set background

View file

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

View file

@ -1,10 +1,11 @@
import { DeleteOutline, FileOpenOutlined } from "@mui/icons-material";
import { Box, Button, Stack, TextField } from "@mui/material";
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 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 { CategoryTitle } from "../CategoryTitle";
import { SettingsItem } from "../SettingsItem";
@ -14,9 +15,17 @@ interface SettingsTabBackgroundProps {
}
export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) => {
// contexts
const { settings, updateSettings } = useSettings();
// atoms
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 = (
settingKey: string,
settingValue: boolean | number | string | number[],
@ -29,10 +38,17 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
},
};
setStagedSettings(newSettings);
return newSettings;
};
const setImageSrc = async (filePath: string) => {
const assetUrl = convertFileSrc(filePath);
setImageUrl(assetUrl);
};
const selectImage = async () => {
const { basename } = await import("@tauri-apps/api/path");
const { appLocalDataDir, basename } = await import("@tauri-apps/api/path");
let selectedFilePath = await open({
multiple: false,
@ -50,14 +66,17 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
}
if (selectedFilePath) {
try {
// get the last filename from the path
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);
}
};
console.log(filename);
console.log(selectedFilePath);
// if there is already a wallpaper file, delete it
const clearImage = async () => {
if (stagedSettings.background.background_image_path) {
try {
await invoke("delete_old_wallpaper_image", {
@ -68,34 +87,74 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
}
}
const destinationFilePath = (await invoke("process_wallpaper_image", {
filePathString: selectedFilePath,
})) as string;
const newSettings = handleSettingsBackgroundValueChange("background_image_path", "");
handleSettingsBackgroundValueChange("background_image_path", destinationFilePath);
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 (settings.background.background_image_path) {
try {
await invoke("delete_old_wallpaper_image", {
filePathString: oldWallpaperPath,
});
} catch (error) {
console.error("deec nuts", error);
console.error("Failed to delete old wallpaper image", error);
}
}
} catch (error) {
console.error(error);
}
};
// TODO: implement
const clearImage = async () => {};
applyWallpaper();
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 (
<Box sx={{ sx }}>
<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
src="/wallpaper.jpg"
src={imageUrl || "oh no"}
alt="Image not found"
width={200}
height={200}
// fill the box r/catsareliquid
layout="fill"
objectFit="cover"
/>
</Box>
<Box
sx={{
mb: 2,
mt: 1,
}}
>
<Stack
@ -104,7 +163,9 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
>
<Button
color="primary"
onClick={selectImage}
onClick={() => {
selectImage().then(() => updateSettings(stagedSettings));
}}
startIcon={<FileOpenOutlined />}
size="small"
variant="outlined"
@ -142,6 +203,13 @@ export const SettingsTabBackground: FC<SettingsTabBackgroundProps> = ({ sx }) =>
/>
}
/>
<button
onClick={() => {
updateSettings(stagedSettings);
}}
>
apply
</button>
</Box>
);
};

View file

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

View file

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

View file

@ -30,7 +30,7 @@ export const readConfigFile = async (): Promise<SettingsType> => {
try {
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) {
existingData = data;
console.log("existing data");
@ -51,6 +51,6 @@ export const readConfigFile = async (): Promise<SettingsType> => {
export const writeConfigFile = async (settingsValues: SettingsType): Promise<void> => {
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.");
};

View file

@ -1,12 +1,9 @@
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";
import { SettingsItem } from "../components/HeaderBar/Settings/SettingsItem";
import { useSettings } from "../contexts/SettingsContext";
import { testing } from "../lib/testing";
export default function Testing() {
// contexts
@ -43,34 +40,12 @@ export default function Testing() {
</button>
<button
onClick={() => {
console.log(testing());
console.log(settings.background.background_image_path);
}}
>
testing
</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>
<SettingsItem
defaultText="#8ab4f8"