team-ljyzipelo

공개
4,416줄179 KB
1#[cfg(all(feature = "ui-fixture", debug_assertions))]
2#[path = "../../../tests/rust-app-ui/scenarios.rs"]
3pub mod scenarios;
4
5use crate::{
6 archive_browser as browser,
7 archive_dialog::{
8 DIALOG_UNAVAILABLE, DialogAnswer, DialogRequest, Dialogs, NativeDialogs, PendingDialog,
9 Purpose,
10 },
11 archive_present as present,
12 archive_theme::{self as theme, Icon},
13 archive_ui::*,
14 window_frame,
15};
16use eframe::egui::{self, Align, Layout, RichText};
17use std::{
18 collections::BTreeSet,
19 path::{Path, PathBuf},
20};
21
22const WORK_WIDTH: f32 = 480.0;
23const CREATE_WIDTH: f32 = 560.0;
24/// 처음 열 때의 높이. 그다음부터는 내용 높이에 맞춤.
25const CREATE_MIN_HEIGHT: f32 = 560.0;
26const CREATE_LIST_HEIGHT: f32 = 288.0;
27
28/// ZIP 만들기 창 목록의 한 행. 디스크에서 읽은 파일이나 폴더임.
29#[derive(Clone)]
30struct SourceRow {
31 name: String,
32 directory: bool,
33 bytes: Option<u64>,
34}
35
36fn source_row(path: &Path) -> SourceRow {
37 let metadata = std::fs::symlink_metadata(path).ok();
38 SourceRow {
39 name: path
40 .file_name()
41 .map(|name| name.to_string_lossy().into_owned())
42 .unwrap_or_default(),
43 // 심볼릭 링크는 따라가지 않으므로 폴더로 보이지 않음.
44 directory: metadata.as_ref().is_some_and(|m| m.is_dir()),
45 bytes: metadata.filter(|m| m.is_file()).map(|m| m.len()),
46 }
47}
48
49/// 폴더 안 항목을 메인 목록과 같은 순서(폴더 먼저, 이름순)로 읽음. 읽지 못하면 None.
50fn read_source_dir(dir: &Path) -> Option<std::rc::Rc<Vec<SourceRow>>> {
51 let mut rows = std::fs::read_dir(dir)
52 .ok()?
53 .filter_map(Result::ok)
54 .map(|entry| source_row(&entry.path()))
55 .collect::<Vec<_>>();
56 rows.sort_by(|a, b| {
57 b.directory
58 .cmp(&a.directory)
59 .then_with(|| a.name.cmp(&b.name))
60 });
61 Some(std::rc::Rc::new(rows))
62}
63
64/// 덮어쓴 뒤 버려 메모리에 암호가 남지 않게 함.
65fn wipe(value: &mut String) {
66 let mut bytes = std::mem::take(value).into_bytes();
67 bytes.fill(0);
68}
69const WORK_MIN_HEIGHT: f32 = 96.0;
70const WORK_MAX_HEIGHT: f32 = 520.0;
71const WORK_RESULT_MAX_HEIGHT: f32 = 220.0;
72
73/// 작업 진행·결과를 보여주는 자식 창의 위치 상태.
74/// 부모 창 기준 상대 위치를 기억해 두고, 부모 창이 움직이면 같은 상대 위치로 따라감.
75struct WorkWindow {
76 open: bool,
77 created: bool,
78 initial: Option<egui::Pos2>,
79 offset: Option<egui::Vec2>,
80 parent: Option<egui::Pos2>,
81 expected: Option<egui::Pos2>,
82 settle_until: f64,
83 height: f32,
84}
85
86impl Default for WorkWindow {
87 fn default() -> Self {
88 Self {
89 open: false,
90 created: false,
91 initial: None,
92 offset: None,
93 parent: None,
94 expected: None,
95 settle_until: 0.0,
96 height: 168.0,
97 }
98 }
99}
100
101impl WorkWindow {
102 /// 부모 창 가운데에 열고, 사용자가 옮긴 상대 위치를 유지한 채 부모 창을 따라가게 함.
103 /// 앱을 쓰는 동안에만 부모 위에 두고, 처음 위치를 담은 ViewportBuilder를 돌려줌.
104 /// Wayland처럼 창 위치를 알 수 없으면 위치는 창 관리자에 맡김.
105 fn builder(
106 &mut self,
107 ctx: &egui::Context,
108 id: egui::ViewportId,
109 size: egui::Vec2,
110 title: &str,
111 decorations: bool,
112 native_dialog_open: bool,
113 ) -> egui::ViewportBuilder {
114 let (parent, parent_focused, now) =
115 ctx.input(|i| (i.viewport().outer_rect, i.viewport().focused, i.time));
116 let (child, child_focused) = ctx.input(|i| {
117 i.raw
118 .viewports
119 .get(&id)
120 .map_or((None, None), |v| (v.outer_rect, v.focused))
121 });
122 let initial_focus_unknown =
123 !self.created && parent_focused.is_none() && child_focused.is_none();
124 self.created = true;
125 let opening = !self.open;
126 if opening {
127 // 처음 열 때 부모 창 가운데에 둠. 닫혔다 다시 열 때는 기억한 위치에 둠.
128 self.open = true;
129 self.initial = parent.map(|p| match self.offset {
130 Some(offset) => (p.min + offset).round(),
131 None => (p.center() - size / 2.0).round(),
132 });
133 self.offset = self.initial.zip(parent).map(|(c, p)| c - p.min);
134 self.parent = parent.map(|p| p.min);
135 self.expected = self.initial;
136 self.settle_until = now + 0.5;
137 }
138 if let (Some(parent), Some(child)) = (parent, child) {
139 let parent_moved = self.parent.is_some_and(|p| (p - parent.min).length() > 0.5);
140 let settled = self
141 .expected
142 .is_some_and(|e| (child.min - e).length() <= 2.0);
143 if settled || now >= self.settle_until {
144 self.settle_until = 0.0;
145 }
146 if parent_moved {
147 if let Some(offset) = self.offset {
148 let target = (parent.min + offset).round();
149 ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
150 self.expected = Some(target);
151 self.settle_until = now + 0.5;
152 }
153 } else if self.settle_until == 0.0 && !settled {
154 // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
155 self.offset = Some(child.min - parent.min);
156 self.expected = Some(child.min);
157 }
158 self.parent = Some(parent.min);
159 }
160 let mut builder = egui::ViewportBuilder::default()
161 .with_title(title)
162 .with_icon(crate::app_icon::load())
163 .with_decorations(decorations)
164 .with_inner_size(size)
165 .with_resizable(false)
166 .with_minimize_button(false)
167 .with_maximize_button(false)
168 .with_taskbar(false)
169 .with_window_level(
170 if !native_dialog_open
171 && (initial_focus_unknown
172 || parent_focused == Some(true)
173 || child_focused == Some(true))
174 {
175 egui::WindowLevel::AlwaysOnTop
176 } else {
177 egui::WindowLevel::Normal
178 },
179 );
180 if let Some(position) = self.initial {
181 builder = builder.with_position(position);
182 }
183 builder
184 }
185}
186
187struct Marquee {
188 // 스크롤 중에도 시작점을 목록 좌표로 유지함.
189 origin: egui::Pos2,
190 base: BTreeSet<u32>,
191 moved: bool,
192}
193
194/// 파일 목록 한 행의 높이. 행 안의 크기 칸(theme::ROW)이 위아래 2px 여백으로 들어감.
195const LIST_ROW: f32 = 36.0;
196
197/// 기본 프로그램으로 열려고 임시 폴더에 푸는 작업. 끝나면 원래 풀 위치로 되돌림.
198struct OpenRequest {
199 folder: PathBuf,
200 /// 풀린 뒤 열 파일의 압축파일 안 경로. 작업자는 새로 만든 상위 폴더도 출력으로 알리므로
201 /// 출력 목록에서 이 경로와 같은 항목을 찾아 엶.
202 name: String,
203 destination: PathBuf,
204 automatic: bool,
205}
206
207/// 찾기 창(Ctrl+F, Ctrl+Shift+F) 크기. 검색어 입력란 아래로 결과 목록이 길게 이어지는
208/// 작은 세로 창임.
209const FIND_WIDTH: f32 = 360.0;
210const FIND_HEIGHT: f32 = 560.0;
211/// 찾기 결과 한 줄(이름과 상위 경로 두 줄)의 높이.
212const FIND_ROW: f32 = 48.0;
213
214/// 찾기 창 상태.
215#[derive(Default)]
216struct FindState {
217 open: bool,
218 /// true면 압축파일 전체의 전체 경로에서 찾음(Ctrl+Shift+F).
219 /// false면 연 폴더 아래의 하위 폴더를 따라 이름에서 찾음(Ctrl+F).
220 whole_path: bool,
221 /// Ctrl+F를 누른 때 보고 있던 폴더.
222 base: String,
223 query: String,
224 results: Vec<browser::Found>,
225 truncated: bool,
226 /// 결과를 마지막으로 계산한 조건. 바뀐 경우에만 다시 찾음.
227 key: Option<(String, bool, String, usize)>,
228 cursor: Option<usize>,
229 focus_query: bool,
230 scroll_to_cursor: bool,
231 offset: f32,
232 win: WorkWindow,
233}
234
235/// 파일 목록의 오른쪽 클릭 메뉴에서 고른 동작.
236enum MenuAction {
237 NewFolder,
238 ChooseFolder,
239}
240
241type Opener = Box<dyn FnMut(&Path) -> Result<(), String>>;
242
243pub struct ArchiveApp {
244 pub model: Model,
245 factory: Box<dyn Factory>,
246 destination: PathBuf,
247 automatic_destination: bool,
248 owned_destination: Option<PathBuf>,
249 gzip_name: String,
250 sources: Vec<PathBuf>,
251 zip_folder: PathBuf,
252 zip_name: String,
253 password: String,
254 password_confirm: String,
255 password_visible: bool,
256 password_challenge: Option<u64>,
257 conflict_challenge: Option<(u64, u64)>,
258 conflict_apply: bool,
259 aes256: bool,
260 create: bool,
261 selected_only: bool,
262 method: Method,
263 seven_zip: bool,
264 /// 7z 만들기에서 "쪼갤 용량 설정"을 켰는지와 입력한 볼륨 크기.
265 split: bool,
266 split_amount: String,
267 split_unit: present::VolumeUnit,
268 dialogs: Box<dyn Dialogs>,
269 picker: Option<(Purpose, std::sync::mpsc::Receiver<DialogAnswer>)>,
270 preview_open: bool,
271 preview_name: String,
272 preview_text: String,
273 preview_texture: Option<egui::TextureHandle>,
274 preview_return_focus: Option<egui::Id>,
275 preview_initial_focus: bool,
276 work: WorkWindow,
277 work_in_parent: bool,
278 create_win: WorkWindow,
279 /// ZIP 만들기 창에서 보고 있는 폴더 (고른 폴더 기준 상대 경로, 비어 있으면 최상위).
280 create_folder: String,
281 create_listing: Option<(PathBuf, Option<std::rc::Rc<Vec<SourceRow>>>)>,
282 /// 마지막으로 누른 폴더 행 (이름, 프레임 번호, 시각). 두 번 누름을 직접 판단할 때 씀.
283 create_last_click: Option<(String, u64, f64)>,
284 /// ZIP 만들기 목록에서 한 번 눌러 선택한 항목 이름. 보고 있는 폴더가 바뀌면 지움.
285 create_selected: Option<String>,
286 zip_password: String,
287 zip_password_confirm: String,
288 zip_password_visible: bool,
289 /// 암호를 지웠으면 입력창의 실행 취소 기록도 다음 그리기 전에 지움.
290 forget_password_history: Vec<&'static str>,
291 /// 작업을 시작한 뒤 작업자가 암호를 요청하면 넘길 암호. 넘기거나 작업이 끝나면 지움.
292 pending_zip_password: Option<String>,
293 custom_frame: bool,
294 release_after_move: bool,
295 folder: String,
296 search: String,
297 list_anchor: Option<usize>,
298 list_cursor: Option<usize>,
299 list_offset: f32,
300 list_focused: bool,
301 marquee: Option<Marquee>,
302 last_request: Option<Start>,
303 recovery_warning: Option<(PathBuf, String)>,
304 targets: Option<BTreeSet<String>>,
305 directories: BTreeSet<String>,
306 dismissed: bool,
307 details: bool,
308 checked_destination: bool,
309 ui_error: Option<String>,
310 initialized: bool,
311 opening: Option<OpenRequest>,
312 /// 마지막 풀기가 기본 프로그램으로 열기였으면 그 항목. 다시 시도할 때 다시 엶.
313 last_open: Option<u32>,
314 /// 압축파일별 열기용 임시 폴더. 앱을 닫을 때 지움.
315 open_roots: Vec<(PathBuf, present::OpenRoot)>,
316 open_count: u64,
317 opener: Opener,
318 find: FindState,
319 /// 이번 화면에서 목록 선택 해제 등 다른 곳이 Esc를 이미 처리했는지.
320 escape_handled: bool,
321 /// 찾기 결과로 이동한 뒤 다음 화면에서 목록에 키보드 초점을 줌.
322 focus_list: bool,
323 /// 지난 화면 끝에 입력란(전체, 목록 위 검색란)에 초점이 있었는지.
324 /// egui는 Esc를 누른 화면이 시작될 때 초점을 먼저 해제하므로 지난 값을 씀.
325 text_focus_before: (bool, bool),
326 #[cfg(all(feature = "ui-fixture", debug_assertions))]
327 scenario_marquee: Option<egui::Rect>,
328 #[cfg(all(feature = "ui-fixture", debug_assertions))]
329 scenario_sources: Option<std::rc::Rc<Vec<SourceRow>>>,
330}
331
332impl ArchiveApp {
333 pub fn new(factory: Box<dyn Factory>, startup: Option<PathBuf>, _fixture: bool) -> Self {
334 let mut app = Self {
335 model: Model::default(),
336 factory,
337 destination: PathBuf::new(),
338 automatic_destination: true,
339 owned_destination: None,
340 gzip_name: String::new(),
341 sources: Vec::new(),
342 zip_folder: present::home_directory(),
343 zip_name: String::new(),
344 password: String::new(),
345 password_confirm: String::new(),
346 password_visible: false,
347 password_challenge: None,
348 conflict_challenge: None,
349 conflict_apply: false,
350 aes256: false,
351 create: false,
352 selected_only: false,
353 method: Method::Deflate,
354 seven_zip: false,
355 split: false,
356 split_amount: "100".into(),
357 split_unit: present::VolumeUnit::Mb,
358 dialogs: Box::new(NativeDialogs),
359 picker: None,
360 preview_open: false,
361 preview_name: String::new(),
362 preview_text: String::new(),
363 preview_texture: None,
364 preview_return_focus: None,
365 preview_initial_focus: false,
366 work: WorkWindow::default(),
367 work_in_parent: false,
368 create_win: WorkWindow::default(),
369 create_folder: String::new(),
370 create_listing: None,
371 create_last_click: None,
372 create_selected: None,
373 zip_password: String::new(),
374 zip_password_confirm: String::new(),
375 zip_password_visible: false,
376 forget_password_history: Vec::new(),
377 pending_zip_password: None,
378 custom_frame: false,
379 release_after_move: false,
380 folder: String::new(),
381 search: String::new(),
382 list_anchor: None,
383 list_cursor: None,
384 list_offset: 0.0,
385 list_focused: false,
386 marquee: None,
387 last_request: None,
388 recovery_warning: None,
389 targets: None,
390 directories: BTreeSet::new(),
391 dismissed: false,
392 details: false,
393 checked_destination: false,
394 ui_error: None,
395 initialized: false,
396 opening: None,
397 last_open: None,
398 open_roots: Vec::new(),
399 open_count: 0,
400 opener: Box::new(present::open_with_default),
401 find: FindState::default(),
402 escape_handled: false,
403 focus_list: false,
404 text_focus_before: (false, false),
405 #[cfg(all(feature = "ui-fixture", debug_assertions))]
406 scenario_marquee: None,
407 #[cfg(all(feature = "ui-fixture", debug_assertions))]
408 scenario_sources: None,
409 };
410 if let Some(path) = startup {
411 app.open_path(path);
412 }
413 app
414 }
415
416 pub fn set_dialogs(&mut self, dialogs: Box<dyn Dialogs>) {
417 self.dialogs = dialogs;
418 }
419
420 /// 파일을 기본 프로그램으로 여는 방법을 바꿈. 시험에서 실제 프로그램 실행을 막을 때 씀.
421 pub fn set_opener(&mut self, opener: Opener) {
422 self.opener = opener;
423 }
424
425 /// 압축파일 안 파일 하나를 임시 폴더에 풀고 기본 프로그램으로 엶.
426 pub fn open_entry(&mut self, entry_id: u32) -> bool {
427 self.release_open();
428 if !self.model.can_extract() || self.opening.is_some() {
429 return false;
430 }
431 let Some(entry) = self.model.entries.iter().find(|e| e.id == entry_id) else {
432 return false;
433 };
434 if entry.kind != Kind::File {
435 return false;
436 }
437 let name = if self
438 .model
439 .list_id
440 .as_ref()
441 .is_some_and(|id| id.format == Format::Gzip)
442 {
443 self.gzip_name.clone()
444 } else {
445 entry.name.clone()
446 };
447 if present::blocked_open(&name) {
448 // 압축을 풀지 않고 바로 안내만 함.
449 self.dismissed = false;
450 self.ui_error = Some(present::open_blocked_text(&name));
451 return false;
452 }
453 let Some(archive) = self.model.archive.clone() else {
454 return false;
455 };
456 let root = match self.open_roots.iter().find(|(a, _)| *a == archive) {
457 Some((_, root)) if root.is_current() => root.path().to_path_buf(),
458 _ => match present::create_open_root(&archive) {
459 Ok(root) => {
460 self.open_roots.retain(|(a, _)| *a != archive);
461 let path = root.path().to_path_buf();
462 self.open_roots.push((archive, root));
463 path
464 }
465 Err(_) => {
466 self.dismissed = false;
467 self.ui_error = Some(present::FOLDER_ERROR.into());
468 return false;
469 }
470 },
471 };
472 // 같은 파일을 여러 번 열어도 충돌하지 않도록 열 때마다 새 하위 폴더에 풂.
473 self.open_count += 1;
474 let folder = present::unique_folder(&root.join(self.open_count.to_string()));
475 let request = OpenRequest {
476 folder: folder.clone(),
477 name: name.replace('\\', "/"),
478 destination: std::mem::replace(&mut self.destination, folder),
479 automatic: std::mem::replace(&mut self.automatic_destination, true),
480 };
481 self.opening = Some(request);
482 if self.extract_selection(Selection::EntryIds(vec![entry_id])) {
483 self.last_open = Some(entry_id);
484 true
485 } else {
486 self.finish_open(false);
487 false
488 }
489 }
490
491 /// 한도를 늘려 다시 시도할 수 있는 결과가 화면에 남아 있는 동안은 열기 상태를 유지함.
492 fn open_retry_pending(&self) -> bool {
493 self.opening.is_some() && !self.dismissed && self.model.can_retry_expanded()
494 }
495
496 /// 다시 시도를 기다리던 열기를 접고 원래 풀 위치로 되돌림. 다른 작업을 시작하기 전에 씀.
497 fn release_open(&mut self) {
498 if self.opening.is_some() && !self.model.busy() {
499 self.finish_open(false);
500 }
501 }
502
503 /// 열기용 풀기가 끝나면 원래 풀 위치를 되돌리고, 성공했으면 기본 프로그램을 실행함.
504 fn finish_open(&mut self, completed: bool) {
505 let Some(request) = self.opening.take() else {
506 return;
507 };
508 self.destination = request.destination;
509 self.automatic_destination = request.automatic;
510 if !completed {
511 return;
512 }
513 let Some(name) = self
514 .model
515 .outputs
516 .iter()
517 .filter(|(_, d)| *d == Disposition::Created)
518 .map(|(name, _)| name.replace('\\', "/"))
519 .find(|name| name.trim_end_matches('/') == request.name)
520 else {
521 self.ui_error = Some(present::OPEN_MISSING.into());
522 return;
523 };
524 let path = name
525 .split('/')
526 .fold(request.folder, |path, part| path.join(part));
527 match (self.opener)(&path) {
528 // 결과 창 없이 바로 열린 파일을 보여 줌.
529 Ok(()) => self.dismissed = true,
530 Err(error) => self.ui_error = Some(error),
531 }
532 }
533
534 /// 압축파일 이름으로 새 폴더를 만들고(같은 이름이 있으면 번호를 붙임) 선택 항목을 풂.
535 fn extract_to_new_folder(&mut self) -> bool {
536 self.release_open();
537 let Some(archive) = self.model.archive.clone() else {
538 return false;
539 };
540 self.destination = present::unique_folder(&present::default_destination(&archive));
541 self.automatic_destination = true;
542 self.begin_extract()
543 }
544
545 /// 창 순서를 지정할 수 없는 환경에서는 부모 안에 작업 화면을 그림.
546 pub fn set_work_window_in_parent(&mut self, enabled: bool) {
547 self.work_in_parent = enabled;
548 }
549
550 /// 운영체제가 창 테두리를 그려 주지 않을 때(GNOME Wayland) 제목 표시줄을 직접 그림.
551 pub fn set_custom_frame(&mut self, custom: bool) {
552 self.custom_frame = custom;
553 }
554
555 pub fn browse_folder(&mut self, folder: &str) {
556 self.folder = folder.trim_matches('/').to_owned();
557 crate::log_trace!("폴더 이동: /{}", self.folder);
558 self.search.clear();
559 self.clear_list_selection();
560 }
561
562 /// 찾기 창이 열려 있는지.
563 pub fn find_open(&self) -> bool {
564 self.find.open
565 }
566
567 /// 찾기 창의 검색어. 시험과 UI 상황 미리보기에서 씀.
568 pub fn set_find_query(&mut self, query: &str) {
569 self.find.query = query.to_owned();
570 }
571
572 /// 찾기 창의 현재 결과.
573 pub fn find_results(&mut self) -> &[browser::Found] {
574 self.refresh_find();
575 &self.find.results
576 }
577
578 /// 찾기 창을 엶. `whole_path`가 false면(Ctrl+F) 지금 보고 있는 폴더 아래에서
579 /// 이름으로 찾고, true면(Ctrl+Shift+F) 압축파일 전체 경로에서 찾음.
580 /// 이미 열려 있으면 찾는 범위만 바꾸고 검색어는 유지함.
581 pub fn open_find(&mut self, whole_path: bool) -> bool {
582 if self.model.archive.is_none() || self.model.list_id.is_none() || self.model.busy() {
583 return false;
584 }
585 if !self.find.open {
586 self.find.win = WorkWindow::default();
587 }
588 self.find.open = true;
589 self.find.whole_path = whole_path;
590 self.find.base = if whole_path {
591 String::new()
592 } else {
593 self.folder.clone()
594 };
595 self.find.key = None;
596 self.find.cursor = None;
597 self.find.focus_query = true;
598 crate::log_debug!(
599 "찾기 창 열기: {}",
600 if whole_path {
601 "전체 경로".to_owned()
602 } else {
603 format!("/{} 아래", self.find.base)
604 }
605 );
606 true
607 }
608
609 pub fn close_find(&mut self) {
610 if self.find.open {
611 crate::log_debug!("찾기 창 닫기");
612 }
613 self.find.open = false;
614 self.find.win = WorkWindow::default();
615 self.find.results.clear();
616 self.find.key = None;
617 self.find.cursor = None;
618 }
619
620 fn refresh_find(&mut self) {
621 let key = (
622 self.find.query.clone(),
623 self.find.whole_path,
624 self.find.base.clone(),
625 self.model.entries.len(),
626 );
627 if self.find.key.as_ref() == Some(&key) {
628 return;
629 }
630 let (results, truncated) = browser::find(
631 &self.model.entries,
632 &self.find.base,
633 &self.find.query,
634 self.find.whole_path,
635 browser::FIND_LIMIT,
636 );
637 crate::log_trace!(
638 "찾기 '{}': {}개{}",
639 self.find.query,
640 results.len(),
641 if truncated { " (일부만 표시)" } else { "" }
642 );
643 self.find.results = results;
644 self.find.truncated = truncated;
645 self.find.cursor = self
646 .find
647 .cursor
648 .filter(|index| *index < self.find.results.len());
649 self.find.key = Some(key);
650 }
651
652 /// 찾기 결과로 이동함. 찾기 창을 닫고, 폴더면 그 폴더를 열고
653 /// 파일이면 들어 있는 폴더를 연 뒤 그 파일을 선택함.
654 pub fn go_to_found(&mut self, found: &browser::Found) {
655 crate::log_debug!("찾기 결과로 이동: /{}", found.path);
656 self.close_find();
657 if found.directory {
658 self.browse_folder(&found.path);
659 } else {
660 let parent = found
661 .path
662 .rsplit_once('/')
663 .map_or("", |(parent, _)| parent)
664 .to_owned();
665 self.browse_folder(&parent);
666 let rows = browser::rows(&self.model.entries, &self.folder, "");
667 if let Some(index) = rows.iter().position(|row| row.name == found.name) {
668 self.select_row(&rows, index, false, false);
669 // 선택한 행이 목록 위쪽에 보이도록 스크롤함.
670 self.list_offset = (index as f32 * LIST_ROW - 2.0 * LIST_ROW).max(0.0);
671 }
672 }
673 self.focus_list = true;
674 }
675
676 pub fn show_create(&mut self, encrypted: bool) {
677 if !self.model.busy() {
678 self.create = true;
679 self.aes256 = encrypted && !self.seven_zip;
680 self.ui_error = None;
681 }
682 }
683
684 fn clear_password(&mut self) {
685 for value in [&mut self.password, &mut self.password_confirm] {
686 let mut bytes = std::mem::take(value).into_bytes();
687 bytes.fill(0);
688 }
689 self.password_visible = false;
690 // 이 함수는 암호 요청이 없는 동안 매 프레임 불리므로, 암호 창을 쓴 뒤에만 기록을 지움.
691 if self.password_challenge.is_some() {
692 self.forget_password_history
693 .extend(["archive-password-input", "archive-password-confirm"]);
694 }
695 }
696
697 /// 지운 암호가 입력창의 실행 취소(Ctrl+Z)로 되살아나지 않게 egui가 보관하는
698 /// 입력창 상태(실행 취소 기록 포함)를 지움.
699 fn forget_password_history(&mut self, ctx: &egui::Context) {
700 if self.forget_password_history.is_empty() {
701 return;
702 }
703 let names = std::mem::take(&mut self.forget_password_history);
704 ctx.data_mut(|data| {
705 for name in names {
706 data.remove::<egui::text_edit::TextEditState>(egui::Id::unique(name));
707 }
708 });
709 }
710
711 fn clear_zip_password(&mut self) {
712 wipe(&mut self.zip_password);
713 wipe(&mut self.zip_password_confirm);
714 if let Some(mut pending) = self.pending_zip_password.take() {
715 wipe(&mut pending);
716 }
717 self.zip_password_visible = false;
718 self.forget_password_history
719 .extend(["zip-password-input", "zip-password-confirm"]);
720 }
721
722 /// 암호로 보호하지 않거나, 두 암호가 같고 1~1024바이트이면 만들 수 있음.
723 fn zip_password_ready(&self) -> bool {
724 !self.aes256
725 || (!self.zip_password.is_empty()
726 && self.zip_password.len() <= 1024
727 && self.zip_password == self.zip_password_confirm)
728 }
729
730 /// 7z 분할을 켰으면 볼륨 바이트 수. 입력이 잘못됐으면 화면에 보일 오류.
731 fn split_volume(&self) -> Result<Option<u64>, &'static str> {
732 if !self.seven_zip || !self.split {
733 return Ok(None);
734 }
735 present::volume_size(&self.split_amount, self.split_unit).map(Some)
736 }
737
738 fn close_create(&mut self) {
739 self.create = false;
740 self.ui_error = None;
741 self.clear_zip_password();
742 self.create_win = WorkWindow::default();
743 }
744
745 /// 압축하기: 묶을 폴더를 운영체제 폴더 선택 창에서 고른 뒤 ZIP 만들기 창을 엶.
746 fn choose_zip_folder(&mut self) {
747 if self.model.busy() || self.picker.is_some() {
748 return;
749 }
750 // 이미 열린 ZIP 만들기 창의 목록과 암호 설정은 새 폴더를 실제로 고른 뒤에만 바꿈.
751 // 선택을 취소하면 그대로 남음(apply_picker의 Purpose::Folder).
752 self.open_picker(Purpose::Folder);
753 }
754
755 /// 폴더 하나를 골랐으면 그 폴더 안을 목록으로 보여 줌. 여러 항목이면 그 항목들을 보여 줌.
756 fn create_root(&self) -> Option<PathBuf> {
757 (self.sources.len() == 1 && self.sources[0].is_dir()).then(|| self.sources[0].clone())
758 }
759
760 fn create_rows(&mut self) -> Option<std::rc::Rc<Vec<SourceRow>>> {
761 #[cfg(all(feature = "ui-fixture", debug_assertions))]
762 if let Some(rows) = &self.scenario_sources {
763 return Some(rows.clone());
764 }
765 let Some(root) = self.create_root() else {
766 return Some(std::rc::Rc::new(
767 self.sources.iter().map(|path| source_row(path)).collect(),
768 ));
769 };
770 let dir = if self.create_folder.is_empty() {
771 root
772 } else {
773 root.join(&self.create_folder)
774 };
775 // 프레임마다 디스크를 읽지 않도록 보고 있는 폴더가 바뀔 때만 다시 읽음.
776 if self
777 .create_listing
778 .as_ref()
779 .is_none_or(|(path, _)| path != &dir)
780 {
781 let rows = read_source_dir(&dir);
782 self.create_listing = Some((dir, rows));
783 }
784 self.create_listing
785 .as_ref()
786 .and_then(|(_, rows)| rows.clone())
787 }
788
789 pub fn open_path(&mut self, archive: PathBuf) {
790 if self.model.busy() {
791 return;
792 }
793 self.release_open();
794 if self
795 .recovery_warning
796 .as_ref()
797 .is_some_and(|(path, _)| path != &archive)
798 {
799 self.recovery_warning = None;
800 }
801 self.clear_password();
802 self.destination = present::default_destination(&archive);
803 self.automatic_destination = true;
804 self.gzip_name = present::gzip_output_name(&archive);
805 self.selected_only = false;
806 self.folder.clear();
807 self.search.clear();
808 self.clear_list_selection();
809 self.close_find();
810 self.targets = None;
811 self.directories.clear();
812 crate::log_debug!("압축파일 열기: {}", archive.display());
813 self.start(Start::List { archive });
814 }
815
816 fn start(&mut self, request: Start) -> bool {
817 // 파일 선택 창이 응답을 기다리는 동안에는 어느 창에서도 새 작업을 시작하지 않음.
818 if self.picker.is_some() {
819 return false;
820 }
821 if matches!(request, Start::RecoverZip { .. }) {
822 self.work = WorkWindow {
823 height: 480.0,
824 ..WorkWindow::default()
825 };
826 }
827 self.last_request = Some(request.clone());
828 self.dismissed = false;
829 self.details = false;
830 self.checked_destination = false;
831 self.ui_error = None;
832 self.model.begin(request, self.factory.as_mut())
833 }
834
835 pub fn choose_destination(&mut self, path: PathBuf) {
836 self.destination = path;
837 self.automatic_destination = false;
838 self.ui_error = None;
839 }
840
841 pub fn add_sources(&mut self, paths: Vec<PathBuf>) {
842 if self.model.busy() {
843 return;
844 }
845 let mut validated = Vec::new();
846 for path in paths {
847 let Ok(metadata) = std::fs::symlink_metadata(&path) else {
848 self.ui_error = Some("파일이나 폴더를 찾지 못했습니다. 다시 선택하세요".into());
849 return;
850 };
851 if metadata.file_type().is_symlink() || !(metadata.is_file() || metadata.is_dir()) {
852 self.ui_error = Some("일반 파일과 폴더만 추가할 수 있습니다".into());
853 return;
854 }
855 let Ok(path) = path.canonicalize() else {
856 return;
857 };
858 if path.to_str().is_none()
859 || !path
860 .file_name()
861 .and_then(|name| name.to_str())
862 .is_some_and(valid_leaf)
863 {
864 self.ui_error = Some("파일이나 폴더의 이름을 확인하세요".into());
865 return;
866 }
867 validated.push(crate::archive_path::worker_path(&path));
868 }
869 let paths = validated;
870 if self.sources.is_empty() {
871 if let Some(first) = paths.first() {
872 self.zip_folder = first.parent().unwrap_or(Path::new("/")).to_path_buf();
873 let name = if first.is_dir() {
874 first.file_name()
875 } else {
876 first.file_stem()
877 };
878 self.zip_name = format!(
879 "{}.{}",
880 name.unwrap_or_default().to_string_lossy(),
881 if self.seven_zip { "7z" } else { "zip" }
882 );
883 }
884 }
885 for path in paths {
886 if !self.sources.contains(&path) {
887 self.sources.push(path);
888 }
889 }
890 self.create_folder.clear();
891 self.create_listing = None;
892 self.create_selected = None;
893 self.create = true;
894 }
895
896 pub fn begin_extract(&mut self) -> bool {
897 self.release_open();
898 self.selected_only = !self.model.selected.is_empty();
899 let selection = if self.selected_only {
900 Selection::EntryIds(
901 browser::expand_selection(&self.model.entries, &self.model.selected)
902 .into_iter()
903 .collect(),
904 )
905 } else {
906 Selection::All
907 };
908 self.extract_selection(selection)
909 }
910
911 fn extract_selection(&mut self, selection: Selection) -> bool {
912 if !self.model.can_extract()
913 || matches!(&selection, Selection::EntryIds(ids) if ids.is_empty())
914 {
915 return false;
916 }
917 self.selected_only = matches!(&selection, Selection::EntryIds(_));
918 if self.opening.is_none() {
919 self.last_open = None;
920 }
921 match present::prepare_destination(&self.destination, self.automatic_destination) {
922 Ok(true) => self.owned_destination = Some(self.destination.clone()),
923 Ok(false) => self.owned_destination = None,
924 Err(_) => {
925 self.ui_error = Some(present::FOLDER_ERROR.into());
926 return false;
927 }
928 }
929 let gzip = self
930 .model
931 .list_id
932 .as_ref()
933 .is_some_and(|id| id.format == Format::Gzip);
934 self.targets = present::target_files(
935 &self.model.entries,
936 &selection,
937 gzip.then_some(self.gzip_name.as_str()),
938 );
939 self.directories = if gzip {
940 BTreeSet::new()
941 } else {
942 present::target_directories(&self.model.entries, &selection)
943 };
944 let request = Start::Extract {
945 archive: self.model.archive.clone().unwrap(),
946 destination: self.destination.clone(),
947 selection,
948 list_id: self.model.list_id.clone().unwrap(),
949 gzip_output_name: gzip.then(|| self.gzip_name.clone()),
950 };
951 if self.start(request) {
952 true
953 } else {
954 if let Some(path) = self.owned_destination.take() {
955 present::remove_owned_empty(&path);
956 }
957 false
958 }
959 }
960
961 fn begin_zip(&mut self) {
962 if self.sources.is_empty() {
963 return;
964 }
965 let extension = if self.seven_zip { ".7z" } else { ".zip" };
966 if !self.zip_name.to_ascii_lowercase().ends_with(extension) {
967 self.zip_name.push_str(extension);
968 }
969 if !valid_leaf(&self.zip_name) {
970 self.ui_error = Some("압축파일 이름을 확인하세요".into());
971 return;
972 }
973 let volume_size = match self.split_volume() {
974 Ok(size) => size,
975 Err(error) => {
976 self.ui_error = Some(error.into());
977 return;
978 }
979 };
980 let output_file = self.zip_folder.join(&self.zip_name);
981 if volume_size.is_some() {
982 // 분할 읽기는 같은 이름의 숫자 조각을 모두 한 묶음으로 보므로 하나라도 있으면 막음.
983 if let Some(existing) = present::existing_volume(&output_file) {
984 self.ui_error = Some(format!(
985 "같은 이름의 분할 파일({existing})이 이미 있습니다. 다른 이름을 입력하세요"
986 ));
987 return;
988 }
989 } else if std::fs::symlink_metadata(&output_file).is_ok() {
990 self.ui_error = Some("같은 이름의 파일이 이미 있습니다. 다른 이름을 입력하세요".into());
991 return;
992 }
993 let mut sources = Vec::new();
994 for path in &self.sources {
995 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
996 self.ui_error = Some(
997 "이름을 읽을 수 없는 파일이 있습니다. 파일 이름을 바꾼 뒤 다시 추가하세요"
998 .into(),
999 );
1000 return;
1001 };
1002 sources.push((path.clone(), name.to_owned()));
1003 }
1004 if self.seven_zip
1005 && (self.aes256
1006 || !self.zip_password.is_empty()
1007 || !self.zip_password_confirm.is_empty())
1008 {
1009 self.ui_error =
1010 Some("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요".into());
1011 return;
1012 }
1013 if !self.zip_password_ready() {
1014 self.ui_error = Some("두 암호가 같은지 확인하세요".into());
1015 return;
1016 }
1017 // 분할하면 볼륨 수를 미리 알 수 없으므로 결과 화면에서 보고된 수로 이름을 다시 정함.
1018 self.targets = Some(
1019 [if volume_size.is_some() {
1020 format!("{}.001", self.zip_name)
1021 } else {
1022 self.zip_name.clone()
1023 }]
1024 .into_iter()
1025 .collect(),
1026 );
1027 self.directories.clear();
1028 // 암호는 ZIP 만들기 창에서 받아 두었다가 작업자가 요청하면 넘김.
1029 let password = self.aes256.then(|| std::mem::take(&mut self.zip_password));
1030 let request = if self.seven_zip {
1031 Start::CreateSevenZip {
1032 sources,
1033 output_file,
1034 volume_size,
1035 }
1036 } else {
1037 Start::CreateZip {
1038 sources,
1039 output_file,
1040 method: self.method,
1041 aes256: self.aes256,
1042 }
1043 };
1044 // 한도 초과 뒤 보류된 열기는 만들기와 무관하므로 시작 전에 접음.
1045 self.release_open();
1046 if self.start(request) {
1047 self.create = false;
1048 self.create_win = WorkWindow::default();
1049 self.clear_zip_password();
1050 self.pending_zip_password = password;
1051 } else if let Some(password) = password {
1052 self.zip_password = password;
1053 }
1054 }
1055
1056 fn open_picker(&mut self, purpose: Purpose) {
1057 if self.model.busy() || self.picker.is_some() {
1058 return;
1059 }
1060 let gzip = self
1061 .model
1062 .list_id
1063 .as_ref()
1064 .is_some_and(|id| id.format == Format::Gzip);
1065 let purpose = match (purpose, gzip) {
1066 (Purpose::Destination, true) => Purpose::SaveGzip,
1067 (Purpose::Retry, true) => Purpose::RetryGzip,
1068 _ => purpose,
1069 };
1070 let directory = match purpose {
1071 Purpose::SaveZip | Purpose::SaveSevenZip => self.zip_folder.clone(),
1072 Purpose::SaveRecoveryZip | Purpose::Destination | Purpose::SaveGzip => self
1073 .model
1074 .archive
1075 .as_ref()
1076 .and_then(|path| path.parent())
1077 .map(Path::to_path_buf)
1078 .unwrap_or_else(present::home_directory),
1079 Purpose::Retry | Purpose::RetryGzip => self.destination.clone(),
1080 _ => self
1081 .sources
1082 .last()
1083 .and_then(|path| path.parent())
1084 .map(Path::to_path_buf)
1085 .unwrap_or_else(present::home_directory),
1086 };
1087 let request = DialogRequest {
1088 purpose,
1089 directory,
1090 file_name: if purpose == Purpose::SaveRecoveryZip {
1091 let stem = self
1092 .model
1093 .archive
1094 .as_ref()
1095 .and_then(|p| p.file_stem())
1096 .unwrap_or_default()
1097 .to_string_lossy();
1098 format!("{stem}-recovered.zip")
1099 } else if matches!(purpose, Purpose::SaveGzip | Purpose::RetryGzip) {
1100 self.gzip_name.clone()
1101 } else {
1102 self.zip_name.clone()
1103 },
1104 };
1105 match self.dialogs.start(request) {
1106 PendingDialog::Ready(answer) => self.apply_picker(purpose, answer),
1107 PendingDialog::Waiting(receiver) => self.picker = Some((purpose, receiver)),
1108 }
1109 }
1110
1111 fn poll_picker(&mut self) {
1112 let Some((purpose, receiver)) = &self.picker else {
1113 return;
1114 };
1115 let purpose = *purpose;
1116 let answer = match receiver.try_recv() {
1117 Ok(answer) => answer,
1118 Err(std::sync::mpsc::TryRecvError::Empty) => return,
1119 Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(DIALOG_UNAVAILABLE.into()),
1120 };
1121 self.picker = None;
1122 self.apply_picker(purpose, answer);
1123 }
1124
1125 fn apply_picker(&mut self, purpose: Purpose, answer: DialogAnswer) {
1126 if answer.is_ok() && self.ui_error.as_deref() == Some(DIALOG_UNAVAILABLE) {
1127 self.ui_error = None;
1128 }
1129 match answer {
1130 Ok(Some(paths)) if !paths.is_empty() => {
1131 let path = paths[0].clone();
1132 match purpose {
1133 Purpose::SaveRecoveryZip => {
1134 if let Some(archive) = self.model.archive.clone() {
1135 self.start(Start::RecoverZip {
1136 archive,
1137 output_file: path,
1138 });
1139 }
1140 }
1141 Purpose::Open => {
1142 if std::fs::symlink_metadata(&path)
1143 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
1144 {
1145 self.open_path(path);
1146 } else {
1147 self.ui_error = Some("일반 압축파일을 선택하세요".into());
1148 }
1149 }
1150 Purpose::Files => self.add_sources(paths),
1151 Purpose::Folder => {
1152 // 새 폴더로 처음부터 시작함. 고른 폴더가 쓸 수 없으면 기존 내용을 되돌림.
1153 let previous = std::mem::take(&mut self.sources);
1154 self.add_sources(paths);
1155 if self.sources.is_empty() {
1156 self.sources = previous;
1157 } else {
1158 self.aes256 = false;
1159 self.clear_zip_password();
1160 self.ui_error = None;
1161 }
1162 }
1163 Purpose::Destination | Purpose::Retry => {
1164 // 다른 폴더를 골랐으면 기본 프로그램 열기가 아닌 일반 풀기로 다시 함.
1165 self.release_open();
1166 self.last_open = None;
1167 self.choose_destination(path);
1168 self.selected_only = !self.model.selected.is_empty();
1169 if purpose == Purpose::Retry {
1170 self.retry();
1171 } else {
1172 self.begin_extract();
1173 }
1174 }
1175 Purpose::SaveGzip | Purpose::RetryGzip => {
1176 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
1177 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
1178 return;
1179 };
1180 if !present::valid_output_leaf(name) {
1181 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
1182 return;
1183 }
1184 let name = name.to_owned();
1185 self.choose_destination(
1186 path.parent().unwrap_or(Path::new("/")).to_path_buf(),
1187 );
1188 self.gzip_name = name.clone();
1189 self.selected_only = !self.model.selected.is_empty();
1190 if purpose == Purpose::RetryGzip {
1191 if let Some(Start::Extract {
1192 gzip_output_name, ..
1193 }) = &mut self.last_request
1194 {
1195 *gzip_output_name = Some(name);
1196 }
1197 self.retry();
1198 } else {
1199 self.begin_extract();
1200 }
1201 }
1202 // 저장 위치를 고르는 사이 ZIP 만들기 창을 닫았으면 아무 작업도 시작하지 않음.
1203 Purpose::SaveZip | Purpose::SaveSevenZip if !self.create => {}
1204 Purpose::SaveZip | Purpose::SaveSevenZip => {
1205 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
1206 self.zip_name = name.to_owned();
1207 self.zip_folder = path.parent().unwrap_or(Path::new("/")).to_path_buf();
1208 self.begin_zip();
1209 }
1210 }
1211 }
1212 }
1213 Ok(_) => {}
1214 Err(error) => self.ui_error = Some(error),
1215 }
1216 }
1217
1218 fn retry(&mut self) {
1219 if let Some(request) = self.last_request.clone() {
1220 match request {
1221 Start::List { archive } => self.open_path(archive),
1222 Start::Preview { .. } | Start::RecoverZip { .. } => {}
1223 Start::Extract { .. } if let Some(entry_id) = self.last_open => {
1224 self.open_entry(entry_id);
1225 }
1226 Start::Extract {
1227 selection,
1228 gzip_output_name,
1229 ..
1230 } => {
1231 if let Some(name) = gzip_output_name {
1232 self.gzip_name = name;
1233 }
1234 self.extract_selection(selection);
1235 }
1236 Start::CreateSevenZip { volume_size, .. } => {
1237 self.set_seven_zip(true);
1238 self.create = true;
1239 self.split = volume_size.is_some();
1240 if let Some(size) = volume_size {
1241 let (amount, unit) = if size % (1 << 30) == 0 {
1242 (size >> 30, present::VolumeUnit::Gb)
1243 } else {
1244 (size >> 20, present::VolumeUnit::Mb)
1245 };
1246 self.split_amount = amount.to_string();
1247 self.split_unit = unit;
1248 }
1249 self.begin_zip();
1250 }
1251 Start::CreateZip { aes256, .. } => {
1252 self.set_seven_zip(false);
1253 self.create = true;
1254 if aes256 {
1255 // 암호는 보관하지 않으므로 ZIP 만들기 창에서 다시 받음.
1256 self.aes256 = true;
1257 } else {
1258 self.begin_zip();
1259 }
1260 }
1261 }
1262 }
1263 }
1264
1265 fn on_drop(&mut self, paths: Vec<PathBuf>) {
1266 if self.preview_open || self.model.busy() || paths.is_empty() {
1267 return;
1268 }
1269 if paths.len() == 1 && !self.create && !paths[0].is_dir() {
1270 if std::fs::symlink_metadata(&paths[0])
1271 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
1272 {
1273 self.open_path(paths[0].clone());
1274 } else {
1275 self.ui_error = Some("일반 압축파일을 선택하세요".into());
1276 }
1277 } else {
1278 self.add_sources(paths);
1279 }
1280 }
1281
1282 fn poll(&mut self) {
1283 let busy = self.model.busy();
1284 let close_before = self.model.close;
1285 self.model.poll();
1286 if close_before == Close::Confirm && self.model.close == Close::Review {
1287 // 종료 확인 창에 답하기 전에 작업이 끝났음. 사용자가 닫기를 승인하지 않았으므로
1288 // 바로 닫지 않고 계속 물음(close_dialog가 작업이 끝난 문구로 바꿔 보여 줌).
1289 self.model.close = Close::Confirm;
1290 }
1291 if busy && !self.model.busy() {
1292 let completed = self.model.confirmed
1293 && self
1294 .model
1295 .terminal
1296 .as_ref()
1297 .is_some_and(|t| t.outcome == Outcome::Completed);
1298 if self.opening.is_some() {
1299 // 열기용 폴더는 앱을 닫을 때 지우므로 풀 위치 소유 기록만 정리함.
1300 self.owned_destination = None;
1301 // 한도 실패는 늘려서 다시 시도할 수 있으므로 열기 상태를 남김.
1302 if completed || !self.open_retry_pending() {
1303 self.finish_open(completed);
1304 }
1305 }
1306 if let Some(path) = self.owned_destination.take() {
1307 if !self.model.confirmed
1308 || self
1309 .model
1310 .terminal
1311 .as_ref()
1312 .is_none_or(|t| t.outcome != Outcome::Completed)
1313 {
1314 present::remove_owned_empty(&path);
1315 }
1316 }
1317 }
1318 if self.opening.is_some() && !self.model.busy() && !self.open_retry_pending() {
1319 // 결과를 닫았거나 다시 시도할 수 없게 되었으면 원래 풀 위치로 되돌림.
1320 self.finish_open(false);
1321 }
1322 }
1323
1324 pub fn show(&mut self, root: &mut egui::Ui) {
1325 let ctx = root.ctx().clone();
1326 self.forget_password_history(&ctx);
1327 if !self.initialized {
1328 theme::apply(&ctx);
1329 self.initialized = true;
1330 }
1331 self.poll();
1332 let preview_was_open = self.preview_open;
1333 self.poll_picker();
1334 if self.model.challenge.is_some_and(|(_, _, encrypt)| encrypt)
1335 && let Some(password) = self.pending_zip_password.take()
1336 {
1337 // ZIP 만들기 창에서 받은 암호를 작업자의 암호 요청에 바로 넘김.
1338 self.model.password(password);
1339 }
1340 if !self.model.busy()
1341 && let Some(mut pending) = self.pending_zip_password.take()
1342 {
1343 wipe(&mut pending);
1344 }
1345 let challenge = self.model.challenge.map(|(id, _, _)| id);
1346 let new_challenge = challenge != self.password_challenge;
1347 if new_challenge || challenge.is_none() {
1348 self.clear_password();
1349 }
1350 self.password_challenge = challenge;
1351 // Esc 처리에 쓰려고 그리기 전에 입력란 초점과 열린 자식 창을 기억함.
1352 self.escape_handled = false;
1353 let (text_focused, main_search_focused) = self.text_focus_before;
1354 let child_open = self.child_window_open();
1355 if self.model.archive.is_some()
1356 && !self.main_modal_open()
1357 && !self.preview_open
1358 && self.model.close == Close::Open
1359 {
1360 // 더 구체적인 Ctrl+Shift+F를 먼저 확인함.
1361 if ctx.input_mut(|i| {
1362 i.consume_key(
1363 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1364 egui::Key::F,
1365 )
1366 }) {
1367 self.open_find(true);
1368 } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)) {
1369 self.open_find(false);
1370 }
1371 }
1372 let dropped = ctx.input(|i| {
1373 i.raw
1374 .dropped_files
1375 .iter()
1376 .map(|file| file.path().to_path_buf())
1377 .collect()
1378 });
1379 if self.picker.is_none() {
1380 self.on_drop(dropped);
1381 }
1382 if ctx.input(|i| i.viewport().close_requested()) {
1383 self.model.request_close();
1384 // 실행 중인 작업이 없으면 결과 확인 안내 없이 바로 닫음.
1385 self.model.acknowledge_close();
1386 if self.model.close != Close::Allowed {
1387 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
1388 }
1389 }
1390 if self.model.close == Close::Review {
1391 // 작업을 취소하고 닫기로 한 뒤 정리가 끝난 경우도 안내 없이 닫음.
1392 self.model.acknowledge_close();
1393 }
1394 if self.model.close == Close::Allowed {
1395 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
1396 }
1397 let title = self
1398 .model
1399 .archive
1400 .as_ref()
1401 .map(|path| {
1402 let full = if path.is_absolute() {
1403 path.clone()
1404 } else {
1405 std::env::current_dir().unwrap_or_default().join(path)
1406 };
1407 format!("{} — Zipelo", full.display())
1408 })
1409 .unwrap_or_else(|| "Zipelo".into());
1410 let short_title = if let Some(path) = title.strip_suffix(" — Zipelo") {
1411 format!(
1412 "{} — Zipelo",
1413 theme::window_title(root, path, ctx.content_rect().width() - 300.0)
1414 )
1415 } else {
1416 title.clone()
1417 };
1418 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
1419 if self.custom_frame
1420 && window_frame::title_bar(
1421 root,
1422 "main",
1423 &title,
1424 window_frame::Buttons {
1425 minimize: true,
1426 maximize: true,
1427 },
1428 )
1429 {
1430 self.release_after_move = true;
1431 }
1432 egui::Panel::top("archive-actions")
1433 .frame(
1434 theme::panel(theme::PANEL)
1435 .corner_radius(0)
1436 .inner_margin(egui::Margin {
1437 left: 12,
1438 right: 12,
1439 // 버튼 안 내용은 보이는 모양 기준으로 가운데에 두므로 위아래를 같게 둠.
1440 top: 4,
1441 bottom: 4,
1442 }),
1443 )
1444 .show(root, |ui| {
1445 ui.horizontal(|ui| {
1446 ui.spacing_mut().item_spacing.x = 2.0;
1447 let idle = !self.model.busy()
1448 && self.model.close == Close::Open
1449 && self.picker.is_none();
1450 if theme::tool(ui, "열기", theme::OPEN, idle, false)
1451 .on_hover_text(&title)
1452 .clicked()
1453 {
1454 self.open_picker(Purpose::Open);
1455 }
1456 if theme::tool(
1457 ui,
1458 "미리보기",
1459 theme::PREVIEW,
1460 idle && self.can_preview() && !self.preview_open,
1461 false,
1462 )
1463 .on_disabled_hover_text(
1464 if self.model.list_id.as_ref().is_some_and(ListId::is_split) {
1465 "분할 압축파일은 미리보기를 지원하지 않습니다"
1466 } else {
1467 "일반 파일 하나를 선택하세요"
1468 },
1469 )
1470 .clicked()
1471 {
1472 self.begin_preview(ui.ctx());
1473 }
1474 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
1475 self.choose_zip_folder();
1476 }
1477 if theme::tool(
1478 ui,
1479 "압축해제",
1480 theme::EXTRACT,
1481 self.model.can_extract(),
1482 true,
1483 )
1484 .clicked()
1485 {
1486 self.open_picker(Purpose::Destination);
1487 }
1488 });
1489 });
1490 egui::Panel::bottom("archive-status")
1491 .exact_size(theme::STATUS_HEIGHT)
1492 .resizable(false)
1493 .frame(
1494 egui::Frame::new()
1495 .fill(theme::STRIPE)
1496 .inner_margin(egui::Margin::symmetric(16, 0)),
1497 )
1498 .show(root, |ui| {
1499 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1500 let selected = rows
1501 .iter()
1502 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
1503 .count();
1504 let rect = ui.max_rect();
1505 let half = (rect.width() - theme::SPACE) / 2.0;
1506 theme::status_text(
1507 ui,
1508 rect,
1509 &format!("{}개 항목", rows.len()),
1510 half,
1511 Align::Min,
1512 );
1513 theme::status_text(ui, rect, &format!("선택 {selected}개"), half, Align::Max);
1514 });
1515 if ctx.embed_viewports()
1516 && !self.work_in_parent
1517 && self.work_visible()
1518 && !self.limit_result_visible()
1519 {
1520 // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
1521 egui::Panel::bottom("archive-work")
1522 .frame(theme::panel(theme::PANEL).corner_radius(0))
1523 .show(root, |ui| self.work_area(ui));
1524 }
1525 egui::CentralPanel::default()
1526 .frame(
1527 theme::panel(theme::PANEL)
1528 .corner_radius(0)
1529 .inner_margin(egui::Margin::ZERO),
1530 )
1531 .show(root, |ui| {
1532 if let Some((_, warning)) = &self.recovery_warning {
1533 ui.colored_label(theme::WARNING, warning);
1534 }
1535 if self.model.archive.is_some() {
1536 self.archive_list(ui);
1537 } else {
1538 self.empty(ui);
1539 }
1540 });
1541 self.forget_password_history(&ctx);
1542 self.preview_dialog(&ctx);
1543 self.work_window(&ctx);
1544 self.limit_result_dialog(&ctx);
1545 self.create_window(&ctx);
1546 self.find_window(&ctx);
1547 if self.model.challenge.is_some() {
1548 self.password_dialog(&ctx, new_challenge);
1549 }
1550 self.resource_dialog(&ctx);
1551 if self.model.conflict.is_some() && self.model.close == Close::Open {
1552 self.conflict_dialog(&ctx);
1553 }
1554 self.close_dialog(&ctx);
1555 self.picker_notice(&ctx);
1556 self.handle_escape(&ctx, text_focused, main_search_focused, child_open);
1557 self.text_focus_before = (
1558 ctx.text_edit_focused(),
1559 ctx.memory(|m| m.has_focus(egui::Id::unique("archive-search"))),
1560 );
1561 if !preview_was_open
1562 && !self.preview_open
1563 && !self.model.busy()
1564 && let Some(id) = self.preview_return_focus.take()
1565 {
1566 ctx.memory_mut(|m| m.request_focus(id));
1567 }
1568 if self.custom_frame {
1569 window_frame::edges(&ctx, true);
1570 }
1571 if self.model.busy() {
1572 ctx.request_repaint_after(std::time::Duration::from_millis(30));
1573 }
1574 }
1575
1576 /// 메인 창 위에 자식 창(모달, 작업 창, 만들기 창, 찾기 창 등)이 떠 있는지.
1577 fn child_window_open(&self) -> bool {
1578 self.find.open
1579 || self.preview_open
1580 || self.create
1581 || self.picker.is_some()
1582 || self.model.challenge.is_some()
1583 || self.model.resource.is_some()
1584 || self.model.conflict.is_some()
1585 || self.model.close != Close::Open
1586 || self.work_visible()
1587 }
1588
1589 /// 다른 곳에서 처리하지 않은 Esc를 처리함. 자식 창이 떠 있으면 그 창을 닫고,
1590 /// 아무 창도 없으면 프로그램을 종료함(작업 중이면 기존 종료 확인을 거침).
1591 /// 암호 입력, 미리보기 등 모달은 Esc를 직접 받아 닫으므로 여기까지 오지 않음.
1592 fn handle_escape(
1593 &mut self,
1594 ctx: &egui::Context,
1595 text_focused: bool,
1596 main_search_focused: bool,
1597 child_open: bool,
1598 ) {
1599 if self.escape_handled
1600 || self.picker.is_some()
1601 || !ctx.input(|i| i.key_pressed(egui::Key::Escape))
1602 {
1603 return;
1604 }
1605 let consume = |ctx: &egui::Context| {
1606 ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
1607 };
1608 if child_open {
1609 if self.find.open && !main_search_focused {
1610 consume(ctx);
1611 crate::log_debug!("Esc: 찾기 창 닫기");
1612 self.close_find();
1613 } else if matches!(self.model.close, Close::Confirm | Close::Waiting) {
1614 consume(ctx);
1615 crate::log_debug!("Esc: 종료 확인 취소");
1616 self.model.keep_open();
1617 } else if self.create && !self.model.busy() {
1618 consume(ctx);
1619 crate::log_debug!("Esc: 만들기 창 닫기");
1620 self.close_create();
1621 } else if !self.model.busy() && self.work_visible() {
1622 consume(ctx);
1623 crate::log_debug!("Esc: 작업 결과 창 닫기");
1624 self.dismissed = true;
1625 self.ui_error = None;
1626 self.model.input_error = None;
1627 }
1628 // 진행 중인 작업 창은 Esc로 닫지 않음. 취소는 [취소] 버튼으로 함.
1629 return;
1630 }
1631 if text_focused {
1632 // 입력란에서 누른 Esc는 입력란 초점만 해제함.
1633 return;
1634 }
1635 consume(ctx);
1636 crate::log_info!("Esc: 프로그램 종료 요청");
1637 ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close);
1638 }
1639
1640 /// 찾기 창. 진행·결과 창처럼 부모 창을 따라가는 별도 창으로 띄우고,
1641 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 창으로 띄움.
1642 fn find_window(&mut self, ctx: &egui::Context) {
1643 if !self.find.open {
1644 return;
1645 }
1646 if self.model.archive.is_none() || self.model.list_id.is_none() {
1647 self.close_find();
1648 return;
1649 }
1650 if self.main_modal_open() || self.preview_open {
1651 // 암호 입력 등 모달을 가리지 않게 잠시 숨김.
1652 self.find.win.open = false;
1653 return;
1654 }
1655 let title = if self.find.whole_path {
1656 "전체 경로에서 찾기"
1657 } else {
1658 "찾기"
1659 };
1660 let mut chosen = None;
1661 let mut close = false;
1662 if ctx.embed_viewports() || self.work_in_parent {
1663 egui::Window::new(title)
1664 .id(egui::Id::unique("archive-find-in-parent"))
1665 .title_bar(false)
1666 .default_pos(ctx.content_rect().right_top() + egui::vec2(-FIND_WIDTH - 24.0, 24.0))
1667 .default_width(FIND_WIDTH)
1668 .min_width(FIND_WIDTH)
1669 .max_width(FIND_WIDTH)
1670 .collapsible(false)
1671 .resizable(false)
1672 .fade_in(false)
1673 .fade_out(false)
1674 .frame(
1675 egui::Frame::new()
1676 .fill(theme::PANEL)
1677 .stroke(egui::Stroke::new(1.0, theme::BORDER))
1678 .inner_margin(egui::Margin::ZERO)
1679 .corner_radius(0),
1680 )
1681 .show(ctx, |ui| {
1682 let spacing = ui.spacing().item_spacing.y;
1683 ui.spacing_mut().item_spacing.y = 0.0;
1684 close = window_frame::in_parent_title(ui, "find-in-parent", title, true);
1685 egui::Frame::new()
1686 .inner_margin(egui::Margin::same(theme::PAD))
1687 .show(ui, |ui| {
1688 ui.spacing_mut().item_spacing.y = spacing;
1689 ui.set_width(FIND_WIDTH - 2.0 * theme::PAD as f32);
1690 let list_height = (ctx.content_rect().height() - 260.0)
1691 .clamp(120.0, FIND_HEIGHT - 200.0);
1692 chosen = self.find_contents(ui, list_height, false);
1693 });
1694 });
1695 } else {
1696 let id = egui::ViewportId::from_hash_of("archive-find");
1697 let window_title = format!("{title} — Zipelo");
1698 let custom_frame = self.custom_frame;
1699 let builder = self.find.win.builder(
1700 ctx,
1701 id,
1702 egui::vec2(FIND_WIDTH, FIND_HEIGHT),
1703 &window_title,
1704 !custom_frame,
1705 self.picker.is_some(),
1706 );
1707 ctx.show_viewport_immediate(id, builder, |ui, class| {
1708 if ui.ctx().input(|i| i.viewport().close_requested()) {
1709 close = true;
1710 }
1711 if ui
1712 .ctx()
1713 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
1714 {
1715 crate::log_debug!("Esc: 찾기 창 닫기");
1716 close = true;
1717 }
1718 // 찾기 창 안에서도 단축키로 찾는 범위를 바꿀 수 있음.
1719 if ui.ctx().input_mut(|i| {
1720 i.consume_key(
1721 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1722 egui::Key::F,
1723 )
1724 }) {
1725 self.find.whole_path = true;
1726 self.find.base.clear();
1727 self.find.focus_query = true;
1728 } else if ui
1729 .ctx()
1730 .input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F))
1731 {
1732 self.find.whole_path = false;
1733 self.find.base = self.folder.clone();
1734 self.find.focus_query = true;
1735 }
1736 if class == egui::ViewportClass::EmbeddedWindow {
1737 ui.set_width(FIND_WIDTH);
1738 chosen = self.find_contents(ui, FIND_HEIGHT - 200.0, false);
1739 return;
1740 }
1741 if custom_frame {
1742 window_frame::title_bar(
1743 ui,
1744 "find",
1745 &window_title,
1746 window_frame::Buttons {
1747 minimize: false,
1748 maximize: false,
1749 },
1750 );
1751 window_frame::edges(ui.ctx(), false);
1752 }
1753 egui::CentralPanel::default()
1754 .frame(
1755 theme::panel(theme::PANEL)
1756 .corner_radius(0)
1757 .inner_margin(egui::Margin::same(theme::PAD)),
1758 )
1759 .show(ui, |ui| {
1760 chosen = self.find_contents(ui, 0.0, true);
1761 });
1762 });
1763 }
1764 if let Some(found) = chosen {
1765 self.go_to_found(&found);
1766 } else if close {
1767 self.close_find();
1768 }
1769 }
1770
1771 /// 찾기 창 내용: 위쪽 검색어 입력란과 그 아래 세로로 긴 결과 목록.
1772 /// `list_height`가 0이면 남은 높이를 모두 목록에 씀. `own_keyboard`가 true면
1773 /// 창 전체가 찾기 창이므로 입력란에 초점이 없어도 화살표와 Enter를 받음.
1774 /// 결과를 골랐으면(더블클릭 또는 Enter) 그 결과를 돌려줌.
1775 fn find_contents(
1776 &mut self,
1777 ui: &mut egui::Ui,
1778 list_height: f32,
1779 own_keyboard: bool,
1780 ) -> Option<browser::Found> {
1781 self.refresh_find();
1782 let scope = if self.find.whole_path {
1783 "압축파일 전체 경로에서 찾습니다".to_owned()
1784 } else {
1785 format!("/{} 아래 모든 폴더에서 이름으로 찾습니다", self.find.base)
1786 };
1787 let width = ui.available_width();
1788 ui.add(egui::Label::new(RichText::new(&scope).color(theme::MUTED)).truncate())
1789 .on_hover_text(&scope);
1790 ui.add_space(theme::SPACE / 2.0);
1791 let query_id = egui::Id::unique("archive-find-query");
1792 let edit = ui.add(
1793 egui::TextEdit::singleline(&mut self.find.query)
1794 .id(query_id)
1795 .char_limit(512)
1796 .desired_width(width)
1797 .hint_text(if self.find.whole_path {
1798 "찾을 경로 입력"
1799 } else {
1800 "찾을 이름 입력"
1801 }),
1802 );
1803 theme::focus(&edit);
1804 if std::mem::take(&mut self.find.focus_query) {
1805 edit.request_focus();
1806 }
1807 if edit.changed() {
1808 self.refresh_find();
1809 self.find.cursor = (!self.find.results.is_empty()).then_some(0);
1810 self.find.offset = 0.0;
1811 self.find.scroll_to_cursor = true;
1812 }
1813 let keyboard = own_keyboard || edit.has_focus() || edit.lost_focus();
1814 let count = self.find.results.len();
1815 let mut chosen = None;
1816 if keyboard && count > 0 {
1817 let (down, up, enter) = ui.input(|i| {
1818 (
1819 i.key_pressed(egui::Key::ArrowDown),
1820 i.key_pressed(egui::Key::ArrowUp),
1821 i.key_pressed(egui::Key::Enter),
1822 )
1823 });
1824 if down || up {
1825 let index = match self.find.cursor {
1826 None => 0,
1827 Some(index) if down => (index + 1).min(count - 1),
1828 Some(index) => index.saturating_sub(1),
1829 };
1830 self.find.cursor = Some(index);
1831 self.find.scroll_to_cursor = true;
1832 }
1833 if enter {
1834 chosen = Some(self.find.cursor.unwrap_or(0));
1835 }
1836 }
1837 ui.add_space(theme::SPACE / 2.0);
1838 let status = if self.find.query.trim().is_empty() {
1839 "검색어를 입력하세요".to_owned()
1840 } else if count == 0 {
1841 "찾은 항목이 없습니다".to_owned()
1842 } else if self.find.truncated {
1843 format!("처음 {count}개만 표시합니다. 검색어를 더 구체적으로 입력하세요")
1844 } else {
1845 format!("{count}개 찾음 · 두 번 누르거나 Enter로 이동")
1846 };
1847 ui.add(
1848 egui::Label::new(
1849 RichText::new(status)
1850 .size(theme::FONT_SMALL)
1851 .color(theme::MUTED),
1852 )
1853 .truncate(),
1854 );
1855 ui.add_space(theme::SPACE / 2.0);
1856 let height = if list_height > 0.0 {
1857 list_height
1858 } else {
1859 ui.available_height().max(FIND_ROW)
1860 };
1861 let (frame_rect, _) =
1862 ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
1863 theme::boxed_field(ui, frame_rect);
1864 let mut list_ui = ui.new_child(
1865 egui::UiBuilder::new()
1866 .max_rect(frame_rect.shrink(1.0))
1867 .layout(Layout::top_down(Align::Min)),
1868 );
1869 let viewport_height = frame_rect.height() - 2.0;
1870 if self.find.scroll_to_cursor
1871 && let Some(index) = self.find.cursor
1872 {
1873 let top = index as f32 * FIND_ROW;
1874 if top < self.find.offset {
1875 self.find.offset = top;
1876 } else if top + FIND_ROW > self.find.offset + viewport_height {
1877 self.find.offset = top + FIND_ROW - viewport_height;
1878 }
1879 }
1880 let mut area = egui::ScrollArea::vertical()
1881 .id_salt("archive-find-results")
1882 .auto_shrink([false, false]);
1883 if std::mem::take(&mut self.find.scroll_to_cursor) {
1884 area = area.vertical_scroll_offset(self.find.offset);
1885 }
1886 let output = area.show_rows(&mut list_ui, FIND_ROW, count, |ui, range| {
1887 ui.spacing_mut().item_spacing.y = 0.0;
1888 let row_width = ui.available_width();
1889 for index in range {
1890 let found = &self.find.results[index];
1891 let (rect, response) =
1892 ui.allocate_exact_size(egui::vec2(row_width, FIND_ROW), egui::Sense::click());
1893 theme::pointer(&response);
1894 let parent = format!(
1895 "/{}",
1896 found.path.rsplit_once('/').map_or("", |(parent, _)| parent)
1897 );
1898 response.widget_info(|| {
1899 egui::WidgetInfo::selected(
1900 egui::Role::ListBoxOption,
1901 true,
1902 self.find.cursor == Some(index),
1903 &found.path,
1904 )
1905 });
1906 theme::row_background(
1907 ui,
1908 rect,
1909 self.find.cursor == Some(index),
1910 response.hovered(),
1911 );
1912 ui.scope_builder(
1913 egui::UiBuilder::new()
1914 .max_rect(rect.shrink2(egui::vec2(10.0, 4.0)))
1915 .layout(Layout::left_to_right(Align::Center)),
1916 |ui| {
1917 ui.style_mut().interaction.selectable_labels = false;
1918 theme::icon(
1919 ui,
1920 if found.directory {
1921 Icon::Folder
1922 } else {
1923 Icon::File
1924 },
1925 20.0,
1926 );
1927 ui.add_space(6.0);
1928 let text_width = ui.available_width();
1929 ui.vertical(|ui| {
1930 ui.spacing_mut().item_spacing.y = 0.0;
1931 theme::bounded_text_hover(ui, &found.name, &found.path, text_width);
1932 ui.add_sized(
1933 egui::vec2(text_width, 18.0),
1934 egui::Label::new(
1935 RichText::new(&parent)
1936 .size(theme::FONT_SMALL)
1937 .color(theme::MUTED),
1938 )
1939 .truncate(),
1940 );
1941 });
1942 },
1943 );
1944 if response.clicked() {
1945 self.find.cursor = Some(index);
1946 }
1947 if response.double_clicked() {
1948 chosen = Some(index);
1949 }
1950 }
1951 });
1952 self.find.offset = output.state.offset().y;
1953 chosen.and_then(|index| self.find.results.get(index).cloned())
1954 }
1955
1956 // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
1957 fn picker_notice(&mut self, ctx: &egui::Context) {
1958 if self.picker.is_none() {
1959 return;
1960 }
1961 egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
1962 ui.set_width(360.0);
1963 ui.label("파일 선택 창에서 선택을 마쳐 주세요");
1964 });
1965 ctx.request_repaint_after(std::time::Duration::from_millis(100));
1966 }
1967
1968 fn empty(&mut self, ui: &mut egui::Ui) {
1969 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
1970 let width = (ui.available_width() * 0.60)
1971 .max(480.0)
1972 .min(ui.available_width());
1973 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
1974 ui.add_space(y);
1975 ui.vertical_centered(|ui| {
1976 let drop_frame = egui::Frame::new()
1977 .fill(if hovered { theme::DROP } else { theme::PANEL })
1978 .corner_radius(theme::DROP_RADIUS)
1979 .inner_margin(egui::Margin::same(theme::DROP_PAD))
1980 .show(ui, |ui| {
1981 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
1982 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
1983 ui.vertical_centered(|ui| {
1984 ui.add_space(theme::PAD as f32);
1985 theme::icon(ui, Icon::Archive, 48.0);
1986 ui.add_space(theme::PAD as f32);
1987 ui.label(
1988 RichText::new(if hovered {
1989 "놓으면 엽니다"
1990 } else {
1991 "압축파일을 여기에 끌어 놓으세요"
1992 })
1993 .size(theme::FONT_LARGE)
1994 .strong(),
1995 );
1996 ui.label("또는");
1997 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
1998 self.open_picker(Purpose::Open);
1999 }
2000 });
2001 });
2002 let rect = drop_frame.response.rect;
2003 if hovered {
2004 ui.painter().rect_stroke(
2005 rect,
2006 12,
2007 egui::Stroke::new(2.0, theme::BLUE),
2008 egui::StrokeKind::Inside,
2009 );
2010 } else {
2011 let stroke = egui::Stroke::new(2.0, theme::DASH);
2012 for (a, b) in [
2013 (rect.left_top(), rect.right_top()),
2014 (rect.right_top(), rect.right_bottom()),
2015 (rect.right_bottom(), rect.left_bottom()),
2016 (rect.left_bottom(), rect.left_top()),
2017 ] {
2018 let direction = (b - a).normalized();
2019 let mut distance = theme::DROP_RADIUS as f32;
2020 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
2021 ui.painter().line_segment(
2022 [
2023 a + direction * distance,
2024 a + direction
2025 * (distance + theme::SPACE)
2026 .min(a.distance(b) - theme::DROP_RADIUS as f32),
2027 ],
2028 stroke,
2029 );
2030 distance += theme::PAD as f32;
2031 }
2032 }
2033 }
2034 ui.add_space(theme::PAD as f32);
2035 ui.colored_label(
2036 theme::MUTED,
2037 "ZIP, 7z, TAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ 파일을 열 수 있습니다",
2038 );
2039 });
2040 }
2041
2042 fn archive_list(&mut self, ui: &mut egui::Ui) {
2043 // 경로 줄은 입력란 높이만 차지하고 창 너비 전체를 회색으로 채움.
2044 let path_row = egui::Frame::new()
2045 .fill(theme::STRIPE)
2046 .inner_margin(egui::Margin {
2047 left: 8,
2048 right: 12,
2049 top: 0,
2050 bottom: 0,
2051 })
2052 .show(ui, |ui| {
2053 ui.set_min_width(ui.available_width());
2054 ui.horizontal(|ui| {
2055 ui.set_height(theme::FIELD);
2056 // 간격은 아래에서 직접 넣어 위치가 흔들리지 않게 함.
2057 ui.spacing_mut().item_spacing.x = 0.0;
2058 let up = theme::flat_icon_button(
2059 ui,
2060 "위로",
2061 theme::UP,
2062 !self.folder.is_empty() && !self.model.busy(),
2063 egui::vec2(theme::FIELD, theme::FIELD),
2064 );
2065 if up.clicked() {
2066 let parent = self
2067 .folder
2068 .rsplit_once('/')
2069 .map_or("", |(parent, _)| parent)
2070 .to_owned();
2071 self.browse_folder(&parent);
2072 }
2073 ui.add_space(6.0);
2074 let path = format!("/{}", self.folder);
2075 let search_width = 240.0;
2076 let gap = 8.0;
2077 let path_width = (ui.available_width() - search_width - gap).max(0.0);
2078 // 두 입력란은 같은 높이의 칸을 받아 같은 세로 위치에 그림.
2079 let (path_rect, _) = ui.allocate_exact_size(
2080 egui::vec2(path_width, theme::FIELD),
2081 egui::Sense::hover(),
2082 );
2083 theme::field_frame(ui, path_rect, false);
2084 // 부모 배치에 영향을 주지 않는 하위 영역에 경로 글자를 그림.
2085 let mut text_ui = ui.new_child(
2086 egui::UiBuilder::new()
2087 .max_rect(path_rect.shrink2(egui::vec2(10.0, 0.0)))
2088 .layout(Layout::left_to_right(Align::Center)),
2089 );
2090 theme::bounded_text(&mut text_ui, &path, (path_width - 20.0).max(0.0));
2091 ui.add_space(gap);
2092 let (search_rect, _) = ui.allocate_exact_size(
2093 egui::vec2(search_width, theme::FIELD),
2094 egui::Sense::hover(),
2095 );
2096 let search_id = egui::Id::unique("archive-search");
2097 let focused = ui.memory(|m| m.has_focus(search_id));
2098 theme::field_frame(ui, search_rect, focused);
2099 let icon = egui::Rect::from_center_size(
2100 egui::pos2(search_rect.left() + 20.0, search_rect.center().y),
2101 egui::vec2(16.0, 16.0),
2102 );
2103 theme::svg_icon(ui.painter(), icon, theme::SEARCH, theme::MUTED);
2104 let search = ui.put(
2105 egui::Rect::from_min_max(
2106 egui::pos2(icon.right() + 8.0, search_rect.top() + 1.0),
2107 egui::pos2(search_rect.right() - 8.0, search_rect.bottom() - 1.0),
2108 ),
2109 egui::TextEdit::singleline(&mut self.search)
2110 .id(search_id)
2111 .frame(egui::Frame::NONE)
2112 .margin(egui::Margin::ZERO)
2113 .align(egui::Align2::LEFT_CENTER)
2114 .hint_text("파일 검색"),
2115 );
2116 if search.changed() {
2117 self.clear_list_selection();
2118 }
2119 });
2120 })
2121 .response
2122 .rect;
2123 // 경로 줄 아래 한 줄이 목록과의 경계이자 입력란의 아래 테두리 역할을 함.
2124 ui.painter().hline(
2125 path_row.x_range(),
2126 path_row.bottom() - 0.5,
2127 egui::Stroke::new(1.0, theme::BORDER),
2128 );
2129 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
2130
2131 // 열 제목 줄 없이 바로 목록을 보여 줌. 이름과 크기는 내용으로 구분됨.
2132 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 40.0).max(120.0);
2133 let active = !self.preview_open
2134 && !self.model.busy()
2135 && !self.create
2136 && self.model.challenge.is_none()
2137 && self.model.close == Close::Open;
2138 let list_id = egui::Id::unique("archive-list");
2139 let background = ui.interact(
2140 ui.available_rect_before_wrap(),
2141 list_id,
2142 if active {
2143 egui::Sense::click_and_drag()
2144 } else {
2145 egui::Sense::hover()
2146 },
2147 );
2148 background
2149 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
2150 if active && std::mem::take(&mut self.focus_list) {
2151 background.request_focus();
2152 }
2153 if background.has_focus() {
2154 ui.ctx().memory_mut(|memory| {
2155 memory.set_focus_lock_filter(
2156 list_id,
2157 egui::EventFilter {
2158 vertical_arrows: true,
2159 escape: true,
2160 ..Default::default()
2161 },
2162 )
2163 });
2164 }
2165 let mut focused = None;
2166 let mut open = None;
2167 let mut open_file = None;
2168 let mut menu_action = None;
2169 let mut next_offset = None;
2170 let output = egui::ScrollArea::vertical()
2171 .id_salt("archive-rows")
2172 .auto_shrink([false, false])
2173 .vertical_scroll_offset(self.list_offset)
2174 .show_viewport(ui, |ui, viewport| {
2175 let origin = ui.max_rect().min;
2176 let clip = ui.clip_rect();
2177 // 행을 누르는 영역은 오른쪽 24px을 비워 둠. 목록이 길어도 그 빈 곳에서
2178 // 끌어서 선택을 시작할 수 있음. 행 배경(선택, 마우스 올림)은 너비를 꽉 채움.
2179 let full_width = ui.available_width();
2180 let width = (full_width - 24.0).max(0.0);
2181 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
2182 let point = ui.input(|i| i.pointer.interact_pos());
2183 if active && let Some(point) = point {
2184 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
2185 let relative = press - origin;
2186 let in_row = relative.x >= 0.0
2187 && relative.x <= width
2188 && relative.y >= 0.0
2189 && relative.y < rows.len() as f32 * LIST_ROW;
2190 // 목록 위에 떠 있는 창(부모 안 작업 창 등)을 누른 경우는 목록 조작이 아님.
2191 let on_list = ui.ctx().layer_id_at(press) == Some(ui.layer_id());
2192 if clip.contains(press)
2193 && on_list
2194 && !in_row
2195 && ui.input(|i| i.pointer.primary_pressed())
2196 {
2197 background.request_focus();
2198 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
2199 self.marquee = Some(Marquee {
2200 origin: relative.to_pos2(),
2201 base: if ctrl {
2202 self.model.selected.clone()
2203 } else {
2204 BTreeSet::new()
2205 },
2206 moved: false,
2207 });
2208 if !ctrl {
2209 self.model.selected.clear();
2210 self.list_anchor = None;
2211 self.list_cursor = None;
2212 }
2213 }
2214 if let Some(drag) = &mut self.marquee {
2215 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
2216 drag.moved |= drag.origin.distance(end) > 3.0;
2217 if drag.moved {
2218 let rect = egui::Rect::from_two_pos(drag.origin, end);
2219 self.model.selected = drag.base.clone();
2220 if rect.left() < width && rect.right() > 0.0 {
2221 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
2222 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
2223 .min(rows.len());
2224 for row in rows.iter().take(last).skip(first) {
2225 self.model.selected.extend(&row.ids);
2226 }
2227 if first < last {
2228 self.list_anchor = Some(first);
2229 self.list_cursor = Some(last - 1);
2230 }
2231 }
2232 let speed = if point.y > clip.bottom() - 24.0 {
2233 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
2234 } else if point.y < clip.top() + 24.0 {
2235 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
2236 } else {
2237 0.0
2238 };
2239 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
2240 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
2241 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
2242 0.0,
2243 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
2244 ));
2245 ui.ctx().request_repaint();
2246 }
2247 }
2248 }
2249 }
2250 let first = (viewport.min.y / LIST_ROW).floor() as usize;
2251 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
2252 for index in first.min(rows.len())..last {
2253 let row = &rows[index];
2254 let rect = egui::Rect::from_min_size(
2255 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
2256 egui::vec2(width, LIST_ROW),
2257 );
2258 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
2259 let response = ui
2260 .interact(
2261 rect,
2262 egui::Id::unique(("archive-row", &row.path)),
2263 if active {
2264 egui::Sense::click()
2265 } else {
2266 egui::Sense::hover()
2267 },
2268 )
2269 .on_hover_text(&row.name);
2270 theme::pointer(&response);
2271 response.widget_info(|| {
2272 egui::WidgetInfo::selected(
2273 egui::Role::ListBoxOption,
2274 active,
2275 selected,
2276 &row.name,
2277 )
2278 });
2279 if response.has_focus() {
2280 focused = Some(index);
2281 ui.ctx().memory_mut(|memory| {
2282 memory.set_focus_lock_filter(
2283 response.id,
2284 egui::EventFilter {
2285 vertical_arrows: true,
2286 escape: true,
2287 ..Default::default()
2288 },
2289 )
2290 });
2291 }
2292 theme::row_background(
2293 ui,
2294 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW)),
2295 selected,
2296 response.hovered(),
2297 );
2298 if response.clicked() {
2299 background.request_focus();
2300 let modifiers = ui.input(|i| i.modifiers);
2301 self.select_row(
2302 &rows,
2303 index,
2304 modifiers.ctrl || modifiers.command,
2305 modifiers.shift,
2306 );
2307 }
2308 if response.double_clicked() {
2309 if row.directory {
2310 open = Some(row.path.clone());
2311 } else if let [id] = row.ids.iter().copied().collect::<Vec<_>>()[..] {
2312 open_file = Some(id);
2313 }
2314 }
2315 if active && response.secondary_clicked() && !selected {
2316 // 선택하지 않은 행을 오른쪽 클릭하면 그 행만 선택한 뒤 메뉴를 엶.
2317 self.select_row(&rows, index, false, false);
2318 }
2319 if active {
2320 response.context_menu(|ui| {
2321 if ui
2322 .button("압축 파일명으로 새 폴더를 만들어 압축 풀기")
2323 .clicked()
2324 {
2325 menu_action = Some(MenuAction::NewFolder);
2326 }
2327 if ui.button("특정 폴더에 압축 풀기").clicked() {
2328 menu_action = Some(MenuAction::ChooseFolder);
2329 }
2330 });
2331 }
2332 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
2333 let name = if row.encrypted {
2334 format!("*{}", row.name)
2335 } else {
2336 row.name.clone()
2337 };
2338 Self::entry_cells(
2339 ui,
2340 rect,
2341 row.directory,
2342 &name,
2343 &row.name,
2344 row.bytes
2345 .map(present::bytes_text)
2346 .unwrap_or_else(|| "—".into()),
2347 name_width,
2348 );
2349 if active
2350 && self.list_cursor == Some(index)
2351 && (response.has_focus() || background.has_focus())
2352 {
2353 ui.painter().rect_stroke(
2354 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW))
2355 .shrink(1.0),
2356 0,
2357 egui::Stroke::new(1.0, theme::BLUE),
2358 egui::StrokeKind::Inside,
2359 );
2360 }
2361 }
2362 if rows.is_empty()
2363 && !(self.model.busy() && matches!(self.last_request, Some(Start::List { .. })))
2364 {
2365 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
2366 ui.centered_and_justified(|ui| {
2367 ui.label(if self.search.is_empty() {
2368 "이 폴더는 비어 있습니다"
2369 } else {
2370 "일치하는 항목이 없습니다"
2371 })
2372 });
2373 });
2374 }
2375 #[cfg(all(feature = "ui-fixture", debug_assertions))]
2376 if let Some(rect) = self.scenario_marquee {
2377 ui.painter().with_clip_rect(clip).rect(
2378 rect.translate(origin.to_vec2()),
2379 0,
2380 theme::BLUE.gamma_multiply(0.16),
2381 egui::Stroke::new(1.0, theme::BLUE),
2382 egui::StrokeKind::Inside,
2383 );
2384 }
2385 if let Some(drag) = &self.marquee
2386 && drag.moved
2387 && let Some(point) = point
2388 {
2389 let rect = egui::Rect::from_two_pos(
2390 origin + drag.origin.to_vec2(),
2391 point.clamp(clip.min, clip.max),
2392 );
2393 ui.painter().with_clip_rect(clip).rect(
2394 rect,
2395 0,
2396 theme::BLUE.gamma_multiply(0.16),
2397 egui::Stroke::new(1.0, theme::BLUE),
2398 egui::StrokeKind::Inside,
2399 );
2400 }
2401 });
2402 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
2403 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
2404 self.marquee = None;
2405 }
2406 let escape_from_list = self.list_focused
2407 && ui.ctx().memory(|memory| memory.focused()).is_none()
2408 && ui.input(|i| i.key_pressed(egui::Key::Escape));
2409 self.list_focused =
2410 active && (background.has_focus() || focused.is_some() || escape_from_list);
2411 if self.list_focused {
2412 if let Some(index) = focused {
2413 self.list_cursor = Some(index);
2414 }
2415 let modifiers = ui.input(|i| i.modifiers);
2416 let ctrl = modifiers.ctrl || modifiers.command;
2417 // 선택이 있으면 Esc는 선택만 해제함. 선택이 없으면 창 닫기로 넘김.
2418 if (!self.model.selected.is_empty() || self.marquee.is_some())
2419 && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
2420 {
2421 self.model.selected.clear();
2422 self.marquee = None;
2423 background.request_focus();
2424 self.escape_handled = true;
2425 }
2426 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
2427 self.model.selected = rows
2428 .iter()
2429 .flat_map(|row| row.ids.iter().copied())
2430 .collect();
2431 self.list_cursor = (!rows.is_empty()).then_some(0);
2432 self.list_anchor = self.list_cursor;
2433 }
2434 if !rows.is_empty() {
2435 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
2436 Some(1isize)
2437 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
2438 Some(-1)
2439 } else {
2440 None
2441 };
2442 if let Some(direction) = direction {
2443 let index = self.list_cursor.map_or(0, |index| {
2444 index.saturating_add_signed(direction).min(rows.len() - 1)
2445 });
2446 if ctrl && !modifiers.shift {
2447 self.list_cursor = Some(index);
2448 } else {
2449 self.select_row(&rows, index, ctrl, modifiers.shift);
2450 }
2451 background.request_focus();
2452 let top = index as f32 * LIST_ROW;
2453 if top < self.list_offset {
2454 self.list_offset = top;
2455 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
2456 self.list_offset = top + LIST_ROW - output.inner_rect.height();
2457 }
2458 ui.ctx().request_repaint();
2459 }
2460 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
2461 let index = self
2462 .list_cursor
2463 .or(focused)
2464 .unwrap_or(0)
2465 .min(rows.len() - 1);
2466 if rows[index].directory {
2467 open = Some(rows[index].path.clone());
2468 } else if let [id] = rows[index].ids.iter().copied().collect::<Vec<_>>()[..] {
2469 open_file = Some(id);
2470 }
2471 }
2472 }
2473 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
2474 open = Some(
2475 self.folder
2476 .rsplit_once('/')
2477 .map_or("", |(parent, _)| parent)
2478 .to_owned(),
2479 );
2480 }
2481 }
2482 // 마우스 옆 버튼(뒤로)을 목록 위에서 누르면 상위 폴더로 이동함.
2483 if active
2484 && !self.folder.is_empty()
2485 && ui.input(|i| {
2486 i.pointer.button_pressed(egui::PointerButton::Extra1)
2487 && i.pointer
2488 .interact_pos()
2489 .is_some_and(|pos| path_row.union(background.rect).contains(pos))
2490 })
2491 {
2492 open = Some(
2493 self.folder
2494 .rsplit_once('/')
2495 .map_or("", |(parent, _)| parent)
2496 .to_owned(),
2497 );
2498 }
2499 if let Some(folder) = open {
2500 self.browse_folder(&folder);
2501 background.request_focus();
2502 }
2503 if let Some(id) = open_file {
2504 self.open_entry(id);
2505 }
2506 match menu_action {
2507 Some(MenuAction::NewFolder) => {
2508 self.extract_to_new_folder();
2509 }
2510 Some(MenuAction::ChooseFolder) => self.open_picker(Purpose::Destination),
2511 None => {}
2512 }
2513 }
2514
2515 fn clear_list_selection(&mut self) {
2516 self.model.selected.clear();
2517 self.list_anchor = None;
2518 self.list_cursor = None;
2519 self.list_offset = 0.0;
2520 self.marquee = None;
2521 }
2522
2523 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
2524 if shift {
2525 let anchor = self
2526 .list_anchor
2527 .unwrap_or(self.list_cursor.unwrap_or(index))
2528 .min(rows.len() - 1);
2529 if !ctrl {
2530 self.model.selected.clear();
2531 }
2532 for row in &rows[anchor.min(index)..=anchor.max(index)] {
2533 self.model.selected.extend(&row.ids);
2534 }
2535 self.list_anchor = Some(anchor);
2536 } else {
2537 if !ctrl {
2538 self.model.selected.clear();
2539 }
2540 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
2541 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
2542 self.model
2543 .selected
2544 .retain(|id| !rows[index].ids.contains(id));
2545 } else {
2546 self.model.selected.extend(&rows[index].ids);
2547 }
2548 self.list_anchor = Some(index);
2549 }
2550 self.list_cursor = Some(index);
2551 }
2552
2553 fn result_visible(&self) -> bool {
2554 !self.dismissed
2555 && !self
2556 .last_request
2557 .as_ref()
2558 .is_some_and(|r| matches!(r, Start::Preview { .. }))
2559 && !self.model.busy()
2560 && self.last_request.as_ref().is_some_and(|request| {
2561 !matches!(request, Start::List { .. })
2562 || self.model.error.is_some()
2563 || self
2564 .model
2565 .terminal
2566 .as_ref()
2567 .is_some_and(|t| t.outcome != Outcome::Completed)
2568 })
2569 }
2570
2571 fn can_preview(&self) -> bool {
2572 self.model.can_preview()
2573 && browser::rows(&self.model.entries, &self.folder, &self.search)
2574 .iter()
2575 .any(|row| !row.directory && row.ids == self.model.selected)
2576 }
2577
2578 fn begin_preview(&mut self, ctx: &egui::Context) {
2579 if !self.can_preview() || self.picker.is_some() {
2580 return;
2581 }
2582 self.preview_texture = None;
2583 self.preview_text.clear();
2584 self.preview_name = self
2585 .model
2586 .entries
2587 .iter()
2588 .find(|e| self.model.selected.contains(&e.id))
2589 .unwrap()
2590 .name
2591 .clone();
2592 self.preview_return_focus = Some(
2593 ctx.memory(|m| m.focused())
2594 .unwrap_or_else(|| egui::Id::unique("archive-list")),
2595 );
2596 self.preview_initial_focus = true;
2597 let request = Start::Preview {
2598 archive: self.model.archive.clone().unwrap(),
2599 entry_id: *self.model.selected.first().unwrap(),
2600 list_id: self.model.list_id.clone().unwrap(),
2601 };
2602 self.preview_open = true;
2603 self.start(request);
2604 }
2605
2606 fn close_preview(&mut self) {
2607 self.preview_open = false;
2608 self.model.dismiss_preview();
2609 self.preview_texture = None;
2610 self.preview_text.clear();
2611 self.dismissed = true;
2612 }
2613
2614 fn preview_dialog(&mut self, ctx: &egui::Context) {
2615 if !self.preview_open
2616 || self.model.challenge.is_some()
2617 || self.model.resource.is_some()
2618 || self.model.close != Close::Open
2619 {
2620 return;
2621 }
2622 if let Some(preview) = self.model.preview.as_mut()
2623 && (!preview.data.is_empty() || preview.info.total_bytes == 0)
2624 {
2625 match preview.info.format {
2626 PreviewFormat::Utf8Text => {
2627 self.preview_text =
2628 String::from_utf8(std::mem::take(&mut preview.data)).unwrap_or_default();
2629 }
2630 PreviewFormat::Rgba8 => {
2631 let width = preview.info.width as usize;
2632 let height = preview.info.height as usize;
2633 let limit = ctx.input(|i| i.max_texture_side).max(1);
2634 let step = width.div_ceil(limit).max(height.div_ceil(limit)).max(1);
2635 let size = [width.div_ceil(step), height.div_ceil(step)];
2636 let mut colors = Vec::with_capacity(size[0] * size[1]);
2637 for y in (0..height).step_by(step) {
2638 for x in (0..width).step_by(step) {
2639 let index = (y * width + x) * 4;
2640 colors.push(egui::Color32::from_rgba_unmultiplied(
2641 preview.data[index],
2642 preview.data[index + 1],
2643 preview.data[index + 2],
2644 preview.data[index + 3],
2645 ));
2646 }
2647 }
2648 let pixels = egui::ColorImage::new(size, colors);
2649 preview.data = Vec::new();
2650 self.preview_texture = Some(ctx.load_texture(
2651 "archive-preview",
2652 pixels,
2653 egui::TextureOptions::LINEAR,
2654 ));
2655 }
2656 }
2657 }
2658 let mut close = false;
2659 let modal = egui::Modal::new(egui::Id::unique("archive-preview")).show(ctx, |ui| {
2660 ui.set_width((ctx.content_rect().width() - 64.0).clamp(240.0, 760.0));
2661 ui.horizontal(|ui| {
2662 ui.heading("미리보기");
2663 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2664 let button = theme::flat_icon_button(
2665 ui,
2666 "미리보기 닫기",
2667 theme::CLOSE,
2668 true,
2669 egui::vec2(36.0, 36.0),
2670 );
2671 if self.preview_initial_focus {
2672 button.request_focus();
2673 self.preview_initial_focus = false;
2674 }
2675 close |= button.clicked();
2676 });
2677 });
2678 ui.add(egui::Label::new(&self.preview_name).truncate())
2679 .on_hover_text(&self.preview_name);
2680 let max_height = (ctx.content_rect().height() - 220.0).clamp(100.0, 560.0);
2681 if self.model.busy() {
2682 ui.label("미리보기를 불러오는 중입니다");
2683 if ui.button("취소").clicked() {
2684 close = true;
2685 }
2686 } else if let Some(error) = self.model.error.as_ref() {
2687 Self::error_notice(ui, error);
2688 } else if let Some(texture) = self.preview_texture.as_ref() {
2689 ui.add(
2690 egui::Image::new(texture)
2691 .max_size(egui::vec2(ui.available_width(), max_height))
2692 .shrink_to_fit(),
2693 );
2694 } else if self.model.preview.is_some() {
2695 egui::ScrollArea::both()
2696 .id_salt("preview-text")
2697 .max_height(max_height)
2698 .show(ui, |ui| {
2699 let mut text = self.preview_text.as_str();
2700 ui.add(
2701 egui::TextEdit::multiline(&mut text)
2702 .desired_width(ui.available_width())
2703 .desired_rows(12)
2704 .frame(egui::Frame::NONE),
2705 );
2706 });
2707 if self.preview_text.is_empty() {
2708 ui.label("빈 텍스트 파일입니다");
2709 }
2710 } else {
2711 let code = self.model.terminal.as_ref().and_then(|t| t.error);
2712 ui.label(match code {
2713 Some(ErrorCode::Limit) => "미리보기 크기 또는 처리 한도를 초과했습니다.",
2714 Some(ErrorCode::Integrity) => "파일이 손상됐거나 UTF-8 텍스트가 아닙니다.",
2715 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature) => {
2716 "이 파일 형식은 미리보기를 지원하지 않습니다."
2717 }
2718 Some(ErrorCode::SourceChanged) => "압축파일이 변경됐습니다. 다시 열어 주세요.",
2719 Some(ErrorCode::WrongPassword) => "암호가 올바르지 않습니다.",
2720 _ => "미리보기를 불러오지 못했습니다.",
2721 });
2722 ui.label("닫은 뒤 파일을 선택하고 [압축해제]를 사용할 수 있습니다.");
2723 }
2724 });
2725 if close || modal.should_close() {
2726 self.close_preview();
2727 }
2728 }
2729
2730 fn limit_result_visible(&self) -> bool {
2731 self.result_visible()
2732 && (self.model.volume_problem.is_some()
2733 || self.model.terminal.as_ref().is_some_and(|terminal| {
2734 terminal.error == Some(ErrorCode::Limit)
2735 || (matches!(
2736 terminal.error,
2737 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature)
2738 ) && self
2739 .model
2740 .archive
2741 .as_ref()
2742 .is_some_and(|p| present::excluded_split(p)))
2743 }))
2744 }
2745
2746 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
2747 if !self.limit_result_visible() || self.main_modal_open() {
2748 return;
2749 }
2750 egui::Modal::new(egui::Id::new("archive-limit-result")).show(ctx, |ui| {
2751 ui.set_width((ctx.content_rect().width() - 64.0).min(WORK_WIDTH));
2752 ui.heading("작업 결과");
2753 self.work_area(ui);
2754 });
2755 }
2756
2757 fn error_notice(ui: &mut egui::Ui, error: &str) {
2758 let response = theme::panel(theme::ERROR_BG)
2759 .show(ui, |ui| {
2760 ui.horizontal_wrapped(|ui| {
2761 theme::icon(ui, Icon::Error, 24.0);
2762 ui.colored_label(theme::ERROR, error);
2763 });
2764 })
2765 .response;
2766 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
2767 }
2768
2769 fn work_visible(&self) -> bool {
2770 !self
2771 .last_request
2772 .as_ref()
2773 .is_some_and(|r| matches!(r, Start::Preview { .. }))
2774 && (self.model.busy()
2775 || self.result_visible()
2776 || (self.ui_error.is_some() && !self.create))
2777 }
2778
2779 /// 메인 창 가운데에 모달(암호 입력, 종료 확인, 파일 선택 안내)이나 같은 자리에 뜨는
2780 /// ZIP 만들기 창이 떠 있는지. 닫기가 정해진 뒤(Allowed)에도 결과 창을 다시 띄우지 않음.
2781 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
2782 fn main_modal_open(&self) -> bool {
2783 (self.create && !self.model.busy())
2784 || self.picker.is_some()
2785 || self.model.challenge.is_some()
2786 || self.model.resource.is_some()
2787 || self.model.conflict.is_some()
2788 || self.model.close != Close::Open
2789 }
2790
2791 fn work_window(&mut self, ctx: &egui::Context) {
2792 if !self.work_visible() {
2793 self.work = WorkWindow::default();
2794 return;
2795 }
2796 if self.limit_result_visible() {
2797 self.work.open = false;
2798 return;
2799 }
2800 if ctx.embed_viewports() && !self.work_in_parent {
2801 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
2802 return;
2803 }
2804 if self.main_modal_open() {
2805 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
2806 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
2807 self.work.open = false;
2808 return;
2809 }
2810 let id = egui::ViewportId::from_hash_of("archive-work");
2811 let title = if self.model.busy() {
2812 present::activity_text(
2813 &self.model,
2814 matches!(
2815 self.last_request,
2816 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2817 ),
2818 )
2819 .to_owned()
2820 } else {
2821 "작업 결과".to_owned()
2822 };
2823 if self.work_in_parent {
2824 // Wayland는 창 올리기를 지원하지 않으므로 부모 안에서 같은 내용을 그림.
2825 // egui 기본 제목 줄의 닫기 버튼은 마우스를 올려도 모양이 바뀌지 않으므로
2826 // 제목 줄을 직접 그리고 별도 창과 같은 닫기 버튼을 씀.
2827 let mut close = false;
2828 let busy = self.model.busy();
2829 egui::Window::new(RichText::new(&title).size(theme::FONT_SMALL))
2830 .id(egui::Id::new("archive-work-in-parent"))
2831 .title_bar(false)
2832 .default_pos(
2833 ctx.content_rect().center() - egui::vec2(WORK_WIDTH, self.work.height) / 2.0,
2834 )
2835 .default_width(WORK_WIDTH)
2836 .min_width(WORK_WIDTH)
2837 .max_width(WORK_WIDTH)
2838 .max_height(WORK_MAX_HEIGHT)
2839 .collapsible(false)
2840 .resizable(false)
2841 .fade_in(false)
2842 .fade_out(false)
2843 .frame(
2844 egui::Frame::new()
2845 .fill(theme::PANEL)
2846 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2847 .inner_margin(egui::Margin::ZERO)
2848 .corner_radius(0),
2849 )
2850 .show(ctx, |ui| {
2851 let spacing = ui.spacing().item_spacing.y;
2852 ui.spacing_mut().item_spacing.y = 0.0;
2853 close = window_frame::in_parent_title(ui, "work-in-parent", &title, !busy);
2854 egui::Frame::new()
2855 .inner_margin(egui::Margin::same(theme::PAD))
2856 .show(ui, |ui| {
2857 ui.spacing_mut().item_spacing.y = spacing;
2858 ui.set_width(WORK_WIDTH - 2.0 * theme::PAD as f32);
2859 self.work_area(ui)
2860 });
2861 });
2862 if close {
2863 self.dismissed = true;
2864 self.ui_error = None;
2865 self.model.input_error = None;
2866 }
2867 return;
2868 }
2869 let window_title = format!("{title} — Zipelo");
2870 let custom_frame = self.custom_frame;
2871 let size = egui::vec2(WORK_WIDTH, self.work.height);
2872 let builder = self.work.builder(
2873 ctx,
2874 id,
2875 size,
2876 &window_title,
2877 !custom_frame,
2878 self.picker.is_some(),
2879 );
2880 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
2881 // 끝난 작업의 결과 창은 Esc로 닫음. 진행 중에는 [취소] 버튼을 씀.
2882 if !self.model.busy()
2883 && ui
2884 .ctx()
2885 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
2886 {
2887 crate::log_debug!("Esc: 작업 결과 창 닫기");
2888 self.dismissed = true;
2889 self.ui_error = None;
2890 self.model.input_error = None;
2891 }
2892 if ui.ctx().input(|i| i.viewport().close_requested()) {
2893 if self.model.busy() {
2894 ui.ctx()
2895 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
2896 } else {
2897 self.dismissed = true;
2898 self.ui_error = None;
2899 self.model.input_error = None;
2900 }
2901 }
2902 if class == egui::ViewportClass::EmbeddedWindow {
2903 ui.set_width(WORK_WIDTH);
2904 self.work_area(ui);
2905 return None;
2906 }
2907 let mut chrome = 0.0;
2908 if custom_frame {
2909 window_frame::title_bar(
2910 ui,
2911 "work",
2912 &window_title,
2913 window_frame::Buttons {
2914 minimize: false,
2915 maximize: false,
2916 },
2917 );
2918 window_frame::edges(ui.ctx(), false);
2919 chrome = window_frame::TITLE_HEIGHT;
2920 }
2921 let margin = theme::PAD as f32;
2922 egui::CentralPanel::default()
2923 .frame(theme::panel(theme::PANEL).corner_radius(0))
2924 .show(ui, |ui| {
2925 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
2926 Some(content.height() + 2.0 * margin + chrome)
2927 })
2928 .inner
2929 });
2930 if let Some(height) = height {
2931 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
2932 if (height - self.work.height).abs() > 1.0 {
2933 self.work.height = height;
2934 }
2935 }
2936 }
2937
2938 fn work_area(&mut self, ui: &mut egui::Ui) {
2939 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
2940 let enabled = self.picker.is_none();
2941 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
2942 }
2943
2944 fn work_contents(&mut self, ui: &mut egui::Ui) {
2945 if self.model.busy() {
2946 self.progress(ui);
2947 } else if self.result_visible() {
2948 self.result(ui);
2949 }
2950 if !self.create
2951 && let Some(error) = &self.ui_error
2952 {
2953 Self::error_notice(ui, error);
2954 if error == present::FOLDER_ERROR
2955 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
2956 {
2957 self.open_picker(Purpose::Destination);
2958 }
2959 }
2960 if let Some(error) = &self.model.input_error {
2961 ui.colored_label(
2962 theme::ERROR,
2963 if error.starts_with("암호는") {
2964 error.as_str()
2965 } else {
2966 if matches!(
2967 self.last_request,
2968 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2969 ) {
2970 "저장 위치와 추가한 항목을 확인하세요"
2971 } else {
2972 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
2973 "원본과 다른 새 복구본 저장 위치를 선택하세요"
2974 } else {
2975 "풀 위치와 선택한 항목을 확인하세요"
2976 }
2977 }
2978 },
2979 );
2980 }
2981 }
2982
2983 fn progress(&mut self, ui: &mut egui::Ui) {
2984 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
2985 ui.strong("ZIP 복구 중");
2986 ui.label(if self.model.recovery_end.is_some() {
2987 "분석 완료 / 복구본 저장과 작업자 종료 확인 중"
2988 } else {
2989 "원본을 분석하고 있습니다. 전체 항목 수는 아직 알 수 없습니다."
2990 });
2991 ui.label(format!(
2992 "확인한 항목 {}개",
2993 self.model.recovery_entries.len()
2994 ));
2995 self.cancel_action(ui, false);
2996 return;
2997 }
2998 if self.model.resource.is_some() {
2999 ui.horizontal(|ui| {
3000 ui.label("사용자 허용을 기다리고 있습니다");
3001 self.cancel_action(ui, false);
3002 });
3003 return;
3004 }
3005 let creating = matches!(
3006 self.last_request,
3007 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3008 );
3009 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
3010 let title = present::activity_text(&self.model, creating);
3011 ui.strong(title);
3012 if let Some((stage, done, total, count)) = self.model.progress {
3013 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
3014 let processed = if stage == Stage::Read {
3015 String::new()
3016 } else {
3017 format!("{count}개 처리함, ")
3018 };
3019 if let Some(total) = total.filter(|n| *n > 0) {
3020 ui.scope(|ui| {
3021 ui.visuals_mut().extreme_bg_color = theme::BORDER;
3022 ui.add(
3023 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
3024 .fill(theme::BLUE)
3025 .desired_height(theme::SPACE * 2.0),
3026 );
3027 });
3028 ui.horizontal(|ui| {
3029 ui.label(format!(
3030 "{:.0}% / {processed}{} / {}",
3031 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
3032 present::bytes_text(done),
3033 present::bytes_text(total)
3034 ));
3035 self.cancel_action(ui, cancelling);
3036 });
3037 } else {
3038 theme::indeterminate(ui);
3039 ui.horizontal(|ui| {
3040 ui.label(format!("{processed}{}", present::bytes_text(done)));
3041 self.cancel_action(ui, cancelling);
3042 });
3043 }
3044 } else {
3045 theme::indeterminate(ui);
3046 ui.horizontal(|ui| {
3047 ui.label("작업을 진행하고 있습니다");
3048 self.cancel_action(ui, cancelling);
3049 });
3050 }
3051 }
3052
3053 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
3054 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3055 if theme::action(ui, "취소", false, !cancelling).clicked() {
3056 self.clear_password();
3057 self.model.cancel();
3058 }
3059 });
3060 }
3061
3062 fn recovery_result(&mut self, ui: &mut egui::Ui) {
3063 let t = self.model.terminal.as_ref();
3064 let summary = self.model.recovery_end.as_ref();
3065 let confirmed = self.model.confirmed && self.model.error.is_none();
3066 let saved = confirmed
3067 && t.is_some_and(|t| t.publication == Publication::Complete && t.created_count == 1)
3068 && summary.is_some_and(|s| s.verified_entries > 0);
3069 let partial = summary.is_some_and(|s| !s.complete());
3070 let title = if !confirmed {
3071 "복구 결과를 확정할 수 없음"
3072 } else if saved && partial {
3073 "일부 항목만 복구함"
3074 } else if saved && t.is_some_and(|t| t.outcome == Outcome::Completed) {
3075 "복구본 저장 완료"
3076 } else if t.is_some_and(|t| t.error == Some(ErrorCode::RecoveryImpossible)) {
3077 "복구 가능한 항목 없음"
3078 } else if t.is_some_and(|t| t.outcome == Outcome::Cancelled) {
3079 "복구를 취소했습니다"
3080 } else {
3081 "복구본 저장을 완료하지 못했습니다"
3082 };
3083 ui.heading(title);
3084 ui.label(
3085 "원본은 수정하지 않습니다. 검증 통과는 손상 전 내용과 동일하다는 보증이 아닙니다.",
3086 );
3087 let output = match &self.last_request {
3088 Some(Start::RecoverZip { output_file, .. }) => output_file.clone(),
3089 _ => return,
3090 };
3091 if saved
3092 || self
3093 .model
3094 .outputs
3095 .iter()
3096 .any(|(_, d)| matches!(d, Disposition::Created | Disposition::CommitUncertain))
3097 {
3098 theme::bounded_text(ui, &output.display().to_string(), ui.available_width());
3099 }
3100 for (name, _) in self
3101 .model
3102 .outputs
3103 .iter()
3104 .filter(|(_, d)| *d == Disposition::PartialRetained)
3105 {
3106 let retained = output.parent().unwrap_or(Path::new("")).join(name);
3107 theme::bounded_text(
3108 ui,
3109 &format!("남은 임시 파일: {}", retained.display()),
3110 ui.available_width(),
3111 );
3112 }
3113 if let Some(error) = &self.model.error {
3114 ui.colored_label(theme::WARNING, error);
3115 }
3116 if let Some(t) = t {
3117 if let Some(code) = t.error {
3118 ui.label(present::error_text(code));
3119 }
3120 for warning in present::publication_warnings(
3121 Some(t),
3122 self.model.confirmed,
3123 Some(&BTreeSet::from([output
3124 .file_name()
3125 .unwrap_or_default()
3126 .to_string_lossy()
3127 .into_owned()])),
3128 &BTreeSet::new(),
3129 &self.model.outputs,
3130 ) {
3131 ui.colored_label(theme::WARNING, warning);
3132 }
3133 if let Some(warning) = present::durability_warning(t.durability) {
3134 ui.colored_label(theme::WARNING, warning);
3135 }
3136 }
3137 let notice = summary.map(|s| {
3138 format!(
3139 "검증되어 포함됨 {}개 / 유실됨 {}개 / 무결성 미확인 {}개{}",
3140 s.verified_entries,
3141 s.lost_entries,
3142 s.unverified_entries,
3143 if s.unknown_loss {
3144 " / 전체 목록을 알 수 없어 추가 유실 여부를 확인할 수 없습니다"
3145 } else {
3146 ""
3147 }
3148 )
3149 });
3150 if let Some(notice) = &notice {
3151 ui.label(notice);
3152 }
3153 egui::ScrollArea::vertical()
3154 .id_salt("recovery-findings")
3155 .max_height(220.0)
3156 .show_rows(ui, 24.0, self.model.recovery_entries.len(), |ui, rows| {
3157 for entry in &self.model.recovery_entries[rows] {
3158 let status = match entry.status {
3159 RecoveryStatus::Verified => "검증되어 포함됨",
3160 RecoveryStatus::Lost => "유실됨",
3161 RecoveryStatus::Unverified => "무결성 미확인",
3162 };
3163 let reason = match entry.reason {
3164 RecoveryReason::None => "내용 검증 통과",
3165 RecoveryReason::HeaderRebuilt => "헤더 재구성",
3166 RecoveryReason::Truncated => "파일 절단",
3167 RecoveryReason::CrcMismatch => "CRC 불일치",
3168 RecoveryReason::DecodeFailure => "압축 데이터 손상",
3169 RecoveryReason::BoundaryUnknown => "항목 경계 불명",
3170 RecoveryReason::UnsupportedFeature => "지원하지 않는 기능",
3171 RecoveryReason::MetadataMissing => "메타정보 누락",
3172 };
3173 theme::bounded_text(
3174 ui,
3175 &format!(
3176 "{status} / {reason}: {}",
3177 entry.name.as_deref().unwrap_or("이름 확인 불가")
3178 ),
3179 ui.available_width(),
3180 );
3181 }
3182 });
3183 if saved && theme::action(ui, "복구본 열기", true, true).clicked() {
3184 self.recovery_warning = partial.then(|| (output.clone(), notice.unwrap_or_default()));
3185 self.open_path(output);
3186 }
3187 if self.model.can_retry_expanded()
3188 && theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked()
3189 {
3190 self.model.retry_expanded(self.factory.as_mut());
3191 }
3192 }
3193
3194 fn result(&mut self, ui: &mut egui::Ui) {
3195 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
3196 self.recovery_result(ui);
3197 return;
3198 }
3199 if self.model.confirmed
3200 && self.model.error.is_none()
3201 && self
3202 .model
3203 .terminal
3204 .as_ref()
3205 .is_some_and(|t| t.error == Some(ErrorCode::Integrity))
3206 && matches!(
3207 self.last_request,
3208 Some(Start::List { .. } | Start::Extract { .. })
3209 )
3210 {
3211 ui.label("원본을 바꾸지 않고 새 ZIP 복구본을 만듭니다. 일부 항목은 복구되지 않을 수 있습니다.");
3212 if theme::action(ui, "복구본 저장 위치 선택", true, true).clicked() {
3213 self.open_picker(Purpose::SaveRecoveryZip);
3214 }
3215 }
3216 let t = self.model.terminal.clone();
3217 let listing = matches!(self.last_request, Some(Start::List { .. }));
3218 let creating = matches!(
3219 self.last_request,
3220 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3221 );
3222 // 분할 7z는 작업자가 보고한 볼륨 수로 기대 이름(이름.7z.001…)을 정함.
3223 let split_targets = match (&self.last_request, t.as_ref()) {
3224 (
3225 Some(Start::CreateSevenZip {
3226 output_file,
3227 volume_size: Some(_),
3228 ..
3229 }),
3230 Some(t),
3231 ) => output_file.file_name().map(|name| {
3232 (1..=t.created_count.clamp(1, present::MAX_VOLUMES))
3233 .map(|index| format!("{}.{index:03}", name.to_string_lossy()))
3234 .collect::<BTreeSet<_>>()
3235 }),
3236 _ => None,
3237 };
3238 let resolved_targets = present::resolved_targets(
3239 split_targets.as_ref().or(self.targets.as_ref()),
3240 &self.model.entries,
3241 matches!(
3242 self.last_request,
3243 Some(Start::Extract {
3244 gzip_output_name: Some(_),
3245 ..
3246 })
3247 )
3248 .then_some(self.gzip_name.as_str()),
3249 &self.model.resolutions,
3250 );
3251 let skipped = self
3252 .model
3253 .resolutions
3254 .iter()
3255 .filter(|r| r.choice == ConflictChoice::Skip)
3256 .count();
3257 let created_names = self
3258 .model
3259 .outputs
3260 .iter()
3261 .filter(|(_, disposition)| *disposition == Disposition::Created)
3262 .map(|(name, _)| name.replace('\\', "/"))
3263 .collect::<BTreeSet<_>>();
3264 let warnings = if listing {
3265 Vec::new()
3266 } else {
3267 present::publication_warnings(
3268 t.as_ref(),
3269 self.model.confirmed,
3270 resolved_targets.as_ref(),
3271 &self.directories,
3272 &self.model.outputs,
3273 )
3274 };
3275 let success = self.model.confirmed
3276 && self.model.error.is_none()
3277 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
3278 && warnings
3279 .iter()
3280 .all(|warning| !creating && *warning == present::CLEANUP_WARNING);
3281 let durability_warning = t
3282 .as_ref()
3283 .filter(|_| self.model.confirmed && !listing)
3284 .and_then(|t| present::durability_warning(t.durability));
3285 let durability_in_details = success
3286 && t.as_ref()
3287 .is_some_and(|t| t.durability == Durability::Unconfirmed);
3288 let cancelled =
3289 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
3290 let title = if success {
3291 if creating {
3292 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3293 "7z 파일을 만들었습니다"
3294 } else {
3295 "ZIP 파일을 만들었습니다"
3296 }
3297 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
3298 "모든 파일을 건너뛰었습니다"
3299 } else {
3300 "압축을 풀었습니다"
3301 }
3302 } else if cancelled {
3303 "작업을 취소했습니다"
3304 } else if listing {
3305 "압축파일을 열지 못했습니다"
3306 } else if creating {
3307 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3308 "7z 파일을 만들지 못했습니다"
3309 } else {
3310 "ZIP 파일을 만들지 못했습니다"
3311 }
3312 } else {
3313 "압축을 풀지 못했습니다"
3314 };
3315 let fill = if success {
3316 theme::SUCCESS_BG
3317 } else if cancelled {
3318 theme::STRIPE
3319 } else {
3320 theme::ERROR_BG
3321 };
3322 let mut choose = false;
3323 let mut retry = false;
3324 let mut expand = false;
3325 let mut reopen = false;
3326 let mut folder = false;
3327 theme::panel(fill).show(ui, |ui| {
3328 ui.horizontal(|ui| {
3329 theme::icon(
3330 ui,
3331 if success {
3332 Icon::Success
3333 } else if cancelled {
3334 Icon::Warning
3335 } else {
3336 Icon::Error
3337 },
3338 24.0,
3339 );
3340 ui.strong(title);
3341 });
3342 let max_height = WORK_RESULT_MAX_HEIGHT;
3343 egui::ScrollArea::vertical()
3344 .id_salt("result-message")
3345 .max_height(max_height)
3346 .show(ui, |ui| {
3347 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
3348 let path = match self.last_request.as_ref() {
3349 Some(Start::CreateSevenZip {
3350 output_file,
3351 volume_size: Some(_),
3352 ..
3353 }) => present::volume_path(output_file, 1).display().to_string(),
3354 Some(
3355 Start::CreateZip { output_file, .. }
3356 | Start::CreateSevenZip { output_file, .. },
3357 ) => output_file.display().to_string(),
3358 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
3359 };
3360 theme::bounded_text(ui, &path, ui.available_width());
3361 if matches!(
3362 self.last_request,
3363 Some(Start::CreateSevenZip {
3364 volume_size: Some(_),
3365 ..
3366 })
3367 ) {
3368 ui.label(format!(
3369 "볼륨 {}개로 나누어 저장했습니다. 풀 때는 첫 볼륨(.001)을 여세요.",
3370 t.as_ref().map_or(0, |t| t.created_count)
3371 ));
3372 }
3373 } else if let Some(problem) = &self.model.volume_problem {
3374 ui.add(egui::Label::new(present::volume_problem_text(problem)).wrap());
3375 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
3376 ui.label(
3377 if matches!(
3378 code,
3379 ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature
3380 ) && self
3381 .model
3382 .archive
3383 .as_ref()
3384 .is_some_and(|p| present::excluded_split(p))
3385 {
3386 present::SPLIT_SUPPORT.to_owned()
3387 } else if creating && code == ErrorCode::SourceChanged {
3388 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
3389 .to_owned()
3390 } else if code == ErrorCode::Limit
3391 && matches!(
3392 self.last_request,
3393 Some(Start::CreateSevenZip {
3394 volume_size: Some(_),
3395 ..
3396 })
3397 )
3398 {
3399 present::VOLUME_LIMIT_ERROR.to_owned()
3400 } else {
3401 present::operation_text(present::error_text(code), creating)
3402 },
3403 );
3404 } else if let Some(error) = &self.model.error {
3405 ui.label(present::operation_text(
3406 present::client_error_text(error),
3407 creating,
3408 ));
3409 }
3410 if skipped > 0 {
3411 ui.label(format!("건너뛴 파일 {skipped}개"));
3412 }
3413 for resolution in self.model.resolutions.iter().filter(|r| {
3414 r.choice == ConflictChoice::Rename
3415 && created_names.contains(&r.relative_name.replace('\\', "/"))
3416 }) {
3417 theme::bounded_text(
3418 ui,
3419 &format!("이름 바꿔 저장: {}", resolution.relative_name),
3420 ui.available_width(),
3421 );
3422 }
3423 for warning in warnings
3424 .iter()
3425 .copied()
3426 .chain(durability_warning.filter(|_| !durability_in_details))
3427 {
3428 ui.horizontal_wrapped(|ui| {
3429 theme::icon(ui, Icon::Warning, 20.0);
3430 ui.colored_label(
3431 theme::WARNING,
3432 present::operation_text(warning, creating),
3433 );
3434 });
3435 }
3436 if !success
3437 && !listing
3438 && present::definitely_unsaved(
3439 t.as_ref(),
3440 self.model.confirmed,
3441 &self.model.outputs,
3442 )
3443 {
3444 ui.label(if creating {
3445 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3446 "7z 파일을 만들지 않았습니다"
3447 } else {
3448 "ZIP 파일을 만들지 않았습니다"
3449 }
3450 } else {
3451 "아무 파일도 풀지 않았습니다"
3452 });
3453 }
3454 if t.as_ref().is_some_and(|t| {
3455 t.error == Some(ErrorCode::Limit)
3456 && (t.created_count > 0
3457 || t.retained_partial_count > 0
3458 || t.publication != Publication::None)
3459 }) {
3460 ui.label(format!(
3461 "{}개 파일이 저장되었거나 일부 남아 있습니다. 저장 위치를 확인하세요.",
3462 t.as_ref().unwrap().created_count
3463 ));
3464 theme::bounded_text(
3465 ui,
3466 &self.destination.display().to_string(),
3467 ui.available_width(),
3468 );
3469 }
3470 if self.details {
3471 theme::panel(theme::STRIPE).show(ui, |ui| {
3472 if durability_in_details {
3473 if let Some(warning) = durability_warning {
3474 ui.label(present::operation_text(warning, creating));
3475 }
3476 }
3477 if let Some(t) = &t {
3478 for line in terminal_lines(t) {
3479 ui.label(line);
3480 }
3481 }
3482 if let Some(error) = &self.model.error {
3483 ui.label(error);
3484 }
3485 for (name, state) in &self.model.outputs {
3486 theme::bounded_text(
3487 ui,
3488 &format!("{name}: {}", disposition_label(*state)),
3489 ui.available_width(),
3490 );
3491 }
3492 });
3493 }
3494 });
3495 let conflict = t
3496 .as_ref()
3497 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
3498 && !creating;
3499 let uncertain = warnings.contains(&present::UNCERTAIN);
3500 if conflict && uncertain {
3501 let response = ui.checkbox(
3502 &mut self.checked_destination,
3503 "기존 풀 위치 폴더를 확인했습니다",
3504 );
3505 theme::pointer(&response);
3506 theme::focus(&response);
3507 }
3508 ui.horizontal(|ui| {
3509 if theme::action(
3510 ui,
3511 if self.details {
3512 "자세히 닫기"
3513 } else {
3514 "자세히 보기"
3515 },
3516 false,
3517 true,
3518 )
3519 .clicked()
3520 {
3521 self.details = !self.details;
3522 }
3523 let action = if success {
3524 Some(("폴더 열기", true))
3525 } else if conflict {
3526 Some((
3527 if self
3528 .model
3529 .list_id
3530 .as_ref()
3531 .is_some_and(|id| id.format == Format::Gzip)
3532 {
3533 "다른 이름으로 저장"
3534 } else {
3535 "다른 폴더에 풀기"
3536 },
3537 !uncertain || self.checked_destination,
3538 ))
3539 } else if t
3540 .as_ref()
3541 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
3542 {
3543 Some((
3544 if creating {
3545 "다시 만들기"
3546 } else {
3547 "압축파일 다시 열기"
3548 },
3549 true,
3550 ))
3551 } else if self.model.can_retry_expanded() {
3552 None
3553 } else if t
3554 .as_ref()
3555 .is_some_and(|t| t.error == Some(ErrorCode::Limit))
3556 {
3557 None
3558 } else if !cancelled && (!uncertain || listing) {
3559 Some(("다시 시도", true))
3560 } else {
3561 None
3562 };
3563 let (confirm, primary) = theme::action_pair(ui, "확인", action);
3564 if confirm {
3565 self.dismissed = true;
3566 self.ui_error = None;
3567 self.model.input_error = None;
3568 }
3569 if primary {
3570 match action.map(|(label, _)| label) {
3571 Some("폴더 열기") => folder = true,
3572 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
3573 choose = true
3574 }
3575 Some("압축파일 다시 열기") => reopen = true,
3576 Some("다시 시도" | "다시 만들기") => retry = true,
3577 _ => {}
3578 }
3579 }
3580 });
3581 if self.model.can_retry_expanded() {
3582 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3583 expand = theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked();
3584 });
3585 }
3586 });
3587 if choose {
3588 self.open_picker(Purpose::Retry);
3589 }
3590 if retry {
3591 self.retry();
3592 }
3593 if expand {
3594 let ready = if matches!(self.last_request, Some(Start::Extract { .. })) {
3595 match present::prepare_destination(&self.destination, self.automatic_destination) {
3596 Ok(created) => {
3597 self.owned_destination = created.then(|| self.destination.clone());
3598 true
3599 }
3600 Err(_) => {
3601 self.ui_error = Some(present::FOLDER_ERROR.into());
3602 false
3603 }
3604 }
3605 } else {
3606 true
3607 };
3608 if ready && self.model.retry_expanded(self.factory.as_mut()) {
3609 self.dismissed = false;
3610 self.details = false;
3611 self.ui_error = None;
3612 }
3613 }
3614 if reopen {
3615 if let Some(path) = self.model.archive.clone() {
3616 self.open_path(path);
3617 }
3618 }
3619 if folder {
3620 let path = match self.last_request.as_ref() {
3621 Some(
3622 Start::CreateZip { output_file, .. }
3623 | Start::CreateSevenZip { output_file, .. },
3624 ) => output_file.parent().unwrap_or(Path::new("/")),
3625 _ => self.destination.as_path(),
3626 };
3627 match present::folder_command(path).spawn() {
3628 Ok(mut child) => {
3629 std::thread::spawn(move || {
3630 let _ = child.wait();
3631 });
3632 }
3633 Err(_) => {
3634 self.ui_error = Some(
3635 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
3636 )
3637 }
3638 }
3639 }
3640 }
3641
3642 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
3643 fn entry_cells(
3644 ui: &mut egui::Ui,
3645 rect: egui::Rect,
3646 directory: bool,
3647 name: &str,
3648 hover: &str,
3649 size: String,
3650 name_width: f32,
3651 ) {
3652 ui.scope_builder(
3653 egui::UiBuilder::new()
3654 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
3655 .layout(Layout::left_to_right(Align::Center)),
3656 |ui| {
3657 ui.style_mut().interaction.selectable_labels = false;
3658 ui.add_space(16.0);
3659 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
3660 theme::bounded_text_hover(ui, name, hover, name_width);
3661 theme::column_label(ui, size, 96.0, Align::Max);
3662 },
3663 );
3664 }
3665
3666 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
3667 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
3668 fn create_window(&mut self, ctx: &egui::Context) {
3669 if !self.create || self.model.busy() {
3670 self.create_win = WorkWindow::default();
3671 return;
3672 }
3673 if ctx.embed_viewports() {
3674 let mut close = false;
3675 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
3676 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
3677 ui.horizontal(|ui| {
3678 ui.heading(if self.seven_zip {
3679 "7z 만들기"
3680 } else {
3681 "ZIP 만들기"
3682 });
3683 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3684 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
3685 close = button.clicked();
3686 });
3687 });
3688 close |= self.create_area(ui);
3689 ui.add_space(theme::SPACE);
3690 close |= self.create_actions(ui);
3691 });
3692 if close || modal.should_close() {
3693 self.close_create();
3694 }
3695 return;
3696 }
3697 let id = egui::ViewportId::from_hash_of("archive-create");
3698 let title = if self.seven_zip {
3699 "7z 만들기 — Zipelo"
3700 } else {
3701 "ZIP 만들기 — Zipelo"
3702 };
3703 let custom_frame = self.custom_frame;
3704 if !self.create_win.open {
3705 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
3706 }
3707 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
3708 let builder =
3709 self.create_win
3710 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
3711 let mut close = false;
3712 let picker_open = self.picker.is_some();
3713 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
3714 if ui.ctx().input(|i| i.viewport().close_requested()) {
3715 close = true;
3716 }
3717 if !picker_open
3718 && ui
3719 .ctx()
3720 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
3721 {
3722 crate::log_debug!("Esc: 만들기 창 닫기");
3723 close = true;
3724 }
3725 if class == egui::ViewportClass::EmbeddedWindow {
3726 ui.set_width(CREATE_WIDTH);
3727 close |= self.create_area(ui);
3728 close |= self.create_actions(ui);
3729 return None;
3730 }
3731 let mut chrome = 0.0;
3732 if custom_frame {
3733 window_frame::title_bar(
3734 ui,
3735 "create",
3736 title,
3737 window_frame::Buttons {
3738 minimize: false,
3739 maximize: false,
3740 },
3741 );
3742 window_frame::edges(ui.ctx(), false);
3743 chrome = window_frame::TITLE_HEIGHT;
3744 }
3745 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
3746 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
3747 .resizable(false)
3748 .show_separator_line(false)
3749 .frame(
3750 egui::Frame::new()
3751 .fill(theme::PANEL)
3752 .inner_margin(egui::Margin {
3753 left: theme::PAD,
3754 right: theme::PAD,
3755 top: 0,
3756 bottom: theme::PAD,
3757 }),
3758 )
3759 .show(ui, |ui| close |= self.create_actions(ui))
3760 .response
3761 .rect
3762 .height();
3763 let margin = theme::PAD as f32;
3764 egui::CentralPanel::default()
3765 .frame(theme::panel(theme::PANEL).corner_radius(0))
3766 .show(ui, |ui| {
3767 let content = ui
3768 .vertical(|ui| close |= self.create_area(ui))
3769 .response
3770 .rect;
3771 Some(content.height() + 2.0 * margin + chrome + actions)
3772 })
3773 .inner
3774 });
3775 if let Some(height) = height {
3776 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
3777 if (height - self.create_win.height).abs() > 1.0 {
3778 self.create_win.height = height;
3779 }
3780 }
3781 if close {
3782 self.close_create();
3783 }
3784 }
3785
3786 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
3787 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
3788 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
3789 let enabled = self.picker.is_none();
3790 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
3791 .inner
3792 }
3793
3794 fn set_seven_zip(&mut self, selected: bool) {
3795 if self.seven_zip == selected {
3796 return;
3797 }
3798 self.seven_zip = selected;
3799 self.aes256 = false;
3800 self.clear_zip_password();
3801 self.ui_error = None;
3802 let name = self.zip_name.clone();
3803 let lower = name.to_ascii_lowercase();
3804 let stem = if lower.ends_with(".zip") {
3805 &name[..name.len() - 4]
3806 } else if lower.ends_with(".7z") {
3807 &name[..name.len() - 3]
3808 } else {
3809 &name
3810 };
3811 self.zip_name = format!("{stem}{}", if selected { ".7z" } else { ".zip" });
3812 }
3813
3814 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
3815 let mut selected = self.seven_zip;
3816 ui.horizontal(|ui| {
3817 ui.label("형식");
3818 ui.selectable_value(&mut selected, false, "ZIP");
3819 ui.selectable_value(&mut selected, true, "7z");
3820 if selected {
3821 ui.label("LZMA2");
3822 }
3823 });
3824 self.set_seven_zip(selected);
3825
3826 let rows = self.create_rows();
3827 let root = self.create_root();
3828
3829 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
3830 ui.horizontal(|ui| {
3831 ui.set_height(theme::FIELD);
3832 ui.spacing_mut().item_spacing.x = 0.0;
3833 let up = theme::flat_icon_button(
3834 ui,
3835 "위로",
3836 theme::UP,
3837 !self.create_folder.is_empty(),
3838 egui::vec2(theme::FIELD, theme::FIELD),
3839 );
3840 if up.clicked() {
3841 self.create_folder = self
3842 .create_folder
3843 .rsplit_once('/')
3844 .map_or("", |(parent, _)| parent)
3845 .to_owned();
3846 self.create_selected = None;
3847 }
3848 ui.add_space(6.0);
3849 let path = match &root {
3850 Some(root) => {
3851 let name = root.file_name().unwrap_or_default().to_string_lossy();
3852 if self.create_folder.is_empty() {
3853 format!("/{name}")
3854 } else {
3855 format!("/{name}/{}", self.create_folder)
3856 }
3857 }
3858 None => "/".to_owned(),
3859 };
3860 let (rect, _) = ui.allocate_exact_size(
3861 egui::vec2(ui.available_width(), theme::FIELD),
3862 egui::Sense::hover(),
3863 );
3864 theme::boxed_field(ui, rect);
3865 theme::field_text(ui, rect, &path);
3866 });
3867 ui.add_space(theme::SPACE);
3868
3869 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
3870 let mut enter = None;
3871 egui::Frame::new()
3872 .stroke(egui::Stroke::new(1.0, theme::BORDER))
3873 .show(ui, |ui| {
3874 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
3875 ui.set_max_height(CREATE_LIST_HEIGHT);
3876 let message = match &rows {
3877 None => Some("폴더를 읽지 못했습니다"),
3878 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
3879 Some(_) => None,
3880 };
3881 if let Some(message) = message {
3882 ui.centered_and_justified(|ui| ui.label(message));
3883 return;
3884 }
3885 let rows = rows.unwrap();
3886 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
3887 egui::ScrollArea::vertical()
3888 .id_salt("create-rows")
3889 .auto_shrink([false, false])
3890 .max_height(CREATE_LIST_HEIGHT)
3891 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
3892 for row in &rows[range] {
3893 let (rect, response) = ui.allocate_exact_size(
3894 egui::vec2(ui.available_width(), LIST_ROW),
3895 egui::Sense::click(),
3896 );
3897 let response = response.on_hover_text(&row.name);
3898 theme::pointer(&response);
3899 response.widget_info(|| {
3900 egui::WidgetInfo::labeled(
3901 egui::Role::ListBoxOption,
3902 true,
3903 &row.name,
3904 )
3905 });
3906 if response.clicked() {
3907 self.create_selected = Some(row.name.clone());
3908 }
3909 theme::row_background(
3910 ui,
3911 rect,
3912 self.create_selected.as_deref() == Some(row.name.as_str()),
3913 response.hovered(),
3914 );
3915 if row.directory && root.is_some() && response.clicked() {
3916 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
3917 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
3918 let frame = ui.ctx().cumulative_frame_nr();
3919 let time = ui.input(|i| i.time);
3920 match &self.create_last_click {
3921 Some((name, last_frame, last_time))
3922 if name == &row.name
3923 && *last_frame != frame
3924 && time - last_time < 0.4 =>
3925 {
3926 enter = Some(row.name.clone());
3927 self.create_last_click = None;
3928 }
3929 Some((name, last_frame, _))
3930 if name == &row.name && *last_frame == frame => {}
3931 _ => {
3932 self.create_last_click =
3933 Some((row.name.clone(), frame, time));
3934 }
3935 }
3936 }
3937 Self::entry_cells(
3938 ui,
3939 rect,
3940 row.directory,
3941 &row.name,
3942 &row.name,
3943 row.bytes.map(present::bytes_text).unwrap_or_default(),
3944 name_width,
3945 );
3946 }
3947 });
3948 });
3949 if let Some(name) = enter {
3950 self.create_folder = if self.create_folder.is_empty() {
3951 name
3952 } else {
3953 format!("{}/{name}", self.create_folder)
3954 };
3955 self.create_selected = None;
3956 }
3957 ui.add_space(theme::SPACE);
3958
3959 if let Some(error) = &self.ui_error {
3960 Self::error_notice(ui, error);
3961 }
3962
3963 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
3964 if self.seven_zip {
3965 ui.label("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요");
3966 self.split_rows(ui);
3967 return false;
3968 }
3969 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
3970 theme::pointer(&check);
3971 theme::focus(&check);
3972 if self.aes256 {
3973 let label_width = 72.0;
3974 ui.horizontal(|ui| {
3975 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
3976 let toggle = if self.zip_password_visible {
3977 "숨기기"
3978 } else {
3979 "보기"
3980 };
3981 let toggle_width = 72.0;
3982 let edit = ui.add_sized(
3983 [
3984 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
3985 theme::FIELD,
3986 ],
3987 egui::TextEdit::singleline(&mut self.zip_password)
3988 .password(!self.zip_password_visible)
3989 .id(egui::Id::unique("zip-password-input"))
3990 .char_limit(1024)
3991 .align(egui::Align2::LEFT_CENTER),
3992 );
3993 theme::focus(&edit);
3994 if theme::action(ui, toggle, false, true).clicked() {
3995 self.zip_password_visible = !self.zip_password_visible;
3996 }
3997 });
3998 ui.horizontal(|ui| {
3999 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
4000 let edit = ui.add_sized(
4001 [
4002 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
4003 theme::FIELD,
4004 ],
4005 egui::TextEdit::singleline(&mut self.zip_password_confirm)
4006 .password(!self.zip_password_visible)
4007 .id(egui::Id::unique("zip-password-confirm"))
4008 .char_limit(1024)
4009 .align(egui::Align2::LEFT_CENTER),
4010 );
4011 theme::focus(&edit);
4012 });
4013 if self.zip_password.len() > 1024 {
4014 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
4015 } else if !self.zip_password_confirm.is_empty()
4016 && self.zip_password != self.zip_password_confirm
4017 {
4018 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
4019 }
4020 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
4021 } else if check.changed()
4022 || !self.zip_password.is_empty()
4023 || !self.zip_password_confirm.is_empty()
4024 {
4025 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
4026 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
4027 self.clear_zip_password();
4028 }
4029 false
4030 }
4031
4032 /// 쪼갤 용량: 체크하면 바로 아래에 볼륨 크기 칸과 MB/GB 선택을 보여 줌.
4033 fn split_rows(&mut self, ui: &mut egui::Ui) {
4034 let check = ui.checkbox(&mut self.split, "쪼갤 용량 설정");
4035 theme::pointer(&check);
4036 theme::focus(&check);
4037 if !self.split {
4038 return;
4039 }
4040 ui.horizontal(|ui| {
4041 ui.add_sized([72.0, theme::FIELD], egui::Label::new("볼륨 크기"));
4042 let edit = ui.add_sized(
4043 [120.0, theme::FIELD],
4044 egui::TextEdit::singleline(&mut self.split_amount)
4045 .id(egui::Id::unique("split-volume-size"))
4046 .char_limit(9)
4047 .align(egui::Align2::LEFT_CENTER),
4048 );
4049 theme::focus(&edit);
4050 for unit in [present::VolumeUnit::Mb, present::VolumeUnit::Gb] {
4051 let choice = ui.selectable_value(&mut self.split_unit, unit, unit.label());
4052 theme::pointer(&choice);
4053 }
4054 });
4055 match self.split_volume() {
4056 Err(error) => {
4057 ui.colored_label(theme::ERROR, error);
4058 }
4059 Ok(_) => {
4060 let name = if self.zip_name.is_empty() {
4061 "이름.7z"
4062 } else {
4063 &self.zip_name
4064 };
4065 ui.label(
4066 RichText::new(format!(
4067 "{name}.001, {name}.002 …로 나누어 저장합니다. 볼륨은 최대 {}개입니다.",
4068 present::MAX_VOLUMES
4069 ))
4070 .color(theme::MUTED),
4071 );
4072 }
4073 }
4074 }
4075
4076 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
4077 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
4078 let ready =
4079 !self.sources.is_empty() && self.zip_password_ready() && self.split_volume().is_ok();
4080 let enabled = self.picker.is_none();
4081 let (cancel, compress) = ui
4082 .add_enabled_ui(enabled, |ui| {
4083 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
4084 })
4085 .inner;
4086 if compress {
4087 self.open_picker(if self.seven_zip {
4088 Purpose::SaveSevenZip
4089 } else {
4090 Purpose::SaveZip
4091 });
4092 }
4093 cancel
4094 }
4095
4096 fn resource_dialog(&mut self, ctx: &egui::Context) {
4097 let Some(question) = self.model.resource.clone() else {
4098 return;
4099 };
4100 let Some(job) = self.model.job_id() else {
4101 return;
4102 };
4103 let mut allow = false;
4104 let mut cancel = false;
4105 let modal = egui::Modal::new(egui::Id::unique(("archive-resource", job, question.id)))
4106 .show(ctx, |ui| {
4107 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
4108 ui.heading(if question.scope.ratio {
4109 "압축률이 매우 높습니다"
4110 } else {
4111 "큰 작업을 허용할까요?"
4112 });
4113 ui.label(match question.action {
4114 ActionKind::List => "압축파일 목록 열기",
4115 ActionKind::Extract => "압축 해제",
4116 ActionKind::CreateZip => "ZIP 만들기",
4117 ActionKind::CreateSevenZip => "7z 만들기",
4118 ActionKind::RecoverZip => "ZIP 복구",
4119 ActionKind::Preview => "파일 미리보기",
4120 });
4121 if question.scope.ratio {
4122 ui.label("작은 압축파일도 많은 저장 공간을 사용할 수 있습니다.");
4123 }
4124 if question.scope.output {
4125 ui.label(format!(
4126 "총량 한도: {}에서 {}로",
4127 present::bytes_text(question.soft_limits.output),
4128 present::bytes_text(question.ceiling.output)
4129 ));
4130 }
4131 if question.scope.entries {
4132 ui.label(format!(
4133 "항목 한도: {}개에서 {}개로",
4134 question.soft_limits.entries, question.ceiling.entries
4135 ));
4136 }
4137 let mut u = question.usage;
4138 let estimated = self.model.estimated_usage();
4139 u.estimated_bytes = u.estimated_bytes.or(estimated.estimated_bytes);
4140 u.estimated_entries = u.estimated_entries.or(estimated.estimated_entries);
4141 let bytes = |value: Option<u64>| {
4142 value
4143 .map(present::bytes_text)
4144 .unwrap_or_else(|| "미확인".into())
4145 };
4146 let entries = |value: Option<u32>| {
4147 value
4148 .map(|n| format!("{n}개"))
4149 .unwrap_or_else(|| "미확인".into())
4150 };
4151 ui.label(format!(
4152 "예상 총량: {} / 실제 총량: {}",
4153 bytes(u.estimated_bytes),
4154 bytes(u.actual_bytes)
4155 ));
4156 ui.label(format!(
4157 "예상 항목: {} / 실제 항목: {}",
4158 entries(u.estimated_entries),
4159 entries(u.actual_entries)
4160 ));
4161 if question.scope.ratio {
4162 ui.label(format!(
4163 "압축 크기: {} / 풀린 크기: {}",
4164 bytes(u.compressed_bytes),
4165 bytes(u.ratio_output_bytes)
4166 ));
4167 }
4168 ui.label(format!(
4169 "확인한 저장 볼륨의 여유 공간: {}",
4170 bytes(u.available_bytes)
4171 ));
4172 ui.label(format!(
4173 "이 작업의 상한: {} / {}개",
4174 present::bytes_text(question.ceiling.output),
4175 question.ceiling.entries
4176 ));
4177 ui.label("이 작업에만 적용합니다. 공간 부족이나 자원 상한에 도달하면 중단합니다.");
4178 ui.horizontal(|ui| {
4179 cancel = theme::action(ui, "취소", false, true).clicked();
4180 allow = theme::action(ui, "이 작업 허용", true, true).clicked();
4181 });
4182 });
4183 if cancel || modal.should_close() {
4184 self.clear_password();
4185 self.model.cancel();
4186 } else if allow {
4187 self.model.resource_reply(job, question.id, true);
4188 }
4189 }
4190
4191 fn conflict_dialog(&mut self, ctx: &egui::Context) {
4192 let conflict = self.model.conflict.clone().unwrap();
4193 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
4194 if self.conflict_challenge != Some(question) {
4195 self.conflict_challenge = Some(question);
4196 self.conflict_apply = false;
4197 }
4198 let mut choice = None;
4199 let mut cancel = false;
4200 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
4201 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
4202 ui.heading("같은 이름의 파일이 있습니다");
4203 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
4204 ui.add_space(theme::SPACE);
4205 egui::Grid::new("conflict-sizes")
4206 .spacing([24.0, 8.0])
4207 .show(ui, |ui| {
4208 ui.label("기존 파일");
4209 ui.label(present::bytes_text(conflict.existing_size));
4210 ui.end_row();
4211 ui.label("압축파일 안의 파일");
4212 ui.label(present::bytes_text(conflict.incoming_size));
4213 ui.end_row();
4214 });
4215 ui.add_space(theme::SPACE);
4216 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
4217 ui.add_space(theme::SPACE);
4218 ui.horizontal_wrapped(|ui| {
4219 for (label, value) in [
4220 ("덮어쓰기", ConflictChoice::Overwrite),
4221 ("건너뛰기", ConflictChoice::Skip),
4222 ("이름 바꿔 저장", ConflictChoice::Rename),
4223 ] {
4224 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
4225 choice = Some(value);
4226 }
4227 }
4228 });
4229 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
4230 if let Some(error) = &self.model.error {
4231 Self::error_notice(ui, present::client_error_text(error));
4232 }
4233 cancel = theme::action(ui, "작업 취소", false, true).clicked();
4234 });
4235 if modal.should_close() || cancel {
4236 self.model.cancel();
4237 } else if let Some(choice) = choice {
4238 self.model.resolve_conflict(choice, self.conflict_apply);
4239 }
4240 }
4241
4242 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
4243 let (_, attempt, encrypt) = self.model.challenge.unwrap();
4244 let mut submit = false;
4245 let mut cancel = false;
4246 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
4247 id == egui::Id::unique("archive-password-input")
4248 || id == egui::Id::unique("archive-password-confirm")
4249 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
4250 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
4251 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
4252 ui.heading(if encrypt {
4253 "ZIP 암호 설정"
4254 } else {
4255 "암호가 필요합니다"
4256 });
4257 if encrypt {
4258 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
4259 } else if let Some(path) = &self.model.archive {
4260 ui.label(format!(
4261 "{}은 암호로 보호되어 있습니다.",
4262 present::middle_text(
4263 &path.file_name().unwrap_or_default().to_string_lossy(),
4264 24
4265 )
4266 ));
4267 }
4268 ui.horizontal(|ui| {
4269 ui.label("암호");
4270 let edit = ui.add(
4271 egui::TextEdit::singleline(&mut self.password)
4272 .password(!self.password_visible)
4273 .id(egui::Id::unique("archive-password-input"))
4274 .char_limit(1024)
4275 .desired_width(232.0),
4276 );
4277 theme::focus(&edit);
4278 if new_challenge {
4279 edit.request_focus();
4280 }
4281 if theme::action(
4282 ui,
4283 if self.password_visible {
4284 "숨기기"
4285 } else {
4286 "보기"
4287 },
4288 false,
4289 true,
4290 )
4291 .clicked()
4292 {
4293 self.password_visible = !self.password_visible;
4294 }
4295 });
4296 if encrypt {
4297 ui.horizontal(|ui| {
4298 ui.label("암호 확인");
4299 let edit = ui.add(
4300 egui::TextEdit::singleline(&mut self.password_confirm)
4301 .password(!self.password_visible)
4302 .id(egui::Id::unique("archive-password-confirm"))
4303 .char_limit(1024)
4304 .desired_width(232.0),
4305 );
4306 theme::focus(&edit);
4307 });
4308 if self.password != self.password_confirm {
4309 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
4310 }
4311 } else if attempt > 1 {
4312 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
4313 }
4314 if self.password.len() > 1024 {
4315 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
4316 }
4317 let valid = !self.password.is_empty()
4318 && self.password.len() <= 1024
4319 && (!encrypt || self.password == self.password_confirm);
4320 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
4321 cancel = actions.0;
4322 submit = actions.1 || (valid && password_enter);
4323 });
4324 if modal.should_close() || cancel {
4325 self.clear_password();
4326 self.model.cancel();
4327 } else if submit {
4328 let password = std::mem::take(&mut self.password);
4329 self.clear_password();
4330 self.model.password(password);
4331 }
4332 }
4333
4334 fn close_dialog(&mut self, ctx: &egui::Context) {
4335 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
4336 if matches!(
4337 self.model.close,
4338 Close::Open | Close::Allowed | Close::Review
4339 ) {
4340 return;
4341 }
4342 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
4343 ui.set_width(420.0);
4344 match self.model.close {
4345 Close::Confirm => {
4346 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
4347 let busy = self.model.busy();
4348 let (heading, text, keep, close) = if busy {
4349 (
4350 "작업 중 닫기",
4351 "작업을 취소하고 닫을까요?",
4352 "계속 작업",
4353 "취소하고 닫기",
4354 )
4355 } else {
4356 (
4357 "닫기",
4358 "작업이 끝났습니다. 창을 닫을까요?",
4359 "열어 두기",
4360 "닫기",
4361 )
4362 };
4363 ui.heading(heading);
4364 ui.label(text);
4365 ui.horizontal(|ui| {
4366 if theme::action(ui, keep, false, true).clicked() {
4367 self.model.keep_open();
4368 }
4369 if theme::action(ui, close, true, true).clicked() {
4370 self.clear_password();
4371 self.model.confirm_close();
4372 }
4373 });
4374 }
4375 Close::Waiting => {
4376 ui.heading("종료 확인 중");
4377 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
4378 if theme::action(ui, "닫기 취소", false, true).clicked() {
4379 self.model.keep_open();
4380 }
4381 }
4382 _ => {}
4383 }
4384 });
4385 }
4386}
4387
4388impl eframe::App for ArchiveApp {
4389 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
4390 self.show(root);
4391 }
4392
4393 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
4394 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
4395 if std::mem::take(&mut self.release_after_move) {
4396 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
4397 raw_input.events.insert(
4398 0,
4399 egui::Event::PointerButton {
4400 pos,
4401 button: egui::PointerButton::Primary,
4402 pressed: false,
4403 modifiers: ctx.input(|i| i.modifiers),
4404 },
4405 );
4406 }
4407 }
4408}
4409impl Drop for ArchiveApp {
4410 fn drop(&mut self) {
4411 self.clear_password();
4412 for (_, root) in self.open_roots.drain(..) {
4413 present::remove_open_root(root);
4414 }
4415 }
4416}