team-ljyzipelo

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