diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 54fbd36..6e794b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,9 @@ jobs: - name: Run ESLint run: yarn lint + - name: Run frontend tests + run: yarn test + - name: Build frontend run: yarn build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d80bbdd..c4c7779 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,6 +44,7 @@ jobs: yarn install --immutable yarn format:check yarn lint + yarn test yarn build - name: Install Rust toolchain diff --git a/README.md b/README.md index 7d1b9f7..e19c760 100644 --- a/README.md +++ b/README.md @@ -32,10 +32,10 @@ Built with [Tauri v2](https://v2.tauri.app/) (Rust `1.100.1`), [Vite](https://vi ## Features -- Parallel multi-core native streaming hashing in Rust (with SIMD-accelerated BLAKE3, CRC32, and XXH3-64), real-time progress bar, mid-calculation cancellation, and post-calculation file size/speed stats -- Case-insensitive hash comparison with match/mismatch banners, live hash-length hints, and disabled-algorithm warnings +- Parallel multi-core native streaming hashing in Rust with pipelined I/O (including slice-by-16 CRC8/CRC16/CRC24, hardware-accelerated SHA-1/SHA-2, and SIMD-accelerated BLAKE3, CRC32, and XXH3-64), completed-bytes progress bar, mid-calculation cancellation for files and text, and post-calculation file size/speed stats +- Case-insensitive hash comparison (normalizing optional `0x` prefixes and whitespace/colon separators) with match/mismatch banners, live hash-length hints, recalculate hints, and disabled-algorithm warnings - One-click VirusTotal lookup for calculated file hashes (using SHA-256, SHA-1, or MD5) -- Native file picker, window drag-and-drop, one-click Copy all, uppercase/lowercase hash output toggle, and CSV/JSON/HTML/TXT export +- Native file picker, window drag-and-drop, one-click Copy all, uppercase/lowercase hash output toggle, and atomic CSV/JSON/HTML/TXT export - Automatic system Light/Dark theme detection with manual override - Persistent navigation sidebar, optional page headers, and configurable header shortcuts for theme switching and language selection - Localized in 11 languages (Deutsch, English, Español, Français, Italiano, 日本語, Nederlands, Português, Русский, Türkçe, Українська) @@ -104,10 +104,16 @@ You can also trigger the **Release** workflow manually via GitHub Actions (`work ```shell yarn lint yarn format:check -cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings +yarn test +cargo fmt --manifest-path src-tauri/Cargo.toml --all -- --check +cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings -D dead_code cargo test --manifest-path src-tauri/Cargo.toml ``` +## AI Disclosure + +AI tools may be used in this project to assist with translations, code refactoring and generating commit messages. All changes are reviewed and verified before being committed. + ## About This project is maintained by CodeDead. You can find more about us using the following links: diff --git a/docs/help.odt b/docs/help.odt index 00e06f7..bdcd95c 100644 Binary files a/docs/help.odt and b/docs/help.odt differ diff --git a/docs/help.pdf b/docs/help.pdf index 659c9a4..d34596c 100644 Binary files a/docs/help.pdf and b/docs/help.pdf differ diff --git a/eslint.config.js b/eslint.config.js index 152d91d..1f6c731 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -17,6 +17,7 @@ export default [ globals: { ...globals.browser, ...globals.es2026, + __APP_VERSION__: 'readonly', }, parserOptions: { ecmaFeatures: { @@ -36,7 +37,7 @@ export default [ }, }, { - files: ['*.config.js'], + files: ['*.config.js', 'tests/**/*.js'], languageOptions: { globals: { ...globals.node, diff --git a/package.json b/package.json index 940ac22..a4457e1 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "tauri:build": "tauri build", "lint": "eslint .", "lint:fix": "eslint . --fix", + "test": "node --test", "format": "prettier --write .", "format:check": "prettier --check ." }, diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 72a12dd..bab0a02 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -735,6 +735,7 @@ dependencies = [ "crc", "crc32fast", "digest", + "libc", "md-5", "md4", "ripemd", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 0a0a602..5b9caff 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -36,6 +36,9 @@ blake2 = "0.11.0" blake3 = "1.8.9" twox-hash = { version = "2.1.5", default-features = false, features = ["std", "xxhash3_64"] } +[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies] +libc = "0.2" + [profile.dev.package.md4] opt-level = 3 diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index e209241..47e1c52 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -7,7 +7,6 @@ "permissions": [ "core:default", "dialog:allow-open", - "dialog:allow-save", "opener:default", "os:default" ] diff --git a/src-tauri/gen/schemas/capabilities.json b/src-tauri/gen/schemas/capabilities.json index 1410a1c..36e1a41 100644 --- a/src-tauri/gen/schemas/capabilities.json +++ b/src-tauri/gen/schemas/capabilities.json @@ -1 +1 @@ -{"default":{"identifier":"default","description":"Capability for the main window","local":true,"windows":["main"],"permissions":["core:default","dialog:allow-open","dialog:allow-save","opener:default","os:default"],"platforms":["linux","macOS","windows"]}} \ No newline at end of file +{"default":{"identifier":"default","description":"Capability for the main window","local":true,"windows":["main"],"permissions":["core:default","dialog:allow-open","opener:default","os:default"],"platforms":["linux","macOS","windows"]}} \ No newline at end of file diff --git a/src-tauri/src/hasher.rs b/src-tauri/src/hasher.rs index 04dd9ec..0023064 100644 --- a/src-tauri/src/hasher.rs +++ b/src-tauri/src/hasher.rs @@ -1,16 +1,16 @@ -use std::fs::File; +use std::fs::{File, OpenOptions}; use std::hash::Hasher as _; use std::io::{self, Read}; use std::path::Path; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc; use std::thread; use std::time::{Duration, Instant}; use blake2::{Blake2b512, Blake2s256}; use blake3::Hasher as Blake3Hasher; -use crc::{CRC_8_SMBUS, CRC_16_ARC, CRC_24_OPENPGP, Crc}; +use crc::{CRC_8_SMBUS, CRC_16_ARC, CRC_24_OPENPGP, Crc, Table}; use crc32fast::Hasher as Crc32Hasher; use digest::Digest; use md4::Md4; @@ -22,12 +22,15 @@ use sha2::{Sha224, Sha256, Sha384, Sha512}; use sha3::{Sha3_256, Sha3_512}; use twox_hash::XxHash3_64; -const CRC8: Crc = Crc::::new(&CRC_8_SMBUS); -const CRC16: Crc = Crc::::new(&CRC_16_ARC); -const CRC24: Crc = Crc::::new(&CRC_24_OPENPGP); +const CRC8: Crc> = Crc::>::new(&CRC_8_SMBUS); +const CRC16: Crc> = Crc::>::new(&CRC_16_ARC); +const CRC24: Crc> = Crc::>::new(&CRC_24_OPENPGP); const CHUNK_SIZE: usize = 2 * 1024 * 1024; +const SUB_CHUNK_SIZE: usize = 64 * 1024; const PARALLEL_THRESHOLD: u64 = 4 * 1024 * 1024; +const SINGLE_PIPELINE_THRESHOLD: u64 = 8 * 1024 * 1024; +const FAST_PARALLEL_THRESHOLD: u64 = 16 * 1024 * 1024; const CHANNEL_DEPTH: usize = 2; const PROGRESS_INTERVAL: Duration = Duration::from_millis(50); @@ -146,14 +149,37 @@ enum SingleHasher { Blake2s256(Box), Blake3(Box), Crc1(u8), - Crc8(crc::Digest<'static, u8>), - Crc16(crc::Digest<'static, u16>), - Crc24(crc::Digest<'static, u32>), + Crc8(crc::Digest<'static, u8, Table<16>>), + Crc16(crc::Digest<'static, u16, Table<16>>), + Crc24(crc::Digest<'static, u32, Table<16>>), Crc32(Crc32Hasher), Xxh3_64(Box), } impl SingleHasher { + fn relative_cost(&self) -> u32 { + match self { + Self::Sha3_512(_) => 6, + Self::Ripemd160(_) => 5, + Self::Sha3_256(_) => 4, + Self::Sha224(_) | Self::Sha256(_) => 3, + Self::Sha384(_) + | Self::Sha512(_) + | Self::Sha1(_) + | Self::Md5(_) + | Self::Blake2s256(_) => 2, + Self::Md4(_) + | Self::Blake2b512(_) + | Self::Blake3(_) + | Self::Crc1(_) + | Self::Crc8(_) + | Self::Crc16(_) + | Self::Crc24(_) + | Self::Crc32(_) + | Self::Xxh3_64(_) => 1, + } + } + fn update(&mut self, data: &[u8]) { match self { Self::Md4(h) => h.update(data), @@ -238,23 +264,23 @@ impl SingleHasher { }, Self::Crc1(val) => HashResult { hash_type: "CRC1".into(), - hash: format!("{val:x}"), + hash: format!("{val:02x}"), }, Self::Crc8(h) => HashResult { hash_type: "CRC8".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:02x}", h.finalize()), }, Self::Crc16(h) => HashResult { hash_type: "CRC16".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:04x}", h.finalize()), }, Self::Crc24(h) => HashResult { hash_type: "CRC24".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:06x}", h.finalize()), }, Self::Crc32(h) => HashResult { hash_type: "CRC32".into(), - hash: format!("{:x}", h.finalize()), + hash: format!("{:08x}", h.finalize()), }, Self::Xxh3_64(h) => HashResult { hash_type: "XXH3-64".into(), @@ -326,12 +352,157 @@ fn build_hashers(options: &HashOptions) -> Vec { hashers } -pub fn hash_bytes(data: &[u8], options: &HashOptions) -> Vec { +fn update_hashers_chunked( + hashers: &mut [SingleHasher], + data: &[u8], + cancel_flag: &AtomicBool, + aborted_flag: Option<&AtomicBool>, +) -> bool { + for sub in data.chunks(SUB_CHUNK_SIZE) { + if cancel_flag.load(Ordering::Relaxed) + || aborted_flag.is_some_and(|flag| flag.load(Ordering::Relaxed)) + { + return false; + } + for hasher in hashers.iter_mut() { + hasher.update(sub); + } + } + true +} + +fn partition_hashers( + hashers: Vec, + worker_count: usize, +) -> Vec> { + let mut indexed: Vec<(usize, SingleHasher)> = hashers.into_iter().enumerate().collect(); + indexed.sort_by(|(idx_a, a), (idx_b, b)| { + b.relative_cost() + .cmp(&a.relative_cost()) + .then_with(|| idx_a.cmp(idx_b)) + }); + + let mut buckets: Vec> = + (0..worker_count).map(|_| Vec::new()).collect(); + let mut bucket_loads = vec![0u32; worker_count]; + for (index, hasher) in indexed { + let target = bucket_loads + .iter() + .enumerate() + .min_by_key(|&(_, load)| load) + .map(|(idx, _)| idx) + .unwrap_or(0); + bucket_loads[target] += hasher.relative_cost(); + buckets[target].push((index, hasher)); + } + buckets +} + +fn should_use_parallel_pipeline( + total_bytes: u64, + hasher_count: usize, + total_cost: u32, + available_workers: usize, +) -> bool { + if available_workers <= 1 || hasher_count == 0 { + return false; + } + if hasher_count == 1 { + return total_bytes >= SINGLE_PIPELINE_THRESHOLD; + } + if total_cost <= 2 { + return total_bytes >= FAST_PARALLEL_THRESHOLD; + } + total_bytes >= PARALLEL_THRESHOLD +} + +pub fn hash_bytes_cancellable( + data: &[u8], + options: &HashOptions, + cancel_flag: &AtomicBool, +) -> Option> { + if cancel_flag.load(Ordering::Relaxed) { + return None; + } + let mut hashers = build_hashers(options); - for hasher in &mut hashers { - hasher.update(data); + if hashers.is_empty() { + return Some(Vec::new()); + } + + let available_workers = thread::available_parallelism() + .map(std::num::NonZeroUsize::get) + .unwrap_or(4); + let total_cost: u32 = hashers.iter().map(SingleHasher::relative_cost).sum(); + + if hashers.len() > 1 + && should_use_parallel_pipeline( + data.len() as u64, + hashers.len(), + total_cost, + available_workers, + ) + { + let total_hashers = hashers.len(); + let worker_count = available_workers.min(total_hashers).max(1); + let buckets = partition_hashers(hashers, worker_count); + + return thread::scope(|scope| { + let mut handles = Vec::with_capacity(worker_count); + for mut bucket in buckets { + handles.push(scope.spawn(move || { + for sub in data.chunks(SUB_CHUNK_SIZE) { + if cancel_flag.load(Ordering::Relaxed) { + return None; + } + for (_, hasher) in &mut bucket { + hasher.update(sub); + } + } + if cancel_flag.load(Ordering::Relaxed) { + return None; + } + Some( + bucket + .into_iter() + .map(|(index, hasher)| (index, hasher.finalize())) + .collect::>(), + ) + })); + } + + let mut indexed_hashes: Vec> = vec![None; total_hashers]; + let mut cancelled = false; + for handle in handles { + match handle.join() { + Ok(Some(results)) => { + for (index, result) in results { + indexed_hashes[index] = Some(result); + } + } + Ok(None) | Err(_) => cancelled = true, + } + } + if cancelled || cancel_flag.load(Ordering::Relaxed) { + return None; + } + Some(indexed_hashes.into_iter().flatten().collect()) + }); + } + + if !update_hashers_chunked(&mut hashers, data, cancel_flag, None) { + return None; + } + if cancel_flag.load(Ordering::Relaxed) { + return None; } - hashers.into_iter().map(SingleHasher::finalize).collect() + Some(hashers.into_iter().map(SingleHasher::finalize).collect()) +} + +#[cfg(test)] +fn hash_bytes(data: &[u8], options: &HashOptions) -> Vec { + let never_cancel = AtomicBool::new(false); + hash_bytes_cancellable(data, options, &never_cancel).unwrap_or_default() } type FileHashBatch = Option<(Vec, u64)>; @@ -346,7 +517,10 @@ fn hash_file_sequential( where F: FnMut(HashProgress), { - let mut buffer = vec![0u8; CHUNK_SIZE.min((total_bytes as usize).max(64 * 1024))]; + let buffer_len = usize::try_from(total_bytes) + .unwrap_or(CHUNK_SIZE) + .clamp(64 * 1024, CHUNK_SIZE); + let mut buffer = vec![0u8; buffer_len]; let mut bytes_processed: u64 = 0; let mut last_emit = Instant::now(); @@ -362,32 +536,41 @@ where } let chunk = &buffer[..bytes_read]; - for hasher in &mut hashers { - hasher.update(chunk); + if !update_hashers_chunked(&mut hashers, chunk, cancel_flag, None) { + return Ok(None); } bytes_processed = bytes_processed.saturating_add(bytes_read as u64); if last_emit.elapsed() >= PROGRESS_INTERVAL { + let effective_total = total_bytes.max(bytes_processed); + let percentage = if bytes_processed < effective_total { + compute_percentage(bytes_processed, effective_total).min(99.9) + } else { + 99.9 + }; on_progress(HashProgress { bytes_processed, - total_bytes, - percentage: compute_percentage(bytes_processed, total_bytes), + total_bytes: effective_total, + percentage, }); last_emit = Instant::now(); } } - let final_total = total_bytes.max(bytes_processed); + if cancel_flag.load(Ordering::Relaxed) { + return Ok(None); + } + on_progress(HashProgress { bytes_processed, - total_bytes: final_total, + total_bytes: bytes_processed, percentage: 100.0, }); Ok(Some(( hashers.into_iter().map(SingleHasher::finalize).collect(), - final_total, + bytes_processed, ))) } @@ -395,74 +578,118 @@ fn hash_file_parallel( file: &mut File, hashers: Vec, total_bytes: u64, + available_workers: usize, cancel_flag: &AtomicBool, on_progress: &mut F, ) -> Result where F: FnMut(HashProgress), { - thread::scope(|scope| { - let mut senders = Vec::with_capacity(hashers.len()); - let mut handles = Vec::with_capacity(hashers.len()); + let total_hashers = hashers.len(); + let worker_count = available_workers.min(total_hashers).max(1); + let buckets = partition_hashers(hashers, worker_count); + + let read_aborted = AtomicBool::new(false); + let completed_bytes = AtomicU64::new(0); + let (recycle_tx, recycle_rx) = mpsc::sync_channel::>(CHANNEL_DEPTH + 2); - for mut hasher in hashers { - let (tx, rx) = mpsc::sync_channel::>(CHANNEL_DEPTH); + thread::scope(|scope| { + let mut senders = Vec::with_capacity(worker_count); + let mut handles = Vec::with_capacity(worker_count); + + for mut bucket in buckets { + let (tx, rx) = mpsc::sync_channel::<(Arc>, usize)>(CHANNEL_DEPTH); + let read_aborted_ref = &read_aborted; + let completed_bytes_ref = &completed_bytes; + let worker_recycle_tx = recycle_tx.clone(); senders.push(tx); handles.push(scope.spawn(move || { - while let Ok(chunk) = rx.recv() { - if cancel_flag.load(Ordering::Relaxed) { - return None; + while let Ok((chunk, len)) = rx.recv() { + let data = &chunk[..len]; + for sub in data.chunks(SUB_CHUNK_SIZE) { + if cancel_flag.load(Ordering::Relaxed) + || read_aborted_ref.load(Ordering::Relaxed) + { + return None; + } + for (_, hasher) in &mut bucket { + hasher.update(sub); + } + } + if let Ok(buf) = Arc::try_unwrap(chunk) { + completed_bytes_ref.fetch_add(len as u64, Ordering::Relaxed); + let _ = worker_recycle_tx.try_send(buf); } - hasher.update(&chunk); } - if cancel_flag.load(Ordering::Relaxed) { + if cancel_flag.load(Ordering::Relaxed) || read_aborted_ref.load(Ordering::Relaxed) { return None; } - Some(hasher.finalize()) + Some( + bucket + .into_iter() + .map(|(index, hasher)| (index, hasher.finalize())) + .collect::>(), + ) })); } - let mut bytes_processed: u64 = 0; + drop(recycle_tx); + + let mut bytes_read_total: u64 = 0; + let mut last_reported_bytes: u64 = 0; let mut last_emit = Instant::now(); let mut read_error: Option = None; let mut cancelled = false; + let mut maybe_emit_progress = |current_read_total: u64, force_check: bool| { + if !force_check && last_emit.elapsed() < PROGRESS_INTERVAL { + return; + } + let done = completed_bytes.load(Ordering::Relaxed); + if done > last_reported_bytes { + let effective_total = total_bytes.max(current_read_total).max(done); + on_progress(HashProgress { + bytes_processed: done, + total_bytes: effective_total, + percentage: compute_percentage(done, effective_total).min(99.9), + }); + last_reported_bytes = done; + last_emit = Instant::now(); + } + }; + loop { if cancel_flag.load(Ordering::Relaxed) { cancelled = true; break; } - let mut buffer = vec![0u8; CHUNK_SIZE]; + let mut buffer = recycle_rx + .try_recv() + .unwrap_or_else(|_| vec![0u8; CHUNK_SIZE]); match read_chunk(file, &mut buffer) { Ok(0) => break, Ok(bytes_read) => { - buffer.truncate(bytes_read); - let chunk: Arc<[u8]> = Arc::from(buffer); + let chunk = Arc::new(buffer); for tx in &senders { - if tx.send(Arc::clone(&chunk)).is_err() { + if tx.send((Arc::clone(&chunk), bytes_read)).is_err() { cancelled = true; break; } } + drop(chunk); + if cancelled { break; } - bytes_processed = bytes_processed.saturating_add(bytes_read as u64); - - if last_emit.elapsed() >= PROGRESS_INTERVAL { - on_progress(HashProgress { - bytes_processed, - total_bytes, - percentage: compute_percentage(bytes_processed, total_bytes), - }); - last_emit = Instant::now(); - } + bytes_read_total = bytes_read_total.saturating_add(bytes_read as u64); + maybe_emit_progress(bytes_read_total, false); } Err(err) => { + read_aborted.store(true, Ordering::Relaxed); read_error = Some(format!("Failed to read file: {err}")); break; } @@ -471,10 +698,30 @@ where drop(senders); - let mut hashes = Vec::with_capacity(handles.len()); + if read_error.is_none() && !cancelled { + loop { + if cancel_flag.load(Ordering::Relaxed) { + cancelled = true; + break; + } + match recycle_rx.recv_timeout(PROGRESS_INTERVAL) { + Ok(_buf) => maybe_emit_progress(bytes_read_total, false), + Err(mpsc::RecvTimeoutError::Timeout) => { + maybe_emit_progress(bytes_read_total, true); + } + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + } + + let mut indexed_hashes: Vec> = vec![None; total_hashers]; for handle in handles { match handle.join() { - Ok(Some(result)) => hashes.push(result), + Ok(Some(results)) => { + for (index, result) in results { + indexed_hashes[index] = Some(result); + } + } Ok(None) => cancelled = true, Err(_) => return Err("Hash worker thread panicked".to_string()), } @@ -488,17 +735,65 @@ where return Ok(None); } - let final_total = total_bytes.max(bytes_processed); + let hashes: Vec = indexed_hashes.into_iter().flatten().collect(); + on_progress(HashProgress { - bytes_processed, - total_bytes: final_total, + bytes_processed: bytes_read_total, + total_bytes: bytes_read_total, percentage: 100.0, }); - Ok(Some((hashes, final_total))) + Ok(Some((hashes, bytes_read_total))) }) } +fn open_file_sequential(path: &Path) -> io::Result { + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_SEQUENTIAL_SCAN: u32 = 0x0800_0000; + OpenOptions::new() + .read(true) + .custom_flags(FILE_FLAG_SEQUENTIAL_SCAN) + .open(path) + } + + #[cfg(not(windows))] + { + let file = OpenOptions::new().read(true).open(path)?; + + #[cfg(target_os = "linux")] + { + use std::os::fd::AsRawFd; + // SAFETY: `file.as_raw_fd()` is a valid open file descriptor; advisory hint only. + unsafe { + libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_SEQUENTIAL); + } + } + + #[cfg(target_os = "macos")] + { + use std::os::fd::AsRawFd; + // SAFETY: `file.as_raw_fd()` is a valid open file descriptor; advisory hint only. + unsafe { + libc::fcntl(file.as_raw_fd(), libc::F_RDAHEAD, 1); + } + } + + Ok(file) + } +} + +fn validate_regular_file_metadata(metadata: &std::fs::Metadata) -> Result<(), String> { + if metadata.is_dir() { + return Err("Selected path is a directory, not a file".to_string()); + } + if !metadata.is_file() { + return Err("Selected path is not a regular file".to_string()); + } + Ok(()) +} + pub fn hash_file_with_progress( path: &Path, options: &HashOptions, @@ -508,11 +803,21 @@ pub fn hash_file_with_progress( where F: FnMut(HashProgress), { - let mut file = File::open(path).map_err(|err| format!("Failed to open file: {err}"))?; - let total_bytes = file + if cancel_flag.load(Ordering::Relaxed) { + return Ok(FileHashOutcome::Cancelled); + } + + let pre_metadata = + std::fs::metadata(path).map_err(|err| format!("Failed to open file: {err}"))?; + validate_regular_file_metadata(&pre_metadata)?; + + let mut file = + open_file_sequential(path).map_err(|err| format!("Failed to open file: {err}"))?; + let metadata = file .metadata() - .map_err(|err| format!("Failed to read file metadata: {err}"))? - .len(); + .map_err(|err| format!("Failed to read file metadata: {err}"))?; + validate_regular_file_metadata(&metadata)?; + let total_bytes = metadata.len(); let hashers = build_hashers(options); if hashers.is_empty() { @@ -523,6 +828,10 @@ where }); } + if cancel_flag.load(Ordering::Relaxed) { + return Ok(FileHashOutcome::Cancelled); + } + let started_at = Instant::now(); on_progress(HashProgress { @@ -531,11 +840,22 @@ where percentage: compute_percentage(0, total_bytes), }); - let batch = if total_bytes >= PARALLEL_THRESHOLD && hashers.len() > 1 { + let available_workers = thread::available_parallelism() + .map(std::num::NonZeroUsize::get) + .unwrap_or(4); + let total_cost: u32 = hashers.iter().map(SingleHasher::relative_cost).sum(); + + let batch = if should_use_parallel_pipeline( + total_bytes, + hashers.len(), + total_cost, + available_workers, + ) { hash_file_parallel( &mut file, hashers, total_bytes, + available_workers, cancel_flag, &mut on_progress, )? @@ -563,6 +883,35 @@ where mod tests { use super::*; use std::io::Write; + use std::path::PathBuf; + use std::sync::atomic::AtomicU64; + + static TEST_FILE_COUNTER: AtomicU64 = AtomicU64::new(0); + + struct TempTestFile(PathBuf); + + impl TempTestFile { + fn create(label: &str, contents: &[u8]) -> Self { + let id = TEST_FILE_COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "deadhash_test_{label}_{}_{id}.tmp", + std::process::id() + )); + let mut file = File::create(&path).unwrap(); + file.write_all(contents).unwrap(); + Self(path) + } + + fn path(&self) -> &Path { + &self.0 + } + } + + impl Drop for TempTestFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } fn all_options() -> HashOptions { HashOptions { @@ -702,17 +1051,13 @@ mod tests { #[test] fn hashes_file_streaming_with_progress() { - let path = std::env::temp_dir().join("deadhash_test_vector.txt"); - { - let mut f = File::create(&path).unwrap(); - f.write_all(b"hello").unwrap(); - } + let temp = TempTestFile::create("vector", b"hello"); let cancel = AtomicBool::new(false); let mut updates = Vec::new(); let outcome = - hash_file_with_progress(&path, &all_options(), &cancel, |p| updates.push(p)).unwrap(); - let _ = std::fs::remove_file(&path); + hash_file_with_progress(temp.path(), &all_options(), &cancel, |p| updates.push(p)) + .unwrap(); match outcome { FileHashOutcome::Completed { @@ -735,18 +1080,14 @@ mod tests { #[test] fn hashes_large_file_parallel_matches_single_pass() { - let path = std::env::temp_dir().join("deadhash_test_parallel.bin"); let payload: Vec = (0..(5 * 1024 * 1024)).map(|i| (i % 251) as u8).collect(); - { - let mut f = File::create(&path).unwrap(); - f.write_all(&payload).unwrap(); - } + let temp = TempTestFile::create("parallel", &payload); let cancel = AtomicBool::new(false); let mut updates = Vec::new(); let outcome = - hash_file_with_progress(&path, &all_options(), &cancel, |p| updates.push(p)).unwrap(); - let _ = std::fs::remove_file(&path); + hash_file_with_progress(temp.path(), &all_options(), &cancel, |p| updates.push(p)) + .unwrap(); match outcome { FileHashOutcome::Completed { @@ -756,7 +1097,7 @@ mod tests { } => { assert_eq!(hashes, hash_bytes(&payload, &all_options())); assert_eq!(total_bytes, payload.len() as u64); - assert!(elapsed_ms > 0.0 && elapsed_ms.is_finite()); + assert!(elapsed_ms >= 0.0 && elapsed_ms.is_finite()); } FileHashOutcome::Cancelled => panic!("expected completed outcome"), } @@ -769,14 +1110,13 @@ mod tests { #[test] fn hashes_empty_file_without_nan() { - let path = std::env::temp_dir().join("deadhash_test_empty.txt"); - File::create(&path).unwrap(); + let temp = TempTestFile::create("empty", b""); let cancel = AtomicBool::new(false); let mut updates = Vec::new(); let outcome = - hash_file_with_progress(&path, &all_options(), &cancel, |p| updates.push(p)).unwrap(); - let _ = std::fs::remove_file(&path); + hash_file_with_progress(temp.path(), &all_options(), &cancel, |p| updates.push(p)) + .unwrap(); let empty_hashes = hash_bytes(b"", &all_options()); assert_eq!( @@ -858,16 +1198,141 @@ mod tests { #[test] fn cancels_file_hashing_cleanly() { - let path = std::env::temp_dir().join("deadhash_test_cancel.bin"); - { - let mut f = File::create(&path).unwrap(); - f.write_all(&vec![0u8; 512 * 1024]).unwrap(); + let temp = TempTestFile::create("cancel", &vec![0u8; 512 * 1024]); + + let cancel = AtomicBool::new(true); + let outcome = + hash_file_with_progress(temp.path(), &all_options(), &cancel, |_| {}).unwrap(); + + assert_eq!(outcome, FileHashOutcome::Cancelled); + } + + #[test] + fn cancels_large_file_parallel_cleanly() { + let payload = vec![0xab_u8; 16 * 1024 * 1024]; + let temp = TempTestFile::create("cancel_parallel", &payload); + + let cancel = AtomicBool::new(false); + let mut saw_mid_progress = false; + let outcome = hash_file_with_progress(temp.path(), &all_options(), &cancel, |progress| { + if progress.bytes_processed > 0 && progress.bytes_processed < progress.total_bytes { + saw_mid_progress = true; + cancel.store(true, Ordering::Relaxed); + } + }) + .unwrap(); + + assert!( + saw_mid_progress, + "expected mid-stream progress before cancellation" + ); + assert_eq!(outcome, FileHashOutcome::Cancelled); + } + + #[test] + fn zero_pads_crc_outputs_to_fixed_hex_widths() { + let opts = HashOptions { + crc1: true, + crc8: true, + crc16: true, + crc24: true, + crc32: true, + ..Default::default() + }; + let empty = hash_bytes(b"", &opts); + fn find<'a>(results: &'a [HashResult], kind: &str) -> &'a str { + results + .iter() + .find(|r| r.hash_type == kind) + .map(|r| r.hash.as_str()) + .unwrap() } + assert_eq!(find(&empty, "CRC1"), "00"); + assert_eq!(find(&empty, "CRC8"), "00"); + assert_eq!(find(&empty, "CRC16"), "0000"); + assert_eq!(find(&empty, "CRC24"), "b704ce"); + assert_eq!(find(&empty, "CRC32"), "00000000"); + + let single_zero = hash_bytes(&[0x05], &opts); + assert_eq!(find(&single_zero, "CRC1"), "05"); + assert_eq!(find(&single_zero, "CRC8").len(), 2); + assert_eq!(find(&single_zero, "CRC16").len(), 4); + assert_eq!(find(&single_zero, "CRC24").len(), 6); + assert_eq!(find(&single_zero, "CRC32").len(), 8); + } + + #[test] + fn rejects_directory_path_cleanly() { + let dir = std::env::temp_dir(); + let cancel = AtomicBool::new(false); + let err = hash_file_with_progress(&dir, &all_options(), &cancel, |_| {}).unwrap_err(); + assert!(err.contains("directory")); + } + + #[test] + fn pre_cancelled_file_hash_exits_before_io_or_progress() { let cancel = AtomicBool::new(true); - let outcome = hash_file_with_progress(&path, &all_options(), &cancel, |_| {}).unwrap(); - let _ = std::fs::remove_file(&path); + let mut updates = Vec::new(); + let outcome = hash_file_with_progress( + Path::new("/definitely/nonexistent/deadhash_test_file"), + &all_options(), + &cancel, + |p| updates.push(p), + ) + .unwrap(); assert_eq!(outcome, FileHashOutcome::Cancelled); + assert!(updates.is_empty()); + } + + #[test] + fn single_algorithm_large_file_pipeline_matches_hash_bytes() { + let payload: Vec = (0..(9 * 1024 * 1024)).map(|i| (i % 199) as u8).collect(); + let temp = TempTestFile::create("single_pipeline", &payload); + let opts = HashOptions { + sha256: true, + ..Default::default() + }; + let cancel = AtomicBool::new(false); + let mut updates = Vec::new(); + let outcome = + hash_file_with_progress(temp.path(), &opts, &cancel, |p| updates.push(p)).unwrap(); + + match outcome { + FileHashOutcome::Completed { + hashes, + total_bytes, + .. + } => { + assert_eq!(hashes, hash_bytes(&payload, &opts)); + assert_eq!(total_bytes, payload.len() as u64); + } + FileHashOutcome::Cancelled => panic!("expected completed outcome"), + } + assert!(updates.len() >= 2); + for mid in &updates[..updates.len() - 1] { + assert!(mid.percentage < 100.0); + } + assert!((updates.last().unwrap().percentage - 100.0).abs() < f64::EPSILON); + } + + #[test] + fn hash_bytes_cancellable_supports_cancellation_and_parallel_inputs() { + let cancel = AtomicBool::new(true); + assert!(hash_bytes_cancellable(b"hello", &all_options(), &cancel).is_none()); + + let payload: Vec = (0..(5 * 1024 * 1024)).map(|i| (i % 251) as u8).collect(); + let active = AtomicBool::new(false); + let parallel_res = hash_bytes_cancellable(&payload, &all_options(), &active).unwrap(); + let mut seq_hashers = build_hashers(&all_options()); + for hasher in &mut seq_hashers { + hasher.update(&payload); + } + let expected: Vec = seq_hashers + .into_iter() + .map(SingleHasher::finalize) + .collect(); + assert_eq!(parallel_res, expected); } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b977fee..9aa5100 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,20 +1,174 @@ mod hasher; -use std::fs; -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::collections::HashSet; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use hasher::{ - FileHashOutcome, HashOptions, HashProgress, HashResult, hash_bytes, hash_file_with_progress, + FileHashOutcome, HashOptions, HashProgress, HashResult, hash_bytes_cancellable, + hash_file_with_progress, }; +use serde::Serialize; use tauri::Manager; use tauri::ipc::Channel; use tauri::path::BaseDirectory; +use tauri_plugin_dialog::DialogExt; use tauri_plugin_opener::OpenerExt; +static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0); + +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +#[serde(tag = "status", rename_all = "camelCase")] +enum TextHashOutcome { + Completed { hashes: Vec }, + Cancelled, +} + +struct ActiveCalculation { + calc_id: u64, + cancel_flag: Arc, +} + +#[derive(Default)] +struct CancelTracker { + active: Option, + highest_registered_id: u64, + pending_cancellations: HashSet, +} + #[derive(Default)] -struct FileHashCancelState(Mutex>>); +struct HashCancelState(Mutex); + +impl HashCancelState { + fn register(&self, calc_id: u64) -> Result>, String> { + let mut guard = self + .0 + .lock() + .map_err(|_| "Failed to acquire cancellation lock".to_string())?; + + if guard.pending_cancellations.remove(&calc_id) || calc_id <= guard.highest_registered_id { + return Ok(None); + } + + guard.highest_registered_id = calc_id; + guard.pending_cancellations.retain(|&id| id > calc_id); + + let cancel_flag = Arc::new(AtomicBool::new(false)); + if let Some(previous) = guard.active.replace(ActiveCalculation { + calc_id, + cancel_flag: Arc::clone(&cancel_flag), + }) { + previous.cancel_flag.store(true, Ordering::Relaxed); + } + Ok(Some(cancel_flag)) + } + + fn cancel(&self, calc_id: Option) -> Result<(), String> { + let mut guard = self + .0 + .lock() + .map_err(|_| "Failed to acquire cancellation lock".to_string())?; + + match calc_id { + Some(id) => { + if let Some(active) = guard.active.as_ref() + && active.calc_id == id + { + active.cancel_flag.store(true, Ordering::Relaxed); + } else if id > guard.highest_registered_id { + guard.pending_cancellations.insert(id); + } + } + None => { + if let Some(active) = guard.active.as_ref() { + active.cancel_flag.store(true, Ordering::Relaxed); + } + } + } + Ok(()) + } + + fn clear_if_same(&self, cancel_flag: &Arc) { + if let Ok(mut guard) = self.0.lock() + && guard + .active + .as_ref() + .is_some_and(|active| Arc::ptr_eq(&active.cancel_flag, cancel_flag)) + { + guard.active = None; + } + } +} + +#[derive(Default)] +struct FileHashCancelState(HashCancelState); + +#[derive(Default)] +struct TextHashCancelState(HashCancelState); + +fn export_filter_for_format(format: &str) -> Result<(&'static str, &'static str), String> { + match format { + "csv" => Ok(("CSV", "csv")), + "json" => Ok(("JSON", "json")), + "html" => Ok(("HTML", "html")), + "txt" => Ok(("Text", "txt")), + other => Err(format!("Unsupported export format: {other}")), + } +} + +fn write_file_atomically(target: &Path, bytes: &[u8]) -> Result<(), String> { + let parent = target + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + let file_name = target + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("export"); + + let mut temp_path = None; + let mut temp_file = None; + + for _ in 0..16 { + let seq = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!(".{file_name}.tmp.{}.{seq}", std::process::id())); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&candidate) + { + Ok(file) => { + temp_path = Some(candidate); + temp_file = Some(file); + break; + } + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(err) => return Err(format!("Failed to export file: {err}")), + } + } + + let (Some(temp_path), Some(mut file)) = (temp_path, temp_file) else { + return Err("Failed to export file: could not create temporary file".to_string()); + }; + + let write_result = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + + if let Err(err) = write_result { + let _ = fs::remove_file(&temp_path); + return Err(format!("Failed to export file: {err}")); + } + + if let Err(err) = fs::rename(&temp_path, target) { + let _ = fs::remove_file(&temp_path); + return Err(format!("Failed to export file: {err}")); + } + + Ok(()) +} fn escape_html(input: &str) -> String { let mut escaped = String::with_capacity(input.len()); @@ -31,12 +185,24 @@ fn escape_html(input: &str) -> String { escaped } +fn escape_csv_field(input: &str) -> String { + if input.contains([',', '"', '\n', '\r']) { + format!("\"{}\"", input.replace('"', "\"\"")) + } else { + input.to_string() + } +} + fn serialize_hashes(format: &str, hashes: &[HashResult]) -> Result { match format { "csv" => { let mut csv_content = String::new(); for item in hashes { - csv_content.push_str(&format!("{},{}\n", item.hash_type, item.hash)); + csv_content.push_str(&format!( + "{},{}\n", + escape_csv_field(&item.hash_type), + escape_csv_field(&item.hash) + )); } Ok(csv_content) } @@ -96,98 +262,137 @@ fn serialize_hashes(format: &str, hashes: &[HashResult]) -> Result, cancel_state: tauri::State<'_, FileHashCancelState>, ) -> Result { - let cancel_flag = Arc::new(AtomicBool::new(false)); - { - let mut guard = cancel_state - .0 - .lock() - .map_err(|_| "Failed to acquire cancellation lock".to_string())?; - if let Some(previous) = guard.replace(Arc::clone(&cancel_flag)) { - previous.store(true, Ordering::Relaxed); - } - } + let Some(cancel_flag) = cancel_state.0.register(calc_id)? else { + return Ok(FileHashOutcome::Cancelled); + }; let task_cancel = Arc::clone(&cancel_flag); - let result = tokio::task::spawn_blocking(move || { + let join_result = tokio::task::spawn_blocking(move || { hash_file_with_progress(&PathBuf::from(file_path), &options, &task_cancel, |p| { let _ = on_progress.send(p); }) }) - .await - .map_err(|err| format!("Hash task failed: {err}"))?; - - if let Ok(mut guard) = cancel_state.0.lock() - && guard - .as_ref() - .is_some_and(|active| Arc::ptr_eq(active, &cancel_flag)) - { - *guard = None; - } + .await; - result + cancel_state.0.clear_if_same(&cancel_flag); + + join_result.map_err(|err| format!("Hash task failed: {err}"))? } #[tauri::command] -fn cancel_file_hash(cancel_state: tauri::State<'_, FileHashCancelState>) -> Result<(), String> { - let guard = cancel_state - .0 - .lock() - .map_err(|_| "Failed to acquire cancellation lock".to_string())?; - if let Some(flag) = guard.as_ref() { - flag.store(true, Ordering::Relaxed); - } - Ok(()) +fn cancel_file_hash( + calc_id: Option, + cancel_state: tauri::State<'_, FileHashCancelState>, +) -> Result<(), String> { + cancel_state.0.cancel(calc_id) } #[tauri::command] async fn calculate_text_hash( text: String, options: HashOptions, -) -> Result, String> { - tokio::task::spawn_blocking(move || hash_bytes(text.as_bytes(), &options)) - .await - .map_err(|err| format!("Hash task failed: {err}")) + calc_id: u64, + cancel_state: tauri::State<'_, TextHashCancelState>, +) -> Result { + let Some(cancel_flag) = cancel_state.0.register(calc_id)? else { + return Ok(TextHashOutcome::Cancelled); + }; + + let task_cancel = Arc::clone(&cancel_flag); + let join_result = tokio::task::spawn_blocking(move || { + hash_bytes_cancellable(text.as_bytes(), &options, &task_cancel) + }) + .await; + + cancel_state.0.clear_if_same(&cancel_flag); + + let maybe_hashes = join_result.map_err(|err| format!("Hash task failed: {err}"))?; + Ok(match maybe_hashes { + Some(hashes) => TextHashOutcome::Completed { hashes }, + None => TextHashOutcome::Cancelled, + }) +} + +#[tauri::command] +fn cancel_text_hash( + calc_id: Option, + cancel_state: tauri::State<'_, TextHashCancelState>, +) -> Result<(), String> { + cancel_state.0.cancel(calc_id) } #[tauri::command] async fn export_hashes( - file_path: String, + app: tauri::AppHandle, + window: tauri::WebviewWindow, format: String, + default_file_name: String, hashes: Vec, -) -> Result<(), String> { +) -> Result { + let (filter_name, extension) = export_filter_for_format(&format)?; + let content = serialize_hashes(&format, &hashes)?; + tokio::task::spawn_blocking(move || { - let content = serialize_hashes(&format, &hashes)?; - fs::write(file_path, content).map_err(|err| format!("Failed to export file: {err}")) + let selected = app + .dialog() + .file() + .set_parent(&window) + .set_file_name(&default_file_name) + .add_filter(filter_name, &[extension]) + .blocking_save_file(); + + let Some(file_path) = selected else { + return Ok(false); + }; + + let target = file_path + .into_path() + .map_err(|err| format!("Invalid export path: {err}"))?; + write_file_atomically(&target, content.as_bytes())?; + Ok(true) }) .await .map_err(|err| format!("Export task failed: {err}"))? } #[tauri::command] -fn open_help_documentation(app: tauri::AppHandle) -> Result<(), String> { - let resource_path = app - .path() - .resolve("docs/help.pdf", BaseDirectory::Resource) - .ok() - .filter(|path| path.is_file()); +async fn open_help_documentation(app: tauri::AppHandle) -> Result<(), String> { + tokio::task::spawn_blocking(move || { + let resource_path = app + .path() + .resolve("docs/help.pdf", BaseDirectory::Resource) + .ok() + .filter(|path| path.is_file()); + + #[cfg(debug_assertions)] + let help_path = resource_path.or_else(|| { + let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../docs/help.pdf"); + dev_path.is_file().then_some(dev_path) + }); - let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../docs/help.pdf"); + #[cfg(not(debug_assertions))] + let help_path = resource_path; - let help_path = resource_path - .or_else(|| dev_path.is_file().then_some(dev_path)) - .ok_or_else(|| "Help documentation file (docs/help.pdf) could not be found".to_string())?; + let help_path = help_path.ok_or_else(|| { + "Help documentation file (docs/help.pdf) could not be found".to_string() + })?; - app.opener() - .open_path(help_path.to_string_lossy(), None::<&str>) - .map_err(|err| format!("Failed to open help documentation: {err}")) + app.opener() + .open_path(help_path.to_string_lossy(), None::<&str>) + .map_err(|err| format!("Failed to open help documentation: {err}")) + }) + .await + .map_err(|err| format!("Help task failed: {err}"))? } pub fn run() { tauri::Builder::default() .manage(FileHashCancelState::default()) + .manage(TextHashCancelState::default()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_os::init()) @@ -195,6 +400,7 @@ pub fn run() { calculate_file_hash, cancel_file_hash, calculate_text_hash, + cancel_text_hash, export_hashes, open_help_documentation ]) @@ -230,6 +436,57 @@ mod tests { ); assert_eq!(escape_html(""), "<a&"'>"); + assert_eq!(escape_csv_field("MD5"), "MD5"); + assert_eq!(escape_csv_field("a,b\"c\nd"), "\"a,b\"\"c\nd\""); assert!(serialize_hashes("xml", &sample).is_err()); + assert!(export_filter_for_format("xml").is_err()); + assert_eq!(export_filter_for_format("csv").unwrap(), ("CSV", "csv")); + } + + #[test] + fn cancel_state_handles_stale_pre_cancelled_and_out_of_order_ids() { + let state = HashCancelState::default(); + + // Cancel before register must prevent registration from starting. + state.cancel(Some(1)).unwrap(); + assert!(state.register(1).unwrap().is_none()); + + let second = state.register(2).unwrap().expect("id 2 should register"); + assert!(!second.load(Ordering::Relaxed)); + + // Out-of-order stale registration must not clobber newer active calculation. + assert!(state.register(1).unwrap().is_none()); + assert!(!second.load(Ordering::Relaxed)); + + let third = state.register(3).unwrap().expect("id 3 should register"); + assert!(second.load(Ordering::Relaxed)); + assert!(!third.load(Ordering::Relaxed)); + + // Stale cancel must not affect newer calculation. + state.cancel(Some(2)).unwrap(); + assert!(!third.load(Ordering::Relaxed)); + + state.cancel(Some(3)).unwrap(); + assert!(third.load(Ordering::Relaxed)); + + state.clear_if_same(&second); + let fourth = state.register(4).unwrap().expect("id 4 should register"); + assert!(!fourth.load(Ordering::Relaxed)); + state.cancel(None).unwrap(); + assert!(fourth.load(Ordering::Relaxed)); + state.clear_if_same(&fourth); + } + + #[test] + fn writes_export_file_atomically() { + let target = + std::env::temp_dir().join(format!("deadhash_atomic_export_{}.txt", std::process::id())); + write_file_atomically(&target, b"first").unwrap(); + assert_eq!(fs::read_to_string(&target).unwrap(), "first"); + + write_file_atomically(&target, b"second").unwrap(); + assert_eq!(fs::read_to_string(&target).unwrap(), "second"); + + let _ = fs::remove_file(&target); } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index b4ebbda..9d26476 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -15,12 +15,14 @@ "title": "DeadHash", "width": 960, "height": 560, + "minWidth": 640, + "minHeight": 420, "decorations": true, "dragDropEnabled": true } ], "security": { - "csp": null + "csp": "default-src 'self'; connect-src 'self' https://api.codedead.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; object-src 'none'; base-uri 'self'" } }, "bundle": { diff --git a/src/App.jsx b/src/App.jsx index 43d4fb4..499e60a 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,76 +1,102 @@ -import { Suspense, lazy, useEffect, useState } from 'react'; -import { BrowserRouter, Route, Routes } from 'react-router'; +import { Suspense, lazy, useEffect, useRef, useState } from 'react'; +import { BrowserRouter, Navigate, Route, Routes } from 'react-router'; import { AppShell, Center, Loader, MantineProvider } from '@mantine/core'; import { useDisclosure } from '@mantine/hooks'; +import { AlertModal } from './components/AlertModal'; import { AppHeader } from './components/AppHeader'; import { AppNavbar } from './components/AppNavbar'; import { DropZone } from './components/DropZone'; +import { ErrorBoundary } from './components/ErrorBoundary'; import { UpdateModal } from './components/UpdateModal'; +import FileHashPage from './pages/FileHashPage'; import { checkForAppUpdates } from './services/updater'; -import { useHash } from './state/hashContext'; +import { useHashActions } from './state/hashContext'; import { useSettings } from './state/settingsContext'; -const FileHashPage = lazy(() => import('./pages/FileHashPage')); const TextHashPage = lazy(() => import('./pages/TextHashPage')); const SettingsPage = lazy(() => import('./pages/SettingsPage')); const AboutPage = lazy(() => import('./pages/AboutPage')); const App = () => { - const { canDragDrop, autoUpdate, updateChecked, setUpdateChecked } = useSettings(); - const { setFilePath } = useHash(); + const { canDragDrop, autoUpdate, t } = useSettings(); + const { setFilePath } = useHashActions(); + const initialAutoUpdateRef = useRef(autoUpdate); + const updateCheckedRef = useRef(false); const [startupUpdate, setStartupUpdate] = useState(null); + const [appError, setAppError] = useState(null); const [navOpened, { toggle: toggleNav, close: closeNav }] = useDisclosure(false); useEffect(() => { - if (!autoUpdate || updateChecked) return; + if (!initialAutoUpdateRef.current || updateCheckedRef.current) return undefined; - setUpdateChecked(true); + let active = true; + const controller = new AbortController(); - checkForAppUpdates() + checkForAppUpdates({ signal: controller.signal }) .then((res) => { + if (!active) return; + updateCheckedRef.current = true; if (res?.updateAvailable) setStartupUpdate(res); }) .catch(() => { + if (active) updateCheckedRef.current = true; // Silently ignore startup update network errors }); - }, [autoUpdate, updateChecked, setUpdateChecked]); + + return () => { + active = false; + controller.abort(); + }; + }, []); return ( - - - - - - - - - - - setStartupUpdate(null)} /> - - - - } - > - - } /> - } /> - } /> - } /> - } /> - } /> - - - - - - + + + + + + + + + + + + setAppError(null)} + /> + setStartupUpdate(null)} + onError={setAppError} + /> + + + + } + > + + } /> + } /> + } /> + } /> + } /> + } /> + + + + + + + ); }; diff --git a/src/components/AlertModal.jsx b/src/components/AlertModal.jsx index 9719d34..cb9c32e 100644 --- a/src/components/AlertModal.jsx +++ b/src/components/AlertModal.jsx @@ -1,8 +1,8 @@ import { Button, Group, Modal, Text } from '@mantine/core'; -import { useSettings } from '../state/settingsContext'; +import { useLocale } from '../state/settingsContext'; export const AlertModal = ({ opened, title, message, onClose }) => { - const { t } = useSettings(); + const { t } = useLocale(); return ( diff --git a/src/components/AppHeader.jsx b/src/components/AppHeader.jsx index a5fca88..b12194b 100644 --- a/src/components/AppHeader.jsx +++ b/src/components/AppHeader.jsx @@ -1,5 +1,6 @@ import { ActionIcon, + Box, Burger, Group, Menu, @@ -8,14 +9,17 @@ import { useComputedColorScheme, useMantineColorScheme, } from '@mantine/core'; -import { IconCheck, IconLanguage, IconMoon, IconSun } from '@tabler/icons-react'; +import IconCheck from '@tabler/icons-react/icons/IconCheck'; +import IconLanguage from '@tabler/icons-react/icons/IconLanguage'; +import IconMoon from '@tabler/icons-react/icons/IconMoon'; +import IconSun from '@tabler/icons-react/icons/IconSun'; import { LANGUAGES } from '../i18n'; import { useSettings } from '../state/settingsContext'; export const AppHeader = ({ navOpened, onToggleNav }) => { const { locale, setLocale, showHeaderThemeButton, showHeaderLanguageButton, t } = useSettings(); const { setColorScheme } = useMantineColorScheme(); - const computedColorScheme = useComputedColorScheme('light', { getInitialValueInEffect: true }); + const computedColorScheme = useComputedColorScheme('light'); const toggleColorScheme = () => { setColorScheme(computedColorScheme === 'dark' ? 'light' : 'dark'); @@ -51,13 +55,15 @@ export const AppHeader = ({ navOpened, onToggleNav }) => { {showHeaderLanguageButton ? ( - - - - - - - + + + + + + + + + {LANGUAGES.map((lang) => ( { - const { t } = useSettings(); +export const AppNavbar = ({ onNavigate, onError }) => { + const { t } = useLocale(); const navigate = useNavigate(); const { pathname } = useLocation(); + const openingHelpRef = useRef(false); const isFileRoute = pathname === '/' || pathname === '/file'; const goTo = (path) => { onNavigate?.(); + if (path === '/file' && isFileRoute) return; if (pathname !== path) { navigate(path); } @@ -27,9 +28,15 @@ export const AppNavbar = ({ onNavigate }) => { const openHelp = () => { onNavigate?.(); - openHelpDocumentation().catch(() => { - // Ignore if no PDF viewer is available - }); + if (openingHelpRef.current) return; + openingHelpRef.current = true; + openHelpDocumentation() + .catch((error) => { + onError?.(String(error)); + }) + .finally(() => { + openingHelpRef.current = false; + }); }; return ( diff --git a/src/components/CompareHashInput.jsx b/src/components/CompareHashInput.jsx index af454b4..91f09e5 100644 --- a/src/components/CompareHashInput.jsx +++ b/src/components/CompareHashInput.jsx @@ -1,26 +1,50 @@ +import { useEffect, useMemo, useRef } from 'react'; import { Stack, Text, TextInput } from '@mantine/core'; -import { useHash } from '../state/hashContext'; -import { useSettings } from '../state/settingsContext'; +import { useHashAlgorithms } from '../state/hashContext'; +import { useLocale } from '../state/settingsContext'; +import { copyFromInputOrValue, mergePastedText, readClipboardText } from '../utils/clipboard'; import { analyzeCompareHash } from '../utils/compare'; import { ContextMenuArea } from './ContextMenuArea'; -export const CompareHashInput = ({ value, onChange }) => { - const { t } = useSettings(); - const { algorithms } = useHash(); +export const CompareHashInput = ({ value, onChange, onError }) => { + const { t } = useLocale(); + const { algorithms } = useHashAlgorithms(); + const inputRef = useRef(null); + const mountedRef = useRef(true); - const handlePaste = () => { - navigator.clipboard.readText().then((text) => { - onChange(text); + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + + const handleCopy = () => { + copyFromInputOrValue(inputRef.current, inputRef.current?.value ?? value).catch((error) => { + if (mountedRef.current) onError?.(String(error)); }); }; - const analysis = analyzeCompareHash(value, algorithms); + const handlePaste = () => { + readClipboardText() + .then((text) => { + if (!mountedRef.current) return; + const currentValue = inputRef.current?.value ?? value; + onChange(mergePastedText(inputRef.current, currentValue, text)); + }) + .catch((error) => { + if (mountedRef.current) onError?.(String(error)); + }); + }; + + const analysis = useMemo(() => analyzeCompareHash(value, algorithms), [value, algorithms]); const candidateLabels = analysis?.candidates.map((alg) => alg.label).join(', ') ?? ''; return ( - navigator.clipboard.writeText(value)} onPaste={handlePaste}> + onChange(e.currentTarget.value)} diff --git a/src/components/ConfirmModal.jsx b/src/components/ConfirmModal.jsx index f5e58ab..d86c7a8 100644 --- a/src/components/ConfirmModal.jsx +++ b/src/components/ConfirmModal.jsx @@ -1,8 +1,8 @@ import { Button, Group, Modal, Text } from '@mantine/core'; -import { useSettings } from '../state/settingsContext'; +import { useLocale } from '../state/settingsContext'; export const ConfirmModal = ({ opened, title, message, onConfirm, onClose }) => { - const { t } = useSettings(); + const { t } = useLocale(); const handleConfirm = () => { onConfirm?.(); diff --git a/src/components/ContextMenuArea.jsx b/src/components/ContextMenuArea.jsx index d7a7631..41a739f 100644 --- a/src/components/ContextMenuArea.jsx +++ b/src/components/ContextMenuArea.jsx @@ -1,27 +1,61 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Box, Menu, Portal } from '@mantine/core'; -import { IconClipboard, IconCopy } from '@tabler/icons-react'; -import { useSettings } from '../state/settingsContext'; +import IconClipboard from '@tabler/icons-react/icons/IconClipboard'; +import IconCopy from '@tabler/icons-react/icons/IconCopy'; +import { useLocale } from '../state/settingsContext'; +import { canReadClipboard } from '../utils/clipboard'; -export const ContextMenuArea = ({ children, onCopy, onPaste }) => { - const { t } = useSettings(); +const isEditableElement = (target) => { + if (!target || typeof target !== 'object') return false; + const tagName = String(target.tagName ?? '').toUpperCase(); + return tagName === 'INPUT' || tagName === 'TEXTAREA' || Boolean(target.isContentEditable); +}; + +export const ContextMenuArea = ({ children, onCopy, onPaste, disabled = false }) => { + const { t } = useLocale(); const [menuPos, setMenuPos] = useState(null); + const openIdRef = useRef(0); + const pasteSupported = Boolean(onPaste) && canReadClipboard(); + const hasActions = !disabled && Boolean(onCopy || pasteSupported); + const isOpen = hasActions && Boolean(menuPos); useEffect(() => { - if (!menuPos) return undefined; + if (!isOpen) return undefined; const close = () => setMenuPos(null); window.addEventListener('click', close); + window.addEventListener('contextmenu', close, true); window.addEventListener('scroll', close, true); + window.addEventListener('blur', close); return () => { window.removeEventListener('click', close); + window.removeEventListener('contextmenu', close, true); window.removeEventListener('scroll', close, true); + window.removeEventListener('blur', close); }; - }, [menuPos]); + }, [isOpen]); const handleContextMenu = (event) => { + if (!hasActions) return; + if (onPaste && !pasteSupported && isEditableElement(event.target)) { + return; + } + event.preventDefault(); + openIdRef.current += 1; + + let x = event.clientX; + let y = event.clientY; + if (x === 0 && y === 0 && typeof event.currentTarget?.getBoundingClientRect === 'function') { + const rect = event.currentTarget.getBoundingClientRect(); + x = Math.round(rect.left + Math.min(rect.width / 2, 24)); + y = Math.round(rect.top + Math.min(rect.height / 2, 24)); + } + + setMenuPos({ x, y, id: openIdRef.current }); + }; + + const preventFocusSteal = (event) => { event.preventDefault(); - setMenuPos({ x: event.clientX, y: event.clientY }); }; return ( @@ -29,17 +63,25 @@ export const ContextMenuArea = ({ children, onCopy, onPaste }) => { {children} - {menuPos ? ( + {isOpen ? ( - - setMenuPos(null)} shadow="md" width={160}> + + setMenuPos(null)} + shadow="md" + width={160} + > - + {onCopy ? ( } + onMouseDown={preventFocusSteal} onClick={() => { onCopy(); setMenuPos(null); @@ -48,9 +90,10 @@ export const ContextMenuArea = ({ children, onCopy, onPaste }) => { {t.copy} ) : null} - {onPaste ? ( + {pasteSupported ? ( } + onMouseDown={preventFocusSteal} onClick={() => { onPaste(); setMenuPos(null); diff --git a/src/components/DropZone.jsx b/src/components/DropZone.jsx index d3418c9..4e43bb1 100644 --- a/src/components/DropZone.jsx +++ b/src/components/DropZone.jsx @@ -1,14 +1,23 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router'; import { Box, Center, Overlay, Paper, Stack, Text } from '@mantine/core'; -import { IconFileUpload } from '@tabler/icons-react'; +import IconFileUpload from '@tabler/icons-react/icons/IconFileUpload'; import { subscribeDragDrop } from '../services/tauri'; -import { useSettings } from '../state/settingsContext'; +import { useLocale } from '../state/settingsContext'; export const DropZone = ({ children, onDrop, enabled, reRoute }) => { - const { t } = useSettings(); + const { t } = useLocale(); const navigate = useNavigate(); const [dragging, setDragging] = useState(false); + const onDropRef = useRef(onDrop); + const reRouteRef = useRef(reRoute); + const navigateRef = useRef(navigate); + + useEffect(() => { + onDropRef.current = onDrop; + reRouteRef.current = reRoute; + navigateRef.current = navigate; + }, [onDrop, reRoute, navigate]); useEffect(() => { if (!enabled) return undefined; @@ -25,8 +34,8 @@ export const DropZone = ({ children, onDrop, enabled, reRoute }) => { } else if (type === 'drop') { setDragging(false); if (paths?.length > 0) { - onDrop?.(paths[0]); - if (reRoute) navigate(reRoute); + onDropRef.current?.(paths[0]); + if (reRouteRef.current) navigateRef.current(reRouteRef.current); } } else { setDragging(false); @@ -45,9 +54,10 @@ export const DropZone = ({ children, onDrop, enabled, reRoute }) => { return () => { active = false; + setDragging(false); unlisten?.(); }; - }, [enabled, onDrop, reRoute, navigate]); + }, [enabled]); return ( diff --git a/src/components/ErrorBoundary.jsx b/src/components/ErrorBoundary.jsx new file mode 100644 index 0000000..9146683 --- /dev/null +++ b/src/components/ErrorBoundary.jsx @@ -0,0 +1,38 @@ +import { Component } from 'react'; +import { Button, Card, Center, Stack, Text, Title } from '@mantine/core'; + +export class ErrorBoundary extends Component { + constructor(props) { + super(props); + this.state = { error: null }; + } + + static getDerivedStateFromError(error) { + return { error }; + } + + handleReload = () => { + this.setState({ error: null }); + window.location.reload(); + }; + + render() { + if (this.state.error) { + return ( +
+ + + {this.props.title ?? 'An error occurred'} + + {String(this.state.error)} + + + + +
+ ); + } + + return this.props.children; + } +} diff --git a/src/components/ExportButton.jsx b/src/components/ExportButton.jsx index 400a95a..762bc38 100644 --- a/src/components/ExportButton.jsx +++ b/src/components/ExportButton.jsx @@ -1,13 +1,11 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Button, Menu } from '@mantine/core'; -import { - IconBraces, - IconCheck, - IconChevronDown, - IconFileCode, - IconFileSpreadsheet, - IconFileText, -} from '@tabler/icons-react'; +import IconBraces from '@tabler/icons-react/icons/IconBraces'; +import IconCheck from '@tabler/icons-react/icons/IconCheck'; +import IconChevronDown from '@tabler/icons-react/icons/IconChevronDown'; +import IconFileCode from '@tabler/icons-react/icons/IconFileCode'; +import IconFileSpreadsheet from '@tabler/icons-react/icons/IconFileSpreadsheet'; +import IconFileText from '@tabler/icons-react/icons/IconFileText'; import { exportHashes } from '../services/tauri'; import { useSettings } from '../state/settingsContext'; import { formatHashesCase } from '../utils/format'; @@ -19,32 +17,78 @@ const EXPORT_FORMATS = [ { id: 'txt', label: 'TXT', icon: IconFileText }, ]; +const EXPORT_FORMAT_LIST = EXPORT_FORMATS.map(({ label }) => label).join(', '); + export const ExportButton = ({ hashes, onError }) => { - const { t, uppercaseHashes } = useSettings(); - const [format, setFormat] = useState('csv'); + const { t, uppercaseHashes, exportFormat, setExportFormat } = useSettings(); + const [exporting, setExporting] = useState(false); + const [exportedHashesRef, setExportedHashesRef] = useState(null); + const exportingRef = useRef(false); + const mountedRef = useRef(true); + const feedbackTimerRef = useRef(null); + const exported = Boolean(hashes && exportedHashesRef === hashes); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + if (feedbackTimerRef.current) clearTimeout(feedbackTimerRef.current); + }; + }, []); - const handleExport = async (targetFormat = format) => { - if (!hashes?.length) return; + const handleExport = async (targetFormat = exportFormat) => { + if (!hashes?.length || exportingRef.current) return; + const targetHashes = hashes; + exportingRef.current = true; + setExporting(true); + setExportedHashesRef(null); + if (feedbackTimerRef.current) { + clearTimeout(feedbackTimerRef.current); + feedbackTimerRef.current = null; + } try { - await exportHashes(targetFormat, formatHashesCase(hashes, uppercaseHashes)); + const saved = await exportHashes( + targetFormat, + formatHashesCase(targetHashes, uppercaseHashes), + ); + if (saved && mountedRef.current) { + setExportedHashesRef(targetHashes); + feedbackTimerRef.current = setTimeout(() => { + if (mountedRef.current) setExportedHashesRef(null); + }, 1500); + } } catch (error) { - onError?.(String(error)); + if (mountedRef.current) onError?.(String(error)); + } finally { + exportingRef.current = false; + if (mountedRef.current) setExporting(false); } }; const handleSelectFormat = (nextFormat) => { - setFormat(nextFormat); + setExportFormat(nextFormat); handleExport(nextFormat); }; return ( - - @@ -53,7 +97,7 @@ export const ExportButton = ({ hashes, onError }) => { } - rightSection={format === id ? : null} + rightSection={exportFormat === id ? : null} onClick={() => handleSelectFormat(id)} > {label} diff --git a/src/components/HashResultCard.jsx b/src/components/HashResultCard.jsx index f255f7f..708769f 100644 --- a/src/components/HashResultCard.jsx +++ b/src/components/HashResultCard.jsx @@ -1,17 +1,54 @@ +import { memo, useEffect, useRef, useState } from 'react'; import { ActionIcon, Badge, Card, Group, Text, ThemeIcon, Tooltip } from '@mantine/core'; -import { useClipboard } from '@mantine/hooks'; -import { IconCheck, IconCopy } from '@tabler/icons-react'; -import { useSettings } from '../state/settingsContext'; +import IconCheck from '@tabler/icons-react/icons/IconCheck'; +import IconCopy from '@tabler/icons-react/icons/IconCopy'; +import { useHashDisplay, useLocale } from '../state/settingsContext'; +import { copySelectionOrValue, copyTextToClipboard } from '../utils/clipboard'; import { formatHash } from '../utils/format'; import { ContextMenuArea } from './ContextMenuArea'; -export const HashResultCard = ({ hashType, hash, compareHash }) => { - const { t, uppercaseHashes } = useSettings(); - const clipboard = useClipboard({ timeout: 1500 }); +export const HashResultCard = memo(({ hashType, hash, isMatch, onError }) => { + const { t } = useLocale(); + const { uppercaseHashes } = useHashDisplay(); + const [copied, setCopied] = useState(false); + const hashTextRef = useRef(null); + const timerRef = useRef(null); + const mountedRef = useRef(true); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + if (timerRef.current) clearTimeout(timerRef.current); + }; + }, []); const displayHash = formatHash(hash, uppercaseHashes); - const trimmedCompare = compareHash?.trim(); - const isMatch = Boolean(trimmedCompare) && trimmedCompare.toLowerCase() === hash.toLowerCase(); + + const markCopied = () => { + if (!mountedRef.current) return; + setCopied(true); + if (timerRef.current) clearTimeout(timerRef.current); + timerRef.current = setTimeout(() => { + if (mountedRef.current) setCopied(false); + }, 1500); + }; + + const handleCopyFull = () => { + copyTextToClipboard(displayHash) + .then(markCopied) + .catch((error) => { + if (mountedRef.current) onError?.(String(error)); + }); + }; + + const handleCopyContext = () => { + copySelectionOrValue(hashTextRef.current, displayHash) + .then(markCopied) + .catch((error) => { + if (mountedRef.current) onError?.(String(error)); + }); + }; return ( @@ -23,22 +60,23 @@ export const HashResultCard = ({ hashType, hash, compareHash }) => { ) : null} - + clipboard.copy(displayHash)} + onClick={handleCopyFull} > - {clipboard.copied ? : } + {copied ? : } - clipboard.copy(displayHash)}> + { ); -}; +}); + +HashResultCard.displayName = 'HashResultCard'; diff --git a/src/components/HashResultList.jsx b/src/components/HashResultList.jsx index a8269c2..09eabde 100644 --- a/src/components/HashResultList.jsx +++ b/src/components/HashResultList.jsx @@ -1,3 +1,4 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; import { ActionIcon, Alert, @@ -10,19 +11,17 @@ import { Title, Tooltip, } from '@mantine/core'; -import { useClipboard } from '@mantine/hooks'; -import { - IconBolt, - IconCheck, - IconClock, - IconCopy, - IconFile, - IconLetterCaseLower, - IconLetterCaseUpper, - IconX, -} from '@tabler/icons-react'; -import { useHash } from '../state/hashContext'; -import { useSettings } from '../state/settingsContext'; +import IconBolt from '@tabler/icons-react/icons/IconBolt'; +import IconCheck from '@tabler/icons-react/icons/IconCheck'; +import IconClock from '@tabler/icons-react/icons/IconClock'; +import IconCopy from '@tabler/icons-react/icons/IconCopy'; +import IconFile from '@tabler/icons-react/icons/IconFile'; +import IconLetterCaseLower from '@tabler/icons-react/icons/IconLetterCaseLower'; +import IconLetterCaseUpper from '@tabler/icons-react/icons/IconLetterCaseUpper'; +import IconX from '@tabler/icons-react/icons/IconX'; +import { useHashAlgorithms } from '../state/hashContext'; +import { useHashDisplay, useLocale, useSettingsActions } from '../state/settingsContext'; +import { copyTextToClipboard } from '../utils/clipboard'; import { evaluateComparison } from '../utils/compare'; import { formatBytes, @@ -32,25 +31,72 @@ import { } from '../utils/format'; import { HashResultCard } from './HashResultCard'; -export const HashResultList = ({ hashes, compareHash, stats }) => { - const { t, uppercaseHashes, setUppercaseHashes } = useSettings(); - const { algorithms } = useHash(); - const clipboard = useClipboard({ timeout: 1500 }); +export const HashResultList = ({ hashes, compareHash, stats, onError }) => { + const { t } = useLocale(); + const { uppercaseHashes } = useHashDisplay(); + const { setUppercaseHashes } = useSettingsActions(); + const { algorithms } = useHashAlgorithms(); + const [copiedHashesRef, setCopiedHashesRef] = useState(null); + const timerRef = useRef(null); + const mountedRef = useRef(true); + const copiedAll = Boolean(hashes && copiedHashesRef === hashes); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + if (timerRef.current) clearTimeout(timerRef.current); + }; + }, []); + + const comparison = useMemo( + () => evaluateComparison(hashes, compareHash, algorithms), + [hashes, compareHash, algorithms], + ); + const matchedTypeSet = useMemo( + () => (comparison?.matched ? new Set(comparison.matchedTypes) : null), + [comparison], + ); + const throughput = useMemo( + () => (stats ? formatThroughput(stats.totalBytes, stats.elapsedMs) : null), + [stats], + ); if (!hashes?.length) return null; - const comparison = evaluateComparison(hashes, compareHash, algorithms); - const throughput = stats ? formatThroughput(stats.totalBytes, stats.elapsedMs) : null; + const handleCopyAll = () => { + const targetHashes = hashes; + copyTextToClipboard(formatHashesForClipboard(targetHashes, uppercaseHashes)) + .then(() => { + if (!mountedRef.current) return; + setCopiedHashesRef(targetHashes); + if (timerRef.current) clearTimeout(timerRef.current); + timerRef.current = setTimeout(() => { + if (mountedRef.current) setCopiedHashesRef(null); + }, 1500); + }) + .catch((error) => { + if (mountedRef.current) onError?.(String(error)); + }); + }; - let mismatchDetail = null; + const mismatchDetails = []; if (comparison && !comparison.matched) { if (!comparison.analysis.isValidHex) { - mismatchDetail = t.compareInvalidHex; - } else if (comparison.missingDisabledCandidates.length > 0) { - const disabledLabels = comparison.missingDisabledCandidates - .map((alg) => alg.label) - .join(', '); - mismatchDetail = t.compareDisabledHint.replace('{x}', disabledLabels); + mismatchDetails.push(t.compareInvalidHex); + } else { + if (comparison.missingUncalculatedCandidates.length > 0) { + const uncalculatedLabels = comparison.missingUncalculatedCandidates + .map((alg) => alg.label) + .join(', '); + mismatchDetails.push(t.compareRecalculateHint.replace('{x}', uncalculatedLabels)); + } + if (comparison.missingDisabledCandidates.length > 0) { + const disabledLabels = comparison.missingDisabledCandidates + .map((alg) => alg.label) + .join(', '); + mismatchDetails.push(t.compareDisabledHint.replace('{x}', disabledLabels)); + } } } @@ -94,13 +140,13 @@ export const HashResultList = ({ hashes, compareHash, stats }) => { @@ -115,11 +161,11 @@ export const HashResultList = ({ hashes, compareHash, stats }) => { {t.compareNoMatch} - {mismatchDetail ? ( - - {mismatchDetail} + {mismatchDetails.map((detail) => ( + + {detail} - ) : null} + ))} ) ) : null} @@ -130,7 +176,8 @@ export const HashResultList = ({ hashes, compareHash, stats }) => { key={`${item.type}-${item.hash}`} hashType={item.type} hash={item.hash} - compareHash={compareHash} + isMatch={Boolean(matchedTypeSet?.has(item.type))} + onError={onError} /> ))} diff --git a/src/components/UpdateCheckModals.jsx b/src/components/UpdateCheckModals.jsx index 6ce429d..b22696b 100644 --- a/src/components/UpdateCheckModals.jsx +++ b/src/components/UpdateCheckModals.jsx @@ -1,14 +1,14 @@ -import { useSettings } from '../state/settingsContext'; +import { useLocale } from '../state/settingsContext'; import { AlertModal } from './AlertModal'; import { UpdateModal } from './UpdateModal'; -export const UpdateCheckModals = ({ result, error, onClearResult, onClearError }) => { - const { t } = useSettings(); +export const UpdateCheckModals = ({ result, error, onClearResult, onClearError, onError }) => { + const { t } = useLocale(); const isUnsupportedPlatform = Boolean(result && result.platformSupported === false); return ( <> - + { - const { t } = useSettings(); +export const UpdateModal = ({ update, onClose, onError }) => { + const { t } = useLocale(); + const openingRef = useRef(false); + const opened = Boolean(update?.updateAvailable); + const hasActions = Boolean(update?.downloadUrl || update?.infoUrl); - if (!update?.updateAvailable) return null; - - const handleDownload = () => { - if (update.downloadUrl) openExternalUrl(update.downloadUrl); + const handleDownload = async () => { + if (openingRef.current) return; + if (update?.downloadUrl) { + openingRef.current = true; + try { + await openExternalUrl(update.downloadUrl); + } catch (error) { + onError?.(String(error)); + } finally { + openingRef.current = false; + } + } onClose(); }; - const handleInfo = () => { - if (update.infoUrl) openExternalUrl(update.infoUrl); + const handleInfo = async () => { + if (openingRef.current || !update?.infoUrl) return; + openingRef.current = true; + try { + await openExternalUrl(update.infoUrl); + } catch (error) { + onClose(); + onError?.(String(error)); + } finally { + openingRef.current = false; + } }; return ( - + - {t.newVersion.replace('{x}', update.version)} + {t.newVersion.replace('{x}', update?.version ?? '')} - - {update.infoUrl ? ( + {update?.infoUrl ? ( ) : null} - {update.downloadUrl ? : null} + {update?.downloadUrl ? : null} ); diff --git a/src/components/VirusTotalButton.jsx b/src/components/VirusTotalButton.jsx index 0ceb17e..05abbbf 100644 --- a/src/components/VirusTotalButton.jsx +++ b/src/components/VirusTotalButton.jsx @@ -1,20 +1,26 @@ +import { useRef } from 'react'; import { Button, Tooltip } from '@mantine/core'; -import { IconExternalLink } from '@tabler/icons-react'; +import IconExternalLink from '@tabler/icons-react/icons/IconExternalLink'; import { openExternalUrl } from '../services/tauri'; -import { useSettings } from '../state/settingsContext'; +import { useLocale } from '../state/settingsContext'; import { getVirusTotalFileUrl } from '../utils/virustotal'; export const VirusTotalButton = ({ hashes, onError }) => { - const { t } = useSettings(); + const { t } = useLocale(); + const openingRef = useRef(false); const url = getVirusTotalFileUrl(hashes); if (!url) return null; const handleOpen = async () => { + if (openingRef.current) return; + openingRef.current = true; try { await openExternalUrl(url); } catch (error) { onError?.(String(error)); + } finally { + openingRef.current = false; } }; diff --git a/src/constants/version.js b/src/constants/version.js new file mode 100644 index 0000000..1338ca6 --- /dev/null +++ b/src/constants/version.js @@ -0,0 +1 @@ +export const FALLBACK_APP_VERSION = typeof __APP_VERSION__ === 'string' ? __APP_VERSION__ : '0.0.0'; diff --git a/src/hooks/useUpdateCheck.js b/src/hooks/useUpdateCheck.js index 382d76f..e6f27aa 100644 --- a/src/hooks/useUpdateCheck.js +++ b/src/hooks/useUpdateCheck.js @@ -1,27 +1,50 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { checkForAppUpdates } from '../services/updater'; export const useUpdateCheck = () => { const [loading, setLoading] = useState(false); const [result, setResult] = useState(null); const [error, setError] = useState(null); + const loadingRef = useRef(false); + const mountedRef = useRef(true); + const controllerRef = useRef(null); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + controllerRef.current?.abort(); + controllerRef.current = null; + }; + }, []); const checkUpdates = useCallback(async () => { - if (loading) return; + if (loadingRef.current) return; + const controller = new AbortController(); + controllerRef.current = controller; + loadingRef.current = true; setLoading(true); setResult(null); setError(null); try { - const update = await checkForAppUpdates(); - setResult(update); + const update = await checkForAppUpdates({ signal: controller.signal }); + if (mountedRef.current && !controller.signal.aborted) { + setResult(update); + } } catch (err) { - setError(String(err)); + if (mountedRef.current && !controller.signal.aborted) { + setError(String(err)); + } } finally { - setLoading(false); + if (controllerRef.current === controller) { + controllerRef.current = null; + } + loadingRef.current = false; + if (mountedRef.current) setLoading(false); } - }, [loading]); + }, []); const clearResult = useCallback(() => setResult(null), []); const clearError = useCallback(() => setError(null), []); @@ -33,5 +56,6 @@ export const useUpdateCheck = () => { checkUpdates, clearResult, clearError, + setError, }; }; diff --git a/src/i18n/index.js b/src/i18n/index.js index 3045c30..0933b8d 100644 --- a/src/i18n/index.js +++ b/src/i18n/index.js @@ -1,36 +1,54 @@ -import de from './locales/de.js'; import en from './locales/en.js'; -import es from './locales/es.js'; -import fr from './locales/fr.js'; -import it from './locales/it.js'; -import ja from './locales/ja.js'; -import nl from './locales/nl.js'; -import pt from './locales/pt.js'; -import ru from './locales/ru.js'; -import tr from './locales/tr.js'; -import uk from './locales/uk.js'; export const DEFAULT_LOCALE = 'en'; export const LANGUAGES = [ - { code: 'de', label: 'Deutsch', messages: de }, - { code: 'en', label: 'English', messages: en }, - { code: 'es', label: 'Español', messages: es }, - { code: 'fr', label: 'Français', messages: fr }, - { code: 'it', label: 'Italiano', messages: it }, - { code: 'ja', label: '日本語', messages: ja }, - { code: 'nl', label: 'Nederlands', messages: nl }, - { code: 'pt', label: 'Português', messages: pt }, - { code: 'ru', label: 'Русский', messages: ru }, - { code: 'tr', label: 'Türkçe', messages: tr }, - { code: 'uk', label: 'Українська', messages: uk }, + { code: 'de', label: 'Deutsch', load: () => import('./locales/de.js') }, + { code: 'en', label: 'English', load: async () => ({ default: en }) }, + { code: 'es', label: 'Español', load: () => import('./locales/es.js') }, + { code: 'fr', label: 'Français', load: () => import('./locales/fr.js') }, + { code: 'it', label: 'Italiano', load: () => import('./locales/it.js') }, + { code: 'ja', label: '日本語', load: () => import('./locales/ja.js') }, + { code: 'nl', label: 'Nederlands', load: () => import('./locales/nl.js') }, + { code: 'pt', label: 'Português', load: () => import('./locales/pt.js') }, + { code: 'ru', label: 'Русский', load: () => import('./locales/ru.js') }, + { code: 'tr', label: 'Türkçe', load: () => import('./locales/tr.js') }, + { code: 'uk', label: 'Українська', load: () => import('./locales/uk.js') }, ]; -const LOCALES_BY_CODE = Object.fromEntries(LANGUAGES.map((lang) => [lang.code, lang.messages])); +const LANGUAGE_BY_CODE = Object.fromEntries(LANGUAGES.map((lang) => [lang.code, lang])); +const LOADED_MESSAGES = { [DEFAULT_LOCALE]: en }; +const IN_FLIGHT_LOADS = new Map(); -export const isValidLocale = (code) => Object.hasOwn(LOCALES_BY_CODE, code); +export const isValidLocale = (code) => Object.hasOwn(LANGUAGE_BY_CODE, code); -export const getMessages = (code) => LOCALES_BY_CODE[code] ?? LOCALES_BY_CODE[DEFAULT_LOCALE]; +export const getMessages = (code) => LOADED_MESSAGES[code] ?? LOADED_MESSAGES[DEFAULT_LOCALE]; + +export const loadMessages = async (code) => { + const targetCode = isValidLocale(code) ? code : DEFAULT_LOCALE; + if (LOADED_MESSAGES[targetCode]) { + return LOADED_MESSAGES[targetCode]; + } + + let pending = IN_FLIGHT_LOADS.get(targetCode); + if (!pending) { + pending = LANGUAGE_BY_CODE[targetCode] + .load() + .then((mod) => { + const messages = mod.default ?? mod; + LOADED_MESSAGES[targetCode] = messages; + IN_FLIGHT_LOADS.delete(targetCode); + return messages; + }) + .catch((error) => { + IN_FLIGHT_LOADS.delete(targetCode); + throw error; + }); + IN_FLIGHT_LOADS.set(targetCode, pending); + } + + return pending; +}; export const migrateLegacyLocaleIndex = (indexStr) => { const index = parseInt(indexStr, 10); diff --git a/src/i18n/locales/de.js b/src/i18n/locales/de.js index a934964..2d78e79 100644 --- a/src/i18n/locales/de.js +++ b/src/i18n/locales/de.js @@ -40,6 +40,9 @@ export default { compareInvalidHex: 'Kein gültiger hexadezimaler Hash', compareLengthHint: '{len} Hex-Zeichen ({algos})', compareDisabledHint: 'In den Einstellungen deaktiviert: {x}', + compareRecalculateHint: 'In den Einstellungen aktiviert — zum Prüfen neu berechnen: {x}', + noAlgorithmsEnabled: + 'Aktivieren Sie mindestens einen Algorithmus in den Einstellungen, um Hashes zu berechnen.', calculate: 'Berechnen', output: 'Ausgabe', copy: 'Kopieren', @@ -61,12 +64,13 @@ export default { cancel: 'Abbrechen', ok: 'OK', errorTitle: 'Ein Fehler ist aufgetreten', + reload: 'Neu laden', yes: 'Ja', no: 'Nein', confirmation: 'Bestätigung', confirmResetSettings: 'Möchten Sie wirklich alle Einstellungen zurücksetzen?', toggleNavigation: 'Navigation umschalten', - dropFilePrompt: 'Datei ablegen, um Hashes zu berechnen', + dropFilePrompt: 'Datei zum Auswählen ablegen', virusTotal: 'VirusTotal', openInVirusTotal: 'In VirusTotal öffnen', }; diff --git a/src/i18n/locales/en.js b/src/i18n/locales/en.js index 72099ec..1a70934 100644 --- a/src/i18n/locales/en.js +++ b/src/i18n/locales/en.js @@ -40,6 +40,8 @@ export default { compareInvalidHex: 'Not a valid hexadecimal hash', compareLengthHint: '{len} hex characters ({algos})', compareDisabledHint: 'Disabled in Settings: {x}', + compareRecalculateHint: 'Enabled in Settings — recalculate to check: {x}', + noAlgorithmsEnabled: 'Enable at least one algorithm in Settings to calculate hashes.', calculate: 'Calculate', output: 'Output', copy: 'Copy', @@ -61,12 +63,13 @@ export default { cancel: 'Cancel', ok: 'OK', errorTitle: 'An error occurred', + reload: 'Reload', yes: 'Yes', no: 'No', confirmation: 'Confirmation', confirmResetSettings: 'Are you sure you want to reset all settings?', toggleNavigation: 'Toggle navigation', - dropFilePrompt: 'Drop file to calculate hashes', + dropFilePrompt: 'Drop file to select', virusTotal: 'VirusTotal', openInVirusTotal: 'Open in VirusTotal', }; diff --git a/src/i18n/locales/es.js b/src/i18n/locales/es.js index 51e819f..eadd8cc 100644 --- a/src/i18n/locales/es.js +++ b/src/i18n/locales/es.js @@ -40,6 +40,8 @@ export default { compareInvalidHex: 'No es un hash hexadecimal válido', compareLengthHint: '{len} caracteres hexadecimales ({algos})', compareDisabledHint: 'Deshabilitado en Configuración: {x}', + compareRecalculateHint: 'Habilitado en Configuración — vuelve a calcular para comprobar: {x}', + noAlgorithmsEnabled: 'Habilita al menos un algoritmo en Configuración para calcular hashes.', calculate: 'Calcular', output: 'Resultado', copy: 'Copiar', @@ -61,12 +63,13 @@ export default { cancel: 'Cancelar', ok: 'Aceptar', errorTitle: 'Se ha producido un error', + reload: 'Recargar', yes: 'Sí', no: 'No', confirmation: 'Confirmación', confirmResetSettings: '¿Estás seguro de que quieres restablecer toda la configuración?', toggleNavigation: 'Alternar navegación', - dropFilePrompt: 'Suelta un archivo para calcular los hashes', + dropFilePrompt: 'Suelta un archivo para seleccionarlo', virusTotal: 'VirusTotal', openInVirusTotal: 'Abrir en VirusTotal', }; diff --git a/src/i18n/locales/fr.js b/src/i18n/locales/fr.js index 6287b0f..a9c651a 100644 --- a/src/i18n/locales/fr.js +++ b/src/i18n/locales/fr.js @@ -40,6 +40,9 @@ export default { compareInvalidHex: "N'est pas une empreinte hexadécimale valide", compareLengthHint: '{len} caractères hexadécimaux ({algos})', compareDisabledHint: 'Désactivé dans les Paramètres : {x}', + compareRecalculateHint: 'Activé dans les Paramètres — recalculez pour vérifier : {x}', + noAlgorithmsEnabled: + 'Activez au moins un algorithme dans les Paramètres pour calculer des empreintes.', calculate: 'Calculer', output: 'Résultat', copy: 'Copier', @@ -61,12 +64,13 @@ export default { cancel: 'Annuler', ok: 'OK', errorTitle: 'Une erreur est survenue', + reload: 'Recharger', yes: 'Oui', no: 'Non', confirmation: 'Confirmation', confirmResetSettings: 'Voulez-vous vraiment réinitialiser tous les paramètres ?', toggleNavigation: 'Afficher ou masquer la navigation', - dropFilePrompt: 'Déposez un fichier pour calculer ses empreintes', + dropFilePrompt: 'Déposez un fichier pour le sélectionner', virusTotal: 'VirusTotal', openInVirusTotal: 'Ouvrir dans VirusTotal', }; diff --git a/src/i18n/locales/it.js b/src/i18n/locales/it.js index 28ac599..c74f080 100644 --- a/src/i18n/locales/it.js +++ b/src/i18n/locales/it.js @@ -40,6 +40,8 @@ export default { compareInvalidHex: 'Non è un hash esadecimale valido', compareLengthHint: '{len} caratteri esadecimali ({algos})', compareDisabledHint: 'Disabilitato nelle Impostazioni: {x}', + compareRecalculateHint: 'Abilitato nelle Impostazioni — ricalcola per verificare: {x}', + noAlgorithmsEnabled: 'Abilita almeno un algoritmo nelle Impostazioni per calcolare gli hash.', calculate: 'Calcola', output: 'Risultato', copy: 'Copia', @@ -61,12 +63,13 @@ export default { cancel: 'Annulla', ok: 'OK', errorTitle: 'Si è verificato un errore', + reload: 'Ricarica', yes: 'Sì', no: 'No', confirmation: 'Conferma', confirmResetSettings: 'Sei sicuro di voler ripristinare tutte le impostazioni?', toggleNavigation: 'Apri o chiudi la navigazione', - dropFilePrompt: 'Trascina un file per calcolare gli hash', + dropFilePrompt: 'Trascina un file per selezionarlo', virusTotal: 'VirusTotal', openInVirusTotal: 'Apri in VirusTotal', }; diff --git a/src/i18n/locales/ja.js b/src/i18n/locales/ja.js index 0469d8e..e81ce06 100644 --- a/src/i18n/locales/ja.js +++ b/src/i18n/locales/ja.js @@ -40,6 +40,9 @@ export default { compareInvalidHex: '有効な16進数ハッシュではありません', compareLengthHint: '{len}桁の16進数 ({algos})', compareDisabledHint: '設定で無効化されています: {x}', + compareRecalculateHint: '設定で有効化されています — 確認するには再計算してください: {x}', + noAlgorithmsEnabled: + 'ハッシュを計算するには、設定で少なくとも1つのアルゴリズムを有効にしてください。', calculate: '計算', output: '出力', copy: 'コピー', @@ -61,12 +64,13 @@ export default { cancel: 'キャンセル', ok: 'OK', errorTitle: 'エラーが発生しました', + reload: '再読み込み', yes: 'はい', no: 'いいえ', confirmation: '確認', confirmResetSettings: 'すべての設定をリセットしてもよろしいですか?', toggleNavigation: 'ナビゲーションを切り替え', - dropFilePrompt: 'ファイルをドロップしてハッシュを計算', + dropFilePrompt: 'ファイルをドロップして選択', virusTotal: 'VirusTotal', openInVirusTotal: 'VirusTotalで開く', }; diff --git a/src/i18n/locales/nl.js b/src/i18n/locales/nl.js index 19d9931..57fdcb5 100644 --- a/src/i18n/locales/nl.js +++ b/src/i18n/locales/nl.js @@ -40,6 +40,9 @@ export default { compareInvalidHex: 'Geen geldige hexadecimale hash', compareLengthHint: '{len} hexadecimale tekens ({algos})', compareDisabledHint: 'Uitgeschakeld in Instellingen: {x}', + compareRecalculateHint: 'Ingeschakeld in Instellingen — bereken opnieuw om te controleren: {x}', + noAlgorithmsEnabled: + 'Schakel ten minste één algoritme in bij Instellingen om hashes te berekenen.', calculate: 'Berekenen', output: 'Uitvoer', copy: 'Kopiëren', @@ -61,12 +64,13 @@ export default { cancel: 'Annuleren', ok: 'OK', errorTitle: 'Er is een fout opgetreden', + reload: 'Opnieuw laden', yes: 'Ja', no: 'Nee', confirmation: 'Bevestiging', confirmResetSettings: 'Weet je zeker dat je alle instellingen wilt herstellen?', toggleNavigation: 'Navigatie in- of uitschakelen', - dropFilePrompt: 'Sleep een bestand hierheen om hashes te berekenen', + dropFilePrompt: 'Sleep een bestand hierheen om te selecteren', virusTotal: 'VirusTotal', openInVirusTotal: 'Openen in VirusTotal', }; diff --git a/src/i18n/locales/pt.js b/src/i18n/locales/pt.js index b6bd171..9471b89 100644 --- a/src/i18n/locales/pt.js +++ b/src/i18n/locales/pt.js @@ -40,6 +40,8 @@ export default { compareInvalidHex: 'Não é um hash hexadecimal válido', compareLengthHint: '{len} caracteres hexadecimais ({algos})', compareDisabledHint: 'Desativado nas Definições: {x}', + compareRecalculateHint: 'Ativado nas Definições — recalcule para verificar: {x}', + noAlgorithmsEnabled: 'Ative pelo menos um algoritmo nas Definições para calcular hashes.', calculate: 'Calcular', output: 'Resultado', copy: 'Copiar', @@ -61,12 +63,13 @@ export default { cancel: 'Cancelar', ok: 'OK', errorTitle: 'Ocorreu um erro', + reload: 'Recarregar', yes: 'Sim', no: 'Não', confirmation: 'Confirmação', confirmResetSettings: 'Tem a certeza de que pretende repor todas as definições?', toggleNavigation: 'Alternar navegação', - dropFilePrompt: 'Largue um ficheiro para calcular os hashes', + dropFilePrompt: 'Largue um ficheiro para o selecionar', virusTotal: 'VirusTotal', openInVirusTotal: 'Abrir no VirusTotal', }; diff --git a/src/i18n/locales/ru.js b/src/i18n/locales/ru.js index 86eaac6..bb6dab3 100644 --- a/src/i18n/locales/ru.js +++ b/src/i18n/locales/ru.js @@ -40,6 +40,8 @@ export default { compareInvalidHex: 'Недопустимый шестнадцатеричный хеш', compareLengthHint: '{len} шестнадцатеричных символов ({algos})', compareDisabledHint: 'Отключено в Настройках: {x}', + compareRecalculateHint: 'Включено в Настройках — пересчитайте для проверки: {x}', + noAlgorithmsEnabled: 'Включите хотя бы один алгоритм в Настройках для вычисления хешей.', calculate: 'Вычислить', output: 'Результат', copy: 'Копировать', @@ -61,12 +63,13 @@ export default { cancel: 'Отмена', ok: 'ОК', errorTitle: 'Произошла ошибка', + reload: 'Перезагрузить', yes: 'Да', no: 'Нет', confirmation: 'Подтверждение', confirmResetSettings: 'Вы уверены, что хотите сбросить все настройки?', toggleNavigation: 'Переключить навигацию', - dropFilePrompt: 'Перетащите файл для вычисления хешей', + dropFilePrompt: 'Перетащите файл для выбора', virusTotal: 'VirusTotal', openInVirusTotal: 'Открыть в VirusTotal', }; diff --git a/src/i18n/locales/tr.js b/src/i18n/locales/tr.js index a85a378..c0987d8 100644 --- a/src/i18n/locales/tr.js +++ b/src/i18n/locales/tr.js @@ -40,6 +40,8 @@ export default { compareInvalidHex: 'Geçerli bir onaltılık özet değeri değil', compareLengthHint: '{len} onaltılık karakter ({algos})', compareDisabledHint: 'Ayarlarda devre dışı: {x}', + compareRecalculateHint: 'Ayarlarda etkin — kontrol etmek için yeniden hesaplayın: {x}', + noAlgorithmsEnabled: 'Hash hesaplamak için Ayarlarda en az bir algoritma etkinleştirin.', calculate: 'Hesapla', output: 'Çıktı', copy: 'Kopyala', @@ -61,12 +63,13 @@ export default { cancel: 'İptal', ok: 'Tamam', errorTitle: 'Bir hata oluştu', + reload: 'Yeniden yükle', yes: 'Evet', no: 'Hayır', confirmation: 'Onay', confirmResetSettings: 'Tüm ayarları sıfırlamak istediğinizden emin misiniz?', toggleNavigation: 'Gezinmeyi aç veya kapat', - dropFilePrompt: 'Özet değerlerini hesaplamak için dosyayı bırakın', + dropFilePrompt: 'Seçmek için dosyayı bırakın', virusTotal: 'VirusTotal', openInVirusTotal: "VirusTotal'de aç", }; diff --git a/src/i18n/locales/uk.js b/src/i18n/locales/uk.js index 5227958..876608e 100644 --- a/src/i18n/locales/uk.js +++ b/src/i18n/locales/uk.js @@ -40,6 +40,8 @@ export default { compareInvalidHex: 'Недійсний шістнадцятковий хеш', compareLengthHint: '{len} шістнадцяткових символів ({algos})', compareDisabledHint: 'Вимкнено в Налаштуваннях: {x}', + compareRecalculateHint: 'Увімкнено в Налаштуваннях — перерахуйте для перевірки: {x}', + noAlgorithmsEnabled: 'Увімкніть щонайменше один алгоритм у Налаштуваннях, щоб обчислити хеші.', calculate: 'Обчислити', output: 'Результат', copy: 'Копіювати', @@ -61,12 +63,13 @@ export default { cancel: 'Скасувати', ok: 'ОК', errorTitle: 'Сталася помилка', + reload: 'Перезавантажити', yes: 'Так', no: 'Ні', confirmation: 'Підтвердження', confirmResetSettings: 'Ви впевнені, що хочете скинути всі налаштування?', toggleNavigation: 'Перемкнути навігацію', - dropFilePrompt: 'Перетягніть файл для обчислення хешів', + dropFilePrompt: 'Перетягніть файл для вибору', virusTotal: 'VirusTotal', openInVirusTotal: 'Відкрити у VirusTotal', }; diff --git a/src/pages/AboutPage.jsx b/src/pages/AboutPage.jsx index 77ecb04..13b2451 100644 --- a/src/pages/AboutPage.jsx +++ b/src/pages/AboutPage.jsx @@ -1,20 +1,23 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Button, Card, Container, SimpleGrid, Stack, Text } from '@mantine/core'; +import { AlertModal } from '../components/AlertModal'; import { PageHeader } from '../components/PageHeader'; -import { UpdateCheckModals } from '../components/UpdateCheckModals'; -import { useUpdateCheck } from '../hooks/useUpdateCheck'; +import { FALLBACK_APP_VERSION } from '../constants/version'; import { getAppVersion, openExternalUrl } from '../services/tauri'; -import { useSettings } from '../state/settingsContext'; +import { useLocale } from '../state/settingsContext'; const LICENSE_URL = 'https://codedead.com/Software/DeadHash/gpl.pdf'; const WEBSITE_URL = 'https://codedead.com'; const AboutPage = () => { - const { t } = useSettings(); - const { result, error, clearResult, clearError } = useUpdateCheck(); - const [appVersion, setAppVersion] = useState('2.2.3'); + const { t } = useLocale(); + const [appVersion, setAppVersion] = useState(FALLBACK_APP_VERSION); + const [error, setError] = useState(null); + const openingRef = useRef(false); + const mountedRef = useRef(true); useEffect(() => { + mountedRef.current = true; let active = true; getAppVersion() .then((version) => { @@ -25,18 +28,31 @@ const AboutPage = () => { }); return () => { active = false; + mountedRef.current = false; }; }, []); + const handleOpenUrl = async (url) => { + if (openingRef.current) return; + openingRef.current = true; + try { + await openExternalUrl(url); + } catch (err) { + if (mountedRef.current) setError(String(err)); + } finally { + openingRef.current = false; + } + }; + return ( <> - setError(null)} /> @@ -46,10 +62,10 @@ const AboutPage = () => { {t.aboutMessage.replace('{x}', appVersion)} - - diff --git a/src/pages/FileHashPage.jsx b/src/pages/FileHashPage.jsx index 3a3b1df..2ae8752 100644 --- a/src/pages/FileHashPage.jsx +++ b/src/pages/FileHashPage.jsx @@ -1,3 +1,4 @@ +import { useEffect, useRef } from 'react'; import { Button, Card, @@ -16,34 +17,87 @@ import { HashResultList } from '../components/HashResultList'; import { PageHeader } from '../components/PageHeader'; import { VirusTotalButton } from '../components/VirusTotalButton'; import { selectFileDialog } from '../services/tauri'; -import { useHash } from '../state/hashContext'; -import { useSettings } from '../state/settingsContext'; +import { + useHashActions, + useHashAlgorithms, + useHashFile, + useHashFileProgress, +} from '../state/hashContext'; +import { useLocale } from '../state/settingsContext'; import { formatBytes } from '../utils/format'; +const FileHashProgress = ({ cancelling, onCancel, cancelLabel }) => { + const progress = useHashFileProgress(); + const rawPercentage = progress?.percentage ?? 0; + const displayPercentage = + rawPercentage >= 100 ? 100 : Math.min(99, Math.max(0, Math.floor(rawPercentage))); + + return ( + + + + + + {formatBytes(progress?.bytesProcessed ?? 0)} / {formatBytes(progress?.totalBytes ?? 0)} + + + {displayPercentage}% + + + + + + ); +}; + const FileHashPage = () => { - const { t } = useSettings(); + const { t } = useLocale(); + const { hasEnabledAlgorithms } = useHashAlgorithms(); + const { file, runFileCalculation } = useHashFile(); const { - file, setFilePath, setFileComparing, setFileCompareHash, setFileError, clearFile, - runFileCalculation, cancelFileCalculation, - } = useHash(); + } = useHashActions(); + + const selectingRef = useRef(false); + const loadingRef = useRef(file.loading); + const mountedRef = useRef(true); + + useEffect(() => { + loadingRef.current = file.loading; + }, [file.loading]); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); const handleSelectFile = async () => { - if (file.loading) return; + if (file.loading || selectingRef.current) return; + selectingRef.current = true; try { const selected = await selectFileDialog(); - if (selected) setFilePath(selected); + if (selected && mountedRef.current && !loadingRef.current) { + setFilePath(selected); + } } catch (error) { - setFileError(String(error)); + if (mountedRef.current) setFileError(String(error)); + } finally { + selectingRef.current = false; } }; - const progressPercentage = file.progress?.percentage ?? 0; + const canClear = Boolean( + file.path || file.hashes?.length > 0 || (file.comparing && file.compareHash), + ); return ( <> @@ -62,10 +116,12 @@ const FileHashPage = () => { - + ) : ( + {canClear ? ( + + ) : null} {file.hashes?.length > 0 ? ( <> - ) : null} - @@ -127,6 +183,7 @@ const FileHashPage = () => { hashes={file.hashes} compareHash={file.comparing ? file.compareHash : null} stats={file.stats} + onError={setFileError} /> diff --git a/src/pages/SettingsPage.jsx b/src/pages/SettingsPage.jsx index bb7b794..433ee2d 100644 --- a/src/pages/SettingsPage.jsx +++ b/src/pages/SettingsPage.jsx @@ -24,7 +24,7 @@ import { } from '../constants/algorithms'; import { useUpdateCheck } from '../hooks/useUpdateCheck'; import { LANGUAGES } from '../i18n'; -import { useHash } from '../state/hashContext'; +import { useHashActions, useHashAlgorithms } from '../state/hashContext'; import { useSettings } from '../state/settingsContext'; const LANGUAGE_SELECT_DATA = LANGUAGES.map((lang) => ({ @@ -51,9 +51,11 @@ const SettingsPage = () => { setUppercaseHashes, resetSettings, } = useSettings(); - const { algorithms, setAlgorithmEnabled, resetAlgorithms } = useHash(); + const { algorithms } = useHashAlgorithms(); + const { setAlgorithmEnabled, resetAlgorithms } = useHashActions(); const { colorScheme, setColorScheme } = useMantineColorScheme(); - const { loading, result, error, checkUpdates, clearResult, clearError } = useUpdateCheck(); + const { loading, result, error, checkUpdates, clearResult, clearError, setError } = + useUpdateCheck(); const [confirmOpen, setConfirmOpen] = useState(false); const handleResetAll = () => { @@ -71,6 +73,7 @@ const SettingsPage = () => { error={error} onClearResult={clearResult} onClearError={clearError} + onError={setError} /> diff --git a/src/pages/TextHashPage.jsx b/src/pages/TextHashPage.jsx index 3c19c8d..2996b25 100644 --- a/src/pages/TextHashPage.jsx +++ b/src/pages/TextHashPage.jsx @@ -1,31 +1,71 @@ -import { Button, Card, Checkbox, Container, Group, Loader, Stack, Textarea } from '@mantine/core'; +import { useEffect, useRef } from 'react'; +import { + Button, + Card, + Checkbox, + Container, + Group, + Loader, + Stack, + Text, + Textarea, +} from '@mantine/core'; import { AlertModal } from '../components/AlertModal'; import { CompareHashInput } from '../components/CompareHashInput'; import { ContextMenuArea } from '../components/ContextMenuArea'; import { ExportButton } from '../components/ExportButton'; import { HashResultList } from '../components/HashResultList'; import { PageHeader } from '../components/PageHeader'; -import { useHash } from '../state/hashContext'; -import { useSettings } from '../state/settingsContext'; +import { useHashActions, useHashAlgorithms, useHashText } from '../state/hashContext'; +import { useLocale } from '../state/settingsContext'; +import { copyFromInputOrValue, mergePastedText, readClipboardText } from '../utils/clipboard'; const TextHashPage = () => { - const { t } = useSettings(); - const { - text, - setTextInput, - setTextComparing, - setTextCompareHash, - setTextError, - clearText, - runTextCalculation, - } = useHash(); + const { t } = useLocale(); + const { hasEnabledAlgorithms } = useHashAlgorithms(); + const { text, runTextCalculation } = useHashText(); + const { setTextInput, setTextComparing, setTextCompareHash, setTextError, clearText } = + useHashActions(); + const textareaRef = useRef(null); + const loadingRef = useRef(text.loading); + const mountedRef = useRef(true); + + useEffect(() => { + loadingRef.current = text.loading; + }, [text.loading]); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + + const handleCopyText = () => { + copyFromInputOrValue(textareaRef.current, textareaRef.current?.value ?? text.input).catch( + (error) => { + if (mountedRef.current) setTextError(String(error)); + }, + ); + }; const handlePasteText = () => { - navigator.clipboard.readText().then((clipboardText) => { - setTextInput(clipboardText); - }); + if (loadingRef.current) return; + readClipboardText() + .then((clipboardText) => { + if (!mountedRef.current || loadingRef.current) return; + const currentValue = textareaRef.current?.value ?? text.input; + setTextInput(mergePastedText(textareaRef.current, currentValue, clipboardText)); + }) + .catch((error) => { + if (mountedRef.current) setTextError(String(error)); + }); }; + const canClear = Boolean( + text.input || text.hashes?.length > 0 || (text.comparing && text.compareHash), + ); + return ( <> @@ -41,10 +81,12 @@ const TextHashPage = () => { navigator.clipboard.writeText(text.input)} - onPaste={handlePasteText} + onCopy={text.input ? handleCopyText : undefined} + onPaste={text.loading ? undefined : handlePasteText} >