team-ljyzipelo

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