team-ljyzipelo

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