From 86f3185c593385c872d7b1929ec92a64ca44aaab Mon Sep 17 00:00:00 2001 From: burnintuna Date: Thu, 23 Jul 2026 20:09:11 +0900 Subject: [PATCH] Release v0.2.3 --- Cargo.lock | 2 +- Cargo.toml | 2 +- .../io.github.comicviewer.Comicviewer.desktop | 4 +- ...ithub.comicviewer.Comicviewer.metainfo.xml | 1 + docs/RELEASING.ko.md | 8 +- packaging/install-or-update.sh | 2 +- src/browser.rs | 45 +- src/database.rs | 168 +++++++ src/main.rs | 88 +++- src/source.rs | 197 +++++++++ src/viewer.rs | 413 +++++++++++++++++- src/window.rs | 392 +++++++++++++++-- src/zip_cache.rs | 1 + 13 files changed, 1255 insertions(+), 68 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 43d3758..c37f0fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -182,7 +182,7 @@ checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" [[package]] name = "comicviewer" -version = "0.2.2" +version = "0.2.3" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index ee19cc1..a779210 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "comicviewer" -version = "0.2.2" +version = "0.2.3" edition = "2024" description = "A comic archive viewer for local and remote locations" license = "GPL-3.0-or-later" diff --git a/data/io.github.comicviewer.Comicviewer.desktop b/data/io.github.comicviewer.Comicviewer.desktop index 7578ae7..ee70b54 100644 --- a/data/io.github.comicviewer.Comicviewer.desktop +++ b/data/io.github.comicviewer.Comicviewer.desktop @@ -4,9 +4,9 @@ Name=Comicviewer Name[ko]=코믹뷰어 Comment=Read comic images stored in ZIP archives Comment[ko]=ZIP으로 압축된 만화 이미지를 봅니다 -Exec=comicviewer +Exec=comicviewer %f Icon=io.github.comicviewer.Comicviewer Terminal=false Categories=Graphics;Viewer; -MimeType=application/zip;application/vnd.comicbook+zip; +MimeType=application/zip;image/jpeg;image/png;image/webp;image/gif;image/bmp;image/avif;video/mp4;video/x-m4v;video/matroska;video/x-matroska;video/webm;video/quicktime;video/vnd.avi;video/x-msvideo;video/mpeg;video/ogg;inode/directory; StartupNotify=true diff --git a/data/io.github.comicviewer.Comicviewer.metainfo.xml b/data/io.github.comicviewer.Comicviewer.metainfo.xml index 7feae22..63dad52 100644 --- a/data/io.github.comicviewer.Comicviewer.metainfo.xml +++ b/data/io.github.comicviewer.Comicviewer.metainfo.xml @@ -26,6 +26,7 @@ + diff --git a/docs/RELEASING.ko.md b/docs/RELEASING.ko.md index 0225d74..fc4f5b0 100644 --- a/docs/RELEASING.ko.md +++ b/docs/RELEASING.ko.md @@ -55,7 +55,7 @@ AppImage 빌드가 끝나면 다음 스크립트로 체크섬과 통합 `tar.gz` 스크립트는 `Cargo.toml`에서 버전을 읽고 다음 파일을 생성합니다. -- `dist/Comicviewer-0.2.2-x86_64.AppImage.sha256` +- `dist/Comicviewer-0.2.3-x86_64.AppImage.sha256` - `dist/Comicviewer-latest-x86_64.tar.gz` - `dist/Comicviewer-latest-x86_64.tar.gz.sha256` @@ -78,10 +78,10 @@ sha256sum -c Comicviewer-latest-x86_64.tar.gz.sha256 ```sh git add Cargo.toml Cargo.lock data packaging README.md docs -git commit -m "Prepare v0.2.2 release" -git tag -a v0.2.2 -m "Comicviewer v0.2.2" +git commit -m "Release v0.2.3" +git tag -a v0.2.3 -m "Comicviewer v0.2.3" git push origin main -git push origin v0.2.2 +git push origin v0.2.3 ``` 이미 원격에 공개한 태그는 이동하거나 덮어쓰지 않습니다. 수정이 필요하면 새 diff --git a/packaging/install-or-update.sh b/packaging/install-or-update.sh index d650193..df1d294 100755 --- a/packaging/install-or-update.sh +++ b/packaging/install-or-update.sh @@ -109,7 +109,7 @@ temporary_appimage="" ln -sfn "${installed_appimage}" "${launcher}" while IFS= read -r line || [ -n "${line}" ]; do case "${line}" in - Exec=*) printf 'Exec="%s"\n' "${launcher}" ;; + Exec=*) printf 'Exec="%s" %%f\n' "${launcher}" ;; *) printf '%s\n' "${line}" ;; esac done < "${desktop_file}" > "${temporary_desktop}" diff --git a/src/browser.rs b/src/browser.rs index d3f31e3..65b5d8a 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -21,6 +21,7 @@ impl EntryKind { pub struct BrowserEntry { pub uri: String, pub name: String, + pub list_name: Option, pub kind: EntryKind, pub size: Option, pub modified: Option, @@ -28,6 +29,12 @@ pub struct BrowserEntry { pub etag: Option, } +impl BrowserEntry { + pub fn display_name(&self) -> &str { + self.list_name.as_deref().unwrap_or(&self.name) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SortField { Name, @@ -62,20 +69,28 @@ pub fn sort_entries( match field { SortField::Name => apply_direction( - natural_cmp_with_case(&left.name, &right.name, case_insensitive), + natural_cmp_with_case(left.display_name(), right.display_name(), case_insensitive), direction, ), SortField::Modified => compare_optional_time(left.modified, right.modified, direction) .then_with(|| { apply_direction( - natural_cmp_with_case(&left.name, &right.name, case_insensitive), + natural_cmp_with_case( + left.display_name(), + right.display_name(), + case_insensitive, + ), direction, ) }), SortField::Created => compare_optional_time(left.created, right.created, direction) .then_with(|| { apply_direction( - natural_cmp_with_case(&left.name, &right.name, case_insensitive), + natural_cmp_with_case( + left.display_name(), + right.display_name(), + case_insensitive, + ), direction, ) }), @@ -212,6 +227,30 @@ mod tests { ); } + #[test] + fn recursive_entries_sort_by_relative_display_path() { + let mut entries = ["10권/page.jpg", "2권/page.jpg"].map(|list_name| BrowserEntry { + uri: format!("file:///{list_name}"), + name: "page.jpg".into(), + list_name: Some(list_name.into()), + kind: EntryKind::Image, + size: None, + modified: None, + created: None, + etag: None, + }); + + sort_entries( + &mut entries, + SortField::Name, + SortDirection::Ascending, + true, + ); + + assert_eq!(entries[0].display_name(), "2권/page.jpg"); + assert_eq!(entries[1].display_name(), "10권/page.jpg"); + } + #[test] fn zip_extension_is_case_insensitive() { assert_eq!(classify_file(Path::new("comic.ZIP")), EntryKind::ZipArchive); diff --git a/src/database.rs b/src/database.rs index c8aa0af..41e114b 100644 --- a/src/database.rs +++ b/src/database.rs @@ -2,8 +2,11 @@ use std::path::Path; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result}; +use gtk::gio::prelude::*; use rusqlite::{Connection, OptionalExtension, params}; +use crate::browser::{BrowserEntry, EntryKind}; + pub struct Database { connection: Connection, } @@ -105,6 +108,124 @@ impl Database { )?; Ok(()) } + + pub fn load_cached_tree(&self, location_id: &str, root_uri: &str) -> Result> { + let mut statement = self.connection.prepare( + "WITH RECURSIVE tree(uri, name, path, entry_kind, size, modified_at, created_at, etag) AS ( + SELECT uri, name, name, entry_kind, size, modified_at, created_at, etag + FROM cached_entries + WHERE location_id = ?1 AND parent_uri = ?2 + UNION ALL + SELECT child.uri, child.name, tree.path || '/' || child.name, + child.entry_kind, child.size, child.modified_at, child.created_at, child.etag + FROM cached_entries AS child + JOIN tree ON child.parent_uri = tree.uri + WHERE child.location_id = ?1 + ) + SELECT uri, name, path, entry_kind, size, modified_at, created_at, etag + FROM tree ORDER BY path", + )?; + let rows = statement.query_map(params![location_id, root_uri], |row| { + let kind = entry_kind_from_i64(row.get(3)?); + let size = row + .get::<_, Option>(4)? + .and_then(|value| u64::try_from(value).ok()); + Ok(BrowserEntry { + uri: row.get(0)?, + name: row.get(1)?, + list_name: Some(row.get(2)?), + kind, + size, + modified: row.get::<_, Option>(5)?.and_then(system_time_from_i64), + created: row.get::<_, Option>(6)?.and_then(system_time_from_i64), + etag: row.get(7)?, + }) + })?; + rows.collect::>>() + .map_err(Into::into) + } + + pub fn replace_cached_tree( + &self, + location_id: &str, + root_uri: &str, + entries: &[BrowserEntry], + ) -> Result<()> { + let transaction = self.connection.unchecked_transaction()?; + transaction.execute( + "WITH RECURSIVE tree(uri) AS ( + SELECT uri FROM cached_entries WHERE location_id = ?1 AND parent_uri = ?2 + UNION + SELECT child.uri FROM cached_entries AS child + JOIN tree ON child.parent_uri = tree.uri + WHERE child.location_id = ?1 + ) + DELETE FROM cached_entries + WHERE location_id = ?1 AND uri IN (SELECT uri FROM tree)", + params![location_id, root_uri], + )?; + let refreshed_at = system_time_to_i64(SystemTime::now()); + { + let mut statement = transaction.prepare( + "INSERT INTO cached_entries + (location_id, parent_uri, uri, name, entry_kind, size, modified_at, + created_at, etag, refreshed_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", + )?; + for entry in entries { + let parent_uri = gtk::gio::File::for_uri(&entry.uri) + .parent() + .map(|parent| parent.uri().to_string()) + .unwrap_or_else(|| root_uri.to_owned()); + statement.execute(params![ + location_id, + parent_uri, + entry.uri, + entry.name, + entry_kind_to_i64(entry.kind), + entry.size.and_then(|value| i64::try_from(value).ok()), + entry.modified.map(system_time_to_i64), + entry.created.map(system_time_to_i64), + entry.etag, + refreshed_at, + ])?; + } + } + transaction.commit()?; + Ok(()) + } +} + +fn entry_kind_to_i64(kind: EntryKind) -> i64 { + match kind { + EntryKind::Directory => 0, + EntryKind::ZipArchive => 1, + EntryKind::Image => 2, + EntryKind::Video => 3, + EntryKind::OtherFile => 4, + } +} + +fn entry_kind_from_i64(value: i64) -> EntryKind { + match value { + 0 => EntryKind::Directory, + 1 => EntryKind::ZipArchive, + 2 => EntryKind::Image, + 3 => EntryKind::Video, + _ => EntryKind::OtherFile, + } +} + +fn system_time_to_i64(time: SystemTime) -> i64 { + time.duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() as i64 +} + +fn system_time_from_i64(seconds: i64) -> Option { + u64::try_from(seconds) + .ok() + .map(|seconds| UNIX_EPOCH + std::time::Duration::from_secs(seconds)) } #[cfg(test)] @@ -122,4 +243,51 @@ mod tests { database.save_progress("test.zip", 9, 20).unwrap(); assert_eq!(database.load_progress("test.zip").unwrap(), Some(9)); } + + #[test] + fn cached_tree_replaces_descendants_and_restores_relative_paths() { + let database = Database::open(Path::new(":memory:")).unwrap(); + let entries = vec![ + BrowserEntry { + uri: "file:///library/series".into(), + name: "series".into(), + list_name: Some("series".into()), + kind: EntryKind::Directory, + size: None, + modified: None, + created: None, + etag: None, + }, + BrowserEntry { + uri: "file:///library/series/book.zip".into(), + name: "book.zip".into(), + list_name: Some("series/book.zip".into()), + kind: EntryKind::ZipArchive, + size: Some(42), + modified: None, + created: None, + etag: Some("v1".into()), + }, + ]; + + database + .replace_cached_tree("library", "file:///library", &entries) + .unwrap(); + let loaded = database + .load_cached_tree("library", "file:///library") + .unwrap(); + assert_eq!(loaded.len(), 2); + assert_eq!(loaded[1].display_name(), "series/book.zip"); + + database + .replace_cached_tree("library", "file:///library", &entries[..1]) + .unwrap(); + assert_eq!( + database + .load_cached_tree("library", "file:///library") + .unwrap() + .len(), + 1 + ); + } } diff --git a/src/main.rs b/src/main.rs index f48b1a6..dccd524 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,36 +8,86 @@ mod viewer; mod window; mod zip_cache; +use std::cell::RefCell; +use std::rc::Rc; + use anyhow::Result; +use gtk::gio; use gtk::prelude::*; const APP_ID: &str = "io.github.comicviewer.Comicviewer"; fn main() { - let application = gtk::Application::builder().application_id(APP_ID).build(); + let application = gtk::Application::builder() + .application_id(APP_ID) + .flags(application_flags()) + .build(); + let state = Rc::new(ApplicationState::default()); - application.connect_activate(|application| { - if let Err(error) = activate(application) { - eprintln!("Comicviewer를 시작하지 못했습니다: {error:#}"); - application.quit(); + let activate_state = Rc::clone(&state); + application.connect_activate(move |application| { + match activate_state.ensure_main_window(application) { + Ok(window) => window.present(), + Err(error) => startup_failed(application, &error), + } + }); + application.connect_open(move |application, files, _| { + match state.ensure_main_window(application) { + Ok(window) => window.open_local_items(files), + Err(error) => startup_failed(application, &error), } }); application.run(); } -fn activate(application: >k::Application) -> Result<()> { - let app_paths = paths::AppPaths::discover()?; - let config = config::AppConfig::load_or_create(&app_paths.config_file)?; - let database = database::Database::open(&app_paths.database_file)?; - let zip_cache = zip_cache::ZipCache::new(app_paths.zip_cache_dir, config.cache_quota_gb)?; - let window = window::ComicWindow::new( - application, - config, - app_paths.config_file, - database, - zip_cache, - )?; - window.present(); - Ok(()) +#[derive(Default)] +struct ApplicationState { + main_window: RefCell>>, +} + +impl ApplicationState { + fn ensure_main_window( + &self, + application: >k::Application, + ) -> Result> { + if let Some(window) = self.main_window.borrow().as_ref() { + return Ok(Rc::clone(window)); + } + let app_paths = paths::AppPaths::discover()?; + let config = config::AppConfig::load_or_create(&app_paths.config_file)?; + let database = database::Database::open(&app_paths.database_file)?; + let zip_cache = zip_cache::ZipCache::new(app_paths.zip_cache_dir, config.cache_quota_gb)?; + let window = Rc::new(window::ComicWindow::new( + application, + config, + app_paths.config_file, + database, + zip_cache, + )?); + self.main_window.replace(Some(Rc::clone(&window))); + Ok(window) + } +} + +fn startup_failed(application: >k::Application, error: &anyhow::Error) { + eprintln!("Comicviewer를 시작하지 못했습니다: {error:#}"); + application.quit(); +} + +fn application_flags() -> gio::ApplicationFlags { + gio::ApplicationFlags::HANDLES_OPEN +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn application_accepts_files_as_a_single_instance() { + let flags = application_flags(); + assert!(flags.contains(gio::ApplicationFlags::HANDLES_OPEN)); + assert!(!flags.contains(gio::ApplicationFlags::NON_UNIQUE)); + assert!(!flags.contains(gio::ApplicationFlags::HANDLES_COMMAND_LINE)); + } } diff --git a/src/source.rs b/src/source.rs index 7dd535e..fc9b2c2 100644 --- a/src/source.rs +++ b/src/source.rs @@ -1,3 +1,4 @@ +use std::collections::{HashSet, VecDeque}; use std::path::Path; use std::time::{Duration, UNIX_EPOCH}; @@ -11,6 +12,17 @@ use crate::browser::{BrowserEntry, EntryKind, classify_file}; use crate::config::{LocationKind, LocationProfile}; const ATTRIBUTES: &str = "standard::display-name,standard::name,standard::type,standard::size,standard::target-uri,mountable::can-mount,time::modified,time::created,etag::value"; +const RECURSIVE_ATTRIBUTES: &str = "standard::display-name,standard::name,standard::type,standard::is-symlink,standard::size,time::modified,time::created,etag::value,id::file,id::filesystem"; +const MAX_RECURSIVE_DIRECTORIES: usize = 10_000; +const MAX_RECURSIVE_ENTRIES: usize = 100_000; + +#[derive(Clone, Copy, Default)] +pub struct RecursiveProgress { + pub directories: usize, + pub scanned: usize, + pub viewable: usize, + pub skipped: usize, +} pub fn root_file(profile: &LocationProfile) -> Result { validate_profile(profile)?; @@ -125,6 +137,7 @@ where entries.push(BrowserEntry { uri, name: info.display_name().into(), + list_name: None, kind, size: info .has_attribute("standard::size") @@ -144,6 +157,143 @@ where Ok(entries) } +pub async fn enumerate_tree_entries( + profile: &LocationProfile, + root: &gio::File, + operation: Option<>k::MountOperation>, + mut progress: F, +) -> Result<(Vec, RecursiveProgress)> +where + F: FnMut(RecursiveProgress), +{ + if profile.kind != LocationKind::Local && !root.is_native() { + let operation = operation.context("원격 폴더 마운트 정보가 없습니다")?; + ensure_mounted(root, profile, operation).await?; + } + let mut pending = VecDeque::from([(root.clone(), String::new())]); + let mut visited = HashSet::new(); + let mut visited_identities = HashSet::new(); + if let Ok(info) = root + .query_info_future( + "id::file,id::filesystem", + gio::FileQueryInfoFlags::NOFOLLOW_SYMLINKS, + glib::Priority::DEFAULT, + ) + .await + && let Some(identity) = recursive_file_identity(&info) + { + visited_identities.insert(identity); + } + let mut entries = Vec::new(); + let mut state = RecursiveProgress::default(); + + while let Some((directory, relative_directory)) = pending.pop_front() { + let directory_uri: String = directory.uri().into(); + if !visited.insert(directory_uri.clone()) { + continue; + } + if visited.len() > MAX_RECURSIVE_DIRECTORIES { + bail!("하위 폴더 수가 안전 제한을 초과합니다 (최대 {MAX_RECURSIVE_DIRECTORIES}개)"); + } + let enumerator = match directory + .enumerate_children_future( + RECURSIVE_ATTRIBUTES, + gio::FileQueryInfoFlags::NOFOLLOW_SYMLINKS, + glib::Priority::DEFAULT, + ) + .await + { + Ok(enumerator) => enumerator, + Err(error) if directory.equal(root) => { + return Err(error) + .with_context(|| format!("폴더에 접근할 수 없습니다: {}", directory.uri())); + } + Err(_) => { + state.skipped += 1; + progress(state); + continue; + } + }; + state.directories += 1; + loop { + let batch = enumerator + .next_files_future(128, glib::Priority::DEFAULT) + .await?; + if batch.is_empty() { + break; + } + state.scanned += batch.len(); + if state.scanned > MAX_RECURSIVE_ENTRIES { + bail!("하위 항목 수가 안전 제한을 초과합니다 (최대 {MAX_RECURSIVE_ENTRIES}개)"); + } + for info in batch { + let child = enumerator.child(&info); + if info.is_symlink() || !is_within_root(&child, root) { + continue; + } + let display_name = info.display_name(); + let relative_name = if relative_directory.is_empty() { + display_name.to_string() + } else { + format!("{relative_directory}/{display_name}") + }; + match info.file_type() { + gio::FileType::Directory => { + if let Some(identity) = recursive_file_identity(&info) + && !visited_identities.insert(identity) + { + continue; + } + pending.push_back((child.clone(), relative_name.clone())); + entries.push(BrowserEntry { + uri: child.uri().into(), + name: display_name.into(), + list_name: Some(relative_name), + kind: EntryKind::Directory, + size: None, + modified: attribute_time(&info, "time::modified"), + created: attribute_time(&info, "time::created"), + etag: info + .has_attribute("etag::value") + .then(|| info.etag()) + .flatten() + .map(Into::into), + }); + } + gio::FileType::Regular => { + let kind = classify_file(Path::new(display_name.as_str())); + if !kind.is_viewable() { + continue; + } + state.viewable += 1; + entries.push(BrowserEntry { + uri: child.uri().into(), + name: display_name.into(), + list_name: Some(relative_name), + kind, + size: info + .has_attribute("standard::size") + .then(|| info.size()) + .filter(|size| *size >= 0) + .map(|size| size as u64), + modified: attribute_time(&info, "time::modified"), + created: attribute_time(&info, "time::created"), + etag: info + .has_attribute("etag::value") + .then(|| info.etag()) + .flatten() + .map(Into::into), + }); + } + _ => {} + } + } + progress(state); + } + } + Ok((entries, state)) +} + pub fn mount_operation( profile: &LocationProfile, parent: &impl glib::object::IsA, @@ -239,8 +389,16 @@ fn attribute_time(info: &gio::FileInfo, attribute: &str) -> Option Option { + let filesystem = info.attribute_string("id::filesystem")?; + let file = info.attribute_string("id::file")?; + Some(format!("{filesystem}:{file}")) +} + #[cfg(test)] mod tests { + use std::fs; + use super::*; #[test] @@ -290,4 +448,43 @@ mod tests { let encoded_input = file_from_user_input(LocationKind::Ftp, encoded.uri().as_str()); assert!(encoded_input.equal(&encoded)); } + + #[test] + fn recursively_lists_viewable_files_without_following_symlinks() { + let directory = tempfile::tempdir().unwrap(); + let subdirectory = directory.path().join("2권"); + fs::create_dir(&subdirectory).unwrap(); + fs::write(directory.path().join("10.zip"), []).unwrap(); + fs::write(subdirectory.join("page2.jpg"), []).unwrap(); + fs::write(subdirectory.join("notes.txt"), []).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(directory.path(), subdirectory.join("loop")).unwrap(); + let profile = LocationProfile { + name: "test".into(), + kind: LocationKind::Local, + address: directory.path().to_string_lossy().into_owned(), + username: String::new(), + password: String::new(), + domain: String::new(), + }; + let root = gio::File::for_path(directory.path()); + let (entries, progress) = glib::MainContext::default() + .block_on(enumerate_tree_entries(&profile, &root, None, |_| {})) + .unwrap(); + + assert!( + entries.iter().any(|entry| { + entry.kind == EntryKind::Directory && entry.display_name() == "2권" + }) + ); + assert!(entries.iter().any(|entry| { + entry.kind == EntryKind::ZipArchive && entry.display_name() == "10.zip" + })); + assert!(entries.iter().any(|entry| { + entry.kind == EntryKind::Image && entry.display_name() == "2권/page2.jpg" + })); + assert!(!entries.iter().any(|entry| entry.name == "notes.txt")); + assert!(!entries.iter().any(|entry| entry.name == "loop")); + assert_eq!(progress.skipped, 0); + } } diff --git a/src/viewer.rs b/src/viewer.rs index 40f30e9..5050408 100644 --- a/src/viewer.rs +++ b/src/viewer.rs @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::rc::{Rc, Weak}; use std::sync::mpsc::{self, TryRecvError}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use gtk::gdk; use gtk::glib; @@ -26,12 +26,12 @@ const MEDIA_VIEWER_CONTROLLER_KEY: &str = "comicviewer-media-viewer-controller"; fn clear_viewer_controller(window: >k::ApplicationWindow) { unsafe { if let Some(controller) = window.steal_data::>(VIEWER_CONTROLLER_KEY) { - controller.stop_animations(); + controller.detach_window_controllers(); } if let Some(controller) = window.steal_data::>(MEDIA_VIEWER_CONTROLLER_KEY) { - controller.stop_playback(); + controller.prepare_for_navigation(); } } } @@ -47,7 +47,45 @@ fn ensure_viewer_close_handler(window: >k::ApplicationWindow) { }); } -pub(crate) fn set_viewer_header(window: >k::ApplicationWindow, header: >k::HeaderBar) { +pub(crate) fn set_viewer_loading(window: >k::ApplicationWindow, loading: bool) { + if !window.has_css_class("viewer-loading-key-handler") { + window.add_css_class("viewer-loading-key-handler"); + let keys = gtk::EventControllerKey::new(); + keys.set_propagation_phase(gtk::PropagationPhase::Capture); + let weak_window = window.downgrade(); + keys.connect_key_pressed(move |_, key, _, _| { + let Some(window) = weak_window.upgrade() else { + return glib::Propagation::Proceed; + }; + if !window.has_css_class("viewer-loading") || !window.is_fullscreen() { + return glib::Propagation::Proceed; + } + if let Some(titlebar) = window.titlebar() { + titlebar.set_visible(true); + } + if key == gdk::Key::Escape + || key + .to_unicode() + .is_some_and(|character| character.eq_ignore_ascii_case(&'f')) + { + window.unfullscreen(); + return glib::Propagation::Stop; + } + glib::Propagation::Proceed + }); + window.add_controller(keys); + } + if loading { + window.add_css_class("viewer-loading"); + } else { + window.remove_css_class("viewer-loading"); + } +} + +pub(crate) fn set_viewer_header( + window: >k::ApplicationWindow, + header: >k::HeaderBar, +) -> gtk::Box { let host = window .titlebar() .and_downcast::() @@ -62,6 +100,8 @@ pub(crate) fn set_viewer_header(window: >k::ApplicationWindow, header: >k::H } header.set_hexpand(true); host.append(header); + host.set_visible(!window.is_fullscreen()); + host } pub struct ViewerWindow; @@ -244,6 +284,7 @@ impl ViewerWindow { }); install_file_drop_target(&window, file_drop_control); ensure_viewer_close_handler(&window); + set_viewer_loading(&window, false); window.set_title(Some(&title)); let header = gtk::HeaderBar::new(); header.set_title_widget(Some(>k::Label::new(Some(&title)))); @@ -255,7 +296,7 @@ impl ViewerWindow { header.pack_end(&download_button); header.pack_end(&favorite_button); header.pack_end(&file_list_button); - set_viewer_header(&window, &header); + let titlebar_host = set_viewer_header(&window, &header); let root = gtk::Box::new(gtk::Orientation::Vertical, 0); let toolbar = gtk::Box::new(gtk::Orientation::Horizontal, 6); @@ -358,6 +399,7 @@ impl ViewerWindow { let controller = Rc::new(ViewerController { window, + titlebar_host, source, database, stack, @@ -372,6 +414,7 @@ impl ViewerWindow { page_label, page_seek, page_seek_row, + toolbar, status_label, previous_button, next_button, @@ -395,6 +438,10 @@ impl ViewerWindow { last_pointer_position: Cell::new(None), key_controller: RefCell::new(None), motion_controller: RefCell::new(None), + fullscreen_key_controller: RefCell::new(None), + fullscreen_ui_hide_timer: RefCell::new(None), + fullscreen_ui_visible: Cell::new(false), + fullscreen_notify_handler: RefCell::new(None), navigation_message, navigation_message_label, navigation_message_generation: Rc::new(Cell::new(0)), @@ -417,6 +464,7 @@ impl ViewerWindow { }), }); controller.connect_signals(); + controller.fullscreen_changed(); if controller.file_list_button.is_active() { controller.refresh_file_list(); } @@ -506,6 +554,7 @@ struct ViewerState { struct ViewerController { window: gtk::ApplicationWindow, + titlebar_host: gtk::Box, source: ArchiveSource, database: Rc, stack: gtk::Stack, @@ -520,6 +569,7 @@ struct ViewerController { page_label: gtk::Label, page_seek: gtk::Scale, page_seek_row: gtk::Box, + toolbar: gtk::Box, status_label: gtk::Label, previous_button: gtk::Button, next_button: gtk::Button, @@ -543,6 +593,10 @@ struct ViewerController { last_pointer_position: Cell>, key_controller: RefCell>, motion_controller: RefCell>, + fullscreen_key_controller: RefCell>, + fullscreen_ui_hide_timer: RefCell>, + fullscreen_ui_visible: Cell, + fullscreen_notify_handler: RefCell>, navigation_message: gtk::Box, navigation_message_label: gtk::Label, navigation_message_generation: Rc>, @@ -612,7 +666,11 @@ impl ViewerController { let controller = Rc::downgrade(self); self.file_list_button.connect_toggled(move |button| { if let Some(controller) = controller.upgrade() { - controller.file_list_panel.set_visible(button.is_active()); + controller.file_list_panel.set_visible( + button.is_active() + && (!controller.window.is_fullscreen() + || controller.fullscreen_ui_visible.get()), + ); if button.is_active() { controller.window.add_css_class("viewer-file-list-visible"); } else { @@ -631,6 +689,22 @@ impl ViewerController { controller.open_file_list_row(row.index()); } }); + let file_list_typeahead = Rc::new(RefCell::new(TypeaheadBuffer::default())); + let file_list_keys = gtk::EventControllerKey::new(); + let controller = Rc::downgrade(self); + file_list_keys.connect_key_pressed(move |_, key, _, modifiers| { + let Some(controller) = controller.upgrade() else { + return glib::Propagation::Proceed; + }; + file_list_typeahead_select( + &controller.file_list, + &controller.file_list_files.borrow(), + &mut file_list_typeahead.borrow_mut(), + key, + modifiers, + ) + }); + self.file_list.add_controller(file_list_keys); let file_list_click = gtk::GestureClick::builder().button(3).build(); let controller = Rc::downgrade(self); file_list_click.connect_pressed(move |_, _, x, y| { @@ -717,13 +791,30 @@ impl ViewerController { self.window.add_controller(motion_controller.clone()); self.motion_controller.replace(Some(motion_controller)); + let fullscreen_keys = gtk::EventControllerKey::new(); + fullscreen_keys.set_propagation_phase(gtk::PropagationPhase::Capture); + let controller = Rc::downgrade(self); + fullscreen_keys.connect_key_pressed(move |_, _, _, _| { + if let Some(controller) = controller.upgrade() + && controller.window.is_fullscreen() + { + controller.show_fullscreen_ui_temporarily(); + } + glib::Propagation::Proceed + }); + self.window.add_controller(fullscreen_keys.clone()); + self.fullscreen_key_controller + .replace(Some(fullscreen_keys)); + let key_controller = gtk::EventControllerKey::new(); let controller = Rc::downgrade(self); key_controller.connect_key_pressed(move |_, key, _, _| { let Some(controller) = controller.upgrade() else { return glib::Propagation::Proceed; }; - controller.hide_seek(); + if !controller.window.is_fullscreen() { + controller.hide_seek(); + } match key { gdk::Key::Home => { controller.seek_edge(false); @@ -783,6 +874,15 @@ impl ViewerController { }); self.window.add_controller(key_controller.clone()); self.key_controller.replace(Some(key_controller)); + let controller = Rc::downgrade(self); + let handler = self + .window + .connect_notify_local(Some("fullscreened"), move |_, _| { + if let Some(controller) = controller.upgrade() { + controller.fullscreen_changed(); + } + }); + self.fullscreen_notify_handler.replace(Some(handler)); } fn open_sibling(&self, forward: bool) { @@ -876,12 +976,22 @@ impl ViewerController { fn detach_window_controllers(&self) { self.stop_animations(); + if let Some(timer) = self.seek_hide_timer.borrow_mut().take() { + timer.remove(); + } + self.cancel_fullscreen_ui_timer(); + if let Some(handler) = self.fullscreen_notify_handler.borrow_mut().take() { + self.window.disconnect(handler); + } if let Some(controller) = self.key_controller.borrow_mut().take() { self.window.remove_controller(&controller); } if let Some(controller) = self.motion_controller.borrow_mut().take() { self.window.remove_controller(&controller); } + if let Some(controller) = self.fullscreen_key_controller.borrow_mut().take() { + self.window.remove_controller(&controller); + } } fn stop_animations(&self) { @@ -913,7 +1023,11 @@ impl ViewerController { return; } self.last_pointer_position.set(Some((x, y))); - self.show_seek_temporarily(); + if self.window.is_fullscreen() { + self.show_fullscreen_ui_temporarily(); + } else { + self.show_seek_temporarily(); + } } fn hide_seek(self: &Rc) { @@ -947,6 +1061,62 @@ impl ViewerController { } } + fn fullscreen_changed(self: &Rc) { + self.cancel_fullscreen_ui_timer(); + self.hide_seek(); + if self.window.is_fullscreen() { + self.set_fullscreen_ui_visible(false); + } else { + self.fullscreen_ui_visible.set(true); + self.titlebar_host.set_visible(true); + self.toolbar.set_visible(true); + self.status_label.set_visible(true); + self.file_list_panel + .set_visible(self.file_list_button.is_active()); + } + } + + fn show_fullscreen_ui_temporarily(self: &Rc) { + if !self.window.is_fullscreen() { + return; + } + self.cancel_fullscreen_ui_timer(); + self.set_fullscreen_ui_visible(true); + let controller = Rc::downgrade(self); + let timer = glib::timeout_add_local_once(Duration::from_secs(5), move || { + if let Some(controller) = controller.upgrade() { + controller.fullscreen_ui_hide_timer.borrow_mut().take(); + controller.set_fullscreen_ui_visible(false); + } + }); + self.fullscreen_ui_hide_timer.replace(Some(timer)); + } + + fn cancel_fullscreen_ui_timer(&self) { + if let Some(timer) = self.fullscreen_ui_hide_timer.borrow_mut().take() { + timer.remove(); + } + } + + fn set_fullscreen_ui_visible(self: &Rc, visible: bool) { + self.fullscreen_ui_visible.set(visible); + self.titlebar_host.set_visible(visible); + self.toolbar.set_visible(visible); + self.page_seek_row.set_visible(visible); + self.status_label.set_visible(visible); + self.file_list_panel + .set_visible(visible && self.file_list_button.is_active()); + self.window.queue_allocate(); + let controller = Rc::downgrade(self); + glib::idle_add_local_once(move || { + if let Some(controller) = controller.upgrade() { + controller.stack.queue_allocate(); + controller.resize_continuous_rows(); + controller.render(); + } + }); + } + fn load_archive(self: &Rc) { self.spinner.start(); let path = self.source.local_path.clone(); @@ -1727,6 +1897,7 @@ impl MediaViewerWindow { }); install_file_drop_target(&window, file_drop_control); ensure_viewer_close_handler(&window); + set_viewer_loading(&window, false); window.set_title(Some(&title)); let header = gtk::HeaderBar::new(); header.set_title_widget(Some(>k::Label::new(Some(&title)))); @@ -1752,7 +1923,7 @@ impl MediaViewerWindow { header.pack_end(&download_button); header.pack_end(&favorite_button); header.pack_end(&file_list_button); - set_viewer_header(&window, &header); + let titlebar_host = set_viewer_header(&window, &header); let root = gtk::Box::new(gtk::Orientation::Vertical, 0); let stack = gtk::Stack::new(); @@ -1816,6 +1987,7 @@ impl MediaViewerWindow { let controller = Rc::new(MediaViewerController { window, + titlebar_host, source, kind, picture, @@ -1845,6 +2017,10 @@ impl MediaViewerWindow { last_pointer_position: Cell::new(None), key_controller: RefCell::new(None), motion_controller: RefCell::new(None), + fullscreen_key_controller: RefCell::new(None), + fullscreen_ui_hide_timer: RefCell::new(None), + fullscreen_ui_visible: Cell::new(false), + fullscreen_notify_handler: RefCell::new(None), navigation_message, navigation_message_label, navigation_message_generation: Rc::new(Cell::new(0)), @@ -1858,6 +2034,7 @@ impl MediaViewerWindow { }); } controller.connect_signals(); + controller.fullscreen_changed(); if controller.file_list_button.is_active() { controller.refresh_file_list(); } @@ -1883,6 +2060,7 @@ impl MediaViewerWindow { struct MediaViewerController { window: gtk::ApplicationWindow, + titlebar_host: gtk::Box, source: ArchiveSource, kind: EntryKind, picture: gtk::Picture, @@ -1912,6 +2090,10 @@ struct MediaViewerController { last_pointer_position: Cell>, key_controller: RefCell>, motion_controller: RefCell>, + fullscreen_key_controller: RefCell>, + fullscreen_ui_hide_timer: RefCell>, + fullscreen_ui_visible: Cell, + fullscreen_notify_handler: RefCell>, navigation_message: gtk::Box, navigation_message_label: gtk::Label, navigation_message_generation: Rc>, @@ -1930,6 +2112,21 @@ impl MediaViewerController { self.window.add_controller(motion_controller.clone()); self.motion_controller.replace(Some(motion_controller)); + let fullscreen_keys = gtk::EventControllerKey::new(); + fullscreen_keys.set_propagation_phase(gtk::PropagationPhase::Capture); + let controller = Rc::downgrade(self); + fullscreen_keys.connect_key_pressed(move |_, _, _, _| { + if let Some(controller) = controller.upgrade() + && controller.window.is_fullscreen() + { + controller.show_fullscreen_ui_temporarily(); + } + glib::Propagation::Proceed + }); + self.window.add_controller(fullscreen_keys.clone()); + self.fullscreen_key_controller + .replace(Some(fullscreen_keys)); + let keys = gtk::EventControllerKey::new(); let controller = Rc::downgrade(self); keys.connect_key_pressed(move |_, key, _, modifiers| { @@ -1943,7 +2140,9 @@ impl MediaViewerController { ) { return glib::Propagation::Proceed; } - controller.hide_seek(); + if !controller.window.is_fullscreen() { + controller.hide_seek(); + } match key { gdk::Key::Left if controller.kind == EntryKind::Video => { controller.seek_video(-VIDEO_SEEK_STEP_US); @@ -2014,6 +2213,15 @@ impl MediaViewerController { self.window.add_controller(keys.clone()); self.key_controller.replace(Some(keys)); let controller = Rc::downgrade(self); + let handler = self + .window + .connect_notify_local(Some("fullscreened"), move |_, _| { + if let Some(controller) = controller.upgrade() { + controller.fullscreen_changed(); + } + }); + self.fullscreen_notify_handler.replace(Some(handler)); + let controller = Rc::downgrade(self); self.favorite_button.connect_clicked(move |_| { if let Some(controller) = controller.upgrade() { let active = (controller.favorite_toggle)(); @@ -2032,7 +2240,11 @@ impl MediaViewerController { let controller = Rc::downgrade(self); self.file_list_button.connect_toggled(move |button| { if let Some(controller) = controller.upgrade() { - controller.file_list_panel.set_visible(button.is_active()); + controller.file_list_panel.set_visible( + button.is_active() + && (!controller.window.is_fullscreen() + || controller.fullscreen_ui_visible.get()), + ); if button.is_active() { controller.window.add_css_class("viewer-file-list-visible"); } else { @@ -2051,6 +2263,22 @@ impl MediaViewerController { controller.open_file_list_row(row.index()); } }); + let file_list_typeahead = Rc::new(RefCell::new(TypeaheadBuffer::default())); + let file_list_keys = gtk::EventControllerKey::new(); + let controller = Rc::downgrade(self); + file_list_keys.connect_key_pressed(move |_, key, _, modifiers| { + let Some(controller) = controller.upgrade() else { + return glib::Propagation::Proceed; + }; + file_list_typeahead_select( + &controller.file_list, + &controller.file_list_files.borrow(), + &mut file_list_typeahead.borrow_mut(), + key, + modifiers, + ) + }); + self.file_list.add_controller(file_list_keys); let file_list_click = gtk::GestureClick::builder().button(3).build(); let controller = Rc::downgrade(self); file_list_click.connect_pressed(move |_, _, x, y| { @@ -2318,7 +2546,11 @@ impl MediaViewerController { return; } self.last_pointer_position.set(Some((x, y))); - self.show_seek_temporarily(); + if self.window.is_fullscreen() { + self.show_fullscreen_ui_temporarily(); + } else { + self.show_seek_temporarily(); + } } fn hide_seek(self: &Rc) { @@ -2377,12 +2609,22 @@ impl MediaViewerController { fn prepare_for_navigation(&self) { self.stop_playback(); + if let Some(timer) = self.seek_hide_timer.borrow_mut().take() { + timer.remove(); + } + self.cancel_fullscreen_ui_timer(); + if let Some(handler) = self.fullscreen_notify_handler.borrow_mut().take() { + self.window.disconnect(handler); + } if let Some(controller) = self.key_controller.borrow_mut().take() { self.window.remove_controller(&controller); } if let Some(controller) = self.motion_controller.borrow_mut().take() { self.window.remove_controller(&controller); } + if let Some(controller) = self.fullscreen_key_controller.borrow_mut().take() { + self.window.remove_controller(&controller); + } } fn stop_playback(&self) { @@ -2400,6 +2642,61 @@ impl MediaViewerController { } } + fn fullscreen_changed(self: &Rc) { + self.cancel_fullscreen_ui_timer(); + self.hide_seek(); + if self.window.is_fullscreen() { + self.set_fullscreen_ui_visible(false); + } else { + self.fullscreen_ui_visible.set(true); + self.titlebar_host.set_visible(true); + self.status_label.set_visible(true); + self.file_list_panel + .set_visible(self.file_list_button.is_active()); + } + } + + fn show_fullscreen_ui_temporarily(self: &Rc) { + if !self.window.is_fullscreen() { + return; + } + self.cancel_fullscreen_ui_timer(); + self.set_fullscreen_ui_visible(true); + let controller = Rc::downgrade(self); + let timer = glib::timeout_add_local_once(Duration::from_secs(5), move || { + if let Some(controller) = controller.upgrade() { + controller.fullscreen_ui_hide_timer.borrow_mut().take(); + controller.set_fullscreen_ui_visible(false); + } + }); + self.fullscreen_ui_hide_timer.replace(Some(timer)); + } + + fn cancel_fullscreen_ui_timer(&self) { + if let Some(timer) = self.fullscreen_ui_hide_timer.borrow_mut().take() { + timer.remove(); + } + } + + fn set_fullscreen_ui_visible(self: &Rc, visible: bool) { + self.fullscreen_ui_visible.set(visible); + self.titlebar_host.set_visible(visible); + self.media_seek_row.set_visible(visible); + self.status_label.set_visible(visible); + self.file_list_panel + .set_visible(visible && self.file_list_button.is_active()); + self.window.queue_allocate(); + let controller = Rc::downgrade(self); + glib::idle_add_local_once(move || { + if let Some(controller) = controller.upgrade() { + controller.stack.queue_allocate(); + controller.picture.queue_allocate(); + controller.video.queue_allocate(); + controller.resize_image_picture(); + } + }); + } + fn load_image(self: &Rc) { self.stack.set_visible_child_name("image"); self.status_label.set_text("이미지를 읽는 중..."); @@ -2458,6 +2755,85 @@ struct ViewerFileList { list: gtk::ListBox, } +#[derive(Default)] +struct TypeaheadBuffer { + query: String, + last_input: Option, +} + +fn file_list_typeahead_select( + list: >k::ListBox, + files: &[SiblingFile], + state: &mut TypeaheadBuffer, + key: gdk::Key, + modifiers: gdk::ModifierType, +) -> glib::Propagation { + let blocked = gdk::ModifierType::CONTROL_MASK + | gdk::ModifierType::ALT_MASK + | gdk::ModifierType::SUPER_MASK; + if modifiers.intersects(blocked) { + return glib::Propagation::Proceed; + } + if key == gdk::Key::Escape { + state.query.clear(); + state.last_input = None; + return glib::Propagation::Proceed; + } + if matches!(key, gdk::Key::space) + || key.to_unicode().is_some_and(|character| { + character.eq_ignore_ascii_case(&'f') || matches!(character, '[' | ']') + }) + { + return glib::Propagation::Proceed; + } + let now = Instant::now(); + if state + .last_input + .is_none_or(|last| now.duration_since(last) > Duration::from_millis(1200)) + { + state.query.clear(); + } + if key == gdk::Key::BackSpace { + return if state.query.pop().is_some() { + state.last_input = Some(now); + glib::Propagation::Stop + } else { + glib::Propagation::Proceed + }; + } + let Some(character) = key.to_unicode().filter(|character| !character.is_control()) else { + return glib::Propagation::Proceed; + }; + let input = character.to_lowercase().collect::(); + let repeated_single = state.query.chars().count() == 1 && state.query == input; + if !repeated_single { + state.query.push_str(&input); + } + state.last_input = Some(now); + let selected = list.selected_row().map(|row| row.index() as usize); + let start = if repeated_single { + selected.map_or(0, |index| index + 1) + } else { + 0 + }; + let found = find_sibling_prefix(files, &state.query, start); + if let Some(row) = found.and_then(|index| list.row_at_index(index as i32)) { + list.select_row(Some(&row)); + let _ = row.grab_focus(); + } + glib::Propagation::Stop +} + +fn find_sibling_prefix(files: &[SiblingFile], query: &str, start: usize) -> Option { + if files.is_empty() { + return None; + } + let query = query.to_lowercase(); + (0..files.len()) + .map(|offset| (start + offset) % files.len()) + .find(|index| files[*index].name.to_lowercase().starts_with(&query)) +} + fn viewer_file_list() -> ViewerFileList { let list = gtk::ListBox::new(); list.set_selection_mode(gtk::SelectionMode::Single); @@ -2943,6 +3319,19 @@ mod tests { assert_eq!(video_volume_target(0.5, 0.05), 0.55); } + #[test] + fn viewer_file_typeahead_wraps_by_display_name() { + let files = ["Alpha.zip", "beta.jpg", "Bravo.mp4"].map(|name| SiblingFile { + uri: format!("file:///{name}"), + name: name.into(), + kind: EntryKind::Image, + }); + + assert_eq!(find_sibling_prefix(&files, "br", 0), Some(2)); + assert_eq!(find_sibling_prefix(&files, "b", 2), Some(2)); + assert_eq!(find_sibling_prefix(&files, "b", 3), Some(1)); + } + #[test] fn navigation_boundary_messages_match_direction() { assert_eq!( diff --git a/src/window.rs b/src/window.rs index 593370e..258c5d6 100644 --- a/src/window.rs +++ b/src/window.rs @@ -1,4 +1,4 @@ -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::fs; use std::path::{Path, PathBuf}; use std::rc::Rc; @@ -17,13 +17,14 @@ use crate::browser::{ use crate::config::{AppConfig, FavoriteEntry, LocationKind, LocationProfile, ViewerMode}; use crate::database::Database; use crate::source::{ - display_remote_uri, ensure_mounted, enumerate_directory, file_from_user_input, is_within_root, - mount_operation, parent_within_root, root_file, validate_profile, + display_remote_uri, ensure_mounted, enumerate_directory, enumerate_tree_entries, + file_from_user_input, is_within_root, mount_operation, parent_within_root, root_file, + validate_profile, }; use crate::viewer::{ FavoriteControl, FileDownloadControl, FileDropControl, FileViewerControls, MediaViewerWindow, SiblingFile, SiblingFileActions, SiblingNavigator, SiblingTarget, ViewModeControl, - ViewerWindow, install_file_drop_target, set_viewer_header, + ViewerWindow, install_file_drop_target, set_viewer_header, set_viewer_loading, }; use crate::zip_cache::ZipCache; @@ -94,7 +95,7 @@ impl ComicWindow { let controls = gtk::Box::new(gtk::Orientation::Horizontal, 6); let search_entry = gtk::SearchEntry::builder() - .placeholder_text("현재 폴더에서 검색") + .placeholder_text("현재 위치 아래 폴더와 ZIP 검색") .hexpand(true) .build(); let sort_dropdown = gtk::DropDown::from_strings(&["이름", "수정 시간", "생성 시간"]); @@ -149,6 +150,10 @@ impl ComicWindow { current_uri: root_uri, entries: Vec::new(), visible_entries: Vec::new(), + recursive_entries: Vec::new(), + recursive_root_uri: None, + recursive_ready: false, + recursive_scanning: false, sort_field: SortField::Name, sort_direction: SortDirection::Ascending, generation: 0, @@ -160,6 +165,8 @@ impl ComicWindow { database: Rc::new(database), zip_cache, listing_task: RefCell::new(None), + search_task: RefCell::new(None), + search_generation: Cell::new(0), }); controller.rebuild_profiles(); @@ -179,6 +186,12 @@ impl ComicWindow { pub fn present(&self) { self.controller.window.present(); } + + pub fn open_local_items(&self, files: &[gio::File]) { + self.present(); + self.controller + .open_dropped_files(files.to_vec(), self.controller.window.clone().upcast()); + } } struct BrowserState { @@ -189,6 +202,10 @@ struct BrowserState { current_uri: String, entries: Vec, visible_entries: Vec, + recursive_entries: Vec, + recursive_root_uri: Option, + recursive_ready: bool, + recursive_scanning: bool, sort_field: SortField, sort_direction: SortDirection, generation: u64, @@ -215,6 +232,8 @@ struct BrowserController { database: Rc, zip_cache: Rc, listing_task: RefCell>>, + search_task: RefCell>>, + search_generation: Cell, } impl BrowserController { @@ -296,7 +315,7 @@ impl BrowserController { .set_list_factory(Some(&location_factory)); let controller = Rc::clone(self); self.search_entry - .connect_search_changed(move |_| controller.render()); + .connect_search_changed(move |_| controller.search_changed()); let controller = Rc::clone(self); self.sort_dropdown .connect_selected_notify(move |_| controller.change_sort_field()); @@ -321,7 +340,7 @@ impl BrowserController { let key_controller = gtk::EventControllerKey::new(); let controller = Rc::clone(self); key_controller.connect_key_pressed(move |_, key, _, modifiers| { - if key == gtk::gdk::Key::BackSpace { + if key == gtk::gdk::Key::BackSpace && !controller.typeahead_is_active() { controller.go_up(); glib::Propagation::Stop } else { @@ -400,6 +419,7 @@ impl BrowserController { fn show_favorites(&self) { self.cancel_listing(); + self.cancel_recursive_search(); self.edit_location_button.set_sensitive(false); self.delete_location_button.set_sensitive(false); self.path_entry.set_text("즐겨찾기"); @@ -495,6 +515,7 @@ impl BrowserController { .unwrap_or_else(|| BrowserEntry { uri: favorite.uri.clone(), name: favorite.name.clone(), + list_name: None, kind, size: None, modified: None, @@ -560,6 +581,7 @@ impl BrowserController { return; } self.cancel_listing(); + self.cancel_recursive_search(); let (profile, uri, generation) = { let mut state = self.state.borrow_mut(); state.generation = state.generation.wrapping_add(1); @@ -605,6 +627,9 @@ impl BrowserController { Ok(entries) => { controller.state.borrow_mut().entries = entries; controller.render(); + if !controller.search_entry.text().is_empty() { + controller.start_recursive_search(); + } } Err(error) => controller.status_label.set_text(&format!("{error:#}")), } @@ -618,6 +643,142 @@ impl BrowserController { } } + fn cancel_recursive_search(&self) { + if let Some(task) = self.search_task.borrow_mut().take() { + task.abort(); + } + self.search_generation + .set(self.search_generation.get().wrapping_add(1)); + let mut state = self.state.borrow_mut(); + state.recursive_entries.clear(); + state.recursive_root_uri = None; + state.recursive_ready = false; + state.recursive_scanning = false; + } + + fn search_changed(self: &Rc) { + if self.search_entry.text().is_empty() { + self.cancel_recursive_search(); + self.render(); + return; + } + self.render(); + if !self.state.borrow().browsing_favorites { + self.start_recursive_search(); + } + } + + fn start_recursive_search(self: &Rc) { + let (profile, root_uri) = { + let mut state = self.state.borrow_mut(); + if state.browsing_favorites + || (state.recursive_root_uri.as_deref() == Some(&state.current_uri) + && (state.recursive_ready || state.recursive_scanning)) + { + return; + } + let root_uri = state.current_uri.clone(); + state.recursive_root_uri = Some(root_uri.clone()); + state.recursive_entries.clear(); + state.recursive_ready = false; + state.recursive_scanning = true; + ( + state + .favorite_profile + .clone() + .unwrap_or_else(|| self.profiles()[state.profile_index].clone()), + root_uri, + ) + }; + if let Some(task) = self.search_task.borrow_mut().take() { + task.abort(); + } + let generation = self.search_generation.get().wrapping_add(1); + self.search_generation.set(generation); + let root = gio::File::for_uri(&root_uri); + let location_id = root_file(&profile) + .map(|root| root.uri().to_string()) + .unwrap_or_else(|_| profile.address.clone()); + if let Ok(cached_entries) = self.database.load_cached_tree(&location_id, &root_uri) + && !cached_entries.is_empty() + { + let mut state = self.state.borrow_mut(); + state.recursive_entries = cached_entries; + state.recursive_ready = true; + drop(state); + self.render(); + } + let operation = mount_operation(&profile, &self.window); + let progress_controller = Rc::downgrade(self); + let controller = Rc::downgrade(self); + let task = glib::MainContext::default().spawn_local(async move { + let result = + enumerate_tree_entries(&profile, &root, Some(&operation), move |progress| { + let Some(controller) = progress_controller.upgrade() else { + return; + }; + if controller.search_generation.get() == generation + && !controller.search_entry.text().is_empty() + { + controller.status_label.set_text(&format!( + "하위 폴더 검색 색인 생성 중... (폴더 {}개, 항목 {}개)", + progress.directories, progress.scanned + )); + } + }) + .await; + let Some(controller) = controller.upgrade() else { + return; + }; + if controller.search_generation.get() != generation + || controller.state.borrow().current_uri != root_uri + { + return; + } + match result { + Ok((entries, progress)) => { + let cache_error = (progress.skipped == 0) + .then(|| { + controller.database.replace_cached_tree( + &location_id, + &root_uri, + &entries, + ) + }) + .transpose() + .err(); + let mut state = controller.state.borrow_mut(); + state.recursive_entries = entries; + state.recursive_ready = true; + state.recursive_scanning = false; + drop(state); + if !controller.search_entry.text().is_empty() { + controller.render(); + if progress.skipped > 0 { + controller.status_label.set_text(&format!( + "검색 결과 생성 완료 · 접근할 수 없는 폴더 {}개 건너뜀", + progress.skipped + )); + } else if let Some(error) = cache_error { + controller + .status_label + .set_text(&format!("검색 색인을 저장할 수 없습니다: {error:#}")); + } + } + } + Err(error) => { + controller.state.borrow_mut().recursive_scanning = false; + if !controller.search_entry.text().is_empty() { + controller + .status_label + .set_text(&format!("하위 폴더 검색을 완료할 수 없습니다: {error:#}")); + } + } + } + }); + self.search_task.replace(Some(task)); + } + fn render(&self) { while let Some(child) = self.list_box.first_child() { self.list_box.remove(&child); @@ -625,10 +786,17 @@ impl BrowserController { let query = self.search_entry.text().to_lowercase(); let case_insensitive = self.config.borrow().case_insensitive_sort; let mut state = self.state.borrow_mut(); - let mut visible_entries: Vec<_> = state - .entries + let recursive_ready = !query.is_empty() + && state.recursive_ready + && state.recursive_root_uri.as_deref() == Some(&state.current_uri); + let source = if recursive_ready { + &state.recursive_entries + } else { + &state.entries + }; + let mut visible_entries: Vec<_> = source .iter() - .filter(|entry| entry.name.to_lowercase().contains(query.as_str())) + .filter(|entry| query.is_empty() || recursive_search_match(entry, query.as_str())) .cloned() .collect(); sort_entries( @@ -642,7 +810,14 @@ impl BrowserController { } let count = visible_entries.len(); state.visible_entries = visible_entries; - self.status_label.set_text(&format!("{count}개 항목")); + let status = if query.is_empty() { + format!("{count}개 항목") + } else if state.recursive_scanning { + format!("현재 폴더 결과 {count}개 · 하위 폴더 색인 생성 중...") + } else { + format!("하위 폴더 검색 결과 {count}개") + }; + self.status_label.set_text(&status); } fn typeahead( @@ -656,10 +831,21 @@ impl BrowserController { if modifiers.intersects(blocked) { return glib::Propagation::Proceed; } - let Some(character) = key - .to_unicode() - .filter(|character| character.is_alphanumeric()) - else { + if key == gtk::gdk::Key::Escape { + let mut state = self.state.borrow_mut(); + state.typeahead_query.clear(); + state.typeahead_last_input = None; + return glib::Propagation::Stop; + } + if key == gtk::gdk::Key::BackSpace { + let mut state = self.state.borrow_mut(); + if state.typeahead_query.pop().is_none() { + return glib::Propagation::Proceed; + } + state.typeahead_last_input = Some(Instant::now()); + return glib::Propagation::Stop; + } + let Some(character) = key.to_unicode().filter(|character| !character.is_control()) else { return glib::Propagation::Proceed; }; @@ -686,7 +872,7 @@ impl BrowserController { 0 }; let found = find_prefix_index(&state.visible_entries, &query, start); - let found_name = found.map(|index| state.visible_entries[index].name.clone()); + let found_name = found.map(|index| state.visible_entries[index].display_name().to_owned()); drop(state); if let Some(index) = found @@ -705,6 +891,14 @@ impl BrowserController { glib::Propagation::Stop } + fn typeahead_is_active(&self) -> bool { + let state = self.state.borrow(); + !state.typeahead_query.is_empty() + && state.typeahead_last_input.is_some_and(|last| { + Instant::now().duration_since(last) <= Duration::from_millis(1200) + }) + } + fn change_sort_field(&self) { self.state.borrow_mut().sort_field = match self.sort_dropdown.selected() { 1 => SortField::Modified, @@ -757,6 +951,23 @@ impl BrowserController { self.refresh(); } EntryKind::ZipArchive | EntryKind::Image | EntryKind::Video => { + if !self.search_entry.text().is_empty() && entry.list_name.is_some() { + let siblings = self + .state + .borrow() + .visible_entries + .iter() + .filter(|candidate| candidate.kind.is_viewable()) + .cloned() + .collect::>(); + self.open_viewable( + entry.clone(), + Rc::new(siblings), + self.current_profile(), + None, + ); + return; + } let current_kind = entry.kind; let case_insensitive = self.config.borrow().case_insensitive_sort; let siblings = { @@ -859,7 +1070,7 @@ impl BrowserController { .iter() .map(|entry| SiblingFile { uri: entry.uri.clone(), - name: entry.name.clone(), + name: entry.display_name().to_owned(), kind: entry.kind, }) .collect() @@ -1075,6 +1286,17 @@ impl BrowserController { actions.set_margin_bottom(6); actions.set_margin_start(6); actions.set_margin_end(6); + if entry.kind == EntryKind::Directory { + let open_folder_button = gtk::Button::with_label("폴더 열기"); + actions.append(&open_folder_button); + let controller = Rc::clone(self); + let popover_to_close = popover.clone(); + let folder_entry = entry.clone(); + open_folder_button.connect_clicked(move |_| { + popover_to_close.popdown(); + controller.open_folder_recursive(folder_entry.clone()); + }); + } if can_favorite { let is_favorite = self.is_favorite(&entry.uri); let favorite_button = gtk::Button::with_label(if is_favorite { @@ -1088,7 +1310,7 @@ impl BrowserController { let favorite_entry = entry.clone(); favorite_button.connect_clicked(move |_| { popover_to_close.popdown(); - let profile = controller.current_profile(); + let profile = controller.profile_for_entry(&favorite_entry); controller.toggle_favorite(&favorite_entry, &profile); }); } @@ -1118,6 +1340,96 @@ impl BrowserController { .any(|favorite| favorite.uri == uri) } + fn profile_for_entry(&self, entry: &BrowserEntry) -> LocationProfile { + if self.state.borrow().browsing_favorites + && let Some(profile) = self + .config + .borrow() + .favorites + .iter() + .find(|favorite| favorite.uri == entry.uri) + .map(|favorite| favorite.profile.clone()) + { + return profile; + } + self.current_profile() + } + + fn open_folder_recursive(self: &Rc, entry: BrowserEntry) { + self.cancel_recursive_search(); + let profile = self.profile_for_entry(&entry); + let Ok(profile_root) = root_file(&profile) else { + self.status_label + .set_text("폴더의 저장된 위치 정보를 확인할 수 없습니다."); + return; + }; + let folder = gio::File::for_uri(&entry.uri); + if !is_within_root(&folder, &profile_root) { + self.status_label + .set_text("저장된 위치의 루트 아래 폴더만 열 수 있습니다."); + return; + } + self.cancel_listing(); + let (generation, sort_field, sort_direction) = { + let mut state = self.state.borrow_mut(); + state.generation = state.generation.wrapping_add(1); + (state.generation, state.sort_field, state.sort_direction) + }; + let case_insensitive = self.config.borrow().case_insensitive_sort; + self.status_label + .set_text("하위 폴더에서 열 수 있는 파일을 찾는 중..."); + let operation = mount_operation(&profile, &self.window); + let progress_controller = Rc::downgrade(self); + let controller = Rc::downgrade(self); + let task = glib::MainContext::default().spawn_local(async move { + let result = + enumerate_tree_entries(&profile, &folder, Some(&operation), move |progress| { + let Some(controller) = progress_controller.upgrade() else { + return; + }; + if controller.state.borrow().generation == generation { + controller.status_label.set_text(&format!( + "하위 폴더 검색 중... (폴더 {}개, 항목 {}개, 파일 {}개)", + progress.directories, progress.scanned, progress.viewable + )); + } + }) + .await; + let Some(controller) = controller.upgrade() else { + return; + }; + if controller.state.borrow().generation != generation { + return; + } + match result { + Ok((mut entries, progress)) => { + entries.retain(|entry| entry.kind.is_viewable()); + sort_entries(&mut entries, sort_field, sort_direction, case_insensitive); + let Some(initial) = entries.first().cloned() else { + controller + .status_label + .set_text("하위 폴더에 열 수 있는 파일이 없습니다."); + return; + }; + let skipped = if progress.skipped == 0 { + String::new() + } else { + format!(" · 접근할 수 없는 폴더 {}개 건너뜀", progress.skipped) + }; + controller.status_label.set_text(&format!( + "하위 폴더에서 {}개 파일을 찾았습니다{skipped}.", + entries.len() + )); + controller.open_viewable(initial, Rc::new(entries), profile, None); + } + Err(error) => controller + .status_label + .set_text(&format!("하위 폴더를 열 수 없습니다: {error:#}")), + } + }); + self.listing_task.replace(Some(task)); + } + fn favorite_control( self: &Rc, entry: &BrowserEntry, @@ -1172,12 +1484,13 @@ impl BrowserController { } let file = file.clone(); self.cancel_listing(); + self.cancel_recursive_search(); let generation = { let mut state = self.state.borrow_mut(); state.generation = state.generation.wrapping_add(1); state.generation }; - self.status_label.set_text("드롭한 항목을 확인하는 중..."); + self.status_label.set_text("열 항목을 확인하는 중..."); let controller = Rc::downgrade(self); let task = glib::MainContext::default().spawn_local(async move { let result: Result<_> = async { @@ -1188,7 +1501,7 @@ impl BrowserController { glib::Priority::DEFAULT, ) .await - .context("드롭한 항목을 확인할 수 없습니다")?; + .context("열 항목을 확인할 수 없습니다")?; let selected = match info.file_type() { gio::FileType::Directory => None, gio::FileType::Regular => { @@ -1221,7 +1534,7 @@ impl BrowserController { let (directory, profile, entries, selected) = match result { Ok(result) => result, Err(error) => { - let message = format!("드롭한 항목을 열 수 없습니다: {error:#}"); + let message = format!("항목을 열 수 없습니다: {error:#}"); controller.status_label.set_text(&message); show_drop_error(&parent, &message); return; @@ -1236,7 +1549,7 @@ impl BrowserController { .find(|entry| gio::File::for_uri(&entry.uri).equal(&selected)) .cloned() else { - show_drop_error(&parent, "드롭한 파일을 부모 폴더에서 찾을 수 없습니다."); + show_drop_error(&parent, "파일을 부모 폴더에서 찾을 수 없습니다."); return; }; let state = controller.state.borrow(); @@ -1248,7 +1561,7 @@ impl BrowserController { controller.config.borrow().case_insensitive_sort, ) else { drop(state); - show_drop_error(&parent, "드롭한 파일의 목록 위치를 확인할 수 없습니다."); + show_drop_error(&parent, "파일의 목록 위치를 확인할 수 없습니다."); return; }; drop(state); @@ -1792,7 +2105,7 @@ fn entry_row(entry: &BrowserEntry) -> gtk::ListBoxRow { content.append(>k::Image::from_icon_name(icon)); content.append( >k::Label::builder() - .label(&entry.name) + .label(entry.display_name()) .hexpand(true) .xalign(0.0) .ellipsize(gtk::pango::EllipsizeMode::Middle) @@ -1823,7 +2136,12 @@ fn find_prefix_index(entries: &[BrowserEntry], query: &str, start: usize) -> Opt let query = query.to_lowercase(); (0..entries.len()) .map(|offset| (start + offset) % entries.len()) - .find(|index| entries[*index].name.to_lowercase().starts_with(&query)) + .find(|index| { + entries[*index] + .display_name() + .to_lowercase() + .starts_with(&query) + }) } fn navigable_sibling(current: EntryKind, candidate: EntryKind) -> bool { @@ -1868,10 +2186,19 @@ fn sorted_navigable_selection( Some((entries, selected)) } +fn recursive_search_match(entry: &BrowserEntry, lowercase_query: &str) -> bool { + matches!(entry.kind, EntryKind::Directory | EntryKind::ZipArchive) + && entry + .display_name() + .to_lowercase() + .contains(lowercase_query) +} + fn favorite_browser_entry(favorite: &FavoriteEntry) -> BrowserEntry { BrowserEntry { uri: favorite.uri.clone(), name: favorite.name.clone(), + list_name: None, kind: if favorite.is_directory { EntryKind::Directory } else { @@ -1889,6 +2216,7 @@ fn show_viewer_loading( file_name: &str, status: &str, ) -> gtk::Label { + set_viewer_loading(window, true); window.set_title(Some(file_name)); let header = gtk::HeaderBar::new(); header.set_title_widget(Some(>k::Label::new(Some(file_name)))); @@ -1953,6 +2281,7 @@ mod tests { BrowserEntry { uri: format!("file:///{name}"), name: name.into(), + list_name: None, kind: EntryKind::Directory, size: None, modified: None, @@ -2044,6 +2373,19 @@ mod tests { assert_eq!(siblings[selected].name, "page10.jpg"); } + #[test] + fn recursive_search_only_matches_folders_and_zip_names() { + let mut folder = entry("Comics"); + folder.list_name = Some("Archive/Comics".into()); + let mut zip = media_entry("book.zip"); + zip.kind = EntryKind::ZipArchive; + let image = media_entry("book.jpg"); + + assert!(recursive_search_match(&folder, "comics")); + assert!(recursive_search_match(&zip, "book")); + assert!(!recursive_search_match(&image, "book")); + } + #[test] fn dropped_directory_creates_local_root_profile() { let directory = tempfile::tempdir().unwrap(); diff --git a/src/zip_cache.rs b/src/zip_cache.rs index 4c118f1..ec5fd61 100644 --- a/src/zip_cache.rs +++ b/src/zip_cache.rs @@ -375,6 +375,7 @@ mod tests { let mut entry = BrowserEntry { uri: "sftp://example.invalid/a.zip".into(), name: "a.zip".into(), + list_name: None, kind: EntryKind::ZipArchive, size: Some(10), modified: None,