Compare commits

..

No commits in common. "main" and "v0.2.10" have entirely different histories.

10 changed files with 272 additions and 1029 deletions

1
.gitignore vendored
View file

@ -9,4 +9,3 @@
/dist/*.tar.gz.part-* /dist/*.tar.gz.part-*
/dist/*.tar.gz.parts.sha256 /dist/*.tar.gz.parts.sha256
/dist/*-install.sh /dist/*-install.sh
/.release-credentials

2
Cargo.lock generated
View file

@ -182,7 +182,7 @@ checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]] [[package]]
name = "comicviewer" name = "comicviewer"
version = "0.2.20" version = "0.2.10"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",

View file

@ -1,6 +1,6 @@
[package] [package]
name = "comicviewer" name = "comicviewer"
version = "0.2.20" version = "0.2.10"
edition = "2024" edition = "2024"
description = "A comic archive viewer for local and remote locations" description = "A comic archive viewer for local and remote locations"
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"
@ -8,7 +8,7 @@ license = "GPL-3.0-or-later"
[dependencies] [dependencies]
anyhow = "1.0" anyhow = "1.0"
chrono = { version = "0.4", default-features = false, features = ["clock"] } chrono = { version = "0.4", default-features = false, features = ["clock"] }
gtk = { package = "gtk4", version = "0.10", features = ["v4_12"] } gtk = { package = "gtk4", version = "0.10", features = ["v4_10"] }
image = { version = "0.25", default-features = false, features = ["avif-native", "bmp", "gif", "jpeg", "png", "webp"] } image = { version = "0.25", default-features = false, features = ["avif-native", "bmp", "gif", "jpeg", "png", "webp"] }
filetime = "0.2" filetime = "0.2"
flate2 = "1.0" flate2 = "1.0"

View file

@ -26,16 +26,6 @@
</provides> </provides>
<content_rating type="oars-1.1" /> <content_rating type="oars-1.1" />
<releases> <releases>
<release version="0.2.20" date="2026-08-21" />
<release version="0.2.19" date="2026-08-21" />
<release version="0.2.18" date="2026-08-21" />
<release version="0.2.17" date="2026-08-21" />
<release version="0.2.16" date="2026-08-21" />
<release version="0.2.15" date="2026-08-21" />
<release version="0.2.14" date="2026-08-21" />
<release version="0.2.13" date="2026-08-21" />
<release version="0.2.12" date="2026-07-29" />
<release version="0.2.11" date="2026-07-24" />
<release version="0.2.10" date="2026-07-24" /> <release version="0.2.10" date="2026-07-24" />
<release version="0.2.9" date="2026-07-24" /> <release version="0.2.9" date="2026-07-24" />
<release version="0.2.8" date="2026-07-24" /> <release version="0.2.8" date="2026-07-24" />

View file

@ -14,7 +14,7 @@ sudo pacman -S fuse2 gtk4 dav1d gvfs gvfs-smb gstreamer curl \
``` ```
- `fuse2`: AppImage 마운트 및 실행 - `fuse2`: AppImage 마운트 및 실행
- `gtk4` 4.12 이상, `dav1d`: 화면 표시와 이미지 디코딩 - `gtk4`, `dav1d`: 화면 표시와 이미지 디코딩
- `gvfs`: FTP와 SFTP 접근 - `gvfs`: FTP와 SFTP 접근
- `gvfs-smb`: SMB 공유 접근 - `gvfs-smb`: SMB 공유 접근
- `gstreamer`, `gst-plugins-*`, `gst-libav`: MP4 등 동영상 재생 - `gstreamer`, `gst-plugins-*`, `gst-libav`: MP4 등 동영상 재생
@ -84,8 +84,6 @@ Comicviewer는 XDG 표준 경로를 사용합니다.
- 메인 창의 `캐시 비우기` 버튼으로 현재 열려 있지 않은 ZIP 캐시를 직접 삭제할 수 있습니다. - 메인 창의 `캐시 비우기` 버튼으로 현재 열려 있지 않은 ZIP 캐시를 직접 삭제할 수 있습니다.
- 캐시 한도는 설정 파일의 `cache_quota_gb`로 변경하며, 0은 영구 캐시를 사용하지 않는 값입니다. - 캐시 한도는 설정 파일의 `cache_quota_gb`로 변경하며, 0은 영구 캐시를 사용하지 않는 값입니다.
- 메인 창 검색은 현재 표시 중인 폴더의 파일명을 필터링하며, 입력을 지우면 전체 목록을 복원합니다. - 메인 창 검색은 현재 표시 중인 폴더의 파일명을 필터링하며, 입력을 지우면 전체 목록을 복원합니다.
- 위치 목록의 `최근 열어본 파일`은 성공적으로 연 ZIP·이미지·동영상을 최신순으로 최대 100개 보관합니다.
- 최근 파일 기록에는 원격 위치 재접속 정보가 함께 저장되며 `최근 기록 비우기`로 전체 기록만 삭제할 수 있습니다.
## 뷰어 조작 ## 뷰어 조작
@ -93,12 +91,10 @@ Comicviewer는 XDG 표준 경로를 사용합니다.
- `Home`과 `End`: 폴더의 첫 번째/마지막 파일 열기 - `Home`과 `End`: 폴더의 첫 번째/마지막 파일 열기
- 동영상에서 `←`와 `→`: 5초 뒤/앞으로 이동 - 동영상에서 `←`와 `→`: 5초 뒤/앞으로 이동
- 동영상에서 `↑`와 `↓`: 음량을 5%씩 조절 - 동영상에서 `↑`와 `↓`: 음량을 5%씩 조절
- 이미지에서 `1`, `2`, `3`, `4`: 폭 맞춤, 높이 맞춤, 2페이지, 100%로 전환 (`3`은 ZIP 뷰어에서 사용)
- 창보다 크게 표시된 이미지에서 `←`, `→`, `↑`, `↓`: 해당 방향으로 최대 100px 이동
- `L`: 우측 파일 목록 표시 또는 숨기기 - `L`: 우측 파일 목록 표시 또는 숨기기
- 파일 목록 상단 검색: 현재 재생 목록을 임시로 필터링하며, 입력을 지우면 전체 목록 복원 - 파일 목록 상단 검색: 현재 재생 목록을 임시로 필터링하며, 입력을 지우면 전체 목록 복원
- About 창의 `업데이트`: Cafe24에서 최신 번들을 내려받아 검증 후 사용자 영역에 설치 - About 창의 `업데이트`: Cafe24에서 최신 번들을 내려받아 검증 후 사용자 영역에 설치
- 이미지에서 `+`/`=`와 `-`: 현재 화면의 이미지를 임시로 10%씩 확대 또는 축소 - 이미지에서 `+`와 `-`: 현재 화면의 이미지를 임시로 10%씩 확대 또는 축소
- 이미지에서 `Ctrl` + 마우스 휠: 현재 화면의 이미지를 임시로 10%씩 확대 또는 축소 - 이미지에서 `Ctrl` + 마우스 휠: 현재 화면의 이미지를 임시로 10%씩 확대 또는 축소
- 2페이지의 `좌→우`/`우→좌` 방향은 마지막 선택을 저장해 다음 뷰어에서 복원 - 2페이지의 `좌→우`/`우→좌` 방향은 마지막 선택을 저장해 다음 뷰어에서 복원
- 전체 화면에서 마우스 클릭: 숨겨진 컨트롤을 5초 동안 표시 - 전체 화면에서 마우스 클릭: 숨겨진 컨트롤을 5초 동안 표시

View file

@ -55,7 +55,7 @@ AppImage 빌드가 끝나면 다음 스크립트로 체크섬과 통합 `tar.gz`
스크립트는 `Cargo.toml`에서 버전을 읽고 다음 파일을 생성합니다. 스크립트는 `Cargo.toml`에서 버전을 읽고 다음 파일을 생성합니다.
- `dist/Comicviewer-0.2.20-x86_64.AppImage.sha256` - `dist/Comicviewer-0.2.10-x86_64.AppImage.sha256`
- `dist/Comicviewer-latest-x86_64.tar.gz` - `dist/Comicviewer-latest-x86_64.tar.gz`
- `dist/Comicviewer-latest-x86_64.tar.gz.sha256` - `dist/Comicviewer-latest-x86_64.tar.gz.sha256`
@ -78,10 +78,10 @@ sha256sum -c Comicviewer-latest-x86_64.tar.gz.sha256
```sh ```sh
git add Cargo.toml Cargo.lock data packaging README.md docs git add Cargo.toml Cargo.lock data packaging README.md docs
git commit -m "Release v0.2.20" git commit -m "Release v0.2.10"
git tag -a v0.2.20 -m "Comicviewer v0.2.20" git tag -a v0.2.10 -m "Comicviewer v0.2.10"
git push origin main git push origin main
git push origin v0.2.20 git push origin v0.2.10
``` ```
이미 원격에 공개한 태그는 이동하거나 덮어쓰지 않습니다. 수정이 필요하면 새 이미 원격에 공개한 태그는 이동하거나 덮어쓰지 않습니다. 수정이 필요하면 새

View file

@ -15,7 +15,6 @@ pub struct AppConfig {
pub two_page_right_to_left: bool, pub two_page_right_to_left: bool,
pub locations: Vec<LocationProfile>, pub locations: Vec<LocationProfile>,
pub favorites: Vec<FavoriteEntry>, pub favorites: Vec<FavoriteEntry>,
pub recent_files: Vec<RecentFileEntry>,
} }
impl Default for AppConfig { impl Default for AppConfig {
@ -28,7 +27,6 @@ impl Default for AppConfig {
two_page_right_to_left: true, two_page_right_to_left: true,
locations: Vec::new(), locations: Vec::new(),
favorites: Vec::new(), favorites: Vec::new(),
recent_files: Vec::new(),
} }
} }
} }
@ -54,13 +52,6 @@ pub struct FavoriteEntry {
pub profile: LocationProfile, 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)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum LocationKind { pub enum LocationKind {
@ -212,18 +203,6 @@ mod tests {
domain: String::new(), 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(); let encoded = toml::to_string(&config).unwrap();
@ -231,8 +210,6 @@ mod tests {
assert_eq!(decoded.locations[0].password, "plain-password"); assert_eq!(decoded.locations[0].password, "plain-password");
assert_eq!(decoded.favorites[0].profile.username, "favorite-reader"); assert_eq!(decoded.favorites[0].profile.username, "favorite-reader");
assert_eq!(decoded.favorites[0].profile.password, "favorite-password"); 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] #[test]
@ -243,7 +220,6 @@ mod tests {
assert_eq!(decoded.viewer_mode, ViewerMode::FitWidth); assert_eq!(decoded.viewer_mode, ViewerMode::FitWidth);
assert!(decoded.two_page_right_to_left); assert!(decoded.two_page_right_to_left);
assert!(decoded.favorites.is_empty()); assert!(decoded.favorites.is_empty());
assert!(decoded.recent_files.is_empty());
} }
#[test] #[test]

View file

@ -16,32 +16,6 @@ const RECURSIVE_ATTRIBUTES: &str = "standard::display-name,standard::name,standa
const MAX_RECURSIVE_DIRECTORIES: usize = 10_000; const MAX_RECURSIVE_DIRECTORIES: usize = 10_000;
const MAX_RECURSIVE_ENTRIES: usize = 100_000; const MAX_RECURSIVE_ENTRIES: usize = 100_000;
#[derive(Default)]
struct EnumerationProgress {
seen: HashSet<String>,
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)] #[derive(Clone, Copy, Default)]
pub struct RecursiveProgress { pub struct RecursiveProgress {
pub directories: usize, pub directories: usize,
@ -138,7 +112,7 @@ where
} }
}; };
let mut entries = Vec::new(); let mut entries = Vec::new();
let mut enumeration = EnumerationProgress::default(); let mut scanned = 0;
loop { loop {
let batch = enumerator let batch = enumerator
@ -147,21 +121,19 @@ where
if batch.is_empty() { if batch.is_empty() {
break; break;
} }
enumeration.begin_batch(); scanned += batch.len();
progress(scanned);
for info in 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() { let kind = match info.file_type() {
gio::FileType::Directory => EntryKind::Directory, gio::FileType::Directory => EntryKind::Directory,
gio::FileType::Mountable | gio::FileType::Shortcut => EntryKind::Directory, gio::FileType::Mountable | gio::FileType::Shortcut => EntryKind::Directory,
gio::FileType::Regular => classify_file(Path::new(info.display_name().as_str())), gio::FileType::Regular => classify_file(Path::new(info.display_name().as_str())),
_ => continue, _ => 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 { entries.push(BrowserEntry {
uri, uri,
name: info.display_name().into(), name: info.display_name().into(),
@ -181,10 +153,6 @@ where
.map(Into::into), .map(Into::into),
}); });
} }
if enumeration.repeated_batch() {
break;
}
progress(enumeration.len());
} }
Ok(entries) Ok(entries)
} }
@ -481,26 +449,6 @@ mod tests {
assert!(encoded_input.equal(&encoded)); 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] #[test]
fn recursively_lists_viewable_files_without_following_symlinks() { fn recursively_lists_viewable_files_without_following_symlinks() {
let directory = tempfile::tempdir().unwrap(); let directory = tempfile::tempdir().unwrap();

View file

@ -23,12 +23,9 @@ const VIDEO_VOLUME_STEP: f64 = 0.05;
const IMAGE_ZOOM_STEP: f64 = 0.1; const IMAGE_ZOOM_STEP: f64 = 0.1;
const IMAGE_ZOOM_MIN: f64 = 0.1; const IMAGE_ZOOM_MIN: f64 = 0.1;
const IMAGE_ZOOM_MAX: f64 = 4.0; const IMAGE_ZOOM_MAX: f64 = 4.0;
const IMAGE_PAN_STEP: f64 = 100.0;
const VIEWER_CONTROLLER_KEY: &str = "comicviewer-viewer-controller"; const VIEWER_CONTROLLER_KEY: &str = "comicviewer-viewer-controller";
const MEDIA_VIEWER_CONTROLLER_KEY: &str = "comicviewer-media-viewer-controller"; const MEDIA_VIEWER_CONTROLLER_KEY: &str = "comicviewer-media-viewer-controller";
const VIEWER_FILE_SEARCH_KEY: &str = "comicviewer-file-search"; 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"; const PRESERVE_SEEK_CLASS: &str = "viewer-preserve-seek";
fn clear_viewer_controller(window: &gtk::ApplicationWindow) { fn clear_viewer_controller(window: &gtk::ApplicationWindow) {
@ -287,19 +284,11 @@ impl ViewerWindow {
} = controls; } = controls;
let direction_control = two_page_direction_control let direction_control = two_page_direction_control
.expect("archive viewer requires a two-page direction control"); .expect("archive viewer requires a two-page direction control");
let title_files = sibling_navigator let title = source.display_name.clone();
.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 let file_list_query = reuse_window
.as_ref() .as_ref()
.map(viewer_file_search_query) .map(viewer_file_search_query)
.unwrap_or_default(); .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() { if let Some(window) = reuse_window.as_ref() {
clear_viewer_controller(window); clear_viewer_controller(window);
} }
@ -316,7 +305,7 @@ impl ViewerWindow {
set_viewer_loading(&window, false); set_viewer_loading(&window, false);
window.set_title(Some(&title)); window.set_title(Some(&title));
let header = gtk::HeaderBar::new(); let header = gtk::HeaderBar::new();
header.set_title_widget(Some(&viewer_title_label(&title))); header.set_title_widget(Some(&gtk::Label::new(Some(&title))));
let favorite_button = gtk::Button::with_label(favorite_label(favorite_control.active)); let favorite_button = gtk::Button::with_label(favorite_label(favorite_control.active));
let download_button = gtk::Button::with_label("파일 다운로드"); let download_button = gtk::Button::with_label("파일 다운로드");
let file_list_button = gtk::ToggleButton::with_label("파일 목록"); let file_list_button = gtk::ToggleButton::with_label("파일 목록");
@ -465,10 +454,8 @@ impl ViewerWindow {
file_list_button, file_list_button,
file_list_panel: file_list.panel, file_list_panel: file_list.panel,
file_list_search: file_list.search, file_list_search: file_list.search,
file_list_scrolled: file_list.scrolled,
file_list: file_list.list, file_list: file_list.list,
file_list_files: RefCell::new(Vec::new()), file_list_files: RefCell::new(Vec::new()),
file_list_scroll_restore: Cell::new(Some(file_list_scroll)),
favorite_button, favorite_button,
favorite_toggle: favorite_control.toggle, favorite_toggle: favorite_control.toggle,
download_button, download_button,
@ -638,10 +625,8 @@ struct ViewerController {
file_list_button: gtk::ToggleButton, file_list_button: gtk::ToggleButton,
file_list_panel: gtk::Box, file_list_panel: gtk::Box,
file_list_search: gtk::SearchEntry, file_list_search: gtk::SearchEntry,
file_list_scrolled: gtk::ScrolledWindow,
file_list: gtk::ListBox, file_list: gtk::ListBox,
file_list_files: RefCell<Vec<SiblingFile>>, file_list_files: RefCell<Vec<SiblingFile>>,
file_list_scroll_restore: Cell<Option<f64>>,
favorite_button: gtk::Button, favorite_button: gtk::Button,
favorite_toggle: Rc<dyn Fn() -> bool>, favorite_toggle: Rc<dyn Fn() -> bool>,
download_button: gtk::Button, download_button: gtk::Button,
@ -655,7 +640,7 @@ struct ViewerController {
key_controller: RefCell<Option<gtk::EventControllerKey>>, key_controller: RefCell<Option<gtk::EventControllerKey>>,
motion_controller: RefCell<Option<gtk::EventControllerMotion>>, motion_controller: RefCell<Option<gtk::EventControllerMotion>>,
fullscreen_key_controller: RefCell<Option<gtk::EventControllerKey>>, fullscreen_key_controller: RefCell<Option<gtk::EventControllerKey>>,
fullscreen_click_controller: RefCell<Option<gtk::EventControllerLegacy>>, fullscreen_click_controller: RefCell<Option<gtk::GestureClick>>,
fullscreen_ui_hide_timer: RefCell<Option<glib::SourceId>>, fullscreen_ui_hide_timer: RefCell<Option<glib::SourceId>>,
fullscreen_ui_visible: Cell<bool>, fullscreen_ui_visible: Cell<bool>,
fullscreen_notify_handler: RefCell<Option<glib::SignalHandlerId>>, fullscreen_notify_handler: RefCell<Option<glib::SignalHandlerId>>,
@ -767,16 +752,6 @@ impl ViewerController {
controller.refresh_file_list(); 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_typeahead = Rc::new(RefCell::new(TypeaheadBuffer::default()));
let file_list_keys = gtk::EventControllerKey::new(); let file_list_keys = gtk::EventControllerKey::new();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
@ -811,24 +786,29 @@ impl ViewerController {
controller.seek_page(index); controller.seek_page(index);
} }
}); });
let seek_events = gtk::EventControllerLegacy::new(); let seek_click = gtk::GestureClick::builder()
seek_events.set_propagation_phase(gtk::PropagationPhase::Capture); .button(gdk::BUTTON_PRIMARY)
.propagation_phase(gtk::PropagationPhase::Capture)
.build();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
seek_events.connect_event(move |_, event| { seek_click.connect_pressed(move |_, _, _, _| {
if event if let Some(controller) = controller.upgrade() {
.downcast_ref::<gdk::ButtonEvent>() controller.begin_seek_interaction();
.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 controller = Rc::downgrade(self);
seek_click.connect_released(move |_, _, _, _| {
if let Some(controller) = controller.upgrade() {
controller.end_seek_interaction();
}
});
let controller = Rc::downgrade(self);
seek_click.connect_cancel(move |_, _| {
if let Some(controller) = controller.upgrade() {
controller.end_seek_interaction();
}
});
self.page_seek.add_controller(seek_click);
let adjustment = self.continuous_scrolled.vadjustment(); let adjustment = self.continuous_scrolled.vadjustment();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
@ -915,17 +895,15 @@ impl ViewerController {
}); });
self.stack.add_controller(scroll_controller); self.stack.add_controller(scroll_controller);
let fullscreen_click = gtk::EventControllerLegacy::new(); let fullscreen_click = gtk::GestureClick::builder()
fullscreen_click.set_propagation_phase(gtk::PropagationPhase::Capture); .button(0)
.propagation_phase(gtk::PropagationPhase::Capture)
.build();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
fullscreen_click.connect_event(move |_, event| { fullscreen_click.connect_pressed(move |_, _, _, _| {
if event.downcast_ref::<gdk::ButtonEvent>().is_some() if let Some(controller) = controller.upgrade() {
&& event.event_type() == gdk::EventType::ButtonPress
&& let Some(controller) = controller.upgrade()
{
controller.controls_clicked(); controller.controls_clicked();
} }
glib::Propagation::Proceed
}); });
self.window.add_controller(fullscreen_click.clone()); self.window.add_controller(fullscreen_click.clone());
self.fullscreen_click_controller self.fullscreen_click_controller
@ -980,16 +958,22 @@ impl ViewerController {
controller.seek_edge(true); controller.seek_edge(true);
glib::Propagation::Stop glib::Propagation::Stop
} }
gdk::Key::Up | gdk::Key::KP_Up if controller.pan_image(false, false) => { gdk::Key::Up | gdk::Key::KP_Up
if matches!(
controller.view_mode(),
ViewMode::ActualSize | ViewMode::FitWidth | ViewMode::Continuous
) =>
{
controller.scroll_vertically(false);
glib::Propagation::Stop glib::Propagation::Stop
} }
gdk::Key::Down | gdk::Key::KP_Down if controller.pan_image(false, true) => { gdk::Key::Down | gdk::Key::KP_Down
glib::Propagation::Stop if matches!(
} controller.view_mode(),
gdk::Key::Left | gdk::Key::KP_Left if controller.pan_image(true, false) => { ViewMode::ActualSize | ViewMode::FitWidth | ViewMode::Continuous
glib::Propagation::Stop ) =>
} {
gdk::Key::Right | gdk::Key::KP_Right if controller.pan_image(true, true) => { controller.scroll_vertically(true);
glib::Propagation::Stop glib::Propagation::Stop
} }
gdk::Key::Left | gdk::Key::KP_Left | gdk::Key::Page_Up => { gdk::Key::Left | gdk::Key::KP_Left | gdk::Key::Page_Up => {
@ -1008,7 +992,7 @@ impl ViewerController {
controller.open_sibling(true); controller.open_sibling(true);
glib::Propagation::Stop glib::Propagation::Stop
} }
gdk::Key::plus | gdk::Key::equal | gdk::Key::KP_Add => { gdk::Key::plus | gdk::Key::KP_Add => {
controller.adjust_image_zoom(true); controller.adjust_image_zoom(true);
glib::Propagation::Stop glib::Propagation::Stop
} }
@ -1016,22 +1000,6 @@ impl ViewerController {
controller.adjust_image_zoom(false); controller.adjust_image_zoom(false);
glib::Propagation::Stop 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) _ if !shortcut_modifiers_blocked(modifiers)
&& key && key
.to_unicode() .to_unicode()
@ -1108,11 +1076,6 @@ impl ViewerController {
if let Some(row) = current.and_then(|index| self.file_list.row_at_index(index as i32)) { if let Some(row) = current.and_then(|index| self.file_list.row_at_index(index as i32)) {
self.file_list.select_row(Some(&row)); 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) { fn open_file_list_row(&self, index: i32) {
@ -1304,11 +1267,6 @@ impl ViewerController {
self.status_label.set_visible(true); self.status_label.set_visible(true);
self.file_list_panel self.file_list_panel
.set_visible(self.file_list_button.is_active()); .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,
);
} }
} }
@ -1349,11 +1307,6 @@ impl ViewerController {
self.status_label.set_visible(visible); self.status_label.set_visible(visible);
self.file_list_panel self.file_list_panel
.set_visible(visible && self.file_list_button.is_active()); .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(); self.window.queue_allocate();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
glib::idle_add_local_once(move || { glib::idle_add_local_once(move || {
@ -1564,15 +1517,6 @@ impl ViewerController {
self.stack.queue_allocate(); self.stack.queue_allocate();
} }
fn select_view_mode(self: &Rc<Self>, 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<Self>) { fn schedule_view_mode_refresh(self: &Rc<Self>) {
let generation = self.view_layout_generation.get().wrapping_add(1); let generation = self.view_layout_generation.get().wrapping_add(1);
self.view_layout_generation.set(generation); self.view_layout_generation.set(generation);
@ -1640,18 +1584,16 @@ impl ViewerController {
self.seek_page(if end { count - 1 } else { 0 }); self.seek_page(if end { count - 1 } else { 0 });
} }
fn pan_image(&self, horizontal: bool, forward: bool) -> bool { fn scroll_vertically(&self, down: bool) {
let scrolled = match self.view_mode() { let adjustment = if self.view_mode() == ViewMode::Continuous {
ViewMode::TwoPage => &self.spread_scrolled, self.continuous_scrolled.vadjustment()
ViewMode::Continuous => &self.continuous_scrolled,
_ => &self.single_scrolled,
};
let adjustment = if horizontal {
scrolled.hadjustment()
} else { } else {
scrolled.vadjustment() self.single_scrolled.vadjustment()
}; };
pan_adjustment(&adjustment, forward) 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 shift_pairing(self: &Rc<Self>, offset: isize) { fn shift_pairing(self: &Rc<Self>, offset: isize) {
@ -1872,8 +1814,8 @@ impl ViewerController {
if (zoom - 1.0).abs() >= f64::EPSILON { if (zoom - 1.0).abs() >= f64::EPSILON {
let (width, height) = zoomed_picture_request( let (width, height) = zoomed_picture_request(
self.view_mode(), self.view_mode(),
self.single_scrolled.width().max(1), self.single_scrolled.allocated_width().max(1),
self.single_scrolled.height().max(1), self.single_scrolled.allocated_height().max(1),
texture_width, texture_width,
texture_height, texture_height,
zoom, zoom,
@ -1891,7 +1833,7 @@ impl ViewerController {
self.single_picture.set_size_request(width, height); self.single_picture.set_size_request(width, height);
} else if let Some((width, height)) = single_picture_request( } else if let Some((width, height)) = single_picture_request(
self.view_mode(), self.view_mode(),
self.stack.width().max(1), self.stack.allocated_width().max(1),
texture_width, texture_width,
texture_height, texture_height,
) { ) {
@ -1935,8 +1877,8 @@ impl ViewerController {
}; };
drop(state); drop(state);
let count = visible.len().max(1) as i32; let count = visible.len().max(1) as i32;
let viewport_width = (self.spread_scrolled.width().max(1) - 8) / count; let viewport_width = (self.spread_scrolled.allocated_width().max(1) - 8) / count;
let viewport_height = self.spread_scrolled.height().max(1); let viewport_height = self.spread_scrolled.allocated_height().max(1);
self.spread_box.set_homogeneous(false); self.spread_box.set_homogeneous(false);
self.spread_box.set_halign(gtk::Align::Center); self.spread_box.set_halign(gtk::Align::Center);
self.spread_box.set_valign(gtk::Align::Center); self.spread_box.set_valign(gtk::Align::Center);
@ -2177,7 +2119,7 @@ impl ViewerController {
} }
fn continuous_content_width(&self) -> i32 { fn continuous_content_width(&self) -> i32 {
continuous_content_width(self.stack.width()) continuous_content_width(self.stack.allocated_width())
} }
fn evict_cache(&self) { fn evict_cache(&self) {
@ -2265,20 +2207,11 @@ impl MediaViewerWindow {
view_mode_control, view_mode_control,
two_page_direction_control: _, two_page_direction_control: _,
} = controls; } = controls;
let title_files = sibling_navigator let title = source.display_name.clone();
.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 let file_list_query = reuse_window
.as_ref() .as_ref()
.map(viewer_file_search_query) .map(viewer_file_search_query)
.unwrap_or_default(); .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() { if let Some(window) = reuse_window.as_ref() {
clear_viewer_controller(window); clear_viewer_controller(window);
} }
@ -2295,14 +2228,13 @@ impl MediaViewerWindow {
set_viewer_loading(&window, false); set_viewer_loading(&window, false);
window.set_title(Some(&title)); window.set_title(Some(&title));
let header = gtk::HeaderBar::new(); let header = gtk::HeaderBar::new();
header.set_title_widget(Some(&viewer_title_label(&title))); header.set_title_widget(Some(&gtk::Label::new(Some(&title))));
let favorite_button = gtk::Button::with_label(favorite_label(favorite_control.active)); let favorite_button = gtk::Button::with_label(favorite_label(favorite_control.active));
let download_button = gtk::Button::with_label("파일 다운로드"); let download_button = gtk::Button::with_label("파일 다운로드");
let file_list_button = gtk::ToggleButton::with_label("파일 목록"); let file_list_button = gtk::ToggleButton::with_label("파일 목록");
file_list_button.set_sensitive(sibling_navigator.is_some()); file_list_button.set_sensitive(sibling_navigator.is_some());
file_list_button.set_active(window.has_css_class("viewer-file-list-visible")); file_list_button.set_active(window.has_css_class("viewer-file-list-visible"));
let loop_check = gtk::CheckButton::with_label("반복 재생"); let loop_check = gtk::CheckButton::with_label("반복 재생");
loop_check.set_active(video_loop_active);
loop_check.set_visible(kind == EntryKind::Video); loop_check.set_visible(kind == EntryKind::Video);
let image_mode_dropdown = gtk::DropDown::from_strings(&["100%", "폭 맞춤", "높이 맞춤"]); let image_mode_dropdown = gtk::DropDown::from_strings(&["100%", "폭 맞춤", "높이 맞춤"]);
let (image_mode_selected, image_mode_change) = let (image_mode_selected, image_mode_change) =
@ -2339,13 +2271,14 @@ impl MediaViewerWindow {
} else { } else {
gtk::Video::new() gtk::Video::new()
}; };
video.set_autoplay(false); video.set_autoplay(true);
video.set_loop(false);
video.set_hexpand(true); video.set_hexpand(true);
video.set_vexpand(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")); stack.add_named(&video, Some("video"));
let status_label = gtk::Label::builder() let status_label = gtk::Label::builder()
.label(&source.display_name) .label(&title)
.xalign(0.0) .xalign(0.0)
.margin_top(6) .margin_top(6)
.margin_bottom(6) .margin_bottom(6)
@ -2405,10 +2338,8 @@ impl MediaViewerWindow {
file_list_button, file_list_button,
file_list_panel: file_list.panel, file_list_panel: file_list.panel,
file_list_search: file_list.search, file_list_search: file_list.search,
file_list_scrolled: file_list.scrolled,
file_list: file_list.list, file_list: file_list.list,
file_list_files: RefCell::new(Vec::new()), file_list_files: RefCell::new(Vec::new()),
file_list_scroll_restore: Cell::new(Some(file_list_scroll)),
favorite_button, favorite_button,
favorite_toggle: favorite_control.toggle, favorite_toggle: favorite_control.toggle,
download_button, download_button,
@ -2431,36 +2362,12 @@ impl MediaViewerWindow {
navigation_message_generation: Rc::new(Cell::new(0)), navigation_message_generation: Rc::new(Cell::new(0)),
}); });
if let Some(stream) = controller.video.media_stream() { if let Some(stream) = controller.video.media_stream() {
stream.set_loop(false);
let status_label = controller.status_label.clone(); let status_label = controller.status_label.clone();
stream.connect_error_notify(move |stream| { stream.connect_error_notify(move |stream| {
if let Some(error) = stream.error() { if let Some(error) = stream.error() {
status_label.set_text(&format!("동영상을 재생할 수 없습니다: {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.connect_signals();
controller.fullscreen_changed(); controller.fullscreen_changed();
@ -2487,7 +2394,6 @@ impl MediaViewerWindow {
EntryKind::Video => { EntryKind::Video => {
controller.stack.set_visible_child_name("video"); controller.stack.set_visible_child_name("video");
if let Some(stream) = controller.video.media_stream() { if let Some(stream) = controller.video.media_stream() {
initialize_video_volume(&stream);
stream.play(); stream.play();
} }
} }
@ -2519,10 +2425,8 @@ struct MediaViewerController {
file_list_button: gtk::ToggleButton, file_list_button: gtk::ToggleButton,
file_list_panel: gtk::Box, file_list_panel: gtk::Box,
file_list_search: gtk::SearchEntry, file_list_search: gtk::SearchEntry,
file_list_scrolled: gtk::ScrolledWindow,
file_list: gtk::ListBox, file_list: gtk::ListBox,
file_list_files: RefCell<Vec<SiblingFile>>, file_list_files: RefCell<Vec<SiblingFile>>,
file_list_scroll_restore: Cell<Option<f64>>,
favorite_button: gtk::Button, favorite_button: gtk::Button,
favorite_toggle: Rc<dyn Fn() -> bool>, favorite_toggle: Rc<dyn Fn() -> bool>,
download_button: gtk::Button, download_button: gtk::Button,
@ -2536,7 +2440,7 @@ struct MediaViewerController {
key_controller: RefCell<Option<gtk::EventControllerKey>>, key_controller: RefCell<Option<gtk::EventControllerKey>>,
motion_controller: RefCell<Option<gtk::EventControllerMotion>>, motion_controller: RefCell<Option<gtk::EventControllerMotion>>,
fullscreen_key_controller: RefCell<Option<gtk::EventControllerKey>>, fullscreen_key_controller: RefCell<Option<gtk::EventControllerKey>>,
fullscreen_click_controller: RefCell<Option<gtk::EventControllerLegacy>>, fullscreen_click_controller: RefCell<Option<gtk::GestureClick>>,
fullscreen_ui_hide_timer: RefCell<Option<glib::SourceId>>, fullscreen_ui_hide_timer: RefCell<Option<glib::SourceId>>,
fullscreen_ui_visible: Cell<bool>, fullscreen_ui_visible: Cell<bool>,
fullscreen_notify_handler: RefCell<Option<glib::SignalHandlerId>>, fullscreen_notify_handler: RefCell<Option<glib::SignalHandlerId>>,
@ -2547,17 +2451,15 @@ struct MediaViewerController {
impl MediaViewerController { impl MediaViewerController {
fn connect_signals(self: &Rc<Self>) { fn connect_signals(self: &Rc<Self>) {
let fullscreen_click = gtk::EventControllerLegacy::new(); let fullscreen_click = gtk::GestureClick::builder()
fullscreen_click.set_propagation_phase(gtk::PropagationPhase::Capture); .button(0)
.propagation_phase(gtk::PropagationPhase::Capture)
.build();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
fullscreen_click.connect_event(move |_, event| { fullscreen_click.connect_pressed(move |_, _, _, _| {
if event.downcast_ref::<gdk::ButtonEvent>().is_some() if let Some(controller) = controller.upgrade() {
&& event.event_type() == gdk::EventType::ButtonPress
&& let Some(controller) = controller.upgrade()
{
controller.controls_clicked(); controller.controls_clicked();
} }
glib::Propagation::Proceed
}); });
self.window.add_controller(fullscreen_click.clone()); self.window.add_controller(fullscreen_click.clone());
self.fullscreen_click_controller self.fullscreen_click_controller
@ -2637,23 +2539,22 @@ impl MediaViewerController {
} }
gdk::Key::Up | gdk::Key::KP_Up gdk::Key::Up | gdk::Key::KP_Up
if controller.kind == EntryKind::Image if controller.kind == EntryKind::Image
&& controller.pan_image(false, false) => && matches!(
controller.image_view_mode(),
ViewMode::ActualSize | ViewMode::FitWidth
) =>
{ {
controller.scroll_image(false);
glib::Propagation::Stop glib::Propagation::Stop
} }
gdk::Key::Down | gdk::Key::KP_Down gdk::Key::Down | gdk::Key::KP_Down
if controller.kind == EntryKind::Image && controller.pan_image(false, true) => if controller.kind == EntryKind::Image
{ && matches!(
glib::Propagation::Stop controller.image_view_mode(),
} ViewMode::ActualSize | ViewMode::FitWidth
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 glib::Propagation::Stop
} }
_ if key.to_unicode() == Some('[') => { _ if key.to_unicode() == Some('[') => {
@ -2664,9 +2565,7 @@ impl MediaViewerController {
controller.open_sibling(true); controller.open_sibling(true);
glib::Propagation::Stop glib::Propagation::Stop
} }
gdk::Key::plus | gdk::Key::equal | gdk::Key::KP_Add gdk::Key::plus | gdk::Key::KP_Add if controller.kind == EntryKind::Image => {
if controller.kind == EntryKind::Image =>
{
controller.adjust_image_zoom(true); controller.adjust_image_zoom(true);
glib::Propagation::Stop glib::Propagation::Stop
} }
@ -2674,18 +2573,6 @@ impl MediaViewerController {
controller.adjust_image_zoom(false); controller.adjust_image_zoom(false);
glib::Propagation::Stop 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 _ if key
.to_unicode() .to_unicode()
.is_some_and(|character| character.eq_ignore_ascii_case(&'l')) => .is_some_and(|character| character.eq_ignore_ascii_case(&'l')) =>
@ -2767,16 +2654,6 @@ impl MediaViewerController {
controller.refresh_file_list(); 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_typeahead = Rc::new(RefCell::new(TypeaheadBuffer::default()));
let file_list_keys = gtk::EventControllerKey::new(); let file_list_keys = gtk::EventControllerKey::new();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
@ -2863,24 +2740,29 @@ impl MediaViewerController {
controller.schedule_seek(index); controller.schedule_seek(index);
} }
}); });
let seek_events = gtk::EventControllerLegacy::new(); let seek_click = gtk::GestureClick::builder()
seek_events.set_propagation_phase(gtk::PropagationPhase::Capture); .button(gdk::BUTTON_PRIMARY)
.propagation_phase(gtk::PropagationPhase::Capture)
.build();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
seek_events.connect_event(move |_, event| { seek_click.connect_pressed(move |_, _, _, _| {
if event if let Some(controller) = controller.upgrade() {
.downcast_ref::<gdk::ButtonEvent>() controller.begin_seek_interaction();
.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); let controller = Rc::downgrade(self);
seek_click.connect_released(move |_, _, _, _| {
if let Some(controller) = controller.upgrade() {
controller.end_seek_interaction();
}
});
let controller = Rc::downgrade(self);
seek_click.connect_cancel(move |_, _| {
if let Some(controller) = controller.upgrade() {
controller.cancel_seek_interaction();
}
});
self.media_seek.add_controller(seek_click);
} }
fn refresh_file_list(&self) { fn refresh_file_list(&self) {
@ -2903,11 +2785,6 @@ impl MediaViewerController {
if let Some(row) = current.and_then(|index| self.file_list.row_at_index(index as i32)) { if let Some(row) = current.and_then(|index| self.file_list.row_at_index(index as i32)) {
self.file_list.select_row(Some(&row)); 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) { fn open_file_list_row(&self, index: i32) {
@ -3054,15 +2931,6 @@ impl MediaViewerController {
} }
} }
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) { fn resize_image_picture(&self) {
let Some((texture_width, texture_height)) = self.image_dimensions.get() else { let Some((texture_width, texture_height)) = self.image_dimensions.get() else {
return; return;
@ -3071,8 +2939,8 @@ impl MediaViewerController {
if (zoom - 1.0).abs() >= f64::EPSILON { if (zoom - 1.0).abs() >= f64::EPSILON {
let (width, height) = zoomed_picture_request( let (width, height) = zoomed_picture_request(
self.image_view_mode(), self.image_view_mode(),
self.image_scrolled.width().max(1), self.image_scrolled.allocated_width().max(1),
self.image_scrolled.height().max(1), self.image_scrolled.allocated_height().max(1),
texture_width, texture_width,
texture_height, texture_height,
zoom, zoom,
@ -3090,7 +2958,7 @@ impl MediaViewerController {
self.picture.set_size_request(width, height); self.picture.set_size_request(width, height);
} else if let Some((width, height)) = single_picture_request( } else if let Some((width, height)) = single_picture_request(
self.image_view_mode(), self.image_view_mode(),
self.stack.width().max(1), self.stack.allocated_width().max(1),
texture_width, texture_width,
texture_height, texture_height,
) { ) {
@ -3098,13 +2966,12 @@ impl MediaViewerController {
} }
} }
fn pan_image(&self, horizontal: bool, forward: bool) -> bool { fn scroll_image(&self, down: bool) {
let adjustment = if horizontal { let adjustment = self.image_scrolled.vadjustment();
self.image_scrolled.hadjustment() let step = adjustment.step_increment().max(64.0);
} else { let delta = if down { step } else { -step };
self.image_scrolled.vadjustment() let maximum = (adjustment.upper() - adjustment.page_size()).max(adjustment.lower());
}; adjustment.set_value((adjustment.value() + delta).clamp(adjustment.lower(), maximum));
pan_adjustment(&adjustment, forward)
} }
fn open_sibling(&self, forward: bool) { fn open_sibling(&self, forward: bool) {
@ -3197,6 +3064,17 @@ impl MediaViewerController {
} }
} }
fn cancel_seek_interaction(self: &Rc<Self>) {
self.pending_seek_index.set(None);
if self.seek_interacting.replace(false) {
if self.window.is_fullscreen() {
self.show_fullscreen_ui_temporarily();
} else {
self.show_seek_temporarily();
}
}
}
fn pointer_moved(self: &Rc<Self>, x: f64, y: f64) { fn pointer_moved(self: &Rc<Self>, x: f64, y: f64) {
if self.last_pointer_position.get() == Some((x, y)) { if self.last_pointer_position.get() == Some((x, y)) {
return; return;
@ -3330,11 +3208,6 @@ impl MediaViewerController {
self.status_label.set_visible(true); self.status_label.set_visible(true);
self.file_list_panel self.file_list_panel
.set_visible(self.file_list_button.is_active()); .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,
);
} }
} }
@ -3374,11 +3247,6 @@ impl MediaViewerController {
self.status_label.set_visible(visible); self.status_label.set_visible(visible);
self.file_list_panel self.file_list_panel
.set_visible(visible && self.file_list_button.is_active()); .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(); self.window.queue_allocate();
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
glib::idle_add_local_once(move || { glib::idle_add_local_once(move || {
@ -3444,26 +3312,9 @@ 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 { struct ViewerFileList {
panel: gtk::Box, panel: gtk::Box,
search: gtk::SearchEntry, search: gtk::SearchEntry,
scrolled: gtk::ScrolledWindow,
list: gtk::ListBox, list: gtk::ListBox,
} }
@ -3596,7 +3447,6 @@ fn viewer_file_list(query: &str) -> ViewerFileList {
ViewerFileList { ViewerFileList {
panel, panel,
search, search,
scrolled,
list, list,
} }
} }
@ -3616,57 +3466,6 @@ fn store_viewer_file_search_query(window: &gtk::ApplicationWindow, query: &str)
} }
} }
fn viewer_file_scroll_position(window: &gtk::ApplicationWindow) -> f64 {
unsafe {
window
.data::<f64>(VIEWER_FILE_SCROLL_KEY)
.map(|position| *position.as_ref())
.unwrap_or_default()
}
}
fn store_viewer_file_scroll_position(window: &gtk::ApplicationWindow, position: f64) {
unsafe {
window.set_data(VIEWER_FILE_SCROLL_KEY, position.max(0.0));
}
}
fn viewer_video_loop_enabled(window: &gtk::ApplicationWindow) -> bool {
unsafe {
window
.data::<bool>(VIEWER_VIDEO_LOOP_KEY)
.is_some_and(|active| *active.as_ref())
}
}
fn store_viewer_video_loop(window: &gtk::ApplicationWindow, active: bool) {
unsafe {
window.set_data(VIEWER_VIDEO_LOOP_KEY, active);
}
}
fn restore_viewer_file_scroll(scrolled: &gtk::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: &gtk::Box,
scrolled: &gtk::ScrolledWindow,
pending: &Cell<Option<f64>>,
) {
if !panel.is_visible() {
return;
}
if let Some(position) = pending.take() {
restore_viewer_file_scroll(scrolled, position);
}
}
fn widget_contains_focus(widget: &impl IsA<gtk::Widget>, window: &gtk::ApplicationWindow) -> bool { fn widget_contains_focus(widget: &impl IsA<gtk::Widget>, window: &gtk::ApplicationWindow) -> bool {
gtk::prelude::GtkWindowExt::focus(window).is_some_and(|focus| { gtk::prelude::GtkWindowExt::focus(window).is_some_and(|focus| {
let widget = widget.as_ref(); let widget = widget.as_ref();
@ -4098,99 +3897,6 @@ fn video_volume_target(volume: f64, delta: f64) -> f64 {
(volume + delta).clamp(0.0, 1.0) (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: &gtk::MediaStream,
check: &gtk::CheckButton,
pending: &Rc<Cell<bool>>,
) {
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<bool>, restart_needed: bool) -> bool {
if !restart_needed {
pending.set(false);
return false;
}
!pending.replace(true)
}
fn initialize_video_volume(stream: &gtk::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: &gtk::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<f64> {
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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -4307,38 +4013,6 @@ mod tests {
assert_eq!(video_volume_target(0.5, 0.05), 0.55); 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] #[test]
fn viewer_file_typeahead_wraps_by_display_name() { fn viewer_file_typeahead_wraps_by_display_name() {
let files = ["Alpha.zip", "beta.jpg", "Bravo.mp4"].map(|name| SiblingFile { let files = ["Alpha.zip", "beta.jpg", "Bravo.mp4"].map(|name| SiblingFile {
@ -4413,28 +4087,6 @@ mod tests {
assert_eq!(seek_sibling_files(files, EntryKind::Image, true).len(), 3); 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] #[test]
fn playlist_search_filters_and_empty_query_restores_files() { fn playlist_search_filters_and_empty_query_restores_files() {
let files = ["Alpha.zip", "beta.jpg", "Bravo.mp4"].map(|name| SiblingFile { let files = ["Alpha.zip", "beta.jpg", "Bravo.mp4"].map(|name| SiblingFile {

View file

@ -21,9 +21,7 @@ use tar::Archive;
use crate::browser::{ use crate::browser::{
BrowserEntry, EntryKind, SortDirection, SortField, classify_file, sort_entries, BrowserEntry, EntryKind, SortDirection, SortField, classify_file, sort_entries,
}; };
use crate::config::{ use crate::config::{AppConfig, FavoriteEntry, LocationKind, LocationProfile, ViewerMode};
AppConfig, FavoriteEntry, LocationKind, LocationProfile, RecentFileEntry, ViewerMode,
};
use crate::database::Database; use crate::database::Database;
use crate::source::{ use crate::source::{
display_remote_uri, ensure_mounted, enumerate_directory, enumerate_tree_entries, display_remote_uri, ensure_mounted, enumerate_directory, enumerate_tree_entries,
@ -38,7 +36,6 @@ use crate::viewer::{
use crate::zip_cache::ZipCache; use crate::zip_cache::ZipCache;
const MOUSE_BACK_BUTTON: u32 = 8; const MOUSE_BACK_BUTTON: u32 = 8;
const RECENT_FILE_LIMIT: usize = 100;
const UPDATE_BUNDLE_URL: &str = const UPDATE_BUNDLE_URL: &str =
"https://burningtuna.cafe24.com/www/Downloads/Comicviewer/Comicviewer-latest-x86_64.tar.gz"; "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"; const UPDATE_CHECKSUM_URL: &str = "https://burningtuna.cafe24.com/www/Downloads/Comicviewer/Comicviewer-latest-x86_64.tar.gz.sha256";
@ -86,14 +83,11 @@ impl ComicWindow {
edit_location_button.set_sensitive(false); edit_location_button.set_sensitive(false);
let delete_location_button = gtk::Button::with_label("삭제"); let delete_location_button = gtk::Button::with_label("삭제");
delete_location_button.set_sensitive(false); delete_location_button.set_sensitive(false);
let clear_recent_button = gtk::Button::with_label("최근 기록 비우기");
clear_recent_button.set_visible(false);
locations.append(&gtk::Label::new(Some("위치"))); locations.append(&gtk::Label::new(Some("위치")));
locations.append(&location_dropdown); locations.append(&location_dropdown);
locations.append(&add_location_button); locations.append(&add_location_button);
locations.append(&edit_location_button); locations.append(&edit_location_button);
locations.append(&delete_location_button); locations.append(&delete_location_button);
locations.append(&clear_recent_button);
let navigation = gtk::Box::new(gtk::Orientation::Horizontal, 6); let navigation = gtk::Box::new(gtk::Orientation::Horizontal, 6);
let up_button = gtk::Button::builder() let up_button = gtk::Button::builder()
@ -131,13 +125,12 @@ impl ComicWindow {
controls.append(&gtk::Label::new(Some("빠른 이미지 로딩"))); controls.append(&gtk::Label::new(Some("빠른 이미지 로딩")));
controls.append(&fast_loading_switch); controls.append(&fast_loading_switch);
let list_selection = gtk::SingleSelection::new(None::<gio::ListModel>); let list_box = gtk::ListBox::new();
let list_view = list_box.set_selection_mode(gtk::SelectionMode::Single);
gtk::ListView::new(Some(list_selection.clone()), None::<gtk::ListItemFactory>); list_box.set_activate_on_single_click(false);
list_view.set_single_click_activate(false);
let scrolled = gtk::ScrolledWindow::builder() let scrolled = gtk::ScrolledWindow::builder()
.vexpand(true) .vexpand(true)
.child(&list_view) .child(&list_box)
.build(); .build();
let status_label = gtk::Label::builder().xalign(0.0).build(); let status_label = gtk::Label::builder().xalign(0.0).build();
@ -155,18 +148,16 @@ impl ComicWindow {
location_dropdown, location_dropdown,
edit_location_button, edit_location_button,
delete_location_button, delete_location_button,
clear_recent_button: clear_recent_button.clone(),
path_entry, path_entry,
search_entry, search_entry,
sort_dropdown, sort_dropdown,
direction_button, direction_button,
list_view, list_box,
list_selection,
status_label, status_label,
state: RefCell::new(BrowserState { state: RefCell::new(BrowserState {
profile_index: 0, profile_index: 0,
favorite_profile: None, favorite_profile: None,
mode: BrowserMode::Directory, browsing_favorites: false,
root_uri: root_uri.clone(), root_uri: root_uri.clone(),
current_uri: root_uri, current_uri: root_uri,
entries: Vec::new(), entries: Vec::new(),
@ -213,7 +204,7 @@ impl ComicWindow {
struct BrowserState { struct BrowserState {
profile_index: usize, profile_index: usize,
favorite_profile: Option<LocationProfile>, favorite_profile: Option<LocationProfile>,
mode: BrowserMode, browsing_favorites: bool,
root_uri: String, root_uri: String,
current_uri: String, current_uri: String,
entries: Vec<BrowserEntry>, entries: Vec<BrowserEntry>,
@ -225,13 +216,6 @@ struct BrowserState {
typeahead_last_input: Option<Instant>, typeahead_last_input: Option<Instant>,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BrowserMode {
Directory,
Favorites,
Recent,
}
struct BrowserController { struct BrowserController {
window: gtk::ApplicationWindow, window: gtk::ApplicationWindow,
about_button: gtk::Button, about_button: gtk::Button,
@ -239,13 +223,11 @@ struct BrowserController {
location_dropdown: gtk::DropDown, location_dropdown: gtk::DropDown,
edit_location_button: gtk::Button, edit_location_button: gtk::Button,
delete_location_button: gtk::Button, delete_location_button: gtk::Button,
clear_recent_button: gtk::Button,
path_entry: gtk::Entry, path_entry: gtk::Entry,
search_entry: gtk::SearchEntry, search_entry: gtk::SearchEntry,
sort_dropdown: gtk::DropDown, sort_dropdown: gtk::DropDown,
direction_button: gtk::ToggleButton, direction_button: gtk::ToggleButton,
list_view: gtk::ListView, list_box: gtk::ListBox,
list_selection: gtk::SingleSelection,
status_label: gtk::Label, status_label: gtk::Label,
state: RefCell<BrowserState>, state: RefCell<BrowserState>,
config: RefCell<AppConfig>, config: RefCell<AppConfig>,
@ -313,10 +295,8 @@ impl BrowserController {
let Some(controller) = controller.upgrade() else { let Some(controller) = controller.upgrade() else {
return; return;
}; };
match special_browser_mode(item.position(), controller.profiles().len()) { if is_favorites_selection(item.position(), controller.profiles().len()) {
Some(BrowserMode::Favorites) => controller.show_favorites(), controller.show_favorites();
Some(BrowserMode::Recent) => controller.show_recent(),
_ => {}
} }
}); });
label.add_controller(click); label.add_controller(click);
@ -348,50 +328,16 @@ impl BrowserController {
case_insensitive_check.connect_toggled(move |check| { case_insensitive_check.connect_toggled(move |check| {
controller.set_case_insensitive_sort(check); controller.set_case_insensitive_sort(check);
}); });
let factory = gtk::SignalListItemFactory::new();
let controller = Rc::downgrade(self);
factory.connect_setup(move |_, item| {
let Some(item) = item.downcast_ref::<gtk::ListItem>() 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);
});
let controller = Rc::downgrade(self);
factory.connect_bind(move |_, item| {
let Some(item) = item.downcast_ref::<gtk::ListItem>() else {
return;
};
let Some(content) = item.child().and_downcast::<gtk::Box>() 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); let controller = Rc::clone(self);
self.list_view self.list_box
.connect_activate(move |_, position| controller.activate_row(position)); .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);
});
self.list_box.add_controller(context_click);
let key_controller = gtk::EventControllerKey::new(); let key_controller = gtk::EventControllerKey::new();
let controller = Rc::clone(self); let controller = Rc::clone(self);
@ -403,7 +349,7 @@ impl BrowserController {
controller.typeahead(key, modifiers) controller.typeahead(key, modifiers)
} }
}); });
self.list_view.add_controller(key_controller); self.list_box.add_controller(key_controller);
let mouse_back = gtk::GestureClick::builder() let mouse_back = gtk::GestureClick::builder()
.button(MOUSE_BACK_BUTTON) .button(MOUSE_BACK_BUTTON)
@ -423,9 +369,6 @@ impl BrowserController {
let controller = Rc::clone(self); let controller = Rc::clone(self);
self.clear_cache_button self.clear_cache_button
.connect_clicked(move |_| controller.show_clear_cache_dialog()); .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<LocationProfile> { fn profiles(&self) -> Vec<LocationProfile> {
@ -451,7 +394,6 @@ impl BrowserController {
.map(|profile| profile.name.clone()) .map(|profile| profile.name.clone())
.collect(); .collect();
names.push("즐겨찾기".into()); names.push("즐겨찾기".into());
names.push("최근 열어본 파일".into());
let names: Vec<_> = names.iter().map(String::as_str).collect(); let names: Vec<_> = names.iter().map(String::as_str).collect();
self.location_dropdown self.location_dropdown
.set_model(Some(&gtk::StringList::new(&names))); .set_model(Some(&gtk::StringList::new(&names)));
@ -460,16 +402,9 @@ impl BrowserController {
fn select_profile(self: &Rc<Self>) { fn select_profile(self: &Rc<Self>) {
let profile_index = self.location_dropdown.selected() as usize; let profile_index = self.location_dropdown.selected() as usize;
let profiles = self.profiles(); let profiles = self.profiles();
match special_browser_mode(self.location_dropdown.selected(), profiles.len()) { if is_favorites_selection(self.location_dropdown.selected(), profiles.len()) {
Some(BrowserMode::Favorites) => { self.show_favorites();
self.show_favorites(); return;
return;
}
Some(BrowserMode::Recent) => {
self.show_recent();
return;
}
_ => {}
} }
let editable = profile_index > 0 && profile_index < profiles.len(); let editable = profile_index > 0 && profile_index < profiles.len();
self.edit_location_button.set_sensitive(editable); self.edit_location_button.set_sensitive(editable);
@ -483,11 +418,10 @@ impl BrowserController {
let mut state = self.state.borrow_mut(); let mut state = self.state.borrow_mut();
state.profile_index = profile_index; state.profile_index = profile_index;
state.favorite_profile = None; state.favorite_profile = None;
state.mode = BrowserMode::Directory; state.browsing_favorites = false;
state.root_uri = root_uri.clone(); state.root_uri = root_uri.clone();
state.current_uri = root_uri; state.current_uri = root_uri;
drop(state); drop(state);
self.update_mode_controls(BrowserMode::Directory);
self.path_entry.set_editable(true); self.path_entry.set_editable(true);
self.search_entry.set_text(""); self.search_entry.set_text("");
self.refresh(); self.refresh();
@ -513,58 +447,24 @@ impl BrowserController {
state.generation = state.generation.wrapping_add(1); state.generation = state.generation.wrapping_add(1);
state.typeahead_query.clear(); state.typeahead_query.clear();
state.typeahead_last_input = None; state.typeahead_last_input = None;
state.mode = BrowserMode::Favorites; state.browsing_favorites = true;
state.favorite_profile = None; state.favorite_profile = None;
state.entries = entries; state.entries = entries;
drop(state); drop(state);
self.update_mode_controls(BrowserMode::Favorites);
self.search_entry.set_text(""); self.search_entry.set_text("");
self.render(); 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<Self>, favorite: FavoriteEntry) { fn open_favorite(self: &Rc<Self>, favorite: FavoriteEntry) {
let Ok(root) = root_file(&favorite.profile) else { let Ok(root) = root_file(&favorite.profile) else {
self.status_label self.status_label
.set_text("저장된 파일의 위치 정보가 올바르지 않습니다."); .set_text("즐겨찾기의 저장된 위치가 올바르지 않습니다.");
return; return;
}; };
let favorite_file = gio::File::for_uri(&favorite.uri); let favorite_file = gio::File::for_uri(&favorite.uri);
if !is_within_root(&favorite_file, &root) { if !is_within_root(&favorite_file, &root) {
self.status_label self.status_label
.set_text("저장된 파일이 위치의 루트 밖을 가리킵니다."); .set_text("즐겨찾기가 저장된 위치의 루트 밖을 가리킵니다.");
return; return;
} }
if favorite.is_directory { if favorite.is_directory {
@ -574,18 +474,17 @@ impl BrowserController {
self.delete_location_button.set_sensitive(false); self.delete_location_button.set_sensitive(false);
let mut state = self.state.borrow_mut(); let mut state = self.state.borrow_mut();
state.favorite_profile = Some(favorite.profile.clone()); state.favorite_profile = Some(favorite.profile.clone());
state.mode = BrowserMode::Directory; state.browsing_favorites = false;
state.root_uri = root.uri().into(); state.root_uri = root.uri().into();
state.current_uri = favorite.uri; state.current_uri = favorite.uri;
drop(state); drop(state);
self.update_mode_controls(BrowserMode::Directory);
self.search_entry.set_text(""); self.search_entry.set_text("");
self.refresh(); self.refresh();
return; return;
} }
self.cancel_listing(); self.cancel_listing();
self.status_label.set_text("저장된 파일에 연결하는 중..."); self.status_label.set_text("즐겨찾기에 연결하는 중...");
let operation = mount_operation(&favorite.profile, &self.window); let operation = mount_operation(&favorite.profile, &self.window);
let controller = Rc::downgrade(self); let controller = Rc::downgrade(self);
let task = glib::MainContext::default().spawn_local(async move { let task = glib::MainContext::default().spawn_local(async move {
@ -618,7 +517,7 @@ impl BrowserController {
if !kind.is_viewable() { if !kind.is_viewable() {
controller controller
.status_label .status_label
.set_text("이 파일 형식은 열 수 없습니다."); .set_text("이 즐겨찾기 파일 형식은 열 수 없습니다.");
return; return;
} }
let entry = folder_entries let entry = folder_entries
@ -655,7 +554,8 @@ impl BrowserController {
} }
fn open_entered_path(self: &Rc<Self>) { fn open_entered_path(self: &Rc<Self>) {
if self.state.borrow().mode != BrowserMode::Directory { let browsing_favorites = self.state.borrow().browsing_favorites;
if browsing_favorites {
return; return;
} }
let profile = self.current_profile(); let profile = self.current_profile();
@ -672,7 +572,8 @@ impl BrowserController {
} }
fn go_up(self: &Rc<Self>) { fn go_up(self: &Rc<Self>) {
if self.state.borrow().mode != BrowserMode::Directory { let browsing_favorites = self.state.borrow().browsing_favorites;
if browsing_favorites {
return; return;
} }
let state = self.state.borrow(); let state = self.state.borrow();
@ -686,17 +587,10 @@ impl BrowserController {
} }
fn refresh(self: &Rc<Self>) { fn refresh(self: &Rc<Self>) {
let mode = self.state.borrow().mode; let browsing_favorites = self.state.borrow().browsing_favorites;
match mode { if browsing_favorites {
BrowserMode::Favorites => { self.show_favorites();
self.show_favorites(); return;
return;
}
BrowserMode::Recent => {
self.show_recent();
return;
}
BrowserMode::Directory => {}
} }
self.cancel_listing(); self.cancel_listing();
let (profile, uri, generation) = { let (profile, uri, generation) = {
@ -715,7 +609,9 @@ impl BrowserController {
state.generation, state.generation,
) )
}; };
self.list_selection.set_model(None::<&gio::ListModel>); while let Some(child) = self.list_box.first_child() {
self.list_box.remove(&child);
}
self.path_entry.set_text(&display_uri(&uri)); self.path_entry.set_text(&display_uri(&uri));
self.status_label self.status_label
.set_text("폴더를 불러오는 중... (0개의 파일/폴더를 읽음)"); .set_text("폴더를 불러오는 중... (0개의 파일/폴더를 읽음)");
@ -727,8 +623,7 @@ impl BrowserController {
let Some(controller) = progress_controller.upgrade() else { let Some(controller) = progress_controller.upgrade() else {
return; return;
}; };
let state = controller.state.borrow(); if controller.state.borrow().generation == generation {
if state.generation == generation && state.mode == BrowserMode::Directory {
controller.status_label.set_text(&format!( controller.status_label.set_text(&format!(
"폴더를 불러오는 중... ({count}개의 파일/폴더를 읽음)" "폴더를 불러오는 중... ({count}개의 파일/폴더를 읽음)"
)); ));
@ -739,7 +634,7 @@ impl BrowserController {
return; return;
}; };
let state = controller.state.borrow(); let state = controller.state.borrow();
let stale = state.generation != generation || state.mode != BrowserMode::Directory; let stale = state.generation != generation || state.browsing_favorites;
drop(state); drop(state);
if stale { if stale {
return; return;
@ -762,6 +657,9 @@ impl BrowserController {
} }
fn render(&self) { 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 query = self.search_entry.text().to_lowercase();
let case_insensitive = self.config.borrow().case_insensitive_sort; let case_insensitive = self.config.borrow().case_insensitive_sort;
let mut state = self.state.borrow_mut(); let mut state = self.state.borrow_mut();
@ -771,23 +669,17 @@ impl BrowserController {
.filter(|entry| browser_search_match(entry, query.as_str())) .filter(|entry| browser_search_match(entry, query.as_str()))
.cloned() .cloned()
.collect(); .collect();
if state.mode != BrowserMode::Recent { sort_entries(
sort_entries( &mut visible_entries,
&mut visible_entries, state.sort_field,
state.sort_field, state.sort_direction,
state.sort_direction, case_insensitive,
case_insensitive, );
); for entry in &visible_entries {
self.list_box.append(&entry_row(entry));
} }
let count = visible_entries.len(); let count = visible_entries.len();
let names = visible_entries
.iter()
.map(BrowserEntry::display_name)
.collect::<Vec<_>>();
let model = gtk::StringList::new(&names);
state.visible_entries = visible_entries; state.visible_entries = visible_entries;
drop(state);
self.list_selection.set_model(Some(&model));
self.status_label.set_text(&format!("{count}개 항목")); self.status_label.set_text(&format!("{count}개 항목"));
} }
@ -820,8 +712,7 @@ impl BrowserController {
return glib::Propagation::Proceed; return glib::Propagation::Proceed;
}; };
let selected = (self.list_selection.selected() != gtk::INVALID_LIST_POSITION) let selected = self.list_box.selected_row().map(|row| row.index() as usize);
.then(|| self.list_selection.selected() as usize);
let now = Instant::now(); let now = Instant::now();
let mut state = self.state.borrow_mut(); let mut state = self.state.borrow_mut();
if state if state
@ -847,12 +738,11 @@ impl BrowserController {
let found_name = found.map(|index| state.visible_entries[index].display_name().to_owned()); let found_name = found.map(|index| state.visible_entries[index].display_name().to_owned());
drop(state); drop(state);
if let Some(index) = found { if let Some(index) = found
self.list_view.scroll_to( && let Some(row) = self.list_box.row_at_index(index as i32)
index as u32, {
gtk::ListScrollFlags::FOCUS | gtk::ListScrollFlags::SELECT, self.list_box.select_row(Some(&row));
None, let _ = row.grab_focus();
);
self.status_label.set_text(&format!( self.status_label.set_text(&format!(
"'{query}'로 이동: {}", "'{query}'로 이동: {}",
found_name.unwrap_or_default() found_name.unwrap_or_default()
@ -893,7 +783,7 @@ impl BrowserController {
self.render(); self.render();
} }
fn activate_row(self: &Rc<Self>, index: u32) { fn activate_row(self: &Rc<Self>, index: i32) {
let Some(entry) = self let Some(entry) = self
.state .state
.borrow() .borrow()
@ -903,40 +793,19 @@ impl BrowserController {
else { else {
return; return;
}; };
let mode = self.state.borrow().mode; let browsing_favorites = self.state.borrow().browsing_favorites;
match mode { if browsing_favorites {
BrowserMode::Favorites => { let favorite = self
let favorite = self .config
.config .borrow()
.borrow() .favorites
.favorites .iter()
.iter() .find(|favorite| favorite.uri == entry.uri)
.find(|favorite| favorite.uri == entry.uri) .cloned();
.cloned(); if let Some(favorite) = favorite {
if let Some(favorite) = favorite { self.open_favorite(favorite);
self.open_favorite(favorite);
}
return;
} }
BrowserMode::Recent => { return;
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 { match entry.kind {
EntryKind::Directory => { EntryKind::Directory => {
@ -1081,9 +950,9 @@ impl BrowserController {
state.sort_direction, state.sort_direction,
case_insensitive, case_insensitive,
); );
let mode = state.mode; let browsing_favorites = state.browsing_favorites;
drop(state); drop(state);
if mode == BrowserMode::Directory && entries.iter().any(|entry| entry.uri == current_uri) { if !browsing_favorites && entries.iter().any(|entry| entry.uri == current_uri) {
Rc::new(entries) Rc::new(entries)
} else { } else {
Rc::clone(fallback) Rc::clone(fallback)
@ -1097,8 +966,6 @@ impl BrowserController {
profile: LocationProfile, profile: LocationProfile,
reuse_window: Option<gtk::ApplicationWindow>, reuse_window: Option<gtk::ApplicationWindow>,
) { ) {
let recent_entry = entry.clone();
let recent_profile = profile.clone();
self.status_label.set_text("ZIP 파일 다운로드 준비 중..."); self.status_label.set_text("ZIP 파일 다운로드 준비 중...");
let progress_label = reuse_window.as_ref().map_or_else( let progress_label = reuse_window.as_ref().map_or_else(
|| self.status_label.clone(), || self.status_label.clone(),
@ -1125,7 +992,6 @@ impl BrowserController {
} }
match result { match result {
Ok(source) => { Ok(source) => {
controller.record_recent_file(&recent_entry, &recent_profile);
controller.status_label.set_text("다운로드 완료"); controller.status_label.set_text("다운로드 완료");
result_label.set_text("ZIP 파일을 여는 중..."); result_label.set_text("ZIP 파일을 여는 중...");
let Some(application) = controller.window.application() else { let Some(application) = controller.window.application() else {
@ -1167,8 +1033,6 @@ impl BrowserController {
profile: LocationProfile, profile: LocationProfile,
reuse_window: Option<gtk::ApplicationWindow>, reuse_window: Option<gtk::ApplicationWindow>,
) { ) {
let recent_entry = entry.clone();
let recent_profile = profile.clone();
let kind = entry.kind; let kind = entry.kind;
self.status_label self.status_label
.set_text("미디어 파일 다운로드 준비 중..."); .set_text("미디어 파일 다운로드 준비 중...");
@ -1197,7 +1061,6 @@ impl BrowserController {
} }
match result { match result {
Ok(source) => { Ok(source) => {
controller.record_recent_file(&recent_entry, &recent_profile);
controller.status_label.set_text("다운로드 완료"); controller.status_label.set_text("다운로드 완료");
result_label.set_text("미디어 파일을 여는 중..."); result_label.set_text("미디어 파일을 여는 중...");
let Some(application) = controller.window.application() else { let Some(application) = controller.window.application() else {
@ -1228,16 +1091,27 @@ impl BrowserController {
); );
} }
fn show_context_menu( fn show_context_menu(self: &Rc<Self>, x: f64, y: f64) {
self: &Rc<Self>, let Some(widget) = self.list_box.pick(x, y, gtk::PickFlags::DEFAULT) else {
position: u32, return;
parent: &impl glib::object::IsA<gtk::Widget>, };
) { let Some(row) = widget
.clone()
.downcast::<gtk::ListBoxRow>()
.ok()
.or_else(|| {
widget
.ancestor(gtk::ListBoxRow::static_type())
.and_then(|widget| widget.downcast::<gtk::ListBoxRow>().ok())
})
else {
return;
};
let Some(entry) = self let Some(entry) = self
.state .state
.borrow() .borrow()
.visible_entries .visible_entries
.get(position as usize) .get(row.index() as usize)
.cloned() .cloned()
else { else {
return; return;
@ -1247,9 +1121,9 @@ impl BrowserController {
if !can_favorite && !can_download { if !can_favorite && !can_download {
return; return;
} }
self.list_selection.set_selected(position); self.list_box.select_row(Some(&row));
let popover = gtk::Popover::new(); let popover = gtk::Popover::new();
popover.set_parent(parent); popover.set_parent(&row);
let actions = gtk::Box::new(gtk::Orientation::Vertical, 4); let actions = gtk::Box::new(gtk::Orientation::Vertical, 4);
actions.set_margin_top(6); actions.set_margin_top(6);
actions.set_margin_bottom(6); actions.set_margin_bottom(6);
@ -1310,32 +1184,16 @@ impl BrowserController {
} }
fn profile_for_entry(&self, entry: &BrowserEntry) -> LocationProfile { fn profile_for_entry(&self, entry: &BrowserEntry) -> LocationProfile {
match self.state.borrow().mode { if self.state.borrow().browsing_favorites
BrowserMode::Favorites => { && let Some(profile) = self
if let Some(profile) = self .config
.config .borrow()
.borrow() .favorites
.favorites .iter()
.iter() .find(|favorite| favorite.uri == entry.uri)
.find(|favorite| favorite.uri == entry.uri) .map(|favorite| favorite.profile.clone())
.map(|favorite| favorite.profile.clone()) {
{ return profile;
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() self.current_profile()
} }
@ -1567,14 +1425,13 @@ impl BrowserController {
let uri: String = directory.uri().into(); let uri: String = directory.uri().into();
let mut state = self.state.borrow_mut(); let mut state = self.state.borrow_mut();
state.favorite_profile = Some(profile); state.favorite_profile = Some(profile);
state.mode = BrowserMode::Directory; state.browsing_favorites = false;
state.root_uri = uri.clone(); state.root_uri = uri.clone();
state.current_uri = uri.clone(); state.current_uri = uri.clone();
state.entries = entries; state.entries = entries;
state.typeahead_query.clear(); state.typeahead_query.clear();
state.typeahead_last_input = None; state.typeahead_last_input = None;
drop(state); drop(state);
self.update_mode_controls(BrowserMode::Directory);
self.path_entry.set_text(&display_uri(&uri)); self.path_entry.set_text(&display_uri(&uri));
self.search_entry.set_text(""); self.search_entry.set_text("");
self.render(); self.render();
@ -1644,7 +1501,8 @@ impl BrowserController {
return was_active; return was_active;
} }
*self.config.borrow_mut() = updated; *self.config.borrow_mut() = updated;
if self.state.borrow().mode == BrowserMode::Favorites { let browsing_favorites = self.state.borrow().browsing_favorites;
if browsing_favorites {
self.show_favorites(); self.show_favorites();
} }
self.status_label.set_text(if active { self.status_label.set_text(if active {
@ -1655,28 +1513,6 @@ impl BrowserController {
active 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( fn choose_download_destination(
self: &Rc<Self>, self: &Rc<Self>,
entry: BrowserEntry, entry: BrowserEntry,
@ -2113,58 +1949,6 @@ impl BrowserController {
}); });
dialog.present(); dialog.present();
} }
fn show_clear_recent_dialog(self: &Rc<Self>) {
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<()> { fn install_latest_update() -> Result<()> {
@ -2370,53 +2154,37 @@ fn display_uri(uri: &str) -> String {
) )
} }
fn entry_content() -> gtk::Box { fn entry_row(entry: &BrowserEntry) -> gtk::ListBoxRow {
let row = gtk::ListBoxRow::new();
let content = gtk::Box::new(gtk::Orientation::Horizontal, 12); let content = gtk::Box::new(gtk::Orientation::Horizontal, 12);
content.set_margin_top(8); content.set_margin_top(8);
content.set_margin_bottom(8); content.set_margin_bottom(8);
content.set_margin_start(10); content.set_margin_start(10);
content.set_margin_end(10); content.set_margin_end(10);
content.append(&gtk::Image::new()); let icon = match entry.kind {
content.append(
&gtk::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: &gtk::Box, entry: &BrowserEntry) {
let icon_name = match entry.kind {
EntryKind::Directory => "folder-symbolic", EntryKind::Directory => "folder-symbolic",
EntryKind::ZipArchive => "package-x-generic-symbolic", EntryKind::ZipArchive => "package-x-generic-symbolic",
EntryKind::Image => "image-x-generic-symbolic", EntryKind::Image => "image-x-generic-symbolic",
EntryKind::Video => "video-x-generic-symbolic", EntryKind::Video => "video-x-generic-symbolic",
EntryKind::OtherFile => "text-x-generic-symbolic", EntryKind::OtherFile => "text-x-generic-symbolic",
}; };
let Some(icon) = content.first_child().and_downcast::<gtk::Image>() else { content.append(&gtk::Image::from_icon_name(icon));
return; content.append(
}; &gtk::Label::builder()
icon.set_icon_name(Some(icon_name)); .label(entry.display_name())
let Some(name) = icon.next_sibling().and_downcast::<gtk::Label>() else { .hexpand(true)
return; .xalign(0.0)
}; .ellipsize(gtk::pango::EllipsizeMode::Middle)
name.set_text(entry.display_name()); .build(),
let Some(modified) = name.next_sibling().and_downcast::<gtk::Label>() else { );
return; for time in [entry.modified, entry.created] {
}; let label = gtk::Label::new(Some(&format_time(time)));
modified.set_text(&format_time(entry.modified)); label.set_width_chars(17);
let Some(created) = modified.next_sibling().and_downcast::<gtk::Label>() else { label.set_xalign(1.0);
return; content.append(&label);
}; }
created.set_text(&format_time(entry.created)); row.set_child(Some(&content));
row
} }
fn format_time(time: Option<std::time::SystemTime>) -> String { fn format_time(time: Option<std::time::SystemTime>) -> String {
@ -2450,15 +2218,8 @@ fn browser_search_match(entry: &BrowserEntry, lowercase_query: &str) -> bool {
lowercase_query.is_empty() || entry.name.to_lowercase().contains(lowercase_query) lowercase_query.is_empty() || entry.name.to_lowercase().contains(lowercase_query)
} }
fn special_browser_mode(selected: u32, profile_count: usize) -> Option<BrowserMode> { fn is_favorites_selection(selected: u32, profile_count: usize) -> bool {
if selected == gtk::INVALID_LIST_POSITION { selected != gtk::INVALID_LIST_POSITION && selected as usize == profile_count
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( fn sorted_navigable_entries(
@ -2512,32 +2273,6 @@ 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( fn show_viewer_loading(
window: &gtk::ApplicationWindow, window: &gtk::ApplicationWindow,
file_name: &str, file_name: &str,
@ -2828,62 +2563,9 @@ mod tests {
assert_eq!(folder.kind, EntryKind::Directory); assert_eq!(folder.kind, EntryKind::Directory);
assert_eq!(archive.kind, EntryKind::ZipArchive); assert_eq!(archive.kind, EntryKind::ZipArchive);
assert_eq!(special_browser_mode(3, 3), Some(BrowserMode::Favorites)); assert!(is_favorites_selection(3, 3));
assert_eq!(special_browser_mode(4, 3), Some(BrowserMode::Recent)); assert!(!is_favorites_selection(2, 3));
assert_eq!(special_browser_mode(2, 3), None); assert!(!is_favorites_selection(gtk::INVALID_LIST_POSITION, 3));
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::<Vec<_>>();
assert_eq!(
kinds,
[EntryKind::Video, EntryKind::Image, EntryKind::ZipArchive]
);
} }
#[test] #[test]