team-ljyzipelo

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