team-ljyzipelo

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