diff --git a/.gitignore b/.gitignore index afa6e8e..e899205 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ /dist/*.tar.gz.part-* /dist/*.tar.gz.parts.sha256 /dist/*-install.sh +/.release-credentials diff --git a/AGENTS.md b/AGENTS.md index 64ce761..39e7884 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,14 +3,14 @@ ## Project Overview Comicviewer is a desktop comic archive viewer for CachyOS and Arch Linux. -It browses local, SMB, FTP, and SFTP locations and opens image files stored in -ZIP archives. +It browses local, SMB, FTP, and SFTP locations and opens ZIP archives, +standalone images, and videos. ## Technology - Rust - GTK4 with GIO/GVfs for desktop and remote filesystem integration -- SQLite for cached directory metadata, search indexes, and reading history +- SQLite for cached directory metadata and reading history - AppImage as the primary distribution format - Korean-first UI with all user-facing strings kept translatable @@ -20,20 +20,46 @@ ZIP archives. - Store credentials as plain text in the application configuration as requested, but restrict the configuration file permissions to `0600`. - Cache remote directory metadata and refresh it asynchronously when browsing. +- Cancel a superseded remote directory request so only the latest request can + consume resources, update progress, or replace browser entries. - Download remote ZIP archives before opening them. - Limit the persistent ZIP cache with a user-configurable LRU quota. The default is 10 GB. A quota of 0 disables persistent ZIP caching and uses temporary files. -- Support JPEG, PNG, WebP, static GIF, BMP, and AVIF images in ZIP archives. +- Evict the oldest unpinned ZIP cache files before a download needs space, at + startup, and after an open archive releases its cache pin. Allow users to clear + cached ZIPs without deleting open archives or reading history. +- Keep temporary remote media in the application cache directory, remove it when + its viewer closes, and clean stale temporary downloads on the next startup. +- Support JPEG, PNG, WebP, GIF, BMP, and AVIF images both standalone and in ZIP + archives. Play animated GIF and WebP frames with their delays and loop counts. +- Support common standalone video formats through GStreamer. In video playback, + Left/Right seek by five seconds and Up/Down adjust volume by five percent. - Sort archive images and browser entries using natural filename ordering. - Support ascending and descending sorting by name, modification time, and creation time. Treat unavailable creation times as unknown rather than inventing values. -- Search folder and ZIP names recursively below the current location using the - cached index. +- Filter the currently displayed browser directory by filename and restore all + entries when the search text is cleared. - Provide 100%, fit-width, fit-height, two-page, and continuous vertical viewing. - Support both right-to-left and left-to-right two-page layouts, plus controls - that advance by one page to adjust page pairing. + that advance by one page to adjust page pairing. Persist the last selected + two-page direction and restore it in newly opened archive viewers. +- Reuse viewer windows when moving between ZIP, image, and video files. Preserve + fullscreen state and keep the registered GTK titlebar widget stable while the + displayed header changes. +- Provide a toggleable file list on the right side of each viewer. Double-click + or Enter opens the selected viewable file; its context menu provides favorite + and download actions. +- Filter each viewer's current file list with a temporary search field and + restore the complete list when the search text is cleared. +- Accept one local file or folder dropped onto the main window or a viewer. + Browse dropped folders in the main window; for dropped files, browse the + parent folder and open the exact naturally sorted item in a new viewer window. +- Save favorites for local and remote folders and files, and preserve the saved + location profile needed to reconnect to remote favorites. - Save progress per ZIP and save the most recently read ZIP for resume support. +- Let users update from the About window by downloading the fixed Cafe24 latest + bundle and checksum, verifying SHA-256, and reusing the atomic installer. ## Data Locations @@ -50,11 +76,23 @@ Do not write application state into the source tree. - Prefer the smallest correct implementation and avoid speculative abstractions. - Keep network and archive work off the GTK main thread. - Show cached directory data immediately, then update it in the background. +- Abort superseded GIO futures and guard asynchronous progress and completion + callbacks against stale generations or closed/reused windows. +- Handle file drops as `COPY` actions through `GdkFileList`. Inspect local paths + asynchronously, reject ambiguous/multiple drops, and never reuse the source + viewer window for a dropped file. - Use atomic writes for configuration, database migrations, and completed remote downloads. Incomplete downloads must use a distinct temporary suffix. +- Reserve persistent cache capacity before writing a known-size remote ZIP. + Cache cleanup must skip active temporary downloads and pinned/open archives. - Do not extract an entire archive to disk. Decode only requested images and prefetch a small window around the current page. -- Validate archive entry sizes and image dimensions before allocation. +- Validate archive entry sizes, image dimensions, animation frame counts, and + cumulative decoded animation size before retaining decoded data. +- Cancel animation timers when pictures are hidden, viewers are replaced, or + windows close. GTK/GDK objects must only be created on the GTK main thread. +- Avoid strong `Rc` cycles between GTK signal handlers and controllers. Viewer + teardown must release temporary files, ZIP cache pins, textures, and timers. - Never trust archive paths or use them as extraction destinations. - Preserve errors from GIO, ZIP parsing, and image decoding and present concise, actionable messages in the UI. @@ -74,8 +112,13 @@ cargo clippy --all-targets --all-features -- -D warnings cargo test --all-features ``` -Add focused tests for natural sorting, cache eviction, metadata refresh, -archive filtering, reading progress, and remote file change detection. +Add focused tests for natural sorting, oldest-first cache eviction, pin and +temporary-file protection, metadata refresh, archive filtering, animated image +decoding, video seek/volume calculations, viewer sibling navigation, reading +progress, dropped-file sorting/index selection, and remote file change +detection. For UI or packaging changes, also run a GTK startup smoke test with +isolated XDG directories; release builds must verify the AppImage and downloaded +release bundle checksums. ## Git Practices diff --git a/Cargo.lock b/Cargo.lock index 8696120..44ba40a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -182,17 +182,19 @@ checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" [[package]] name = "comicviewer" -version = "0.2.1" +version = "0.2.20" dependencies = [ "anyhow", "chrono", "filetime", + "flate2", "gtk4", "image", "percent-encoding", "rusqlite", "serde", "sha2", + "tar", "tempfile", "toml 0.9.12+spec-1.1.0", "zip", @@ -1211,6 +1213,17 @@ dependencies = [ "version-compare", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "target-lexicon" version = "0.13.5" @@ -1475,6 +1488,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "zerocopy" version = "0.8.54" diff --git a/Cargo.toml b/Cargo.toml index 72c8f1c..3b72bf0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "comicviewer" -version = "0.2.1" +version = "0.2.20" edition = "2024" description = "A comic archive viewer for local and remote locations" license = "GPL-3.0-or-later" @@ -8,14 +8,16 @@ license = "GPL-3.0-or-later" [dependencies] anyhow = "1.0" chrono = { version = "0.4", default-features = false, features = ["clock"] } -gtk = { package = "gtk4", version = "0.10", features = ["v4_10"] } +gtk = { package = "gtk4", version = "0.10", features = ["v4_12"] } image = { version = "0.25", default-features = false, features = ["avif-native", "bmp", "gif", "jpeg", "png", "webp"] } filetime = "0.2" +flate2 = "1.0" percent-encoding = "2.3" rusqlite = { version = "0.37", features = ["bundled"] } serde = { version = "1.0", features = ["derive"] } sha2 = "0.10" tempfile = "3.20" +tar = "0.4" toml = "0.9" zip = { version = "8", default-features = false, features = ["deflate"] } 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 84e954c..1949cfa 100644 --- a/data/io.github.comicviewer.Comicviewer.metainfo.xml +++ b/data/io.github.comicviewer.Comicviewer.metainfo.xml @@ -26,6 +26,25 @@ + + + + + + + + + + + + + + + + + + + diff --git a/docs/INSTALL.ko.md b/docs/INSTALL.ko.md index a116d4c..4c2b483 100644 --- a/docs/INSTALL.ko.md +++ b/docs/INSTALL.ko.md @@ -9,15 +9,16 @@ Comicviewer는 CachyOS와 Arch Linux에서 사용할 수 있는 만화·미디 설치합니다. 설치 과정에서 `sudo` 암호와 pacman 확인을 요청할 수 있습니다. ```sh -sudo pacman -S fuse2 gtk4 dav1d gvfs gvfs-smb gstreamer \ +sudo pacman -S fuse2 gtk4 dav1d gvfs gvfs-smb gstreamer curl \ gst-plugins-base gst-plugins-good gst-plugins-bad gst-libav ``` - `fuse2`: AppImage 마운트 및 실행 -- `gtk4`, `dav1d`: 화면 표시와 이미지 디코딩 +- `gtk4` 4.12 이상, `dav1d`: 화면 표시와 이미지 디코딩 - `gvfs`: FTP와 SFTP 접근 - `gvfs-smb`: SMB 공유 접근 - `gstreamer`, `gst-plugins-*`, `gst-libav`: MP4 등 동영상 재생 +- `curl`: About 창에서 최신 업데이트 다운로드 ## 2. 권장 방법: 통합 번들로 설치 또는 업데이트 @@ -82,6 +83,9 @@ Comicviewer는 XDG 표준 경로를 사용합니다. - 기본 영구 ZIP 캐시 한도는 10GB이며 오래된 파일부터 자동으로 삭제됩니다. - 메인 창의 `캐시 비우기` 버튼으로 현재 열려 있지 않은 ZIP 캐시를 직접 삭제할 수 있습니다. - 캐시 한도는 설정 파일의 `cache_quota_gb`로 변경하며, 0은 영구 캐시를 사용하지 않는 값입니다. +- 메인 창 검색은 현재 표시 중인 폴더의 파일명을 필터링하며, 입력을 지우면 전체 목록을 복원합니다. +- 위치 목록의 `최근 열어본 파일`은 성공적으로 연 ZIP·이미지·동영상을 최신순으로 최대 100개 보관합니다. +- 최근 파일 기록에는 원격 위치 재접속 정보가 함께 저장되며 `최근 기록 비우기`로 전체 기록만 삭제할 수 있습니다. ## 뷰어 조작 @@ -89,8 +93,19 @@ Comicviewer는 XDG 표준 경로를 사용합니다. - `Home`과 `End`: 폴더의 첫 번째/마지막 파일 열기 - 동영상에서 `←`와 `→`: 5초 뒤/앞으로 이동 - 동영상에서 `↑`와 `↓`: 음량을 5%씩 조절 -- `파일 목록`: 우측 폴더 목록 표시 또는 숨기기 +- 이미지에서 `1`, `2`, `3`, `4`: 폭 맞춤, 높이 맞춤, 2페이지, 100%로 전환 (`3`은 ZIP 뷰어에서 사용) +- 창보다 크게 표시된 이미지에서 `←`, `→`, `↑`, `↓`: 해당 방향으로 최대 100px 이동 +- `L`: 우측 파일 목록 표시 또는 숨기기 +- 파일 목록 상단 검색: 현재 재생 목록을 임시로 필터링하며, 입력을 지우면 전체 목록 복원 +- About 창의 `업데이트`: Cafe24에서 최신 번들을 내려받아 검증 후 사용자 영역에 설치 +- 이미지에서 `+`/`=`와 `-`: 현재 화면의 이미지를 임시로 10%씩 확대 또는 축소 +- 이미지에서 `Ctrl` + 마우스 휠: 현재 화면의 이미지를 임시로 10%씩 확대 또는 축소 +- 2페이지의 `좌→우`/`우→좌` 방향은 마지막 선택을 저장해 다음 뷰어에서 복원 +- 전체 화면에서 마우스 클릭: 숨겨진 컨트롤을 5초 동안 표시 +- 전체 화면에서 `←`, `→`, `↑`, `↓`: 컨트롤을 즉시 숨기고 해당 키 동작 실행 - 파일 목록의 더블클릭 또는 선택 후 `Enter`: 해당 파일 열기 - 파일 목록의 우클릭: 즐겨찾기 추가·제거 또는 다운로드 +- 메인 창이나 뷰어에 로컬 파일 드롭: 부모 폴더를 열고 새 뷰어에서 해당 파일 열기 +- 메인 창이나 뷰어에 로컬 폴더 드롭: 메인 창에서 해당 폴더 열기 애니메이션 GIF와 WebP는 standalone 이미지와 ZIP 내부 이미지에서 재생됩니다. diff --git a/docs/RELEASING.ko.md b/docs/RELEASING.ko.md index 8f8694b..b124f8f 100644 --- a/docs/RELEASING.ko.md +++ b/docs/RELEASING.ko.md @@ -55,7 +55,7 @@ AppImage 빌드가 끝나면 다음 스크립트로 체크섬과 통합 `tar.gz` 스크립트는 `Cargo.toml`에서 버전을 읽고 다음 파일을 생성합니다. -- `dist/Comicviewer-0.2.1-x86_64.AppImage.sha256` +- `dist/Comicviewer-0.2.20-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.1 release" -git tag -a v0.2.1 -m "Comicviewer v0.2.1" +git commit -m "Release v0.2.20" +git tag -a v0.2.20 -m "Comicviewer v0.2.20" git push origin main -git push origin v0.2.1 +git push origin v0.2.20 ``` 이미 원격에 공개한 태그는 이동하거나 덮어쓰지 않습니다. 수정이 필요하면 새 diff --git a/packaging/install-or-update.sh b/packaging/install-or-update.sh index d650193..fbc1893 100755 --- a/packaging/install-or-update.sh +++ b/packaging/install-or-update.sh @@ -39,7 +39,7 @@ install_dependencies() { fi set -- - for package in fuse2 gtk4 dav1d gvfs gvfs-smb gstreamer gst-plugins-base \ + for package in fuse2 gtk4 dav1d gvfs gvfs-smb gstreamer curl gst-plugins-base \ gst-plugins-good gst-plugins-bad gst-libav; do if ! pacman -Q "${package}" >/dev/null 2>&1; then set -- "$@" "${package}" @@ -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/config.rs b/src/config.rs index 9378f78..905b382 100644 --- a/src/config.rs +++ b/src/config.rs @@ -12,8 +12,10 @@ pub struct AppConfig { pub fast_image_loading: bool, pub case_insensitive_sort: bool, pub viewer_mode: ViewerMode, + pub two_page_right_to_left: bool, pub locations: Vec, pub favorites: Vec, + pub recent_files: Vec, } impl Default for AppConfig { @@ -23,8 +25,10 @@ impl Default for AppConfig { fast_image_loading: true, case_insensitive_sort: true, viewer_mode: ViewerMode::FitWidth, + two_page_right_to_left: true, locations: Vec::new(), favorites: Vec::new(), + recent_files: Vec::new(), } } } @@ -50,6 +54,13 @@ pub struct FavoriteEntry { pub profile: LocationProfile, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RecentFileEntry { + pub name: String, + pub uri: String, + pub profile: LocationProfile, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum LocationKind { @@ -179,6 +190,7 @@ mod tests { fast_image_loading: true, case_insensitive_sort: true, viewer_mode: ViewerMode::FitWidth, + two_page_right_to_left: true, locations: vec![LocationProfile { name: "테스트".into(), kind: LocationKind::Sftp, @@ -200,6 +212,18 @@ mod tests { domain: String::new(), }, }], + recent_files: vec![RecentFileEntry { + name: "최근 영상.mp4".into(), + uri: "sftp://example.invalid/comics/recent.mp4".into(), + profile: LocationProfile { + name: "최근 서버".into(), + kind: LocationKind::Sftp, + address: "sftp://example.invalid/comics".into(), + username: "recent-reader".into(), + password: "recent-password".into(), + domain: String::new(), + }, + }], }; let encoded = toml::to_string(&config).unwrap(); @@ -207,6 +231,8 @@ mod tests { assert_eq!(decoded.locations[0].password, "plain-password"); assert_eq!(decoded.favorites[0].profile.username, "favorite-reader"); assert_eq!(decoded.favorites[0].profile.password, "favorite-password"); + assert_eq!(decoded.recent_files[0].profile.username, "recent-reader"); + assert_eq!(decoded.recent_files[0].profile.password, "recent-password"); } #[test] @@ -215,7 +241,9 @@ mod tests { assert!(decoded.fast_image_loading); assert!(decoded.case_insensitive_sort); assert_eq!(decoded.viewer_mode, ViewerMode::FitWidth); + assert!(decoded.two_page_right_to_left); assert!(decoded.favorites.is_empty()); + assert!(decoded.recent_files.is_empty()); } #[test] @@ -231,4 +259,17 @@ mod tests { } assert_eq!(ViewerMode::from_dropdown_index(99), ViewerMode::FitWidth); } + + #[test] + fn two_page_direction_defaults_to_rtl_and_round_trips_ltr() { + let existing: AppConfig = toml::from_str("cache_quota_gb = 10\n").unwrap(); + assert!(existing.two_page_right_to_left); + + let config = AppConfig { + two_page_right_to_left: false, + ..AppConfig::default() + }; + let decoded: AppConfig = toml::from_str(&toml::to_string(&config).unwrap()).unwrap(); + assert!(!decoded.two_page_right_to_left); + } } 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..bf6b8e2 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,43 @@ 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(Default)] +struct EnumerationProgress { + seen: HashSet, + new_in_batch: usize, +} + +impl EnumerationProgress { + fn begin_batch(&mut self) { + self.new_in_batch = 0; + } + + fn record(&mut self, uri: String) -> bool { + let inserted = self.seen.insert(uri); + self.new_in_batch += usize::from(inserted); + inserted + } + + fn repeated_batch(&self) -> bool { + self.new_in_batch == 0 + } + + fn len(&self) -> usize { + self.seen.len() + } +} + +#[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)?; @@ -100,7 +138,7 @@ where } }; let mut entries = Vec::new(); - let mut scanned = 0; + let mut enumeration = EnumerationProgress::default(); loop { let batch = enumerator @@ -109,22 +147,25 @@ where if batch.is_empty() { break; } - scanned += batch.len(); - progress(scanned); + enumeration.begin_batch(); for info in batch { + let child = enumerator.child(&info); + let uri: String = info + .attribute_string("standard::target-uri") + .map_or_else(|| child.uri().into(), Into::into); + if !enumeration.record(uri.clone()) { + continue; + } let kind = match info.file_type() { gio::FileType::Directory => EntryKind::Directory, gio::FileType::Mountable | gio::FileType::Shortcut => EntryKind::Directory, gio::FileType::Regular => classify_file(Path::new(info.display_name().as_str())), _ => continue, }; - let child = enumerator.child(&info); - let uri = info - .attribute_string("standard::target-uri") - .map_or_else(|| child.uri().into(), Into::into); entries.push(BrowserEntry { uri, name: info.display_name().into(), + list_name: None, kind, size: info .has_attribute("standard::size") @@ -140,10 +181,151 @@ where .map(Into::into), }); } + if enumeration.repeated_batch() { + break; + } + progress(enumeration.len()); } 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 +421,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 +480,63 @@ mod tests { let encoded_input = file_from_user_input(LocationKind::Ftp, encoded.uri().as_str()); assert!(encoded_input.equal(&encoded)); } + + #[test] + fn enumeration_allows_large_unique_directories_and_stops_repeated_batches() { + let mut enumeration = EnumerationProgress::default(); + for batch_start in (0..330_001).step_by(128) { + enumeration.begin_batch(); + for index in batch_start..(batch_start + 128).min(330_001) { + assert!(enumeration.record(format!("smb://server/share/file-{index}"))); + } + assert!(!enumeration.repeated_batch()); + } + assert_eq!(enumeration.len(), 330_001); + + enumeration.begin_batch(); + for index in 0..128 { + assert!(!enumeration.record(format!("smb://server/share/file-{index}"))); + } + assert!(enumeration.repeated_batch()); + assert_eq!(enumeration.len(), 330_001); + } + + #[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 883ab74..eb0ee7c 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; @@ -20,18 +20,26 @@ const FAST_CACHE_LIMIT_BYTES: usize = 1024 * 1024 * 1024; const FAST_CACHE_LIMIT_PAGES: usize = 64; const VIDEO_SEEK_STEP_US: i64 = 5_000_000; const VIDEO_VOLUME_STEP: f64 = 0.05; +const IMAGE_ZOOM_STEP: f64 = 0.1; +const IMAGE_ZOOM_MIN: f64 = 0.1; +const IMAGE_ZOOM_MAX: f64 = 4.0; +const IMAGE_PAN_STEP: f64 = 100.0; const VIEWER_CONTROLLER_KEY: &str = "comicviewer-viewer-controller"; const MEDIA_VIEWER_CONTROLLER_KEY: &str = "comicviewer-media-viewer-controller"; +const VIEWER_FILE_SEARCH_KEY: &str = "comicviewer-file-search"; +const VIEWER_FILE_SCROLL_KEY: &str = "comicviewer-file-scroll"; +const VIEWER_VIDEO_LOOP_KEY: &str = "comicviewer-video-loop"; +const PRESERVE_SEEK_CLASS: &str = "viewer-preserve-seek"; 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 +55,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 key == gdk::Key::Escape + || key + .to_unicode() + .is_some_and(|character| character.eq_ignore_ascii_case(&'f')) + { + window.unfullscreen(); + if let Some(titlebar) = window.titlebar() { + titlebar.set_visible(true); + } + 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,15 +108,17 @@ 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; pub struct SiblingNavigator { - position: Rc Option<(usize, usize)>>, navigate: Rc bool>, files: Rc Vec>, actions: Rc, + recursive: bool, } type SiblingActionResolver = dyn Fn(&str) -> Option; @@ -90,16 +138,16 @@ pub struct SiblingFileActions { impl SiblingNavigator { pub fn new( - position: Rc Option<(usize, usize)>>, navigate: Rc bool>, files: Rc Vec>, actions: Rc, + recursive: bool, ) -> Self { Self { - position, navigate, files, actions, + recursive, } } @@ -122,14 +170,14 @@ impl SiblingNavigator { ) } - fn position(&self) -> Option<(usize, usize)> { - (self.position)() - } - fn files(&self) -> Vec { (self.files)() } + fn seek_files(&self, current_kind: EntryKind) -> Vec { + seek_sibling_files(self.files(), current_kind, self.recursive) + } + fn open_uri(&self, uri: &str, window: gtk::ApplicationWindow) -> bool { let files = self.files(); let Some(index) = files.iter().position(|file| file.uri == uri) else { @@ -178,12 +226,44 @@ pub struct ViewModeControl { pub change: Rc, } +pub struct TwoPageDirectionControl { + pub selected: u32, + pub change: Rc bool>, +} + pub struct FileViewerControls { pub sibling_navigator: Option, pub favorite_control: FavoriteControl, pub download_control: FileDownloadControl, + pub file_drop_control: FileDropControl, pub reuse_window: Option, pub view_mode_control: Option, + pub two_page_direction_control: Option, +} + +#[derive(Clone)] +pub struct FileDropControl { + pub handle: Rc, gtk::Window)>, +} + +pub(crate) fn install_file_drop_target(window: >k::ApplicationWindow, control: FileDropControl) { + if window.has_css_class("comicviewer-file-drop-target") { + return; + } + window.add_css_class("comicviewer-file-drop-target"); + let target = gtk::DropTarget::new(gdk::FileList::static_type(), gdk::DragAction::COPY); + let weak_window = window.downgrade(); + target.connect_drop(move |_, value, _, _| { + let Ok(file_list) = value.get::() else { + return false; + }; + let Some(window) = weak_window.upgrade() else { + return false; + }; + (control.handle)(file_list.files(), window.upcast()); + true + }); + window.add_controller(target); } impl ViewerWindow { @@ -200,10 +280,26 @@ impl ViewerWindow { sibling_navigator, favorite_control, download_control, + file_drop_control, reuse_window, view_mode_control: _, + two_page_direction_control, } = controls; - let title = source.display_name.clone(); + let direction_control = two_page_direction_control + .expect("archive viewer requires a two-page direction control"); + let title_files = sibling_navigator + .as_ref() + .map(SiblingNavigator::files) + .unwrap_or_default(); + let title = viewer_file_title(&source.display_name, &source.source_uri, &title_files); + let file_list_query = reuse_window + .as_ref() + .map(viewer_file_search_query) + .unwrap_or_default(); + let file_list_scroll = reuse_window + .as_ref() + .map(viewer_file_scroll_position) + .unwrap_or_default(); if let Some(window) = reuse_window.as_ref() { clear_viewer_controller(window); } @@ -215,10 +311,12 @@ impl ViewerWindow { .default_height(850) .build() }); + 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)))); + header.set_title_widget(Some(&viewer_title_label(&title))); let favorite_button = gtk::Button::with_label(favorite_label(favorite_control.active)); let download_button = gtk::Button::with_label("파일 다운로드"); let file_list_button = gtk::ToggleButton::with_label("파일 목록"); @@ -227,7 +325,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); @@ -248,7 +346,8 @@ impl ViewerWindow { let page_label = gtk::Label::new(Some("- / -")); page_label.set_hexpand(true); let direction_dropdown = gtk::DropDown::from_strings(&["좌→우", "우→좌"]); - direction_dropdown.set_selected(1); + let direction_selected = direction_control.selected.min(1); + direction_dropdown.set_selected(direction_selected); let mode_dropdown = gtk::DropDown::from_strings(&[ "100%", "폭 맞춤", @@ -279,6 +378,11 @@ impl ViewerWindow { spread_box.set_homogeneous(true); spread_box.append(&left_picture); spread_box.append(&right_picture); + let spread_scrolled = gtk::ScrolledWindow::builder() + .hexpand(true) + .vexpand(true) + .child(&spread_box) + .build(); let continuous_box = gtk::Box::new(gtk::Orientation::Vertical, 8); continuous_box.set_halign(gtk::Align::Fill); @@ -291,7 +395,7 @@ impl ViewerWindow { stack.set_hexpand(true); stack.set_vexpand(true); stack.add_named(&single_scrolled, Some("single")); - stack.add_named(&spread_box, Some("spread")); + stack.add_named(&spread_scrolled, Some("spread")); stack.add_named(&continuous_scrolled, Some("continuous")); let spinner = gtk::Spinner::new(); @@ -321,7 +425,7 @@ impl ViewerWindow { window_overlay.add_overlay(&navigation_message); window_overlay.set_hexpand(true); window_overlay.set_vexpand(true); - let file_list = viewer_file_list(); + let file_list = viewer_file_list(&file_list_query); file_list.panel.set_visible(file_list_button.is_active()); let viewer_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0); viewer_layout.append(&window_overlay); @@ -330,6 +434,7 @@ impl ViewerWindow { let controller = Rc::new(ViewerController { window, + titlebar_host, source, database, stack, @@ -338,12 +443,15 @@ impl ViewerWindow { single_picture, left_picture, right_picture, + spread_box, + spread_scrolled, continuous_box, continuous_scrolled, spinner, page_label, page_seek, page_seek_row, + toolbar, status_label, previous_button, next_button, @@ -356,17 +464,29 @@ impl ViewerWindow { sibling_navigator, file_list_button, file_list_panel: file_list.panel, + file_list_search: file_list.search, + file_list_scrolled: file_list.scrolled, file_list: file_list.list, file_list_files: RefCell::new(Vec::new()), + file_list_scroll_restore: Cell::new(Some(file_list_scroll)), favorite_button, favorite_toggle: favorite_control.toggle, download_button, file_download: download_control.download, view_mode_change: view_mode_control.change, + direction_change: direction_control.change, + direction_selected: Cell::new(direction_selected), seek_hide_timer: RefCell::new(None), + seek_interacting: Cell::new(false), last_pointer_position: Cell::new(None), key_controller: RefCell::new(None), motion_controller: RefCell::new(None), + fullscreen_key_controller: RefCell::new(None), + fullscreen_click_controller: RefCell::new(None), + fullscreen_ui_hide_timer: RefCell::new(None), + fullscreen_ui_visible: Cell::new(false), + fullscreen_notify_handler: RefCell::new(None), + image_zoom: Cell::new(1.0), navigation_message, navigation_message_label, navigation_message_generation: Rc::new(Cell::new(0)), @@ -389,6 +509,15 @@ impl ViewerWindow { }), }); controller.connect_signals(); + controller.fullscreen_changed(); + if controller.window.has_css_class(PRESERVE_SEEK_CLASS) { + controller.window.remove_css_class(PRESERVE_SEEK_CLASS); + if controller.window.is_fullscreen() { + controller.show_fullscreen_ui_temporarily(); + } else { + controller.show_seek_temporarily(); + } + } if controller.file_list_button.is_active() { controller.refresh_file_list(); } @@ -478,6 +607,7 @@ struct ViewerState { struct ViewerController { window: gtk::ApplicationWindow, + titlebar_host: gtk::Box, source: ArchiveSource, database: Rc, stack: gtk::Stack, @@ -486,12 +616,15 @@ struct ViewerController { single_picture: gtk::Picture, left_picture: gtk::Picture, right_picture: gtk::Picture, + spread_box: gtk::Box, + spread_scrolled: gtk::ScrolledWindow, continuous_box: gtk::Box, continuous_scrolled: gtk::ScrolledWindow, spinner: gtk::Spinner, 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, @@ -503,18 +636,30 @@ struct ViewerController { case_insensitive_sort: bool, sibling_navigator: Option, file_list_button: gtk::ToggleButton, - file_list_panel: gtk::ScrolledWindow, + file_list_panel: gtk::Box, + file_list_search: gtk::SearchEntry, + file_list_scrolled: gtk::ScrolledWindow, file_list: gtk::ListBox, file_list_files: RefCell>, + file_list_scroll_restore: Cell>, favorite_button: gtk::Button, favorite_toggle: Rc bool>, download_button: gtk::Button, file_download: Rc, view_mode_change: Rc, + direction_change: Rc bool>, + direction_selected: Cell, seek_hide_timer: RefCell>, + seek_interacting: Cell, last_pointer_position: Cell>, key_controller: RefCell>, motion_controller: RefCell>, + fullscreen_key_controller: RefCell>, + fullscreen_click_controller: RefCell>, + fullscreen_ui_hide_timer: RefCell>, + fullscreen_ui_visible: Cell, + fullscreen_notify_handler: RefCell>, + image_zoom: Cell, navigation_message: gtk::Box, navigation_message_label: gtk::Label, navigation_message_generation: Rc>, @@ -531,13 +676,13 @@ impl ViewerController { let controller = Rc::downgrade(self); self.previous_button.connect_clicked(move |_| { if let Some(controller) = controller.upgrade() { - controller.navigate(false); + controller.navigate_from_button(false); } }); let controller = Rc::downgrade(self); self.next_button.connect_clicked(move |_| { if let Some(controller) = controller.upgrade() { - controller.navigate(true); + controller.navigate_from_button(true); } }); let controller = Rc::downgrade(self); @@ -556,15 +701,23 @@ impl ViewerController { self.mode_dropdown.connect_selected_notify(move |dropdown| { if let Some(controller) = controller.upgrade() { (controller.view_mode_change)(dropdown.selected()); + controller.image_zoom.set(1.0); controller.apply_view_mode(); } }); let controller = Rc::downgrade(self); - self.direction_dropdown.connect_selected_notify(move |_| { - if let Some(controller) = controller.upgrade() { - controller.render(); - } - }); + self.direction_dropdown + .connect_selected_notify(move |dropdown| { + if let Some(controller) = controller.upgrade() { + let selected = dropdown.selected().min(1); + if (controller.direction_change)(selected) { + controller.direction_selected.set(selected); + controller.render(); + } else { + dropdown.set_selected(controller.direction_selected.get()); + } + } + }); let controller = Rc::downgrade(self); self.favorite_button.connect_clicked(move |_| { if let Some(controller) = controller.upgrade() { @@ -584,7 +737,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 { @@ -603,6 +760,39 @@ impl ViewerController { controller.open_file_list_row(row.index()); } }); + let controller = Rc::downgrade(self); + self.file_list_search.connect_search_changed(move |search| { + if let Some(controller) = controller.upgrade() { + store_viewer_file_search_query(&controller.window, search.text().as_str()); + controller.refresh_file_list(); + } + }); + let controller = Rc::downgrade(self); + self.file_list_scrolled + .vadjustment() + .connect_value_changed(move |adjustment| { + if let Some(controller) = controller.upgrade() + && controller.file_list_scroll_restore.get().is_none() + { + store_viewer_file_scroll_position(&controller.window, adjustment.value()); + } + }); + 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| { @@ -621,6 +811,24 @@ impl ViewerController { controller.seek_page(index); } }); + let seek_events = gtk::EventControllerLegacy::new(); + seek_events.set_propagation_phase(gtk::PropagationPhase::Capture); + let controller = Rc::downgrade(self); + seek_events.connect_event(move |_, event| { + if event + .downcast_ref::() + .is_some_and(|event| event.button() == gdk::BUTTON_PRIMARY) + && let Some(controller) = controller.upgrade() + { + match event.event_type() { + gdk::EventType::ButtonPress => controller.begin_seek_interaction(), + gdk::EventType::ButtonRelease => controller.end_seek_interaction(), + _ => {} + } + } + glib::Propagation::Proceed + }); + self.page_seek.add_controller(seek_events); let adjustment = self.continuous_scrolled.vadjustment(); let controller = Rc::downgrade(self); @@ -650,22 +858,51 @@ impl ViewerController { } }); let controller = Rc::downgrade(self); + self.single_scrolled + .connect_notify_local(Some("height"), move |_, _| { + if let Some(controller) = controller.upgrade() { + controller.resize_single_picture(); + } + }); + let controller = Rc::downgrade(self); self.single_picture .connect_notify_local(Some("width"), move |_, _| { if let Some(controller) = controller.upgrade() { controller.resize_single_picture(); } }); + let controller = Rc::downgrade(self); + self.spread_scrolled + .connect_notify_local(Some("width"), move |_, _| { + if let Some(controller) = controller.upgrade() { + controller.resize_spread_pictures(); + } + }); + let controller = Rc::downgrade(self); + self.spread_scrolled + .connect_notify_local(Some("height"), move |_, _| { + if let Some(controller) = controller.upgrade() { + controller.resize_spread_pictures(); + } + }); let scroll_controller = gtk::EventControllerScroll::new( gtk::EventControllerScrollFlags::VERTICAL | gtk::EventControllerScrollFlags::DISCRETE, ); scroll_controller.set_propagation_phase(gtk::PropagationPhase::Capture); let controller = Rc::downgrade(self); - scroll_controller.connect_scroll(move |_, _, delta_y| { + scroll_controller.connect_scroll(move |scroll, _, delta_y| { let Some(controller) = controller.upgrade() else { return glib::Propagation::Proceed; }; + if scroll + .current_event_state() + .contains(gdk::ModifierType::CONTROL_MASK) + && delta_y != 0.0 + { + controller.adjust_image_zoom(delta_y < 0.0); + return glib::Propagation::Stop; + } if matches!( controller.view_mode(), ViewMode::ActualSize | ViewMode::FitWidth | ViewMode::Continuous @@ -678,6 +915,22 @@ impl ViewerController { }); self.stack.add_controller(scroll_controller); + let fullscreen_click = gtk::EventControllerLegacy::new(); + fullscreen_click.set_propagation_phase(gtk::PropagationPhase::Capture); + let controller = Rc::downgrade(self); + fullscreen_click.connect_event(move |_, event| { + if event.downcast_ref::().is_some() + && event.event_type() == gdk::EventType::ButtonPress + && let Some(controller) = controller.upgrade() + { + controller.controls_clicked(); + } + glib::Propagation::Proceed + }); + self.window.add_controller(fullscreen_click.clone()); + self.fullscreen_click_controller + .replace(Some(fullscreen_click)); + let motion_controller = gtk::EventControllerMotion::new(); motion_controller.set_propagation_phase(gtk::PropagationPhase::Capture); let controller = Rc::downgrade(self); @@ -689,13 +942,35 @@ 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 |_, key, _, _| { + if let Some(controller) = controller.upgrade() + && !widget_contains_focus(&controller.file_list_search, &controller.window) + && controller.window.is_fullscreen() + && fullscreen_direction_key(key) + { + controller.hide_fullscreen_ui_now(); + } + 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, _, _| { + key_controller.connect_key_pressed(move |_, key, _, modifiers| { let Some(controller) = controller.upgrade() else { return glib::Propagation::Proceed; }; - controller.hide_seek(); + if widget_contains_focus(&controller.file_list_search, &controller.window) { + return glib::Propagation::Proceed; + } + if !controller.window.is_fullscreen() { + controller.hide_seek(); + } match key { gdk::Key::Home => { controller.seek_edge(false); @@ -705,29 +980,23 @@ impl ViewerController { controller.seek_edge(true); glib::Propagation::Stop } - gdk::Key::Up - if matches!( - controller.view_mode(), - ViewMode::ActualSize | ViewMode::FitWidth | ViewMode::Continuous - ) => - { - controller.scroll_vertically(false); + gdk::Key::Up | gdk::Key::KP_Up if controller.pan_image(false, false) => { glib::Propagation::Stop } - gdk::Key::Down - if matches!( - controller.view_mode(), - ViewMode::ActualSize | ViewMode::FitWidth | ViewMode::Continuous - ) => - { - controller.scroll_vertically(true); + gdk::Key::Down | gdk::Key::KP_Down if controller.pan_image(false, true) => { glib::Propagation::Stop } - gdk::Key::Left | gdk::Key::Page_Up => { + gdk::Key::Left | gdk::Key::KP_Left if controller.pan_image(true, false) => { + glib::Propagation::Stop + } + gdk::Key::Right | gdk::Key::KP_Right if controller.pan_image(true, true) => { + glib::Propagation::Stop + } + gdk::Key::Left | gdk::Key::KP_Left | gdk::Key::Page_Up => { controller.navigate(false); glib::Propagation::Stop } - gdk::Key::Right | gdk::Key::Page_Down | gdk::Key::space => { + gdk::Key::Right | gdk::Key::KP_Right | gdk::Key::Page_Down | gdk::Key::space => { controller.navigate(true); glib::Propagation::Stop } @@ -739,6 +1008,38 @@ impl ViewerController { controller.open_sibling(true); glib::Propagation::Stop } + gdk::Key::plus | gdk::Key::equal | gdk::Key::KP_Add => { + controller.adjust_image_zoom(true); + glib::Propagation::Stop + } + gdk::Key::minus | gdk::Key::KP_Subtract => { + controller.adjust_image_zoom(false); + glib::Propagation::Stop + } + gdk::Key::_1 | gdk::Key::KP_1 => { + controller.select_view_mode(1); + glib::Propagation::Stop + } + gdk::Key::_2 | gdk::Key::KP_2 => { + controller.select_view_mode(2); + glib::Propagation::Stop + } + gdk::Key::_3 | gdk::Key::KP_3 => { + controller.select_view_mode(3); + glib::Propagation::Stop + } + gdk::Key::_4 | gdk::Key::KP_4 => { + controller.select_view_mode(0); + glib::Propagation::Stop + } + _ if !shortcut_modifiers_blocked(modifiers) + && key + .to_unicode() + .is_some_and(|character| character.eq_ignore_ascii_case(&'l')) => + { + controller.toggle_file_list(); + glib::Propagation::Stop + } _ if key .to_unicode() .is_some_and(|character| character.eq_ignore_ascii_case(&'f')) => @@ -755,6 +1056,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) { @@ -767,6 +1077,17 @@ impl ViewerController { } } + fn toggle_file_list(&self) { + if !self.file_list_button.is_sensitive() { + return; + } + let active = !self.file_list_button.is_active(); + self.file_list_button.set_active(active); + if self.window.is_fullscreen() { + self.file_list_panel.set_visible(active); + } + } + fn refresh_file_list(&self) { while let Some(child) = self.file_list.first_child() { self.file_list.remove(&child); @@ -776,6 +1097,7 @@ impl ViewerController { .as_ref() .map(SiblingNavigator::files) .unwrap_or_default(); + let files = filter_sibling_files(files, self.file_list_search.text().as_str()); let current = files .iter() .position(|file| file.uri == self.source.source_uri); @@ -786,6 +1108,11 @@ impl ViewerController { if let Some(row) = current.and_then(|index| self.file_list.row_at_index(index as i32)) { self.file_list.select_row(Some(&row)); } + restore_pending_viewer_file_scroll( + &self.file_list_panel, + &self.file_list_scrolled, + &self.file_list_scroll_restore, + ); } fn open_file_list_row(&self, index: i32) { @@ -848,12 +1175,25 @@ 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); + } + if let Some(controller) = self.fullscreen_click_controller.borrow_mut().take() { + self.window.remove_controller(&controller); + } } fn stop_animations(&self) { @@ -874,25 +1214,58 @@ impl ViewerController { let timer = glib::timeout_add_local_once(Duration::from_secs(5), move || { if let Some(controller) = controller.upgrade() { controller.seek_hide_timer.borrow_mut().take(); - controller.set_seek_visible(false); + if !controller.seek_interacting.get() { + controller.set_seek_visible(false); + } } }); self.seek_hide_timer.replace(Some(timer)); } + fn begin_seek_interaction(self: &Rc) { + self.seek_interacting.set(true); + if let Some(timer) = self.seek_hide_timer.borrow_mut().take() { + timer.remove(); + } + self.cancel_fullscreen_ui_timer(); + if self.window.is_fullscreen() { + self.set_fullscreen_ui_visible(true); + } else { + self.set_seek_visible(true); + } + } + + fn end_seek_interaction(self: &Rc) { + self.seek_interacting.set(false); + if self.window.is_fullscreen() { + self.show_fullscreen_ui_temporarily(); + } else { + self.show_seek_temporarily(); + } + } + fn pointer_moved(self: &Rc, x: f64, y: f64) { if self.last_pointer_position.get() == Some((x, y)) { return; } self.last_pointer_position.set(Some((x, y))); - self.show_seek_temporarily(); + } + + fn controls_clicked(self: &Rc) { + if self.window.is_fullscreen() { + self.show_fullscreen_ui_temporarily(); + } else { + self.show_seek_temporarily(); + } } fn hide_seek(self: &Rc) { if let Some(timer) = self.seek_hide_timer.borrow_mut().take() { timer.remove(); } - self.set_seek_visible(false); + if !self.seek_interacting.get() { + self.set_seek_visible(false); + } } fn set_seek_visible(self: &Rc, visible: bool) { @@ -919,6 +1292,79 @@ 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()); + restore_pending_viewer_file_scroll( + &self.file_list_panel, + &self.file_list_scrolled, + &self.file_list_scroll_restore, + ); + } + } + + 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 hide_fullscreen_ui_now(self: &Rc) { + if self.window.is_fullscreen() && !self.seek_interacting.get() { + self.cancel_fullscreen_ui_timer(); + self.set_fullscreen_ui_visible(false); + } + } + + 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()); + restore_pending_viewer_file_scroll( + &self.file_list_panel, + &self.file_list_scrolled, + &self.file_list_scroll_restore, + ); + 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(); @@ -1097,6 +1543,36 @@ impl ViewerController { self.schedule_view_mode_refresh(); } + fn adjust_image_zoom(self: &Rc, zoom_in: bool) { + let zoom = next_image_zoom(self.image_zoom.get(), zoom_in); + if (zoom - self.image_zoom.get()).abs() < f64::EPSILON { + return; + } + self.image_zoom.set(zoom); + if (zoom - 1.0).abs() < f64::EPSILON { + self.apply_view_mode(); + return; + } + match self.view_mode() { + ViewMode::TwoPage => self.resize_spread_pictures(), + ViewMode::Continuous => { + self.resize_continuous_rows(); + self.continuous_scrolled(); + } + _ => self.resize_single_picture(), + } + self.stack.queue_allocate(); + } + + fn select_view_mode(self: &Rc, index: u32) { + if self.mode_dropdown.selected() != index { + self.mode_dropdown.set_selected(index); + } else { + self.image_zoom.set(1.0); + self.apply_view_mode(); + } + } + fn schedule_view_mode_refresh(self: &Rc) { let generation = self.view_layout_generation.get().wrapping_add(1); self.view_layout_generation.set(generation); @@ -1122,7 +1598,13 @@ impl ViewerController { }); } - fn navigate(self: &Rc, forward: bool) { + fn navigate_from_button(self: &Rc, forward: bool) { + if self.navigate(forward) && (self.image_zoom.replace(1.0) - 1.0).abs() >= f64::EPSILON { + self.apply_view_mode(); + } + } + + fn navigate(self: &Rc, forward: bool) -> bool { let step = if self.view_mode() == ViewMode::TwoPage { 2 } else { @@ -1130,7 +1612,7 @@ impl ViewerController { }; let mut state = self.state.borrow_mut(); if state.pages.is_empty() { - return; + return false; } let next = if forward { state.anchor.saturating_add(step).min(state.pages.len() - 1) @@ -1138,7 +1620,7 @@ impl ViewerController { state.anchor.saturating_sub(step) }; if next == state.anchor { - return; + return false; } state.anchor = next; drop(state); @@ -1147,6 +1629,7 @@ impl ViewerController { if self.view_mode() == ViewMode::Continuous { self.schedule_scroll_to_anchor(); } + true } fn seek_edge(self: &Rc, end: bool) { @@ -1157,16 +1640,18 @@ impl ViewerController { self.seek_page(if end { count - 1 } else { 0 }); } - fn scroll_vertically(&self, down: bool) { - let adjustment = if self.view_mode() == ViewMode::Continuous { - self.continuous_scrolled.vadjustment() - } else { - self.single_scrolled.vadjustment() + fn pan_image(&self, horizontal: bool, forward: bool) -> bool { + let scrolled = match self.view_mode() { + ViewMode::TwoPage => &self.spread_scrolled, + ViewMode::Continuous => &self.continuous_scrolled, + _ => &self.single_scrolled, }; - let step = adjustment.step_increment().max(64.0); - let delta = if down { step } else { -step }; - let maximum = (adjustment.upper() - adjustment.page_size()).max(adjustment.lower()); - adjustment.set_value((adjustment.value() + delta).clamp(adjustment.lower(), maximum)); + let adjustment = if horizontal { + scrolled.hadjustment() + } else { + scrolled.vadjustment() + }; + pan_adjustment(&adjustment, forward) } fn shift_pairing(self: &Rc, offset: isize) { @@ -1339,7 +1824,7 @@ impl ViewerController { }; if let Some(frame) = frame { frame.set_ratio(ratio); - frame.set_size_request(-1, row_height(self.continuous_content_width(), ratio)); + self.resize_continuous_rows(); } } self.evict_cache(); @@ -1382,15 +1867,100 @@ impl ViewerController { .and_then(|page| page.frames.first()) .map(|frame| (frame.texture.width(), frame.texture.height())) }; - if let Some((texture_width, texture_height)) = dimensions - && let Some((width, height)) = single_picture_request( + if let Some((texture_width, texture_height)) = dimensions { + let zoom = self.image_zoom.get(); + if (zoom - 1.0).abs() >= f64::EPSILON { + let (width, height) = zoomed_picture_request( + self.view_mode(), + self.single_scrolled.width().max(1), + self.single_scrolled.height().max(1), + texture_width, + texture_height, + zoom, + ); + self.single_box.set_hexpand(true); + self.single_box.set_vexpand(true); + self.single_box.set_halign(gtk::Align::Fill); + self.single_box.set_valign(gtk::Align::Fill); + self.single_picture.set_can_shrink(false); + self.single_picture.set_hexpand(false); + self.single_picture.set_vexpand(false); + self.single_picture.set_content_fit(gtk::ContentFit::Fill); + self.single_picture.set_halign(gtk::Align::Center); + self.single_picture.set_valign(gtk::Align::Center); + self.single_picture.set_size_request(width, height); + } else if let Some((width, height)) = single_picture_request( self.view_mode(), - self.stack.allocated_width().max(1), + self.stack.width().max(1), texture_width, texture_height, - ) + ) { + self.single_picture.set_size_request(width, height); + } + } + } + + fn resize_spread_pictures(&self) { + let zoom = self.image_zoom.get(); + if (zoom - 1.0).abs() < f64::EPSILON { + self.spread_box.set_homogeneous(true); + self.spread_box.set_halign(gtk::Align::Fill); + self.spread_box.set_valign(gtk::Align::Fill); + for picture in [&self.left_picture, &self.right_picture] { + picture.set_can_shrink(true); + picture.set_hexpand(true); + picture.set_vexpand(true); + picture.set_content_fit(gtk::ContentFit::Contain); + picture.set_size_request(-1, -1); + } + return; + } + let visible = self.visible_indices(); + let state = self.state.borrow(); + let page_dimensions = |position: usize| { + visible.get(position).and_then(|index| { + state + .cache + .get(index) + .and_then(|page| page.frames.first()) + .map(|frame| (frame.texture.width(), frame.texture.height())) + }) + }; + let first = page_dimensions(0); + let second = page_dimensions(1); + let dimensions = if self.direction_dropdown.selected() == 1 { + [second, first] + } else { + [first, second] + }; + drop(state); + let count = visible.len().max(1) as i32; + let viewport_width = (self.spread_scrolled.width().max(1) - 8) / count; + let viewport_height = self.spread_scrolled.height().max(1); + self.spread_box.set_homogeneous(false); + self.spread_box.set_halign(gtk::Align::Center); + self.spread_box.set_valign(gtk::Align::Center); + for (picture, dimensions) in [&self.left_picture, &self.right_picture] + .into_iter() + .zip(dimensions) { - self.single_picture.set_size_request(width, height); + let Some((texture_width, texture_height)) = dimensions else { + picture.set_size_request(1, 1); + continue; + }; + let (width, height) = zoomed_picture_request( + ViewMode::FitHeight, + viewport_width, + viewport_height, + texture_width, + texture_height, + zoom, + ); + picture.set_can_shrink(false); + picture.set_hexpand(false); + picture.set_vexpand(false); + picture.set_content_fit(gtk::ContentFit::Fill); + picture.set_size_request(width, height); } } @@ -1429,6 +1999,7 @@ impl ViewerController { ); } self.status_label.set_text(&status); + self.resize_spread_pictures(); } fn render_continuous(&self, visible: &[usize]) { @@ -1584,7 +2155,14 @@ impl ViewerController { } fn resize_continuous_rows(&self) { - let width = self.continuous_content_width(); + let zoom = self.image_zoom.get(); + let width = scaled_dimension(self.continuous_content_width(), zoom); + let zoomed = (zoom - 1.0).abs() >= f64::EPSILON; + self.continuous_box.set_halign(if zoomed { + gtk::Align::Center + } else { + gtk::Align::Fill + }); let rows: Vec<_> = self .state .borrow() @@ -1593,12 +2171,13 @@ impl ViewerController { .map(|row| (row.frame.clone(), row.ratio)) .collect(); for (frame, ratio) in rows { - frame.set_size_request(-1, row_height(width, ratio)); + frame.set_hexpand(!zoomed); + frame.set_size_request(if zoomed { width } else { -1 }, row_height(width, ratio)); } } fn continuous_content_width(&self) -> i32 { - continuous_content_width(self.stack.allocated_width()) + continuous_content_width(self.stack.width()) } fn evict_cache(&self) { @@ -1681,10 +2260,25 @@ impl MediaViewerWindow { sibling_navigator, favorite_control, download_control, + file_drop_control, reuse_window, view_mode_control, + two_page_direction_control: _, } = controls; - let title = source.display_name.clone(); + let title_files = sibling_navigator + .as_ref() + .map(SiblingNavigator::files) + .unwrap_or_default(); + let title = viewer_file_title(&source.display_name, &source.source_uri, &title_files); + let file_list_query = reuse_window + .as_ref() + .map(viewer_file_search_query) + .unwrap_or_default(); + let file_list_scroll = reuse_window + .as_ref() + .map(viewer_file_scroll_position) + .unwrap_or_default(); + let video_loop_active = reuse_window.as_ref().is_some_and(viewer_video_loop_enabled); if let Some(window) = reuse_window.as_ref() { clear_viewer_controller(window); } @@ -1696,16 +2290,19 @@ impl MediaViewerWindow { .default_height(850) .build() }); + 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)))); + header.set_title_widget(Some(&viewer_title_label(&title))); let favorite_button = gtk::Button::with_label(favorite_label(favorite_control.active)); let download_button = gtk::Button::with_label("파일 다운로드"); let file_list_button = gtk::ToggleButton::with_label("파일 목록"); file_list_button.set_sensitive(sibling_navigator.is_some()); file_list_button.set_active(window.has_css_class("viewer-file-list-visible")); let loop_check = gtk::CheckButton::with_label("반복 재생"); + loop_check.set_active(video_loop_active); loop_check.set_visible(kind == EntryKind::Video); let image_mode_dropdown = gtk::DropDown::from_strings(&["100%", "폭 맞춤", "높이 맞춤"]); let (image_mode_selected, image_mode_change) = @@ -1722,7 +2319,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(); @@ -1742,14 +2339,13 @@ impl MediaViewerWindow { } else { gtk::Video::new() }; - video.set_autoplay(true); + video.set_autoplay(false); + video.set_loop(false); video.set_hexpand(true); video.set_vexpand(true); - let video_for_loop = video.clone(); - loop_check.connect_toggled(move |check| video_for_loop.set_loop(check.is_active())); stack.add_named(&video, Some("video")); let status_label = gtk::Label::builder() - .label(&title) + .label(&source.display_name) .xalign(0.0) .margin_top(6) .margin_bottom(6) @@ -1758,10 +2354,12 @@ impl MediaViewerWindow { .build(); let media_seek = navigation_scale(); let media_seek_row = navigation_scale_row(&media_seek); - if let Some((current, count)) = sibling_navigator + let seek_files = sibling_navigator .as_ref() - .and_then(SiblingNavigator::position) - { + .map(|navigator| navigator.seek_files(kind)) + .unwrap_or_default(); + if let Some(current) = seek_position(&seek_files, &source.source_uri) { + let count = seek_files.len(); media_seek.set_range(0.0, navigation_scale_upper(count)); media_seek.set_value(current as f64); media_seek.set_sensitive(count > 1); @@ -1777,7 +2375,7 @@ impl MediaViewerWindow { window_overlay.add_overlay(&navigation_message); window_overlay.set_hexpand(true); window_overlay.set_vexpand(true); - let file_list = viewer_file_list(); + let file_list = viewer_file_list(&file_list_query); file_list.panel.set_visible(file_list_button.is_active()); let viewer_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0); viewer_layout.append(&window_overlay); @@ -1786,6 +2384,7 @@ impl MediaViewerWindow { let controller = Rc::new(MediaViewerController { window, + titlebar_host, source, kind, picture, @@ -1794,17 +2393,22 @@ impl MediaViewerWindow { image_mode_dropdown, image_mode_change, image_dimensions: Cell::new(None), + image_zoom: Cell::new(1.0), image_animation_generation: Rc::new(AnimationState::default()), video, stack, status_label, media_seek, media_seek_row, + seek_files: RefCell::new(seek_files), sibling_navigator, file_list_button, file_list_panel: file_list.panel, + file_list_search: file_list.search, + file_list_scrolled: file_list.scrolled, file_list: file_list.list, file_list_files: RefCell::new(Vec::new()), + file_list_scroll_restore: Cell::new(Some(file_list_scroll)), favorite_button, favorite_toggle: favorite_control.toggle, download_button, @@ -1812,22 +2416,62 @@ impl MediaViewerWindow { seek_generation: Cell::new(0), seek_opening: Cell::new(false), seek_hide_timer: RefCell::new(None), + seek_interacting: Cell::new(false), + pending_seek_index: Cell::new(None), last_pointer_position: Cell::new(None), key_controller: RefCell::new(None), motion_controller: RefCell::new(None), + fullscreen_key_controller: RefCell::new(None), + fullscreen_click_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)), }); if let Some(stream) = controller.video.media_stream() { + stream.set_loop(false); let status_label = controller.status_label.clone(); stream.connect_error_notify(move |stream| { if let Some(error) = stream.error() { status_label.set_text(&format!("동영상을 재생할 수 없습니다: {error}")); } }); + let restart_pending = Rc::new(Cell::new(false)); + let loop_check_for_end = loop_check.downgrade(); + let restart_pending_for_end = Rc::clone(&restart_pending); + stream.connect_ended_notify(move |stream| { + let Some(check) = loop_check_for_end.upgrade() else { + return; + }; + schedule_video_loop_restart(stream, &check, &restart_pending_for_end); + }); + let loop_check_for_timestamp = loop_check.downgrade(); + let restart_pending_for_timestamp = Rc::clone(&restart_pending); + stream.connect_timestamp_notify(move |stream| { + let Some(check) = loop_check_for_timestamp.upgrade() else { + return; + }; + schedule_video_loop_restart(stream, &check, &restart_pending_for_timestamp); + }); + let stream_for_loop_check = stream.clone(); + let window_for_loop_check = controller.window.clone(); + loop_check.connect_toggled(move |check| { + store_viewer_video_loop(&window_for_loop_check, check.is_active()); + schedule_video_loop_restart(&stream_for_loop_check, check, &restart_pending); + }); } controller.connect_signals(); + controller.fullscreen_changed(); + if controller.window.has_css_class(PRESERVE_SEEK_CLASS) { + controller.window.remove_css_class(PRESERVE_SEEK_CLASS); + if controller.window.is_fullscreen() { + controller.show_fullscreen_ui_temporarily(); + } else { + controller.show_seek_temporarily(); + } + } if controller.file_list_button.is_active() { controller.refresh_file_list(); } @@ -1843,6 +2487,7 @@ impl MediaViewerWindow { EntryKind::Video => { controller.stack.set_visible_child_name("video"); if let Some(stream) = controller.video.media_stream() { + initialize_video_volume(&stream); stream.play(); } } @@ -1853,6 +2498,7 @@ impl MediaViewerWindow { struct MediaViewerController { window: gtk::ApplicationWindow, + titlebar_host: gtk::Box, source: ArchiveSource, kind: EntryKind, picture: gtk::Picture, @@ -1861,17 +2507,22 @@ struct MediaViewerController { image_mode_dropdown: gtk::DropDown, image_mode_change: Option>, image_dimensions: Cell>, + image_zoom: Cell, image_animation_generation: Rc, video: gtk::Video, stack: gtk::Stack, status_label: gtk::Label, media_seek: gtk::Scale, media_seek_row: gtk::Box, + seek_files: RefCell>, sibling_navigator: Option, file_list_button: gtk::ToggleButton, - file_list_panel: gtk::ScrolledWindow, + file_list_panel: gtk::Box, + file_list_search: gtk::SearchEntry, + file_list_scrolled: gtk::ScrolledWindow, file_list: gtk::ListBox, file_list_files: RefCell>, + file_list_scroll_restore: Cell>, favorite_button: gtk::Button, favorite_toggle: Rc bool>, download_button: gtk::Button, @@ -1879,9 +2530,16 @@ struct MediaViewerController { seek_generation: Cell, seek_opening: Cell, seek_hide_timer: RefCell>, + seek_interacting: Cell, + pending_seek_index: Cell>, last_pointer_position: Cell>, key_controller: RefCell>, motion_controller: RefCell>, + fullscreen_key_controller: RefCell>, + fullscreen_click_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>, @@ -1889,6 +2547,22 @@ struct MediaViewerController { impl MediaViewerController { fn connect_signals(self: &Rc) { + let fullscreen_click = gtk::EventControllerLegacy::new(); + fullscreen_click.set_propagation_phase(gtk::PropagationPhase::Capture); + let controller = Rc::downgrade(self); + fullscreen_click.connect_event(move |_, event| { + if event.downcast_ref::().is_some() + && event.event_type() == gdk::EventType::ButtonPress + && let Some(controller) = controller.upgrade() + { + controller.controls_clicked(); + } + glib::Propagation::Proceed + }); + self.window.add_controller(fullscreen_click.clone()); + self.fullscreen_click_controller + .replace(Some(fullscreen_click)); + let motion_controller = gtk::EventControllerMotion::new(); motion_controller.set_propagation_phase(gtk::PropagationPhase::Capture); let controller = Rc::downgrade(self); @@ -1900,12 +2574,32 @@ 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 |_, key, _, _| { + if let Some(controller) = controller.upgrade() + && !widget_contains_focus(&controller.file_list_search, &controller.window) + && controller.window.is_fullscreen() + && fullscreen_direction_key(key) + { + controller.hide_fullscreen_ui_now(); + } + 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| { let Some(controller) = controller.upgrade() else { return glib::Propagation::Proceed; }; + if widget_contains_focus(&controller.file_list_search, &controller.window) { + return glib::Propagation::Proceed; + } if modifiers.intersects( gdk::ModifierType::CONTROL_MASK | gdk::ModifierType::ALT_MASK @@ -1913,21 +2607,23 @@ 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 => { + gdk::Key::Left | gdk::Key::KP_Left if controller.kind == EntryKind::Video => { controller.seek_video(-VIDEO_SEEK_STEP_US); glib::Propagation::Stop } - gdk::Key::Right if controller.kind == EntryKind::Video => { + gdk::Key::Right | gdk::Key::KP_Right if controller.kind == EntryKind::Video => { controller.seek_video(VIDEO_SEEK_STEP_US); glib::Propagation::Stop } - gdk::Key::Up if controller.kind == EntryKind::Video => { + gdk::Key::Up | gdk::Key::KP_Up if controller.kind == EntryKind::Video => { controller.adjust_video_volume(VIDEO_VOLUME_STEP); glib::Propagation::Stop } - gdk::Key::Down if controller.kind == EntryKind::Video => { + gdk::Key::Down | gdk::Key::KP_Down if controller.kind == EntryKind::Video => { controller.adjust_video_volume(-VIDEO_VOLUME_STEP); glib::Propagation::Stop } @@ -1939,24 +2635,25 @@ impl MediaViewerController { controller.open_edge(true); glib::Propagation::Stop } - gdk::Key::Up + gdk::Key::Up | gdk::Key::KP_Up if controller.kind == EntryKind::Image - && matches!( - controller.image_view_mode(), - ViewMode::ActualSize | ViewMode::FitWidth - ) => + && controller.pan_image(false, false) => { - controller.scroll_image(false); glib::Propagation::Stop } - gdk::Key::Down - if controller.kind == EntryKind::Image - && matches!( - controller.image_view_mode(), - ViewMode::ActualSize | ViewMode::FitWidth - ) => + gdk::Key::Down | gdk::Key::KP_Down + if controller.kind == EntryKind::Image && controller.pan_image(false, true) => + { + glib::Propagation::Stop + } + gdk::Key::Left | gdk::Key::KP_Left + if controller.kind == EntryKind::Image && controller.pan_image(true, false) => + { + glib::Propagation::Stop + } + gdk::Key::Right | gdk::Key::KP_Right + if controller.kind == EntryKind::Image && controller.pan_image(true, true) => { - controller.scroll_image(true); glib::Propagation::Stop } _ if key.to_unicode() == Some('[') => { @@ -1967,6 +2664,35 @@ impl MediaViewerController { controller.open_sibling(true); glib::Propagation::Stop } + gdk::Key::plus | gdk::Key::equal | gdk::Key::KP_Add + if controller.kind == EntryKind::Image => + { + controller.adjust_image_zoom(true); + glib::Propagation::Stop + } + gdk::Key::minus | gdk::Key::KP_Subtract if controller.kind == EntryKind::Image => { + controller.adjust_image_zoom(false); + glib::Propagation::Stop + } + gdk::Key::_1 | gdk::Key::KP_1 if controller.kind == EntryKind::Image => { + controller.select_image_view_mode(1); + glib::Propagation::Stop + } + gdk::Key::_2 | gdk::Key::KP_2 if controller.kind == EntryKind::Image => { + controller.select_image_view_mode(2); + glib::Propagation::Stop + } + gdk::Key::_4 | gdk::Key::KP_4 if controller.kind == EntryKind::Image => { + controller.select_image_view_mode(0); + glib::Propagation::Stop + } + _ if key + .to_unicode() + .is_some_and(|character| character.eq_ignore_ascii_case(&'l')) => + { + controller.toggle_file_list(); + glib::Propagation::Stop + } _ if key .to_unicode() .is_some_and(|character| character.eq_ignore_ascii_case(&'f')) => @@ -1984,6 +2710,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)(); @@ -2002,7 +2737,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 { @@ -2021,6 +2760,39 @@ impl MediaViewerController { controller.open_file_list_row(row.index()); } }); + let controller = Rc::downgrade(self); + self.file_list_search.connect_search_changed(move |search| { + if let Some(controller) = controller.upgrade() { + store_viewer_file_search_query(&controller.window, search.text().as_str()); + controller.refresh_file_list(); + } + }); + let controller = Rc::downgrade(self); + self.file_list_scrolled + .vadjustment() + .connect_value_changed(move |adjustment| { + if let Some(controller) = controller.upgrade() + && controller.file_list_scroll_restore.get().is_none() + { + store_viewer_file_scroll_position(&controller.window, adjustment.value()); + } + }); + 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| { @@ -2035,6 +2807,7 @@ impl MediaViewerController { .connect_selected_notify(move |dropdown| { if let Some(controller) = controller.upgrade() { change(dropdown.selected()); + controller.image_zoom.set(1.0); controller.apply_image_view_mode(); } }); @@ -2047,21 +2820,67 @@ impl MediaViewerController { } }); let controller = Rc::downgrade(self); + self.image_scrolled + .connect_notify_local(Some("height"), move |_, _| { + if let Some(controller) = controller.upgrade() { + controller.resize_image_picture(); + } + }); + let image_scroll = gtk::EventControllerScroll::new( + gtk::EventControllerScrollFlags::VERTICAL | gtk::EventControllerScrollFlags::DISCRETE, + ); + image_scroll.set_propagation_phase(gtk::PropagationPhase::Capture); + let controller = Rc::downgrade(self); + image_scroll.connect_scroll(move |scroll, _, delta_y| { + let Some(controller) = controller.upgrade() else { + return glib::Propagation::Proceed; + }; + if controller.kind == EntryKind::Image + && scroll + .current_event_state() + .contains(gdk::ModifierType::CONTROL_MASK) + && delta_y != 0.0 + { + controller.adjust_image_zoom(delta_y < 0.0); + glib::Propagation::Stop + } else { + glib::Propagation::Proceed + } + }); + self.image_scrolled.add_controller(image_scroll); + let controller = Rc::downgrade(self); self.media_seek.connect_value_changed(move |scale| { let Some(controller) = controller.upgrade() else { return; }; - let Some(navigator) = &controller.sibling_navigator else { - return; - }; - let Some((_, count)) = navigator.position() else { - return; - }; + let count = controller.seek_files.borrow().len(); let Some(index) = page_seek_index(scale.value(), count) else { return; }; - controller.schedule_seek(index); + if controller.seek_interacting.get() { + controller.pending_seek_index.set(Some(index)); + } else { + controller.schedule_seek(index); + } }); + let seek_events = gtk::EventControllerLegacy::new(); + seek_events.set_propagation_phase(gtk::PropagationPhase::Capture); + let controller = Rc::downgrade(self); + seek_events.connect_event(move |_, event| { + if event + .downcast_ref::() + .is_some_and(|event| event.button() == gdk::BUTTON_PRIMARY) + && let Some(controller) = controller.upgrade() + { + match event.event_type() { + gdk::EventType::ButtonPress => controller.begin_seek_interaction(), + gdk::EventType::ButtonRelease => controller.end_seek_interaction(), + _ => {} + } + } + glib::Propagation::Proceed + }); + self.media_seek.add_controller(seek_events); } fn refresh_file_list(&self) { @@ -2073,6 +2892,7 @@ impl MediaViewerController { .as_ref() .map(SiblingNavigator::files) .unwrap_or_default(); + let files = filter_sibling_files(files, self.file_list_search.text().as_str()); let current = files .iter() .position(|file| file.uri == self.source.source_uri); @@ -2083,6 +2903,11 @@ impl MediaViewerController { if let Some(row) = current.and_then(|index| self.file_list.row_at_index(index as i32)) { self.file_list.select_row(Some(&row)); } + restore_pending_viewer_file_scroll( + &self.file_list_panel, + &self.file_list_scrolled, + &self.file_list_scroll_restore, + ); } fn open_file_list_row(&self, index: i32) { @@ -2136,6 +2961,17 @@ impl MediaViewerController { } } + fn toggle_file_list(&self) { + if !self.file_list_button.is_sensitive() { + return; + } + let active = !self.file_list_button.is_active(); + self.file_list_button.set_active(active); + if self.window.is_fullscreen() { + self.file_list_panel.set_visible(active); + } + } + fn seek_video(&self, delta: i64) { let Some(stream) = self .video @@ -2201,13 +3037,60 @@ impl MediaViewerController { self.stack.queue_allocate(); } + fn adjust_image_zoom(&self, zoom_in: bool) { + if self.kind != EntryKind::Image { + return; + } + let zoom = next_image_zoom(self.image_zoom.get(), zoom_in); + if (zoom - self.image_zoom.get()).abs() < f64::EPSILON { + return; + } + self.image_zoom.set(zoom); + if (zoom - 1.0).abs() < f64::EPSILON { + self.apply_image_view_mode(); + } else { + self.resize_image_picture(); + self.stack.queue_allocate(); + } + } + + fn select_image_view_mode(&self, index: u32) { + if self.image_mode_dropdown.selected() != index { + self.image_mode_dropdown.set_selected(index); + } else { + self.image_zoom.set(1.0); + self.apply_image_view_mode(); + } + } + fn resize_image_picture(&self) { let Some((texture_width, texture_height)) = self.image_dimensions.get() else { return; }; - if let Some((width, height)) = single_picture_request( + let zoom = self.image_zoom.get(); + if (zoom - 1.0).abs() >= f64::EPSILON { + let (width, height) = zoomed_picture_request( + self.image_view_mode(), + self.image_scrolled.width().max(1), + self.image_scrolled.height().max(1), + texture_width, + texture_height, + zoom, + ); + self.image_box.set_hexpand(true); + self.image_box.set_vexpand(true); + self.image_box.set_halign(gtk::Align::Fill); + self.image_box.set_valign(gtk::Align::Fill); + self.picture.set_can_shrink(false); + self.picture.set_hexpand(false); + self.picture.set_vexpand(false); + self.picture.set_content_fit(gtk::ContentFit::Fill); + self.picture.set_halign(gtk::Align::Center); + self.picture.set_valign(gtk::Align::Center); + self.picture.set_size_request(width, height); + } else if let Some((width, height)) = single_picture_request( self.image_view_mode(), - self.stack.allocated_width().max(1), + self.stack.width().max(1), texture_width, texture_height, ) { @@ -2215,12 +3098,13 @@ impl MediaViewerController { } } - fn scroll_image(&self, down: bool) { - let adjustment = self.image_scrolled.vadjustment(); - let step = adjustment.step_increment().max(64.0); - let delta = if down { step } else { -step }; - let maximum = (adjustment.upper() - adjustment.page_size()).max(adjustment.lower()); - adjustment.set_value((adjustment.value() + delta).clamp(adjustment.lower(), maximum)); + fn pan_image(&self, horizontal: bool, forward: bool) -> bool { + let adjustment = if horizontal { + self.image_scrolled.hadjustment() + } else { + self.image_scrolled.vadjustment() + }; + pan_adjustment(&adjustment, forward) } fn open_sibling(&self, forward: bool) { @@ -2262,11 +3146,9 @@ impl MediaViewerController { if let Some(timer) = self.seek_hide_timer.borrow_mut().take() { timer.remove(); } - if let Some((current, count)) = self - .sibling_navigator - .as_ref() - .and_then(SiblingNavigator::position) - { + let seek_files = self.seek_files.borrow(); + if let Some(current) = seek_position(&seek_files, &self.source.source_uri) { + let count = seek_files.len(); self.media_seek .set_range(0.0, navigation_scale_upper(count)); self.media_seek.set_sensitive(count > 1); @@ -2277,25 +3159,66 @@ impl MediaViewerController { let timer = glib::timeout_add_local_once(Duration::from_secs(5), move || { if let Some(controller) = controller.upgrade() { controller.seek_hide_timer.borrow_mut().take(); - controller.set_seek_visible(false); + if !controller.seek_interacting.get() { + controller.set_seek_visible(false); + } } }); self.seek_hide_timer.replace(Some(timer)); } + fn begin_seek_interaction(self: &Rc) { + self.seek_interacting.set(true); + self.pending_seek_index.set(None); + self.seek_generation + .set(self.seek_generation.get().wrapping_add(1)); + if let Some(timer) = self.seek_hide_timer.borrow_mut().take() { + timer.remove(); + } + self.cancel_fullscreen_ui_timer(); + if self.window.is_fullscreen() { + self.set_fullscreen_ui_visible(true); + } else { + self.set_seek_visible(true); + } + } + + fn end_seek_interaction(self: &Rc) { + if !self.seek_interacting.replace(false) { + return; + } + if self.window.is_fullscreen() { + self.show_fullscreen_ui_temporarily(); + } else { + self.show_seek_temporarily(); + } + if let Some(index) = self.pending_seek_index.take() { + self.schedule_seek(index); + } + } + fn pointer_moved(self: &Rc, x: f64, y: f64) { if self.last_pointer_position.get() == Some((x, y)) { return; } self.last_pointer_position.set(Some((x, y))); - self.show_seek_temporarily(); + } + + fn controls_clicked(self: &Rc) { + if self.window.is_fullscreen() { + self.show_fullscreen_ui_temporarily(); + } else { + self.show_seek_temporarily(); + } } fn hide_seek(self: &Rc) { if let Some(timer) = self.seek_hide_timer.borrow_mut().take() { timer.remove(); } - self.set_seek_visible(false); + if !self.seek_interacting.get() { + self.set_seek_visible(false); + } } fn set_seek_visible(self: &Rc, visible: bool) { @@ -2315,14 +3238,13 @@ impl MediaViewerController { } fn schedule_seek(self: &Rc, index: usize) { - let Some(navigator) = &self.sibling_navigator else { + if self.sibling_navigator.is_none() { + return; + } + let Some(file) = self.seek_files.borrow().get(index).cloned() else { return; }; - if navigator - .position() - .is_none_or(|(current, _)| index == current) - || self.seek_opening.get() - { + if file.uri == self.source.source_uri || self.seek_opening.get() { return; } let generation = self.seek_generation.get().wrapping_add(1); @@ -2338,21 +3260,48 @@ impl MediaViewerController { let Some(navigator) = &controller.sibling_navigator else { return; }; - if navigator.open_index(index, controller.window.clone()) { - controller.seek_opening.set(true); + let Some(uri) = controller + .seek_files + .borrow() + .get(index) + .map(|file| file.uri.clone()) + else { + return; + }; + controller.seek_opening.set(true); + controller.window.add_css_class(PRESERVE_SEEK_CLASS); + if navigator.open_uri(&uri, controller.window.clone()) { controller.prepare_for_navigation(); + } else { + controller.seek_opening.set(false); + controller.window.remove_css_class(PRESERVE_SEEK_CLASS); } }); } fn prepare_for_navigation(&self) { + self.seek_generation + .set(self.seek_generation.get().wrapping_add(1)); 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); + } + if let Some(controller) = self.fullscreen_click_controller.borrow_mut().take() { + self.window.remove_controller(&controller); + } } fn stop_playback(&self) { @@ -2370,6 +3319,78 @@ 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()); + restore_pending_viewer_file_scroll( + &self.file_list_panel, + &self.file_list_scrolled, + &self.file_list_scroll_restore, + ); + } + } + + 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 hide_fullscreen_ui_now(self: &Rc) { + if self.window.is_fullscreen() && !self.seek_interacting.get() { + self.cancel_fullscreen_ui_timer(); + self.set_fullscreen_ui_visible(false); + } + } + + 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()); + restore_pending_viewer_file_scroll( + &self.file_list_panel, + &self.file_list_scrolled, + &self.file_list_scroll_restore, + ); + 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("이미지를 읽는 중..."); @@ -2423,23 +3444,234 @@ fn favorite_label(active: bool) -> &'static str { } } +fn viewer_title_label(title: &str) -> gtk::Label { + gtk::Label::builder() + .label(title) + .hexpand(true) + .ellipsize(gtk::pango::EllipsizeMode::Middle) + .tooltip_text(title) + .build() +} + +fn viewer_file_title(display_name: &str, current_uri: &str, files: &[SiblingFile]) -> String { + seek_position(files, current_uri).map_or_else( + || display_name.to_owned(), + |index| format!("{display_name} ({}/{})", index + 1, files.len()), + ) +} + struct ViewerFileList { - panel: gtk::ScrolledWindow, + panel: gtk::Box, + search: gtk::SearchEntry, + scrolled: gtk::ScrolledWindow, list: gtk::ListBox, } -fn viewer_file_list() -> ViewerFileList { +#[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') + || character.eq_ignore_ascii_case(&'l') + || 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 fullscreen_direction_key(key: gdk::Key) -> bool { + matches!( + key, + gdk::Key::Left + | gdk::Key::Right + | gdk::Key::Up + | gdk::Key::Down + | gdk::Key::KP_Left + | gdk::Key::KP_Right + | gdk::Key::KP_Up + | gdk::Key::KP_Down + ) +} + +fn shortcut_modifiers_blocked(modifiers: gdk::ModifierType) -> bool { + modifiers.intersects( + gdk::ModifierType::CONTROL_MASK + | gdk::ModifierType::ALT_MASK + | gdk::ModifierType::SUPER_MASK, + ) +} + +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(query: &str) -> ViewerFileList { + let search = gtk::SearchEntry::builder() + .placeholder_text("재생 목록 검색") + .margin_top(8) + .margin_bottom(8) + .margin_start(8) + .margin_end(8) + .build(); + search.set_text(query); let list = gtk::ListBox::new(); list.set_selection_mode(gtk::SelectionMode::Single); list.set_activate_on_single_click(false); - let panel = gtk::ScrolledWindow::builder() - .width_request(280) + let scrolled = gtk::ScrolledWindow::builder() .vexpand(true) .child(&list) .build(); + let panel = gtk::Box::new(gtk::Orientation::Vertical, 0); + panel.set_width_request(280); + panel.set_vexpand(true); + panel.append(&search); + panel.append(&scrolled); panel.add_css_class("sidebar"); panel.set_visible(false); - ViewerFileList { panel, list } + ViewerFileList { + panel, + search, + scrolled, + list, + } +} + +fn viewer_file_search_query(window: >k::ApplicationWindow) -> String { + unsafe { + window + .data::(VIEWER_FILE_SEARCH_KEY) + .map(|query| query.as_ref().clone()) + .unwrap_or_default() + } +} + +fn store_viewer_file_search_query(window: >k::ApplicationWindow, query: &str) { + unsafe { + window.set_data(VIEWER_FILE_SEARCH_KEY, query.to_owned()); + } +} + +fn viewer_file_scroll_position(window: >k::ApplicationWindow) -> f64 { + unsafe { + window + .data::(VIEWER_FILE_SCROLL_KEY) + .map(|position| *position.as_ref()) + .unwrap_or_default() + } +} + +fn store_viewer_file_scroll_position(window: >k::ApplicationWindow, position: f64) { + unsafe { + window.set_data(VIEWER_FILE_SCROLL_KEY, position.max(0.0)); + } +} + +fn viewer_video_loop_enabled(window: >k::ApplicationWindow) -> bool { + unsafe { + window + .data::(VIEWER_VIDEO_LOOP_KEY) + .is_some_and(|active| *active.as_ref()) + } +} + +fn store_viewer_video_loop(window: >k::ApplicationWindow, active: bool) { + unsafe { + window.set_data(VIEWER_VIDEO_LOOP_KEY, active); + } +} + +fn restore_viewer_file_scroll(scrolled: >k::ScrolledWindow, position: f64) { + let scrolled = scrolled.clone(); + glib::idle_add_local_once(move || { + let adjustment = scrolled.vadjustment(); + let maximum = (adjustment.upper() - adjustment.page_size()).max(adjustment.lower()); + adjustment.set_value(position.clamp(adjustment.lower(), maximum)); + }); +} + +fn restore_pending_viewer_file_scroll( + panel: >k::Box, + scrolled: >k::ScrolledWindow, + pending: &Cell>, +) { + if !panel.is_visible() { + return; + } + if let Some(position) = pending.take() { + restore_viewer_file_scroll(scrolled, position); + } +} + +fn widget_contains_focus(widget: &impl IsA, window: >k::ApplicationWindow) -> bool { + gtk::prelude::GtkWindowExt::focus(window).is_some_and(|focus| { + let widget = widget.as_ref(); + focus == *widget || focus.is_ancestor(widget) + }) } fn viewer_file_row(file: &SiblingFile) -> gtk::ListBoxRow { @@ -2631,6 +3863,52 @@ fn single_picture_request( } } +fn next_image_zoom(current: f64, zoom_in: bool) -> f64 { + let multiplier = if zoom_in { + 1.0 + IMAGE_ZOOM_STEP + } else { + 1.0 - IMAGE_ZOOM_STEP + }; + ((current * multiplier * 10_000.0).round() / 10_000.0).clamp(IMAGE_ZOOM_MIN, IMAGE_ZOOM_MAX) +} + +fn scaled_dimension(value: i32, zoom: f64) -> i32 { + ((value.max(1) as f64 * zoom).round() as i32).clamp(1, 30_000) +} + +fn zoomed_picture_request( + mode: ViewMode, + viewport_width: i32, + viewport_height: i32, + texture_width: i32, + texture_height: i32, + zoom: f64, +) -> (i32, i32) { + let viewport_width = viewport_width.max(1); + let viewport_height = viewport_height.max(1); + let texture_width = texture_width.max(1); + let texture_height = texture_height.max(1); + let (base_width, base_height) = match mode { + ViewMode::ActualSize => (texture_width, texture_height), + ViewMode::FitWidth | ViewMode::Continuous => ( + viewport_width, + row_height(viewport_width, texture_width as f32 / texture_height as f32), + ), + ViewMode::FitHeight | ViewMode::TwoPage => { + let scale = (viewport_width as f64 / texture_width as f64) + .min(viewport_height as f64 / texture_height as f64); + ( + (texture_width as f64 * scale).round() as i32, + (texture_height as f64 * scale).round() as i32, + ) + } + }; + ( + scaled_dimension(base_width, zoom.clamp(IMAGE_ZOOM_MIN, IMAGE_ZOOM_MAX)), + scaled_dimension(base_height, zoom.clamp(IMAGE_ZOOM_MIN, IMAGE_ZOOM_MAX)), + ) +} + fn texture_frames(page: DecodedPage) -> (Rc, usize) { let width = page.width; let height = page.height; @@ -2784,6 +4062,29 @@ fn sibling_index(current: usize, count: usize, forward: bool) -> Option { } } +fn seek_sibling_files( + mut files: Vec, + current_kind: EntryKind, + recursive: bool, +) -> Vec { + if current_kind == EntryKind::Image && !recursive { + files.retain(|file| file.kind != EntryKind::ZipArchive); + } + files +} + +fn filter_sibling_files(mut files: Vec, query: &str) -> Vec { + let query = query.to_lowercase(); + if !query.is_empty() { + files.retain(|file| file.name.to_lowercase().contains(&query)); + } + files +} + +fn seek_position(files: &[SiblingFile], current_uri: &str) -> Option { + files.iter().position(|file| file.uri == current_uri) +} + fn video_seek_target(timestamp: i64, duration: i64, delta: i64) -> i64 { let target = timestamp.saturating_add(delta).max(0); if duration > 0 { @@ -2797,6 +4098,99 @@ fn video_volume_target(volume: f64, delta: f64) -> f64 { (volume + delta).clamp(0.0, 1.0) } +fn video_loop_restart_needed( + ended: bool, + timestamp: i64, + duration: i64, + loop_active: bool, +) -> bool { + loop_active && (ended || (duration > 0 && timestamp >= duration)) +} + +fn schedule_video_loop_restart( + stream: >k::MediaStream, + check: >k::CheckButton, + pending: &Rc>, +) { + let restart_needed = video_loop_restart_needed( + stream.is_ended(), + stream.timestamp(), + stream.duration(), + check.is_active(), + ); + if !begin_video_loop_restart(pending, restart_needed) { + return; + } + let stream = stream.clone(); + let check = check.downgrade(); + let pending = Rc::clone(pending); + glib::timeout_add_local_once(Duration::from_millis(50), move || { + let Some(check) = check.upgrade() else { + pending.set(false); + return; + }; + if video_loop_restart_needed( + stream.is_ended(), + stream.timestamp(), + stream.duration(), + check.is_active(), + ) { + stream.pause(); + stream.seek(0); + stream.play(); + } + pending.set(false); + }); +} + +fn begin_video_loop_restart(pending: &Cell, restart_needed: bool) -> bool { + if !restart_needed { + pending.set(false); + return false; + } + !pending.replace(true) +} + +fn initialize_video_volume(stream: >k::MediaStream) { + let volume = stream.volume().clamp(0.0, 1.0); + // Force the realized playback backend and GTK controls to receive the same initial value. + stream.set_volume(if volume > 0.0 { 0.0 } else { 1.0 }); + stream.set_volume(volume); +} + +fn pan_adjustment(adjustment: >k::Adjustment, forward: bool) -> bool { + let Some(value) = image_pan_target( + adjustment.value(), + adjustment.lower(), + adjustment.upper(), + adjustment.page_size(), + forward, + ) else { + return false; + }; + adjustment.set_value(value); + true +} + +fn image_pan_target( + value: f64, + lower: f64, + upper: f64, + page_size: f64, + forward: bool, +) -> Option { + let maximum = (upper - page_size).max(lower); + if maximum <= lower { + return None; + } + let delta = if forward { + IMAGE_PAN_STEP + } else { + -IMAGE_PAN_STEP + }; + Some((value + delta).clamp(lower, maximum)) +} + #[cfg(test)] mod tests { use super::*; @@ -2913,6 +4307,172 @@ mod tests { assert_eq!(video_volume_target(0.5, 0.05), 0.55); } + #[test] + fn video_loop_restarts_only_after_ending_when_enabled() { + assert!(video_loop_restart_needed(true, 0, 10, true)); + assert!(video_loop_restart_needed(false, 11, 10, true)); + assert!(!video_loop_restart_needed(false, 9, 10, true)); + assert!(!video_loop_restart_needed(false, 11, 0, true)); + assert!(!video_loop_restart_needed(true, 10, 10, false)); + } + + #[test] + fn video_loop_can_restart_more_than_once() { + let pending = Cell::new(false); + assert!(begin_video_loop_restart(&pending, true)); + assert!(!begin_video_loop_restart(&pending, true)); + pending.set(false); + assert!(begin_video_loop_restart(&pending, true)); + assert!(!begin_video_loop_restart(&pending, false)); + } + + #[test] + fn image_pan_moves_at_most_100_pixels_and_consumes_clipped_axis() { + assert_eq!( + image_pan_target(250.0, 0.0, 1_000.0, 400.0, true), + Some(350.0) + ); + assert_eq!( + image_pan_target(600.0, 0.0, 1_000.0, 400.0, true), + Some(600.0) + ); + assert_eq!(image_pan_target(0.0, 0.0, 400.0, 400.0, true), None); + } + + #[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 fullscreen_direction_keys_hide_controls() { + for key in [ + gdk::Key::Left, + gdk::Key::Right, + gdk::Key::Up, + gdk::Key::Down, + gdk::Key::KP_Left, + gdk::Key::KP_Right, + gdk::Key::KP_Up, + gdk::Key::KP_Down, + ] { + assert!(fullscreen_direction_key(key)); + } + assert!(!fullscreen_direction_key(gdk::Key::bracketleft)); + assert!(!fullscreen_direction_key(gdk::Key::bracketright)); + assert!(!fullscreen_direction_key(gdk::Key::f)); + } + + #[test] + fn image_zoom_changes_by_ten_percent_and_clamps() { + assert_eq!(next_image_zoom(1.0, true), 1.1); + assert_eq!(next_image_zoom(1.0, false), 0.9); + assert_eq!(next_image_zoom(1.1, true), 1.21); + assert_eq!(next_image_zoom(1.1, false), 0.99); + assert_eq!(next_image_zoom(IMAGE_ZOOM_MAX, true), IMAGE_ZOOM_MAX); + assert_eq!(next_image_zoom(IMAGE_ZOOM_MIN, false), IMAGE_ZOOM_MIN); + } + + #[test] + fn ordinary_image_seek_excludes_zip_but_recursive_seek_keeps_it() { + let files = vec![ + SiblingFile { + uri: "file:///book.zip".into(), + name: "book.zip".into(), + kind: EntryKind::ZipArchive, + }, + SiblingFile { + uri: "file:///page.jpg".into(), + name: "page.jpg".into(), + kind: EntryKind::Image, + }, + SiblingFile { + uri: "file:///clip.mp4".into(), + name: "clip.mp4".into(), + kind: EntryKind::Video, + }, + ]; + + let ordinary = seek_sibling_files(files.clone(), EntryKind::Image, false); + assert_eq!(ordinary.len(), 2); + assert!( + !ordinary + .iter() + .any(|file| file.kind == EntryKind::ZipArchive) + ); + assert_eq!(seek_position(&ordinary, "file:///page.jpg"), Some(0)); + assert_eq!(seek_position(&ordinary, "file:///clip.mp4"), Some(1)); + assert_eq!(seek_sibling_files(files, EntryKind::Image, true).len(), 3); + } + + #[test] + fn viewer_title_includes_current_file_index() { + let files = ["first.zip", "second.jpg", "third.mp4"].map(|name| SiblingFile { + uri: format!("file:///{name}"), + name: name.into(), + kind: EntryKind::Image, + }); + + assert_eq!( + viewer_file_title("second.jpg", "file:///second.jpg", &files), + "second.jpg (2/3)" + ); + assert_eq!( + viewer_file_title("missing.jpg", "file:///missing.jpg", &files), + "missing.jpg" + ); + assert_eq!( + viewer_file_title("only.jpg", "file:///only.jpg", &[]), + "only.jpg" + ); + } + + #[test] + fn playlist_search_filters_and_empty_query_restores_files() { + let files = ["Alpha.zip", "beta.jpg", "Bravo.mp4"].map(|name| SiblingFile { + uri: format!("file:///{name}"), + name: name.into(), + kind: EntryKind::Image, + }); + + let filtered = filter_sibling_files(files.to_vec(), "BRAV"); + assert_eq!(filtered.len(), 1); + assert_eq!(filtered[0].name, "Bravo.mp4"); + assert_eq!(filter_sibling_files(files.to_vec(), "").len(), 3); + } + + #[test] + fn file_list_shortcut_rejects_command_modifiers() { + assert!(!shortcut_modifiers_blocked(gdk::ModifierType::SHIFT_MASK)); + assert!(shortcut_modifiers_blocked(gdk::ModifierType::CONTROL_MASK)); + assert!(shortcut_modifiers_blocked(gdk::ModifierType::ALT_MASK)); + assert!(shortcut_modifiers_blocked(gdk::ModifierType::SUPER_MASK)); + } + + #[test] + fn zoomed_image_request_preserves_aspect_ratio() { + assert_eq!( + zoomed_picture_request(ViewMode::ActualSize, 1000, 800, 800, 1600, 1.1), + (880, 1760) + ); + assert_eq!( + zoomed_picture_request(ViewMode::FitWidth, 1000, 800, 800, 1600, 0.9), + (900, 1800) + ); + assert_eq!( + zoomed_picture_request(ViewMode::FitHeight, 1000, 800, 800, 1600, 1.1), + (440, 880) + ); + } + #[test] fn navigation_boundary_messages_match_direction() { assert_eq!( diff --git a/src/window.rs b/src/window.rs index e60c6d3..f4830f5 100644 --- a/src/window.rs +++ b/src/window.rs @@ -1,32 +1,48 @@ -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::fs; +use std::io::Read; use std::path::{Path, PathBuf}; +use std::process::Command; use std::rc::Rc; +use std::sync::mpsc; +use std::thread; use std::time::{Duration, Instant}; -use anyhow::Result; +use anyhow::{Context, Result, bail}; use chrono::{DateTime, Local}; +use flate2::read::GzDecoder; use gtk::gio; use gtk::gio::prelude::*; use gtk::glib; use gtk::prelude::*; +use sha2::{Digest, Sha256}; +use tar::Archive; use crate::browser::{ BrowserEntry, EntryKind, SortDirection, SortField, classify_file, sort_entries, }; -use crate::config::{AppConfig, FavoriteEntry, LocationKind, LocationProfile, ViewerMode}; +use crate::config::{ + AppConfig, FavoriteEntry, LocationKind, LocationProfile, RecentFileEntry, 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, FileViewerControls, MediaViewerWindow, SiblingFile, - SiblingFileActions, SiblingNavigator, SiblingTarget, ViewModeControl, ViewerWindow, - set_viewer_header, + FavoriteControl, FileDownloadControl, FileDropControl, FileViewerControls, MediaViewerWindow, + SiblingFile, SiblingFileActions, SiblingNavigator, SiblingTarget, TwoPageDirectionControl, + ViewModeControl, ViewerWindow, install_file_drop_target, set_viewer_header, set_viewer_loading, }; use crate::zip_cache::ZipCache; +const MOUSE_BACK_BUTTON: u32 = 8; +const RECENT_FILE_LIMIT: usize = 100; +const UPDATE_BUNDLE_URL: &str = + "https://burningtuna.cafe24.com/www/Downloads/Comicviewer/Comicviewer-latest-x86_64.tar.gz"; +const UPDATE_CHECKSUM_URL: &str = "https://burningtuna.cafe24.com/www/Downloads/Comicviewer/Comicviewer-latest-x86_64.tar.gz.sha256"; + pub struct ComicWindow { controller: Rc, } @@ -70,11 +86,14 @@ impl ComicWindow { edit_location_button.set_sensitive(false); let delete_location_button = gtk::Button::with_label("삭제"); delete_location_button.set_sensitive(false); + let clear_recent_button = gtk::Button::with_label("최근 기록 비우기"); + clear_recent_button.set_visible(false); locations.append(>k::Label::new(Some("위치"))); locations.append(&location_dropdown); locations.append(&add_location_button); locations.append(&edit_location_button); locations.append(&delete_location_button); + locations.append(&clear_recent_button); let navigation = gtk::Box::new(gtk::Orientation::Horizontal, 6); let up_button = gtk::Button::builder() @@ -112,12 +131,13 @@ impl ComicWindow { controls.append(>k::Label::new(Some("빠른 이미지 로딩"))); controls.append(&fast_loading_switch); - let list_box = gtk::ListBox::new(); - list_box.set_selection_mode(gtk::SelectionMode::Single); - list_box.set_activate_on_single_click(false); + let list_selection = gtk::SingleSelection::new(None::); + let list_view = + gtk::ListView::new(Some(list_selection.clone()), None::); + list_view.set_single_click_activate(false); let scrolled = gtk::ScrolledWindow::builder() .vexpand(true) - .child(&list_box) + .child(&list_view) .build(); let status_label = gtk::Label::builder().xalign(0.0).build(); @@ -135,16 +155,18 @@ impl ComicWindow { location_dropdown, edit_location_button, delete_location_button, + clear_recent_button: clear_recent_button.clone(), path_entry, search_entry, sort_dropdown, direction_button, - list_box, + list_view, + list_selection, status_label, state: RefCell::new(BrowserState { profile_index: 0, favorite_profile: None, - browsing_favorites: false, + mode: BrowserMode::Directory, root_uri: root_uri.clone(), current_uri: root_uri, entries: Vec::new(), @@ -160,6 +182,7 @@ impl ComicWindow { database: Rc::new(database), zip_cache, listing_task: RefCell::new(None), + update_in_progress: Rc::new(Cell::new(false)), }); controller.rebuild_profiles(); @@ -171,6 +194,7 @@ impl ComicWindow { case_insensitive_check, fast_loading_switch, ); + install_file_drop_target(&controller.window, controller.file_drop_control()); controller.refresh(); Ok(Self { controller }) } @@ -178,12 +202,18 @@ 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 { profile_index: usize, favorite_profile: Option, - browsing_favorites: bool, + mode: BrowserMode, root_uri: String, current_uri: String, entries: Vec, @@ -195,6 +225,13 @@ struct BrowserState { typeahead_last_input: Option, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BrowserMode { + Directory, + Favorites, + Recent, +} + struct BrowserController { window: gtk::ApplicationWindow, about_button: gtk::Button, @@ -202,11 +239,13 @@ struct BrowserController { location_dropdown: gtk::DropDown, edit_location_button: gtk::Button, delete_location_button: gtk::Button, + clear_recent_button: gtk::Button, path_entry: gtk::Entry, search_entry: gtk::SearchEntry, sort_dropdown: gtk::DropDown, direction_button: gtk::ToggleButton, - list_box: gtk::ListBox, + list_view: gtk::ListView, + list_selection: gtk::SingleSelection, status_label: gtk::Label, state: RefCell, config: RefCell, @@ -214,6 +253,7 @@ struct BrowserController { database: Rc, zip_cache: Rc, listing_task: RefCell>>, + update_in_progress: Rc>, } impl BrowserController { @@ -273,8 +313,10 @@ impl BrowserController { let Some(controller) = controller.upgrade() else { return; }; - if is_favorites_selection(item.position(), controller.profiles().len()) { - controller.show_favorites(); + match special_browser_mode(item.position(), controller.profiles().len()) { + Some(BrowserMode::Favorites) => controller.show_favorites(), + Some(BrowserMode::Recent) => controller.show_recent(), + _ => {} } }); label.add_controller(click); @@ -306,28 +348,73 @@ impl BrowserController { case_insensitive_check.connect_toggled(move |check| { controller.set_case_insensitive_sort(check); }); - let controller = Rc::clone(self); - self.list_box - .connect_row_activated(move |_, row| controller.activate_row(row.index())); - - let context_click = gtk::GestureClick::builder().button(3).build(); - let controller = Rc::clone(self); - context_click.connect_pressed(move |_, _, x, y| { - controller.show_context_menu(x, y); + let factory = gtk::SignalListItemFactory::new(); + let controller = Rc::downgrade(self); + factory.connect_setup(move |_, item| { + let Some(item) = item.downcast_ref::() else { + return; + }; + let content = entry_content(); + item.set_child(Some(&content)); + let context_click = gtk::GestureClick::builder().button(3).build(); + let item = item.downgrade(); + let controller = controller.clone(); + let menu_parent = content.clone(); + context_click.connect_pressed(move |_, _, _, _| { + let Some(item) = item.upgrade() else { + return; + }; + let Some(controller) = controller.upgrade() else { + return; + }; + controller.show_context_menu(item.position(), &menu_parent); + }); + content.add_controller(context_click); }); - self.list_box.add_controller(context_click); + let controller = Rc::downgrade(self); + factory.connect_bind(move |_, item| { + let Some(item) = item.downcast_ref::() else { + return; + }; + let Some(content) = item.child().and_downcast::() else { + return; + }; + let Some(controller) = controller.upgrade() else { + return; + }; + let state = controller.state.borrow(); + let Some(entry) = state.visible_entries.get(item.position() as usize) else { + return; + }; + bind_entry_content(&content, entry); + }); + self.list_view.set_factory(Some(&factory)); + let controller = Rc::clone(self); + self.list_view + .connect_activate(move |_, position| controller.activate_row(position)); 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 { controller.typeahead(key, modifiers) } }); - self.list_box.add_controller(key_controller); + self.list_view.add_controller(key_controller); + + let mouse_back = gtk::GestureClick::builder() + .button(MOUSE_BACK_BUTTON) + .propagation_phase(gtk::PropagationPhase::Capture) + .build(); + let controller = Rc::clone(self); + mouse_back.connect_pressed(move |gesture, _, _, _| { + gesture.set_state(gtk::EventSequenceState::Claimed); + controller.go_up(); + }); + self.window.add_controller(mouse_back); let controller = Rc::clone(self); fast_loading_switch.connect_active_notify(move |switch| { @@ -336,6 +423,9 @@ impl BrowserController { let controller = Rc::clone(self); self.clear_cache_button .connect_clicked(move |_| controller.show_clear_cache_dialog()); + let controller = Rc::clone(self); + self.clear_recent_button + .connect_clicked(move |_| controller.show_clear_recent_dialog()); } fn profiles(&self) -> Vec { @@ -361,6 +451,7 @@ impl BrowserController { .map(|profile| profile.name.clone()) .collect(); names.push("즐겨찾기".into()); + names.push("최근 열어본 파일".into()); let names: Vec<_> = names.iter().map(String::as_str).collect(); self.location_dropdown .set_model(Some(>k::StringList::new(&names))); @@ -369,9 +460,16 @@ impl BrowserController { fn select_profile(self: &Rc) { let profile_index = self.location_dropdown.selected() as usize; let profiles = self.profiles(); - if is_favorites_selection(self.location_dropdown.selected(), profiles.len()) { - self.show_favorites(); - return; + match special_browser_mode(self.location_dropdown.selected(), profiles.len()) { + Some(BrowserMode::Favorites) => { + self.show_favorites(); + return; + } + Some(BrowserMode::Recent) => { + self.show_recent(); + return; + } + _ => {} } let editable = profile_index > 0 && profile_index < profiles.len(); self.edit_location_button.set_sensitive(editable); @@ -385,10 +483,11 @@ impl BrowserController { let mut state = self.state.borrow_mut(); state.profile_index = profile_index; state.favorite_profile = None; - state.browsing_favorites = false; + state.mode = BrowserMode::Directory; state.root_uri = root_uri.clone(); state.current_uri = root_uri; drop(state); + self.update_mode_controls(BrowserMode::Directory); self.path_entry.set_editable(true); self.search_entry.set_text(""); self.refresh(); @@ -414,24 +513,58 @@ impl BrowserController { state.generation = state.generation.wrapping_add(1); state.typeahead_query.clear(); state.typeahead_last_input = None; - state.browsing_favorites = true; + state.mode = BrowserMode::Favorites; state.favorite_profile = None; state.entries = entries; drop(state); + self.update_mode_controls(BrowserMode::Favorites); self.search_entry.set_text(""); self.render(); } + fn show_recent(&self) { + self.cancel_listing(); + self.edit_location_button.set_sensitive(false); + self.delete_location_button.set_sensitive(false); + self.path_entry.set_text("최근 열어본 파일"); + self.path_entry.set_editable(false); + let entries = self + .config + .borrow() + .recent_files + .iter() + .map(recent_file_browser_entry) + .collect(); + let mut state = self.state.borrow_mut(); + state.generation = state.generation.wrapping_add(1); + state.typeahead_query.clear(); + state.typeahead_last_input = None; + state.mode = BrowserMode::Recent; + state.favorite_profile = None; + state.entries = entries; + drop(state); + self.update_mode_controls(BrowserMode::Recent); + self.search_entry.set_text(""); + self.render(); + } + + fn update_mode_controls(&self, mode: BrowserMode) { + let recent = mode == BrowserMode::Recent; + self.clear_recent_button.set_visible(recent); + self.sort_dropdown.set_sensitive(!recent); + self.direction_button.set_sensitive(!recent); + } + fn open_favorite(self: &Rc, favorite: FavoriteEntry) { let Ok(root) = root_file(&favorite.profile) else { self.status_label - .set_text("즐겨찾기의 저장된 위치가 올바르지 않습니다."); + .set_text("저장된 파일의 위치 정보가 올바르지 않습니다."); return; }; let favorite_file = gio::File::for_uri(&favorite.uri); if !is_within_root(&favorite_file, &root) { self.status_label - .set_text("즐겨찾기가 저장된 위치의 루트 밖을 가리킵니다."); + .set_text("저장된 파일이 위치의 루트 밖을 가리킵니다."); return; } if favorite.is_directory { @@ -441,17 +574,18 @@ impl BrowserController { self.delete_location_button.set_sensitive(false); let mut state = self.state.borrow_mut(); state.favorite_profile = Some(favorite.profile.clone()); - state.browsing_favorites = false; + state.mode = BrowserMode::Directory; state.root_uri = root.uri().into(); state.current_uri = favorite.uri; drop(state); + self.update_mode_controls(BrowserMode::Directory); self.search_entry.set_text(""); self.refresh(); return; } self.cancel_listing(); - self.status_label.set_text("즐겨찾기에 연결하는 중..."); + self.status_label.set_text("저장된 파일에 연결하는 중..."); let operation = mount_operation(&favorite.profile, &self.window); let controller = Rc::downgrade(self); let task = glib::MainContext::default().spawn_local(async move { @@ -484,7 +618,7 @@ impl BrowserController { if !kind.is_viewable() { controller .status_label - .set_text("이 즐겨찾기 파일 형식은 열 수 없습니다."); + .set_text("이 파일 형식은 열 수 없습니다."); return; } let entry = folder_entries @@ -494,6 +628,7 @@ impl BrowserController { .unwrap_or_else(|| BrowserEntry { uri: favorite.uri.clone(), name: favorite.name.clone(), + list_name: None, kind, size: None, modified: None, @@ -520,8 +655,7 @@ impl BrowserController { } fn open_entered_path(self: &Rc) { - let browsing_favorites = self.state.borrow().browsing_favorites; - if browsing_favorites { + if self.state.borrow().mode != BrowserMode::Directory { return; } let profile = self.current_profile(); @@ -538,8 +672,7 @@ impl BrowserController { } fn go_up(self: &Rc) { - let browsing_favorites = self.state.borrow().browsing_favorites; - if browsing_favorites { + if self.state.borrow().mode != BrowserMode::Directory { return; } let state = self.state.borrow(); @@ -553,10 +686,17 @@ impl BrowserController { } fn refresh(self: &Rc) { - let browsing_favorites = self.state.borrow().browsing_favorites; - if browsing_favorites { - self.show_favorites(); - return; + let mode = self.state.borrow().mode; + match mode { + BrowserMode::Favorites => { + self.show_favorites(); + return; + } + BrowserMode::Recent => { + self.show_recent(); + return; + } + BrowserMode::Directory => {} } self.cancel_listing(); let (profile, uri, generation) = { @@ -564,6 +704,8 @@ impl BrowserController { state.generation = state.generation.wrapping_add(1); state.typeahead_query.clear(); state.typeahead_last_input = None; + state.entries.clear(); + state.visible_entries.clear(); ( state .favorite_profile @@ -573,6 +715,7 @@ impl BrowserController { state.generation, ) }; + self.list_selection.set_model(None::<&gio::ListModel>); self.path_entry.set_text(&display_uri(&uri)); self.status_label .set_text("폴더를 불러오는 중... (0개의 파일/폴더를 읽음)"); @@ -584,7 +727,8 @@ impl BrowserController { let Some(controller) = progress_controller.upgrade() else { return; }; - if controller.state.borrow().generation == generation { + let state = controller.state.borrow(); + if state.generation == generation && state.mode == BrowserMode::Directory { controller.status_label.set_text(&format!( "폴더를 불러오는 중... ({count}개의 파일/폴더를 읽음)" )); @@ -595,7 +739,7 @@ impl BrowserController { return; }; let state = controller.state.borrow(); - let stale = state.generation != generation || state.browsing_favorites; + let stale = state.generation != generation || state.mode != BrowserMode::Directory; drop(state); if stale { return; @@ -618,29 +762,32 @@ impl BrowserController { } fn render(&self) { - while let Some(child) = self.list_box.first_child() { - self.list_box.remove(&child); - } 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 .iter() - .filter(|entry| entry.name.to_lowercase().contains(query.as_str())) + .filter(|entry| browser_search_match(entry, query.as_str())) .cloned() .collect(); - sort_entries( - &mut visible_entries, - state.sort_field, - state.sort_direction, - case_insensitive, - ); - for entry in &visible_entries { - self.list_box.append(&entry_row(entry)); + if state.mode != BrowserMode::Recent { + sort_entries( + &mut visible_entries, + state.sort_field, + state.sort_direction, + case_insensitive, + ); } let count = visible_entries.len(); + let names = visible_entries + .iter() + .map(BrowserEntry::display_name) + .collect::>(); + let model = gtk::StringList::new(&names); state.visible_entries = visible_entries; + drop(state); + self.list_selection.set_model(Some(&model)); self.status_label.set_text(&format!("{count}개 항목")); } @@ -655,14 +802,26 @@ 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; }; - let selected = self.list_box.selected_row().map(|row| row.index() as usize); + let selected = (self.list_selection.selected() != gtk::INVALID_LIST_POSITION) + .then(|| self.list_selection.selected() as usize); let now = Instant::now(); let mut state = self.state.borrow_mut(); if state @@ -685,14 +844,15 @@ 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 - && let Some(row) = self.list_box.row_at_index(index as i32) - { - self.list_box.select_row(Some(&row)); - let _ = row.grab_focus(); + if let Some(index) = found { + self.list_view.scroll_to( + index as u32, + gtk::ListScrollFlags::FOCUS | gtk::ListScrollFlags::SELECT, + None, + ); self.status_label.set_text(&format!( "'{query}'로 이동: {}", found_name.unwrap_or_default() @@ -704,6 +864,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, @@ -725,7 +893,7 @@ impl BrowserController { self.render(); } - fn activate_row(self: &Rc, index: i32) { + fn activate_row(self: &Rc, index: u32) { let Some(entry) = self .state .borrow() @@ -735,19 +903,40 @@ impl BrowserController { else { return; }; - let browsing_favorites = self.state.borrow().browsing_favorites; - if browsing_favorites { - let favorite = self - .config - .borrow() - .favorites - .iter() - .find(|favorite| favorite.uri == entry.uri) - .cloned(); - if let Some(favorite) = favorite { - self.open_favorite(favorite); + let mode = self.state.borrow().mode; + match mode { + BrowserMode::Favorites => { + let favorite = self + .config + .borrow() + .favorites + .iter() + .find(|favorite| favorite.uri == entry.uri) + .cloned(); + if let Some(favorite) = favorite { + self.open_favorite(favorite); + } + return; } - return; + BrowserMode::Recent => { + let recent = self + .config + .borrow() + .recent_files + .iter() + .find(|recent| recent.uri == entry.uri) + .cloned(); + if let Some(recent) = recent { + self.open_favorite(FavoriteEntry { + name: recent.name, + uri: recent.uri, + is_directory: false, + profile: recent.profile, + }); + } + return; + } + BrowserMode::Directory => {} } match entry.kind { EntryKind::Directory => { @@ -799,21 +988,9 @@ impl BrowserController { siblings: Rc>, profile: LocationProfile, ) -> SiblingNavigator { + let recursive = siblings.iter().any(|entry| entry.list_name.is_some()); let current_uri = entry.uri.clone(); let current_kind = entry.kind; - let position_controller = Rc::downgrade(self); - let position_uri = current_uri.clone(); - let position_fallback = Rc::clone(&siblings); - let position = Rc::new(move || { - let controller = position_controller.upgrade()?; - let siblings = - controller.navigation_siblings(&position_uri, current_kind, &position_fallback); - siblings - .iter() - .position(|entry| entry.uri == position_uri) - .map(|current| (current, siblings.len())) - }); - let controller = Rc::downgrade(self); let navigate_siblings = Rc::clone(&siblings); let navigate_current_uri = current_uri.clone(); @@ -827,6 +1004,7 @@ impl BrowserController { &navigate_current_uri, current_kind, &navigate_siblings, + recursive, ); let Some(current) = siblings .iter() @@ -854,11 +1032,11 @@ impl BrowserController { return Vec::new(); }; controller - .navigation_siblings(&files_current_uri, current_kind, &files_fallback) + .navigation_siblings(&files_current_uri, current_kind, &files_fallback, recursive) .iter() .map(|entry| SiblingFile { uri: entry.uri.clone(), - name: entry.name.clone(), + name: entry.display_name().to_owned(), kind: entry.kind, }) .collect() @@ -873,6 +1051,7 @@ impl BrowserController { &actions_current_uri, current_kind, &actions_fallback, + recursive, ); let entry = entries.iter().find(|entry| entry.uri == uri)?; Some(SiblingFileActions { @@ -880,7 +1059,7 @@ impl BrowserController { download: controller.download_control(entry), }) }); - SiblingNavigator::new(position, navigate, files, actions) + SiblingNavigator::new(navigate, files, actions, recursive) } fn navigation_siblings( @@ -888,7 +1067,11 @@ impl BrowserController { current_uri: &str, current_kind: EntryKind, fallback: &Rc>, + fixed: bool, ) -> Rc> { + if fixed { + return Rc::clone(fallback); + } let case_insensitive = self.config.borrow().case_insensitive_sort; let state = self.state.borrow(); let entries = sorted_navigable_entries( @@ -898,9 +1081,9 @@ impl BrowserController { state.sort_direction, case_insensitive, ); - let browsing_favorites = state.browsing_favorites; + let mode = state.mode; drop(state); - if !browsing_favorites && entries.iter().any(|entry| entry.uri == current_uri) { + if mode == BrowserMode::Directory && entries.iter().any(|entry| entry.uri == current_uri) { Rc::new(entries) } else { Rc::clone(fallback) @@ -914,6 +1097,8 @@ impl BrowserController { profile: LocationProfile, reuse_window: Option, ) { + let recent_entry = entry.clone(); + let recent_profile = profile.clone(); self.status_label.set_text("ZIP 파일 다운로드 준비 중..."); let progress_label = reuse_window.as_ref().map_or_else( || self.status_label.clone(), @@ -940,11 +1125,13 @@ impl BrowserController { } match result { Ok(source) => { + controller.record_recent_file(&recent_entry, &recent_profile); controller.status_label.set_text("다운로드 완료"); result_label.set_text("ZIP 파일을 여는 중..."); let Some(application) = controller.window.application() else { return; }; + let direction_control = controller.two_page_direction_control(); ViewerWindow::open( &application, source, @@ -956,8 +1143,10 @@ impl BrowserController { sibling_navigator: Some(navigator), favorite_control, download_control, + file_drop_control: controller.file_drop_control(), reuse_window, view_mode_control: None, + two_page_direction_control: Some(direction_control), }, ); } @@ -978,6 +1167,8 @@ impl BrowserController { profile: LocationProfile, reuse_window: Option, ) { + let recent_entry = entry.clone(); + let recent_profile = profile.clone(); let kind = entry.kind; self.status_label .set_text("미디어 파일 다운로드 준비 중..."); @@ -1006,6 +1197,7 @@ impl BrowserController { } match result { Ok(source) => { + controller.record_recent_file(&recent_entry, &recent_profile); controller.status_label.set_text("다운로드 완료"); result_label.set_text("미디어 파일을 여는 중..."); let Some(application) = controller.window.application() else { @@ -1019,8 +1211,10 @@ impl BrowserController { sibling_navigator: Some(navigator), favorite_control, download_control, + file_drop_control: controller.file_drop_control(), reuse_window, view_mode_control, + two_page_direction_control: None, }, ); } @@ -1034,27 +1228,16 @@ impl BrowserController { ); } - fn show_context_menu(self: &Rc, x: f64, y: f64) { - let Some(widget) = self.list_box.pick(x, y, gtk::PickFlags::DEFAULT) else { - return; - }; - let Some(row) = widget - .clone() - .downcast::() - .ok() - .or_else(|| { - widget - .ancestor(gtk::ListBoxRow::static_type()) - .and_then(|widget| widget.downcast::().ok()) - }) - else { - return; - }; + fn show_context_menu( + self: &Rc, + position: u32, + parent: &impl glib::object::IsA, + ) { let Some(entry) = self .state .borrow() .visible_entries - .get(row.index() as usize) + .get(position as usize) .cloned() else { return; @@ -1064,14 +1247,25 @@ impl BrowserController { if !can_favorite && !can_download { return; } - self.list_box.select_row(Some(&row)); + self.list_selection.set_selected(position); let popover = gtk::Popover::new(); - popover.set_parent(&row); + popover.set_parent(parent); let actions = gtk::Box::new(gtk::Orientation::Vertical, 4); actions.set_margin_top(6); 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 { @@ -1085,7 +1279,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); }); } @@ -1115,6 +1309,111 @@ impl BrowserController { .any(|favorite| favorite.uri == uri) } + fn profile_for_entry(&self, entry: &BrowserEntry) -> LocationProfile { + match self.state.borrow().mode { + BrowserMode::Favorites => { + if let Some(profile) = self + .config + .borrow() + .favorites + .iter() + .find(|favorite| favorite.uri == entry.uri) + .map(|favorite| favorite.profile.clone()) + { + return profile; + } + } + BrowserMode::Recent => { + if let Some(profile) = self + .config + .borrow() + .recent_files + .iter() + .find(|recent| recent.uri == entry.uri) + .map(|recent| recent.profile.clone()) + { + return profile; + } + } + BrowserMode::Directory => {} + } + self.current_profile() + } + + fn open_folder_recursive(self: &Rc, entry: BrowserEntry) { + 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, @@ -1147,6 +1446,141 @@ impl BrowserController { } } + fn file_drop_control(self: &Rc) -> FileDropControl { + let controller = Rc::downgrade(self); + FileDropControl { + handle: Rc::new(move |files, parent| { + if let Some(controller) = controller.upgrade() { + controller.open_dropped_files(files, parent); + } + }), + } + } + + fn open_dropped_files(self: &Rc, files: Vec, parent: gtk::Window) { + let [file] = files.as_slice() else { + show_drop_error(&parent, "한 번에 하나의 파일 또는 폴더만 열 수 있습니다."); + return; + }; + if !file.is_native() { + show_drop_error(&parent, "로컬 파일 또는 폴더만 드래그해서 열 수 있습니다."); + return; + } + let file = file.clone(); + self.cancel_listing(); + let generation = { + let mut state = self.state.borrow_mut(); + state.generation = state.generation.wrapping_add(1); + state.generation + }; + self.status_label.set_text("열 항목을 확인하는 중..."); + let controller = Rc::downgrade(self); + let task = glib::MainContext::default().spawn_local(async move { + let result: Result<_> = async { + let info = file + .query_info_future( + "standard::type,standard::display-name", + gio::FileQueryInfoFlags::NONE, + glib::Priority::DEFAULT, + ) + .await + .context("열 항목을 확인할 수 없습니다")?; + let selected = match info.file_type() { + gio::FileType::Directory => None, + gio::FileType::Regular => { + if !classify_file(Path::new(info.display_name().as_str())).is_viewable() { + bail!("지원하지 않는 파일 형식입니다: {}", info.display_name()); + } + Some(file.clone()) + } + _ => bail!("일반 파일 또는 폴더만 열 수 있습니다"), + }; + let directory = selected + .as_ref() + .and_then(gio::File::parent) + .unwrap_or_else(|| file.clone()); + let profile = local_profile_for_directory(&directory)?; + let operation = mount_operation(&profile, &parent); + let entries = + enumerate_directory(&profile, directory.uri().as_str(), &operation, |_| {}) + .await?; + Ok((directory, profile, entries, selected)) + } + .await; + + let Some(controller) = controller.upgrade() else { + return; + }; + if controller.state.borrow().generation != generation || !parent.is_visible() { + return; + } + let (directory, profile, entries, selected) = match result { + Ok(result) => result, + Err(error) => { + let message = format!("항목을 열 수 없습니다: {error:#}"); + controller.status_label.set_text(&message); + show_drop_error(&parent, &message); + return; + } + }; + controller.show_dropped_directory(&directory, profile.clone(), entries.clone()); + let Some(selected) = selected else { + return; + }; + let Some(entry) = entries + .iter() + .find(|entry| gio::File::for_uri(&entry.uri).equal(&selected)) + .cloned() + else { + show_drop_error(&parent, "파일을 부모 폴더에서 찾을 수 없습니다."); + return; + }; + let state = controller.state.borrow(); + let Some((siblings, _selected_index)) = sorted_navigable_selection( + &entries, + &entry.uri, + state.sort_field, + state.sort_direction, + controller.config.borrow().case_insensitive_sort, + ) else { + drop(state); + show_drop_error(&parent, "파일의 목록 위치를 확인할 수 없습니다."); + return; + }; + drop(state); + controller.open_viewable(entry, Rc::new(siblings), profile, None); + }); + self.listing_task.replace(Some(task)); + } + + fn show_dropped_directory( + &self, + directory: &gio::File, + profile: LocationProfile, + entries: Vec, + ) { + self.location_dropdown + .set_selected(gtk::INVALID_LIST_POSITION); + self.edit_location_button.set_sensitive(false); + self.delete_location_button.set_sensitive(false); + self.path_entry.set_editable(true); + let uri: String = directory.uri().into(); + let mut state = self.state.borrow_mut(); + state.favorite_profile = Some(profile); + state.mode = BrowserMode::Directory; + state.root_uri = uri.clone(); + state.current_uri = uri.clone(); + state.entries = entries; + state.typeahead_query.clear(); + state.typeahead_last_input = None; + drop(state); + self.update_mode_controls(BrowserMode::Directory); + self.path_entry.set_text(&display_uri(&uri)); + self.search_entry.set_text(""); + self.render(); + self.window.present(); + } + fn view_mode_control(self: &Rc) -> ViewModeControl { let selected = self.config.borrow().viewer_mode.dropdown_index(); let controller = Rc::downgrade(self); @@ -1173,6 +1607,33 @@ impl BrowserController { } } + fn two_page_direction_control(self: &Rc) -> TwoPageDirectionControl { + let selected = u32::from(self.config.borrow().two_page_right_to_left); + let controller = Rc::downgrade(self); + TwoPageDirectionControl { + selected, + change: Rc::new(move |index| { + let Some(controller) = controller.upgrade() else { + return false; + }; + let right_to_left = index == 1; + if controller.config.borrow().two_page_right_to_left == right_to_left { + return true; + } + let mut updated = controller.config.borrow().clone(); + updated.two_page_right_to_left = right_to_left; + if let Err(error) = updated.save(&controller.config_path) { + controller + .status_label + .set_text(&format!("2페이지 방향을 저장할 수 없습니다: {error:#}")); + return false; + } + *controller.config.borrow_mut() = updated; + true + }), + } + } + fn toggle_favorite(&self, entry: &BrowserEntry, profile: &LocationProfile) -> bool { let mut updated = self.config.borrow().clone(); let was_active = self.is_favorite(&entry.uri); @@ -1183,8 +1644,7 @@ impl BrowserController { return was_active; } *self.config.borrow_mut() = updated; - let browsing_favorites = self.state.borrow().browsing_favorites; - if browsing_favorites { + if self.state.borrow().mode == BrowserMode::Favorites { self.show_favorites(); } self.status_label.set_text(if active { @@ -1195,6 +1655,28 @@ impl BrowserController { active } + fn record_recent_file(&self, entry: &BrowserEntry, profile: &LocationProfile) { + let mut updated = self.config.borrow().clone(); + record_recent_file(&mut updated, entry, profile); + if let Err(error) = updated.save(&self.config_path) { + self.status_label + .set_text(&format!("최근 파일 기록을 저장할 수 없습니다: {error:#}")); + return; + } + *self.config.borrow_mut() = updated; + if self.state.borrow().mode == BrowserMode::Recent { + let entries = self + .config + .borrow() + .recent_files + .iter() + .map(recent_file_browser_entry) + .collect(); + self.state.borrow_mut().entries = entries; + self.render(); + } + } + fn choose_download_destination( self: &Rc, entry: BrowserEntry, @@ -1337,18 +1819,72 @@ impl BrowserController { "사용한 라이브러리\n\ GTK4 / GIO · GStreamer · image · zip · rusqlite / SQLite\n\ serde · toml · anyhow · chrono · filetime · percent-encoding\n\ - sha2 · tempfile", + sha2 · tempfile · flate2 · tar", )); libraries.set_xalign(0.0); libraries.set_wrap(true); let close_button = gtk::Button::with_label("닫기"); - close_button.set_halign(gtk::Align::End); + let update_button = gtk::Button::with_label("업데이트"); + let update_status = gtk::Label::new(None); + update_status.set_wrap(true); + update_status.set_xalign(0.0); + let actions = gtk::Box::new(gtk::Orientation::Horizontal, 8); + actions.set_halign(gtk::Align::End); + actions.append(&update_button); + actions.append(&close_button); + if self.update_in_progress.get() { + update_button.set_sensitive(false); + update_status.set_text("다른 업데이트 작업이 진행 중입니다."); + } let dialog_to_close = dialog.clone(); close_button.connect_clicked(move |_| dialog_to_close.close()); + let status = update_status.clone(); + let update_in_progress = Rc::clone(&self.update_in_progress); + update_button.connect_clicked(move |button| { + if update_in_progress.replace(true) { + return; + } + button.set_sensitive(false); + status.set_text("업데이트를 다운로드하고 검증하는 중..."); + let (sender, receiver) = mpsc::channel(); + thread::spawn(move || { + let result = install_latest_update().map_err(|error| format!("{error:#}")); + let _ = sender.send(result); + }); + let button = button.clone(); + let status = status.clone(); + let update_in_progress = Rc::clone(&update_in_progress); + glib::timeout_add_local(Duration::from_millis(100), move || { + match receiver.try_recv() { + Ok(Ok(())) => { + update_in_progress.set(false); + status.set_text( + "업데이트를 완료했습니다. 앱을 종료한 뒤 ~/.local/bin/comicviewer로 다시 실행해 주세요.", + ); + button.set_label("업데이트 완료"); + glib::ControlFlow::Break + } + Ok(Err(error)) => { + update_in_progress.set(false); + status.set_text(&format!("업데이트 실패: {error}")); + button.set_sensitive(true); + glib::ControlFlow::Break + } + Err(mpsc::TryRecvError::Empty) => glib::ControlFlow::Continue, + Err(mpsc::TryRecvError::Disconnected) => { + update_in_progress.set(false); + status.set_text("업데이트 작업이 예기치 않게 종료되었습니다."); + button.set_sensitive(true); + glib::ControlFlow::Break + } + } + }); + }); content.append(&name); content.append(&contact); content.append(&libraries); - content.append(&close_button); + content.append(&update_status); + content.append(&actions); dialog.set_child(Some(&content)); dialog.present(); } @@ -1577,6 +2113,202 @@ impl BrowserController { }); dialog.present(); } + + fn show_clear_recent_dialog(self: &Rc) { + let dialog = gtk::Window::builder() + .title("최근 기록 비우기") + .transient_for(&self.window) + .modal(true) + .resizable(false) + .default_width(420) + .build(); + let content = gtk::Box::new(gtk::Orientation::Vertical, 16); + content.set_margin_top(18); + content.set_margin_bottom(12); + content.set_margin_start(18); + content.set_margin_end(18); + let message = gtk::Label::new(Some( + "최근 열어본 파일 기록을 모두 삭제하시겠습니까?\n즐겨찾기와 ZIP 읽기 진행도는 유지됩니다.", + )); + message.set_wrap(true); + message.set_xalign(0.0); + let actions = gtk::Box::new(gtk::Orientation::Horizontal, 6); + actions.set_halign(gtk::Align::End); + let cancel_button = gtk::Button::with_label("취소"); + let clear_button = gtk::Button::with_label("모두 삭제"); + clear_button.add_css_class("destructive-action"); + actions.append(&cancel_button); + actions.append(&clear_button); + content.append(&message); + content.append(&actions); + dialog.set_child(Some(&content)); + + let dialog_to_close = dialog.clone(); + cancel_button.connect_clicked(move |_| dialog_to_close.close()); + let controller = Rc::clone(self); + let dialog_to_close = dialog.clone(); + clear_button.connect_clicked(move |_| { + let mut updated = controller.config.borrow().clone(); + updated.recent_files.clear(); + if let Err(error) = updated.save(&controller.config_path) { + controller + .status_label + .set_text(&format!("최근 기록을 삭제할 수 없습니다: {error:#}")); + return; + } + *controller.config.borrow_mut() = updated; + controller.show_recent(); + controller + .status_label + .set_text("최근 기록을 삭제했습니다."); + dialog_to_close.close(); + }); + dialog.present(); + } +} + +fn install_latest_update() -> Result<()> { + let directory = tempfile::tempdir().context("업데이트 임시 폴더를 만들 수 없습니다")?; + let archive = directory.path().join("Comicviewer-latest-x86_64.tar.gz"); + let checksum = directory + .path() + .join("Comicviewer-latest-x86_64.tar.gz.sha256"); + download_update_file(UPDATE_BUNDLE_URL, &archive)?; + download_update_file(UPDATE_CHECKSUM_URL, &checksum)?; + + let checksum_text = + fs::read_to_string(&checksum).context("업데이트 체크섬을 읽을 수 없습니다")?; + let expected = parse_update_checksum(&checksum_text)?; + let actual = sha256_file(&archive)?; + if actual != expected { + bail!("다운로드한 업데이트 체크섬이 일치하지 않습니다"); + } + + let extraction = directory.path().join("extracted"); + fs::create_dir(&extraction).context("업데이트 압축 해제 폴더를 만들 수 없습니다")?; + extract_update_archive(&archive, &extraction)?; + let installer = extraction + .join("Comicviewer-latest-x86_64") + .join("install-or-update.sh"); + if !installer.is_file() { + bail!("업데이트 번들에 설치 스크립트가 없습니다"); + } + run_update_command( + Command::new("sh") + .arg(&installer) + .env("COMICVIEWER_SKIP_DEPENDENCIES", "1"), + "업데이트 설치에 실패했습니다", + ) +} + +fn download_update_file(url: &str, destination: &Path) -> Result<()> { + let url = format!("{url}?from={}", env!("CARGO_PKG_VERSION")); + run_update_command( + Command::new("curl") + .arg("--fail") + .arg("--silent") + .arg("--show-error") + .arg("--location") + .arg("--proto") + .arg("=https") + .arg("--proto-redir") + .arg("=https") + .arg("--connect-timeout") + .arg("15") + .arg("--max-time") + .arg("300") + .arg("--max-filesize") + .arg((512_u64 * 1024 * 1024).to_string()) + .arg("--retry") + .arg("3") + .arg("--output") + .arg(destination) + .arg(url), + "업데이트를 다운로드할 수 없습니다. curl 설치와 네트워크 연결을 확인해 주세요", + ) +} + +fn run_update_command(command: &mut Command, context: &str) -> Result<()> { + let output = command.output().with_context(|| context.to_owned())?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr) + .trim() + .chars() + .take(600) + .collect::(); + if stderr.is_empty() { + bail!("{context}"); + } + bail!("{context}: {stderr}") +} + +fn extract_update_archive(archive_path: &Path, destination: &Path) -> Result<()> { + const MAX_ENTRIES: usize = 32; + const MAX_EXTRACTED_BYTES: u64 = 512 * 1024 * 1024; + + let file = fs::File::open(archive_path).context("업데이트 압축 파일을 열 수 없습니다")?; + let decoder = GzDecoder::new(file); + let mut archive = Archive::new(decoder); + let mut count = 0_usize; + let mut extracted_bytes = 0_u64; + for entry in archive + .entries() + .context("업데이트 압축 목록을 읽을 수 없습니다")? + { + let mut entry = entry.context("업데이트 압축 항목을 읽을 수 없습니다")?; + count += 1; + if count > MAX_ENTRIES { + bail!("업데이트 압축 항목 수가 안전 제한을 초과합니다"); + } + let entry_type = entry.header().entry_type(); + if !entry_type.is_file() && !entry_type.is_dir() { + bail!("업데이트 압축에 허용되지 않은 파일 종류가 있습니다"); + } + let path = entry + .path() + .context("업데이트 압축 경로가 올바르지 않습니다")?; + if !path.starts_with("Comicviewer-latest-x86_64") { + bail!("업데이트 압축 경로가 올바르지 않습니다"); + } + extracted_bytes = extracted_bytes.saturating_add(entry.header().size().unwrap_or(u64::MAX)); + if extracted_bytes > MAX_EXTRACTED_BYTES { + bail!("업데이트 압축 크기가 안전 제한을 초과합니다"); + } + if !entry + .unpack_in(destination) + .context("업데이트 압축을 풀 수 없습니다")? + { + bail!("업데이트 압축 경로가 임시 폴더를 벗어납니다"); + } + } + Ok(()) +} + +fn parse_update_checksum(contents: &str) -> Result { + let checksum = contents + .split_whitespace() + .next() + .filter(|checksum| { + checksum.len() == 64 && checksum.chars().all(|value| value.is_ascii_hexdigit()) + }) + .context("업데이트 체크섬 파일이 올바르지 않습니다")?; + Ok(checksum.to_ascii_lowercase()) +} + +fn sha256_file(path: &Path) -> Result { + let mut file = fs::File::open(path).context("다운로드한 업데이트를 읽을 수 없습니다")?; + let mut digest = Sha256::new(); + let mut buffer = [0_u8; 64 * 1024]; + loop { + let count = file.read(&mut buffer)?; + if count == 0 { + break; + } + digest.update(&buffer[..count]); + } + Ok(format!("{:x}", digest.finalize())) } fn location_kind_index(kind: LocationKind) -> u32 { @@ -1599,6 +2331,37 @@ fn home_profile() -> LocationProfile { } } +fn local_profile_for_directory(directory: &gio::File) -> Result { + let path = directory + .path() + .context("로컬 폴더 경로를 확인할 수 없습니다")?; + let address = path + .to_str() + .context("UTF-8로 표현할 수 없는 로컬 경로는 열 수 없습니다")?; + let name = path + .file_name() + .and_then(|name| name.to_str()) + .filter(|name| !name.is_empty()) + .unwrap_or(address) + .to_owned(); + Ok(LocationProfile { + name, + kind: LocationKind::Local, + address: address.to_owned(), + username: String::new(), + password: String::new(), + domain: String::new(), + }) +} + +fn show_drop_error(parent: >k::Window, message: &str) { + gtk::AlertDialog::builder() + .modal(true) + .message(message) + .build() + .show(Some(parent)); +} + fn display_uri(uri: &str) -> String { let file = gio::File::for_uri(uri); file.path().map_or_else( @@ -1607,37 +2370,53 @@ fn display_uri(uri: &str) -> String { ) } -fn entry_row(entry: &BrowserEntry) -> gtk::ListBoxRow { - let row = gtk::ListBoxRow::new(); +fn entry_content() -> gtk::Box { let content = gtk::Box::new(gtk::Orientation::Horizontal, 12); content.set_margin_top(8); content.set_margin_bottom(8); content.set_margin_start(10); content.set_margin_end(10); - let icon = match entry.kind { + content.append(>k::Image::new()); + content.append( + >k::Label::builder() + .hexpand(true) + .xalign(0.0) + .ellipsize(gtk::pango::EllipsizeMode::Middle) + .build(), + ); + for _ in 0..2 { + let label = gtk::Label::new(None); + label.set_width_chars(17); + label.set_xalign(1.0); + content.append(&label); + } + content +} + +fn bind_entry_content(content: >k::Box, entry: &BrowserEntry) { + let icon_name = match entry.kind { EntryKind::Directory => "folder-symbolic", EntryKind::ZipArchive => "package-x-generic-symbolic", EntryKind::Image => "image-x-generic-symbolic", EntryKind::Video => "video-x-generic-symbolic", EntryKind::OtherFile => "text-x-generic-symbolic", }; - content.append(>k::Image::from_icon_name(icon)); - content.append( - >k::Label::builder() - .label(&entry.name) - .hexpand(true) - .xalign(0.0) - .ellipsize(gtk::pango::EllipsizeMode::Middle) - .build(), - ); - for time in [entry.modified, entry.created] { - let label = gtk::Label::new(Some(&format_time(time))); - label.set_width_chars(17); - label.set_xalign(1.0); - content.append(&label); - } - row.set_child(Some(&content)); - row + let Some(icon) = content.first_child().and_downcast::() else { + return; + }; + icon.set_icon_name(Some(icon_name)); + let Some(name) = icon.next_sibling().and_downcast::() else { + return; + }; + name.set_text(entry.display_name()); + let Some(modified) = name.next_sibling().and_downcast::() else { + return; + }; + modified.set_text(&format_time(entry.modified)); + let Some(created) = modified.next_sibling().and_downcast::() else { + return; + }; + created.set_text(&format_time(entry.created)); } fn format_time(time: Option) -> String { @@ -1655,15 +2434,31 @@ 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 { current.is_viewable() && candidate.is_viewable() } -fn is_favorites_selection(selected: u32, profile_count: usize) -> bool { - selected != gtk::INVALID_LIST_POSITION && selected as usize == profile_count +fn browser_search_match(entry: &BrowserEntry, lowercase_query: &str) -> bool { + lowercase_query.is_empty() || entry.name.to_lowercase().contains(lowercase_query) +} + +fn special_browser_mode(selected: u32, profile_count: usize) -> Option { + if selected == gtk::INVALID_LIST_POSITION { + return None; + } + match selected as usize { + index if index == profile_count => Some(BrowserMode::Favorites), + index if index == profile_count + 1 => Some(BrowserMode::Recent), + _ => None, + } } fn sorted_navigable_entries( @@ -1682,10 +2477,29 @@ fn sorted_navigable_entries( siblings } +fn sorted_navigable_selection( + entries: &[BrowserEntry], + selected_uri: &str, + sort_field: SortField, + sort_direction: SortDirection, + case_insensitive: bool, +) -> Option<(Vec, usize)> { + let entries = sorted_navigable_entries( + entries, + EntryKind::Image, + sort_field, + sort_direction, + case_insensitive, + ); + let selected = entries.iter().position(|entry| entry.uri == selected_uri)?; + Some((entries, selected)) +} + 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 { @@ -1698,11 +2512,38 @@ fn favorite_browser_entry(favorite: &FavoriteEntry) -> BrowserEntry { } } +fn recent_file_browser_entry(recent: &RecentFileEntry) -> BrowserEntry { + BrowserEntry { + uri: recent.uri.clone(), + name: recent.name.clone(), + list_name: None, + kind: classify_file(Path::new(&recent.name)), + size: None, + modified: None, + created: None, + etag: None, + } +} + +fn record_recent_file(config: &mut AppConfig, entry: &BrowserEntry, profile: &LocationProfile) { + config.recent_files.retain(|recent| recent.uri != entry.uri); + config.recent_files.insert( + 0, + RecentFileEntry { + name: entry.name.clone(), + uri: entry.uri.clone(), + profile: profile.clone(), + }, + ); + config.recent_files.truncate(RECENT_FILE_LIMIT); +} + fn show_viewer_loading( window: >k::ApplicationWindow, 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)))); @@ -1767,6 +2608,7 @@ mod tests { BrowserEntry { uri: format!("file:///{name}"), name: name.into(), + list_name: None, kind: EntryKind::Directory, size: None, modified: None, @@ -1835,6 +2677,139 @@ mod tests { ); } + #[test] + fn dropped_file_selection_uses_sorted_parent_index() { + let entries = [ + media_entry("page10.jpg"), + entry("folder"), + media_entry("page2.jpg"), + ]; + let selected_uri = entries[0].uri.clone(); + + let (siblings, selected) = sorted_navigable_selection( + &entries, + &selected_uri, + SortField::Name, + SortDirection::Ascending, + true, + ) + .unwrap(); + + assert_eq!(siblings.len(), 2); + assert_eq!(siblings[0].name, "page2.jpg"); + assert_eq!(siblings[selected].name, "page10.jpg"); + } + + #[test] + fn mouse_back_button_matches_standard_x11_button() { + assert_eq!(MOUSE_BACK_BUTTON, 8); + } + + #[test] + fn dropped_directory_creates_local_root_profile() { + let directory = tempfile::tempdir().unwrap(); + let file = gio::File::for_path(directory.path()); + + let profile = local_profile_for_directory(&file).unwrap(); + + assert_eq!(profile.kind, LocationKind::Local); + assert_eq!(Path::new(&profile.address), directory.path()); + assert!(profile.username.is_empty()); + assert!(profile.password.is_empty()); + } + + #[test] + fn browser_search_filters_all_current_directory_entry_kinds() { + let folder = entry("Comics"); + let image = media_entry("cover.jpg"); + + assert!(browser_search_match(&folder, "comic")); + assert!(browser_search_match(&image, "cover")); + assert!(!browser_search_match(&image, "comic")); + assert!(browser_search_match(&image, "")); + let mut nested = media_entry("cover.jpg"); + nested.list_name = Some("Comics/cover.jpg".into()); + assert!(!browser_search_match(&nested, "comic")); + } + + #[test] + fn update_checksum_parser_validates_sha256_text() { + let checksum = + "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789 bundle.tar.gz\n"; + assert_eq!( + parse_update_checksum(checksum).unwrap(), + "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789" + ); + assert!(parse_update_checksum("not-a-checksum").is_err()); + } + + #[test] + fn update_sha256_matches_known_content() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("content"); + fs::write(&file, b"abc").unwrap(); + assert_eq!( + sha256_file(&file).unwrap(), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn update_archive_extracts_regular_files_and_rejects_symlinks() { + let directory = tempfile::tempdir().unwrap(); + let valid_archive = directory.path().join("valid.tar.gz"); + { + let file = fs::File::create(&valid_archive).unwrap(); + let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default()); + let mut archive = tar::Builder::new(encoder); + let content = b"#!/bin/sh\n"; + let mut header = tar::Header::new_gnu(); + header.set_size(content.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + archive + .append_data( + &mut header, + "Comicviewer-latest-x86_64/install-or-update.sh", + &content[..], + ) + .unwrap(); + archive.into_inner().unwrap().finish().unwrap(); + } + let extracted = directory.path().join("valid"); + fs::create_dir(&extracted).unwrap(); + extract_update_archive(&valid_archive, &extracted).unwrap(); + assert!( + extracted + .join("Comicviewer-latest-x86_64/install-or-update.sh") + .is_file() + ); + + let link_archive = directory.path().join("link.tar.gz"); + { + let file = fs::File::create(&link_archive).unwrap(); + let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default()); + let mut archive = tar::Builder::new(encoder); + let mut header = tar::Header::new_gnu(); + header.set_entry_type(tar::EntryType::Symlink); + header.set_size(0); + header.set_mode(0o777); + header.set_link_name("../../escape").unwrap(); + header.set_cksum(); + archive + .append_data( + &mut header, + "Comicviewer-latest-x86_64/link", + std::io::empty(), + ) + .unwrap(); + archive.into_inner().unwrap().finish().unwrap(); + } + let rejected = directory.path().join("rejected"); + fs::create_dir(&rejected).unwrap(); + assert!(extract_update_archive(&link_archive, &rejected).is_err()); + } + #[test] fn favorites_are_rendered_as_browser_paths_and_files() { let profile = home_profile(); @@ -1853,9 +2828,62 @@ mod tests { assert_eq!(folder.kind, EntryKind::Directory); assert_eq!(archive.kind, EntryKind::ZipArchive); - assert!(is_favorites_selection(3, 3)); - assert!(!is_favorites_selection(2, 3)); - assert!(!is_favorites_selection(gtk::INVALID_LIST_POSITION, 3)); + assert_eq!(special_browser_mode(3, 3), Some(BrowserMode::Favorites)); + assert_eq!(special_browser_mode(4, 3), Some(BrowserMode::Recent)); + assert_eq!(special_browser_mode(2, 3), None); + assert_eq!(special_browser_mode(gtk::INVALID_LIST_POSITION, 3), None); + } + + #[test] + fn recent_files_move_to_front_and_keep_only_100() { + let profile = LocationProfile { + name: "원격".into(), + kind: LocationKind::Sftp, + address: "sftp://example.invalid/comics".into(), + username: "reader".into(), + password: "password".into(), + domain: String::new(), + }; + let mut config = AppConfig::default(); + for index in 0..=RECENT_FILE_LIMIT { + let entry = media_entry(&format!("page{index}.jpg")); + record_recent_file(&mut config, &entry, &profile); + } + assert_eq!(config.recent_files.len(), RECENT_FILE_LIMIT); + assert_eq!(config.recent_files[0].name, "page100.jpg"); + assert!( + !config + .recent_files + .iter() + .any(|recent| recent.name == "page0.jpg") + ); + + let entry = media_entry("page50.jpg"); + record_recent_file(&mut config, &entry, &profile); + assert_eq!(config.recent_files.len(), RECENT_FILE_LIMIT); + assert_eq!(config.recent_files[0].name, "page50.jpg"); + assert_eq!(config.recent_files[0].profile.password, "password"); + } + + #[test] + fn recent_files_support_all_viewer_file_types() { + let profile = home_profile(); + let mut config = AppConfig::default(); + for name in ["book.zip", "page.jpg", "clip.mp4"] { + let mut entry = media_entry(name); + entry.kind = classify_file(Path::new(name)); + record_recent_file(&mut config, &entry, &profile); + } + let kinds = config + .recent_files + .iter() + .map(recent_file_browser_entry) + .map(|entry| entry.kind) + .collect::>(); + assert_eq!( + kinds, + [EntryKind::Video, EntryKind::Image, EntryKind::ZipArchive] + ); } #[test] 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,