team-ljyzipelo

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