team-ljyzipelo

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