Skip to content

🆙 Upscayl - #1 Free and Open Source AI Image Upscaler for Linux, MacOS and Windows.

MOD: Refactor few codes; Suggestions

abhishek-gaonkar177b555a5550
diff --git a/electron/commands/paste-image.ts b/electron/commands/paste-image.ts
index 27aa9e5..1107647 100644
--- a/electron/commands/paste-image.ts
+++ b/electron/commands/paste-image.ts
@@ -1,63 +1,45 @@
import { getMainWindow } from "../main-window";
import logit from "../utils/logit";
import fs from "fs";
-import { tmpdir, homedir } from "os";
import path from "path";
import { ELECTRON_COMMANDS } from "../../common/electron-commands";
interface IClipboardFileParameters {
name: string;
+ path: string;
extension: string;
size: number;
type: string;
encodedBuffer: string;
}
-const createTempFileFromClipboard = (
- appFolderPrefix: string,
+const createTempFileFromClipboard = async (
inputFileParams: IClipboardFileParameters,
- onSuccessCallback: (inputFilePath: string, outputFilePath: string) => void,
- onErrorCallback: (error: Error) => void,
-) => {
- let tempDirectory = fs.mkdtempSync(path.join(tmpdir(), appFolderPrefix));
- let tempFilePath = path.join(tempDirectory, inputFileParams.name);
+): Promise<string> => {
+ const tempFilePath = path.join(inputFileParams.path, inputFileParams.name);
+ const buffer = Buffer.from(inputFileParams.encodedBuffer, "base64");
- fs.writeFile(
- tempFilePath,
- Buffer.from(inputFileParams.encodedBuffer, "base64"),
- (err) => {
- if (err) {
- onErrorCallback(new Error("No permission to temp folder"));
- return;
- }
- let homeDirectoryAsOutputFolder = homedir();
- onSuccessCallback(tempFilePath, homeDirectoryAsOutputFolder);
- },
- );
+ await fs.promises.writeFile(tempFilePath, buffer);
+ return tempFilePath;
};
-const pasteImage = (event, file: IClipboardFileParameters) => {
+const pasteImage = async (event, file: IClipboardFileParameters) => {
const mainWindow = getMainWindow();
if (!mainWindow) return;
if (!file || !file.name || !file.encodedBuffer) return;
- const appFolderPrefix = "upscayl";
- createTempFileFromClipboard(
- appFolderPrefix,
- file,
- (imageFilePath, homeDirectory) => {
- mainWindow.webContents.send(ELECTRON_COMMANDS.PASTE_IMAGE_SAVE_SUCCESS, [
- imageFilePath,
- homeDirectory,
- ]);
- },
- (error) => {
- logit(error.message);
- mainWindow.webContents.send(
- ELECTRON_COMMANDS.PASTE_IMAGE_SAVE_ERROR,
- error.message,
- );
- },
- );
+ try {
+ const imageFilePath = await createTempFileFromClipboard(file);
+ mainWindow.webContents.send(
+ ELECTRON_COMMANDS.PASTE_IMAGE_SAVE_SUCCESS,
+ imageFilePath,
+ );
+ } catch (error: any) {
+ logit(error.message);
+ mainWindow.webContents.send(
+ ELECTRON_COMMANDS.PASTE_IMAGE_SAVE_ERROR,
+ error.message,
+ );
+ }
};
export default pasteImage;
diff --git a/renderer/components/main-content/index.tsx b/renderer/components/main-content/index.tsx
index 216a689..e158abf 100644
--- a/renderer/components/main-content/index.tsx
+++ b/renderer/components/main-content/index.tsx
@@ -2,7 +2,7 @@
import useLogger from "../hooks/use-logger";
import { useState, useMemo, useEffect } from "react";
import { ELECTRON_COMMANDS } from "@common/electron-commands";
-import { useAtomValue, useSetAtom } from "jotai";
+import { useAtom, useAtomValue } from "jotai";
import {
batchModeAtom,
lensSizeAtom,
@@ -63,7 +63,7 @@ const MainContent = ({
const { toast } = useToast();
const version = useUpscaylVersion();
- const setOutputPath = useSetAtom(savedOutputPathAtom);
+ const [outputPath, setOutputPath] = useAtom(savedOutputPathAtom);
const progress = useAtomValue(progressAtom);
const batchMode = useAtomValue(batchModeAtom);
@@ -163,57 +163,66 @@ const MainContent = ({
};
const handlePaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
- resetImagePaths();
e.preventDefault();
- if (e.clipboardData.files.length) {
- const fileObject = e.clipboardData.files[0];
- const currentDate = new Date(Date.now());
- const currentTime = `${currentDate.getHours()}-${currentDate.getMinutes()}-${currentDate.getSeconds()}`;
- const fileName = `${currentTime}-${fileObject.name}`;
- const file = {
- name: fileName,
- extension: fileName.split(".").pop() as ImageFormat,
- size: fileObject.size,
- type: fileObject.type.split("/")[0],
- encodedBuffer: "",
- };
+ if (outputPath) {
+ resetImagePaths();
+ if (e.clipboardData.files.length) {
+ const fileObject = e.clipboardData.files[0];
+ const currentDate = new Date(Date.now());
+ const currentTime = `${currentDate.getHours()}-${currentDate.getMinutes()}-${currentDate.getSeconds()}`;
+ const fileName = `.temp-${currentTime}-${fileObject.name || "image"}`;
+ const file = {
+ name: fileName,
+ path: outputPath,
+ extension: fileName.split(".").pop() as ImageFormat,
+ size: fileObject.size,
+ type: fileObject.type.split("/")[0],
+ encodedBuffer: "",
+ };
- logit(
- "📋 Pasted file: ",
- JSON.stringify({
- type: file.type,
- name: file.name,
- extension: file.extension,
- }),
- );
+ logit(
+ "📋 Pasted file: ",
+ JSON.stringify({
+ name: file.name,
+ path: file.path,
+ extension: file.extension,
+ }),
+ );
- if (
- file.type === "image" &&
- VALID_IMAGE_FORMATS.includes(file.extension)
- ) {
- const reader = new FileReader();
- reader.onload = async (event) => {
- const result = event.target?.result;
- if (typeof result === "string") {
- file.encodedBuffer = Buffer.from(result, "utf-8").toString(
- "base64",
- );
- } else if (result instanceof ArrayBuffer) {
- file.encodedBuffer = Buffer.from(new Uint8Array(result)).toString(
- "base64",
- );
- } else {
- logit("🚫 Invalid file pasted");
- toast({
- title: t("ERRORS.INVALID_IMAGE_ERROR.TITLE"),
- description: t(
- "ERRORS.INVALID_IMAGE_ERROR.CLIPBOARD_DESCRIPTION",
- ),
- });
- }
- window.electron.send(ELECTRON_COMMANDS.PASTE_IMAGE, file);
- };
- reader.readAsArrayBuffer(fileObject);
+ if (
+ file.type === "image" &&
+ VALID_IMAGE_FORMATS.includes(file.extension)
+ ) {
+ const reader = new FileReader();
+ reader.onload = async (event) => {
+ const result = event.target?.result;
+ if (typeof result === "string") {
+ file.encodedBuffer = Buffer.from(result, "utf-8").toString(
+ "base64",
+ );
+ } else if (result instanceof ArrayBuffer) {
+ file.encodedBuffer = Buffer.from(new Uint8Array(result)).toString(
+ "base64",
+ );
+ } else {
+ logit("🚫 Invalid file pasted");
+ toast({
+ title: t("ERRORS.INVALID_IMAGE_ERROR.TITLE"),
+ description: t(
+ "ERRORS.INVALID_IMAGE_ERROR.CLIPBOARD_DESCRIPTION",
+ ),
+ });
+ }
+ window.electron.send(ELECTRON_COMMANDS.PASTE_IMAGE, file);
+ };
+ reader.readAsArrayBuffer(fileObject);
+ } else {
+ logit("🚫 Invalid file pasted");
+ toast({
+ title: t("ERRORS.INVALID_IMAGE_ERROR.TITLE"),
+ description: t("ERRORS.INVALID_IMAGE_ERROR.CLIPBOARD_DESCRIPTION"),
+ });
+ }
} else {
logit("🚫 Invalid file pasted");
toast({
@@ -222,45 +231,39 @@ const MainContent = ({
});
}
} else {
- logit("🚫 Invalid file pasted");
toast({
- title: t("ERRORS.INVALID_IMAGE_ERROR.TITLE"),
- description: t("ERRORS.INVALID_IMAGE_ERROR.CLIPBOARD_DESCRIPTION"),
+ title: t("ERRORS.NO_OUTPUT_FOLDER_ERROR.TITLE"),
+ description: t("ERRORS.NO_OUTPUT_FOLDER_ERROR.DESCRIPTION"),
});
}
};
useEffect(() => {
+ // Events
const handlePasteEvent = (e) => handlePaste(e);
+ const handlePasteImageSaveSuccess = (_: any, imageFilePath: string) => {
+ setImagePath(imageFilePath);
+ validateImagePath(imageFilePath);
+ };
+ const handlePasteImageSaveError = (_: any, error: string) => {
+ toast({
+ title: t("ERRORS.NO_IMAGE_ERROR.TITLE"),
+ description: error,
+ });
+ };
window.addEventListener("paste", handlePasteEvent);
window.electron.on(
ELECTRON_COMMANDS.PASTE_IMAGE_SAVE_SUCCESS,
- (_: any, output: string[]) => {
- let [imageFilePath, homeDirectory] = output;
- setImagePath(imageFilePath);
- var dirname = getDirectoryFromPath(homeDirectory, false);
- logit("🗂 Setting output path: ", dirname);
- if (!FEATURE_FLAGS.APP_STORE_BUILD) {
- if (!rememberOutputFolder) {
- setOutputPath(dirname);
- }
- }
- validateImagePath(imageFilePath);
- },
+ handlePasteImageSaveSuccess,
);
window.electron.on(
ELECTRON_COMMANDS.PASTE_IMAGE_SAVE_ERROR,
- (_: any, error: string) => {
- toast({
- title: t("ERRORS.NO_IMAGE_ERROR.TITLE"),
- description: error,
- });
- },
+ handlePasteImageSaveError,
);
return () => {
window.removeEventListener("paste", handlePasteEvent);
};
- }, [t]);
+ }, [t, outputPath]);
return (
<div
diff --git a/renderer/locales/en.json b/renderer/locales/en.json
index 02e6bd0..cad561d 100644
--- a/renderer/locales/en.json
+++ b/renderer/locales/en.json
@@ -193,6 +193,10 @@
"GENERIC_ERROR": {
"TITLE": "Error"
},
+ "NO_OUTPUT_FOLDER_ERROR": {
+ "TITLE": "Set Output Folder",
+ "DESCRIPTION": "Please select an output folder first"
+ },
"INVALID_IMAGE_ERROR": {
"TITLE": "Invalid Image",
"DESCRIPTION": "Please select/paste an image with a valid extension like PNG, JPG, JPEG, JFIF or WEBP.",
diff --git a/renderer/locales/es.json b/renderer/locales/es.json
index ae20c8c..bbd9c03 100644
--- a/renderer/locales/es.json
+++ b/renderer/locales/es.json
@@ -193,6 +193,10 @@
"GENERIC_ERROR": {
"TITLE": "Error"
},
+ "NO_OUTPUT_FOLDER_ERROR": {
+ "TITLE": "Establecer carpeta de salida",
+ "DESCRIPTION": "Por favor, selecciona primero una carpeta de salida"
+ },
"INVALID_IMAGE_ERROR": {
"TITLE": "Imagen inválida",
"DESCRIPTION": "Por favor, selecciona/pega una imagen con una extensión válida como PNG, JPG, JPEG, JFIF o WEBP.",
diff --git a/renderer/locales/fr.json b/renderer/locales/fr.json
index d1f75d1..6aea5ce 100644
--- a/renderer/locales/fr.json
+++ b/renderer/locales/fr.json
@@ -193,6 +193,10 @@
"GENERIC_ERROR": {
"TITLE": "Erreur"
},
+ "NO_OUTPUT_FOLDER_ERROR": {
+ "TITLE": "Définir le dossier de sortie",
+ "DESCRIPTION": "Veuillez d'abord sélectionner un dossier de sortie"
+ },
"INVALID_IMAGE_ERROR": {
"TITLE": "Image invalide",
"DESCRIPTION": "Veuillez sélectionner/coller une image avec une extension valide comme PNG, JPG, JPEG, JFIF ou WEBP.",
diff --git a/renderer/locales/ja.json b/renderer/locales/ja.json
index f60bb87..b385f78 100644
--- a/renderer/locales/ja.json
+++ b/renderer/locales/ja.json
@@ -193,6 +193,10 @@
"GENERIC_ERROR": {
"TITLE": "エラー"
},
+ "NO_OUTPUT_FOLDER_ERROR": {
+ "TITLE": "出力フォルダを設定",
+ "DESCRIPTION": "まず出力フォルダを選択してください"
+ },
"INVALID_IMAGE_ERROR": {
"TITLE": "無効な画像",
"DESCRIPTION": "PNG、JPG、JPEG、JFIF、または WEBP のような有効な拡張子の画像を選択/貼り付けてください。",
diff --git a/renderer/locales/ru.json b/renderer/locales/ru.json
index ecce345..ad03a22 100644
--- a/renderer/locales/ru.json
+++ b/renderer/locales/ru.json
@@ -193,6 +193,10 @@
"GENERIC_ERROR": {
"TITLE": "Ошибка"
},
+ "NO_OUTPUT_FOLDER_ERROR": {
+ "TITLE": "Установить папку вывода",
+ "DESCRIPTION": "Пожалуйста, сначала выберите папку вывода"
+ },
"INVALID_IMAGE_ERROR": {
"TITLE": "Неверное изображение",
"DESCRIPTION": "Пожалуйста, выберите/вставьте изображение с допустимым расширением, таким как PNG, JPG, JPEG, JFIF или WEBP.",
diff --git a/renderer/locales/zh.json b/renderer/locales/zh.json
index b8ea7b6..c2b715b 100644
--- a/renderer/locales/zh.json
+++ b/renderer/locales/zh.json
@@ -193,6 +193,10 @@
"GENERIC_ERROR": {
"TITLE": "错误"
},
+ "NO_OUTPUT_FOLDER_ERROR": {
+ "TITLE": "选择输出文件夹",
+ "DESCRIPTION": "请先选择一个输出文件夹"
+ },
"INVALID_IMAGE_ERROR": {
"TITLE": "图片无效",
"DESCRIPTION": "请选择/粘貼一个扩展名为 PNG、JPG、JPEG、JFIF 或 WEBP 的有效图片",