浏览代码

[feat](app) update UI components and add compression features

AkiraBit 2 月之前
父节点
当前提交
6f4a1d212b

+ 158 - 0
CONTRIBUTING.md

@@ -0,0 +1,158 @@
+<!-- omit in toc -->
+
+# Contributing to PicSharp
+
+First off, thanks for taking the time to contribute! ❤️
+
+All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉
+
+> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
+>
+> - Star the project
+> - Tweet about it
+> - Refer this project in your project's readme
+> - Mention the project at local meetups and tell your friends/colleagues
+
+<!-- omit in toc -->
+
+## Table of Contents
+
+- [I Have a Question](#i-have-a-question)
+  - [I Want To Contribute](#i-want-to-contribute)
+  - [Reporting Bugs](#reporting-bugs)
+  - [Suggesting Enhancements](#suggesting-enhancements)
+  - [Your First Code Contribution](#your-first-code-contribution)
+  - [Improving The Documentation](#improving-the-documentation)
+- [Styleguides](#styleguides)
+  - [Commit Messages](#commit-messages)
+- [Join The Project Team](#join-the-project-team)
+
+## I Have a Question
+
+> If you want to ask a question, we assume that you have read the available [Documentation](https://github.com/AkiraBit/PicSharp).
+
+Before you ask a question, it is best to search for existing [Issues](https://github.com/AkiraBit/PicSharp/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.
+
+If you then still feel the need to ask a question and need clarification, we recommend the following:
+
+- Open an [Issue](https://github.com/AkiraBit/PicSharp/issues/new).
+- Provide as much context as you can about what you're running into.
+- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant.
+
+We will then take care of the issue as soon as possible.
+
+<!--
+You might want to create a separate issue tag for questions and include it in this description. People should then tag their issues accordingly.
+
+Depending on how large the project is, you may want to outsource the questioning, e.g. to Stack Overflow or Gitter. You may add additional contact and information possibilities:
+- IRC
+- Slack
+- Gitter
+- Stack Overflow tag
+- Blog
+- FAQ
+- Roadmap
+- E-Mail List
+- Forum
+-->
+
+## I Want To Contribute
+
+> ### Legal Notice <!-- omit in toc -->
+>
+> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project licence.
+
+### Reporting Bugs
+
+<!-- omit in toc -->
+
+#### Before Submitting a Bug Report
+
+A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
+
+- Make sure that you are using the latest version.
+- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://github.com/AkiraBit/PicSharp). If you are looking for support, you might want to check [this section](#i-have-a-question)).
+- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/AkiraBit/PicSharp/issues?q=label%3Abug).
+- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue.
+- Collect information about the bug:
+  - Stack trace (Traceback)
+  - OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
+  - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant.
+  - Possibly your input and the output
+  - Can you reliably reproduce the issue? And can you also reproduce it with older versions?
+
+<!-- omit in toc -->
+
+#### How Do I Submit a Good Bug Report?
+
+> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to <fengyvxiu@gmail.com>.
+
+<!-- You may add a PGP key to allow the messages to be sent encrypted as well. -->
+
+We use GitHub issues to track bugs and errors. If you run into an issue with the project:
+
+- Open an [Issue](https://github.com/AkiraBit/PicSharp/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
+- Explain the behavior you would expect and the actual behavior.
+- Please provide as much context as possible and describe the _reproduction steps_ that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
+- Provide the information you collected in the previous section.
+
+Once it's filed:
+
+- The project team will label the issue accordingly.
+- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
+- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
+
+<!-- You might want to create an issue template for bugs and errors that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->
+
+### Suggesting Enhancements
+
+This section guides you through submitting an enhancement suggestion for PicSharp, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.
+
+<!-- omit in toc -->
+
+#### Before Submitting an Enhancement
+
+- Make sure that you are using the latest version.
+- Read the [documentation](https://github.com/AkiraBit/PicSharp) carefully and find out if the functionality is already covered, maybe by an individual configuration.
+- Perform a [search](https://github.com/AkiraBit/PicSharp/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
+- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
+
+<!-- omit in toc -->
+
+#### How Do I Submit a Good Enhancement Suggestion?
+
+Enhancement suggestions are tracked as [GitHub issues](https://github.com/AkiraBit/PicSharp/issues).
+
+- Use a **clear and descriptive title** for the issue to identify the suggestion.
+- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
+- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
+- You may want to **include screenshots or screen recordings** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [LICEcap](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and the built-in [screen recorder in GNOME](https://help.gnome.org/users/gnome-help/stable/screen-shot-record.html.en) or [SimpleScreenRecorder](https://github.com/MaartenBaert/ssr) on Linux. <!-- this should only be included if the project has a GUI -->
+- **Explain why this enhancement would be useful** to most PicSharp users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
+
+<!-- You might want to create an issue template for enhancement suggestions that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->
+
+### Your First Code Contribution
+
+<!-- TODO
+include Setup of env, IDE and typical getting started instructions?
+
+-->
+
+### Improving The Documentation
+
+<!-- TODO
+Updating, improving and correcting the documentation
+
+-->
+
+## Styleguides
+
+### Commit Messages
+
+<!-- TODO
+
+-->
+
+## Join The Project Team
+
+<!-- TODO -->

+ 62 - 1
README.md

@@ -14,7 +14,55 @@ A simple, efficient, and flexible cross-platform desktop image compression appli
 - **Windows:** Coming soon
 - **Linux:** Coming soon
 
-## Features
+## Key Features
+
+### Compress Localy & TinyPNG
+
+![Compress Localy & TinyPNG](./doc/Local-Compress&TinyPNG.png)
+
+### Powerful Batch Processing
+
+![Powerful Batch Processing](./doc/Powerful-Batch-Processing.png)
+
+### Watch Mode
+
+![Watch Mode](./doc/Watch-Mode.png)
+
+### Rich Configuration
+
+| **General**                | **Description**               | **Status** |
+| -------------------------- | ----------------------------- | ---------- |
+| **Internationalization**   | Partial support: zh-CN, en-US | ✅         |
+| **Dark/Light Theme**       | -                             | ✅         |
+| **System Notifications**   | -                             | ✅         |
+| **Startup on Boot**        | -                             | ✅         |
+| **Auto Check for Updates** | -                             | ✅         |
+
+---
+
+| **Compression**            | **Description**                                                                                                                                      | **Status** |
+| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
+| **Compression Mode**       | Default use Tinypng, if Tinypng compression fails, switch to local compression for retry.                                                            | ✅         |
+| **Compression Type**       | Optional lossless compression and lossy compression are available. When the image does not support lossless compression, switch to lossy compression | ✅         |
+| **Compression Level**      | Five levels can be selected. When using lossy compression, setting a reasonable compression level can achieve the best visual effect.                | ✅         |
+| **Save Type**              | How to save compressed images after compression.                                                                                                     | ✅         |
+| **Compression Rate Limit** | When the image compression rate is below the set threshold, saving will not be performed.                                                            | ✅         |
+
+---
+
+| **TinyPNG**             | **Description**                                                                                            | **Status** |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------- | ---------- |
+| **API Keys Management** | Manage multiple TinyPNG API keys and provide functions such as availability detection and usage monitoring | ✅         |
+| **Preserve Metadata**   | Select the metadata to preserve during compression.                                                        | ✅         |
+
+### Easy to use
+
+| **Feature**             | **Description**                              | **Status** |
+| ----------------------- | -------------------------------------------- | ---------- |
+| **FinderServices menu** | Use Finder Services menu to compress images. | ✅         |
+| **DeepLink**            | Use DeepLink to compress images.             | ✅         |
+
+## Summary
 
 - **Powerful Batch Processing:** Based on Rust implementation, it scans selected files or directories with high performance and low resource consumption, identifying and processing image files within them. Even 100,000+ images can be handled with ease.
 - **TinyPNG Integration:** Optional TinyPNG compression is available, with account pool management for automatic selection during task processing. Supported image formats: PNG/Animated PNG, JPEG, WebP, AVIF.
@@ -24,3 +72,16 @@ A simple, efficient, and flexible cross-platform desktop image compression appli
 - **Convenient Operations:** Drag and drop files into the application or onto the application icon for quick opening, select files or directories in Mac Finder and choose a compression method from the "Services" menu, and more.
 - **Rich Application Configuration:** Offers dark/light themes, multiple languages, system notifications, startup on boot, save methods for processed images, save locations, number of parallel tasks, and more.
 - **Open Integration:** Provides image compression invocation capabilities via DeepLink, allowing automation tools to call it and enhance your workflow.
+
+## Roadmap
+
+- [ ] Add Windows support
+- [ ] Add Linux support
+
+## Contributing
+
+If you want to help out please see [CONTRIBUTING.md](CONTRIBUTING.md) to see how to get started.
+
+## Support
+
+If you enjoy this project consider giving it a star ⭐.

+ 25 - 0
apps/picsharp-app/index.html

@@ -6,6 +6,31 @@
   <link rel="icon" type="image/png" href="public/logo.png" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>PicSharp</title>
+  <style>
+    html,
+    body,
+    #root{
+      height: 100%;
+      overflow: hidden;
+    }
+    html.dark {
+      background-color: rgb(25, 25, 25)!important;
+    }
+    html.light {
+      background: white!important;
+    }
+
+  </style>
+  <script>
+    const root = window.document.documentElement;
+    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
+    const currentTheme = localStorage.getItem('app-theme') || 'system';
+    if(currentTheme === 'system') {
+      root.classList.add(mediaQuery.matches ? 'dark' : 'light');
+    }else{
+      root.classList.add(currentTheme);
+    }
+  </script>
 </head>
 
 <body class="font-mono">

+ 2 - 0
apps/picsharp-app/src/components/layouts/app-layout.tsx

@@ -104,6 +104,7 @@ export default function AppLayout() {
         const paths = event.payload as string[];
         const hasSpawned = await spawnNewWindow('ns_compress', paths);
         if (!hasSpawned) {
+          getCurrentWebviewWindow().show();
           process('ns_compress', paths);
         }
       });
@@ -112,6 +113,7 @@ export default function AppLayout() {
         const paths = event.payload as string[];
         const hasSpawned = await spawnNewWindow('ns_watch_and_compress', paths);
         if (!hasSpawned) {
+          getCurrentWebviewWindow().show();
           process('ns_watch_and_compress', paths);
         }
       });

+ 1 - 1
apps/picsharp-app/src/components/layouts/sidebar-nav.tsx

@@ -80,7 +80,7 @@ export default function SidebarNav() {
   return (
     <TooltipProvider delayDuration={500}>
       <div
-        className='light:border-gray-200 flex h-screen w-[73px] flex-shrink-0 flex-col justify-between border-r bg-neutral-50 pb-4 pt-12 dark:bg-neutral-800'
+        className='light:border-gray-200 flex h-screen w-[67px] flex-shrink-0 flex-col justify-between border-r bg-neutral-50 pb-4 pt-12 dark:bg-neutral-800'
         data-tauri-drag-region='true'
       >
         <div className='flex flex-col items-center justify-center gap-2'>

+ 5 - 5
apps/picsharp-app/src/i18n/locales/en-US.ts

@@ -135,7 +135,7 @@ const enUS = {
   'settings.about.version.title': 'Current Version V{{version}}',
   // Settings.About.Version
   'settings.about.version.description':
-    'PicSharp is licensed under the <license>AGPL-3.0</license> License.',
+    'PicSharp is open source software released under the <license>AGPL-3.0</license> license.',
   'settings.about.version.check_update': 'Check Update',
   'settings.about.version.no_update_available': 'Current is the latest version',
   'settings.about.version.check_update_failed': 'Check Update Failed, Please Try Again',
@@ -153,12 +153,12 @@ const enUS = {
   'compression.file_action.copy_path': 'Copy File Path',
   'compression.file_action.copy_file': 'Copy File',
   'compression.file_action.delete_in_list': 'Remove from Current List',
-  'compression.toolbar.info.total_files': 'Number of Images',
+  'compression.toolbar.info.total_files': 'Total',
   'compression.toolbar.info.files_size': 'Storage Space',
   'compression.toolbar.info.saved_volume': 'Space Saved',
-  'compression.toolbar.info.saved_volume_rate': 'Compression Rate',
-  'compression.toolbar.info.total_original_size': 'Original Size',
-  'compression.toolbar.info.total_saved_volume': 'Space Reduced',
+  'compression.toolbar.info.saved_volume_rate': 'Reduced',
+  'compression.toolbar.info.total_original_size': 'Original',
+  'compression.toolbar.info.total_saved_volume': 'Compressed',
   processing: 'Processing',
   saving: 'Saving',
   compressed: 'Compressed',

+ 4 - 4
apps/picsharp-app/src/i18n/locales/zh-CN.ts

@@ -151,12 +151,12 @@ export default {
   'compression.file_action.copy_path': '复制路径',
   'compression.file_action.copy_file': '复制文件',
   'compression.file_action.delete_in_list': '从当前列表中删除',
-  'compression.toolbar.info.total_files': '图片数',
+  'compression.toolbar.info.total_files': '图片数',
   'compression.toolbar.info.files_size': '占用空间',
   'compression.toolbar.info.saved_volume': '节省空间',
-  'compression.toolbar.info.saved_volume_rate': '压缩率',
-  'compression.toolbar.info.total_original_size': '压缩前占用空间',
-  'compression.toolbar.info.total_saved_volume': '压缩后节省',
+  'compression.toolbar.info.saved_volume_rate': '减少',
+  'compression.toolbar.info.total_original_size': '压缩前',
+  'compression.toolbar.info.total_saved_volume': '压缩后',
   processing: '处理中',
   saving: '保存中',
   compressed: '压缩完成',

+ 1 - 1
apps/picsharp-app/src/index.css

@@ -23,7 +23,7 @@ body,
 #root{
   height: 100vh;
   overflow: hidden;
-  background: transparent;
+  /* background: transparent; */
   /* user-select: none; */
 }
 

+ 0 - 1
apps/picsharp-app/src/pages/compression/classic-file-manager.tsx

@@ -8,7 +8,6 @@ import { Empty } from 'antd';
 import { isValidArray, preventDefault } from '@/utils';
 import { useNavigate } from '@/hooks/useNavigate';
 import { useI18n } from '@/i18n';
-import { ScrollArea } from '@/components/ui/scroll-area';
 
 function FileManager() {
   const { files } = useCompressionStore(useSelector(['files']));

+ 15 - 11
apps/picsharp-app/src/pages/compression/toolbar-info.tsx

@@ -7,27 +7,31 @@ import { Info } from 'lucide-react';
 import { useI18n } from '@/i18n';
 import { humanSize } from '@/utils/fs';
 import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card';
+import { correctFloat } from '@/utils';
 
 const PopoverContent = () => {
   const { files } = useCompressionStore(useSelector(['files']));
   const t = useI18n();
 
-  // 压缩前文件总大小
-  const totalOriginalSize = files.reduce((acc, file) => {
-    return acc + file.bytesSize;
+  const originalSize = files.reduce((acc, file) => {
+    return acc + (file.bytesSize || 0);
   }, 0);
 
-  // 压缩后节省
-  const totalSavedVolume = files.reduce((acc, file) => {
+  const compressedSize = files.reduce((acc, file) => {
     if (file.compressedBytesSize) {
-      return acc + (file.bytesSize - file.compressedBytesSize);
+      return acc + (file.compressedBytesSize || 0);
     }
     return acc;
   }, 0);
 
-  // 压缩率
-  const compressRate =
-    totalSavedVolume > 0 ? ((totalSavedVolume / totalOriginalSize) * 100).toFixed(2) : '0';
+  const reducedSize = files.reduce((acc, file) => {
+    if (file.compressedBytesSize) {
+      return acc + ((file.bytesSize || 0) - (file.compressedBytesSize || 0));
+    }
+    return acc;
+  }, 0);
+
+  const compressRate = reducedSize > 0 ? correctFloat((reducedSize / originalSize) * 100, 1) : '0';
 
   return (
     <div className='flex items-center'>
@@ -38,12 +42,12 @@ const PopoverContent = () => {
       <Separator orientation='vertical' className='mx-6 h-[40px]' />
       <div className='flex flex-col items-center'>
         <div className='text-sm'>{t('compression.toolbar.info.total_original_size')}</div>
-        <div className='text-lg font-bold'>{humanSize(totalOriginalSize)}</div>
+        <div className='text-lg font-bold'>{humanSize(originalSize)}</div>
       </div>
       <Separator orientation='vertical' className='mx-6 h-[40px]' />
       <div className='flex flex-col items-center'>
         <div className='text-sm'>{t('compression.toolbar.info.total_saved_volume')}</div>
-        <div className='text-lg font-bold'>{humanSize(totalSavedVolume)}</div>
+        <div className='text-lg font-bold'>{humanSize(compressedSize)}</div>
       </div>
       <Separator orientation='vertical' className='mx-6 h-[40px]' />
       <div className='flex flex-col items-center'>

+ 67 - 0
apps/picsharp-app/src/utils/logger.ts

@@ -0,0 +1,67 @@
+import { isProd } from '.';
+import {
+  info as tauriInfo,
+  debug as tauriDebug,
+  trace as tauriTrace,
+  warn as tauriWarn,
+  error as tauriError,
+} from '@tauri-apps/plugin-log';
+
+interface Logger {
+  log: (message: string, ...args: unknown[]) => void;
+  info: (message: string, ...args: unknown[]) => void;
+  debug: (message: string, ...args: unknown[]) => void;
+  trace: (message: string, ...args: unknown[]) => void;
+  warn: (message: string, ...args: unknown[]) => void;
+  error: (message: string, ...args: unknown[]) => void;
+}
+
+const devLogger: Logger = {
+  log: console.log,
+  info: console.info,
+  debug: console.debug,
+  trace: console.trace,
+  warn: console.warn,
+  error: console.error,
+};
+
+const prodLogger: Logger = {
+  log: (message, ...args) => {
+    tauriInfo(formatMessage(message, args));
+    console.log(message, ...args);
+  },
+  info: (message, ...args) => {
+    tauriInfo(formatMessage(message, args));
+    console.info(message, ...args);
+  },
+  debug: (message, ...args) => {
+    tauriDebug(formatMessage(message, args));
+    console.debug(message, ...args);
+  },
+  trace: (message, ...args) => {
+    tauriTrace(formatMessage(message, args));
+    console.trace(message, ...args);
+  },
+  warn: (message, ...args) => {
+    tauriWarn(formatMessage(message, args));
+    console.warn(message, ...args);
+  },
+  error: (message, ...args) => {
+    tauriError(formatMessage(message, args));
+    console.error(message, ...args);
+  },
+};
+
+function formatMessage(message: string, args: unknown[]): string {
+  if (args.length === 0) {
+    return message;
+  }
+  try {
+    return `${message} ${args.map((arg) => (typeof arg === 'object' && arg !== null ? JSON.stringify(arg) : String(arg))).join(' ')}`;
+  } catch (e) {
+    // Fallback for circular structures or other stringify errors
+    return `${message} ${args.map((arg) => String(arg)).join(' ')}`;
+  }
+}
+
+export const logger: Logger = isProd ? prodLogger : devLogger;

二进制
doc/Local-Compress&TinyPNG.png


二进制
doc/Powerful-Batch-Processing.png


二进制
doc/Watch-Mode.png


+ 5 - 1
packages/picsharp-sidecar/src/controllers/compress/jpeg.ts

@@ -75,7 +75,11 @@ app.post('/', zValidator('json', PayloadSchema), async (context) => {
   options = OptionsSchema.parse(options);
   process_options = ProcessOptionsSchema.parse(process_options);
   const originalSize = await getFileSize(input_path);
-  const compressedImageBuffer = await sharp(input_path).jpeg(process_options).toBuffer();
+  const compressedImageBuffer = await sharp(input_path, {
+    limitInputPixels: false,
+  })
+    .jpeg(process_options)
+    .toBuffer();
   const compressedSize = compressedImageBuffer.byteLength;
   const compressionRate = calCompressionRate(originalSize, compressedSize);
   const availableCompressRate = compressionRate >= (options.limit_compress_rate || 0);

+ 5 - 1
packages/picsharp-sidecar/src/controllers/compress/png.ts

@@ -69,7 +69,11 @@ app.post('/', zValidator('json', PayloadSchema), async (context) => {
   options = OptionsSchema.parse(options);
   process_options = ProcessOptionsSchema.parse(process_options);
   const originalSize = await getFileSize(input_path);
-  const compressedImageBuffer = await sharp(input_path).png(process_options).toBuffer();
+  const compressedImageBuffer = await sharp(input_path, {
+    limitInputPixels: false,
+  })
+    .png(process_options)
+    .toBuffer();
   const compressedSize = compressedImageBuffer.byteLength;
   const compressionRate = calCompressionRate(originalSize, compressedSize);
   const availableCompressRate = compressionRate >= (options.limit_compress_rate || 0);