team-ljyzipelo

공개
4,715줄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 paths.is_empty() {
1504 return;
1505 }
1506 // 목록 항목을 끌다가 Zipelo 창 위에 놓으면 Zipelo가 넘긴 임시 폴더의 경로가 다시
1507 // 들어옴. 그 파일을 압축파일로 열지 않고 무시함.
1508 if paths.iter().any(|path| {
1509 self.open_roots
1510 .iter()
1511 .any(|(_, root)| path.starts_with(root.path()))
1512 }) {
1513 crate::log_debug!("Zipelo 임시 폴더의 항목을 자기 창에 놓음: 무시");
1514 return;
1515 }
1516 if self.preview_open || self.model.busy() {
1517 return;
1518 }
1519 if paths.len() == 1 && !self.create && !paths[0].is_dir() {
1520 if std::fs::symlink_metadata(&paths[0])
1521 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
1522 {
1523 self.open_path(paths[0].clone());
1524 } else {
1525 self.ui_error = Some("일반 압축파일을 선택하세요".into());
1526 }
1527 } else {
1528 self.add_sources(paths);
1529 }
1530 }
1531
1532 fn poll(&mut self) {
1533 let busy = self.model.busy();
1534 let close_before = self.model.close;
1535 self.model.poll();
1536 if close_before == Close::Confirm && self.model.close == Close::Review {
1537 // 종료 확인 창에 답하기 전에 작업이 끝났음. 사용자가 닫기를 승인하지 않았으므로
1538 // 바로 닫지 않고 계속 물음(close_dialog가 작업이 끝난 문구로 바꿔 보여 줌).
1539 self.model.close = Close::Confirm;
1540 }
1541 if busy && !self.model.busy() {
1542 let completed = self.model.confirmed
1543 && self
1544 .model
1545 .terminal
1546 .as_ref()
1547 .is_some_and(|t| t.outcome == Outcome::Completed);
1548 if self.opening.is_some() {
1549 // 열기용 폴더는 앱을 닫을 때 지우므로 풀 위치 소유 기록만 정리함.
1550 self.owned_destination = None;
1551 // 한도 실패는 늘려서 다시 시도할 수 있으므로 열기 상태를 남김.
1552 if completed || !self.open_retry_pending() {
1553 self.finish_open(completed);
1554 }
1555 }
1556 if let Some(path) = self.owned_destination.take() {
1557 if !self.model.confirmed
1558 || self
1559 .model
1560 .terminal
1561 .as_ref()
1562 .is_none_or(|t| t.outcome != Outcome::Completed)
1563 {
1564 present::remove_owned_empty(&path);
1565 }
1566 }
1567 }
1568 if self.opening.is_some() && !self.model.busy() && !self.open_retry_pending() {
1569 // 결과를 닫았거나 다시 시도할 수 없게 되었으면 원래 풀 위치로 되돌림.
1570 self.finish_open(false);
1571 }
1572 }
1573
1574 pub fn show(&mut self, root: &mut egui::Ui) {
1575 let ctx = root.ctx().clone();
1576 self.forget_password_history(&ctx);
1577 if !self.initialized {
1578 theme::apply(&ctx);
1579 self.initialized = true;
1580 }
1581 self.poll();
1582 self.poll_drag_out();
1583 let preview_was_open = self.preview_open;
1584 self.poll_picker();
1585 if self.model.challenge.is_some_and(|(_, _, encrypt)| encrypt)
1586 && let Some(password) = self.pending_zip_password.take()
1587 {
1588 // ZIP 만들기 창에서 받은 암호를 작업자의 암호 요청에 바로 넘김.
1589 self.model.password(password);
1590 }
1591 if !self.model.busy()
1592 && let Some(mut pending) = self.pending_zip_password.take()
1593 {
1594 wipe(&mut pending);
1595 }
1596 let challenge = self.model.challenge.map(|(id, _, _)| id);
1597 let new_challenge = challenge != self.password_challenge;
1598 if new_challenge || challenge.is_none() {
1599 self.clear_password();
1600 }
1601 self.password_challenge = challenge;
1602 // Esc 처리에 쓰려고 그리기 전에 입력란 초점과 열린 자식 창을 기억함.
1603 self.escape_handled = false;
1604 let (text_focused, main_search_focused) = self.text_focus_before;
1605 let child_open = self.child_window_open();
1606 if self.model.archive.is_some()
1607 && !self.main_modal_open()
1608 && !self.preview_open
1609 && self.model.close == Close::Open
1610 {
1611 // 더 구체적인 Ctrl+Shift+F를 먼저 확인함.
1612 if ctx.input_mut(|i| {
1613 i.consume_key(
1614 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1615 egui::Key::F,
1616 )
1617 }) {
1618 self.open_find(true);
1619 } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)) {
1620 self.open_find(false);
1621 }
1622 }
1623 let dropped = ctx.input(|i| {
1624 i.raw
1625 .dropped_files
1626 .iter()
1627 .map(|file| file.path().to_path_buf())
1628 .collect()
1629 });
1630 if self.picker.is_none() {
1631 self.on_drop(dropped);
1632 }
1633 if ctx.input(|i| i.viewport().close_requested()) {
1634 self.model.request_close();
1635 // 실행 중인 작업이 없으면 결과 확인 안내 없이 바로 닫음.
1636 self.model.acknowledge_close();
1637 if self.model.close != Close::Allowed {
1638 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
1639 }
1640 }
1641 if self.model.close == Close::Review {
1642 // 작업을 취소하고 닫기로 한 뒤 정리가 끝난 경우도 안내 없이 닫음.
1643 self.model.acknowledge_close();
1644 }
1645 if self.model.close == Close::Allowed {
1646 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
1647 }
1648 let title = self
1649 .model
1650 .archive
1651 .as_ref()
1652 .map(|path| {
1653 let full = if path.is_absolute() {
1654 path.clone()
1655 } else {
1656 std::env::current_dir().unwrap_or_default().join(path)
1657 };
1658 format!("{} — Zipelo", full.display())
1659 })
1660 .unwrap_or_else(|| "Zipelo".into());
1661 let short_title = if let Some(path) = title.strip_suffix(" — Zipelo") {
1662 format!(
1663 "{} — Zipelo",
1664 theme::window_title(root, path, ctx.content_rect().width() - 300.0)
1665 )
1666 } else {
1667 title.clone()
1668 };
1669 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
1670 if self.custom_frame
1671 && window_frame::title_bar(
1672 root,
1673 "main",
1674 &title,
1675 window_frame::Buttons {
1676 minimize: true,
1677 maximize: true,
1678 },
1679 )
1680 {
1681 self.release_after_move = true;
1682 }
1683 egui::Panel::top("archive-actions")
1684 .frame(
1685 theme::panel(theme::PANEL)
1686 .corner_radius(0)
1687 .inner_margin(egui::Margin {
1688 left: 12,
1689 right: 12,
1690 // 버튼 안 내용은 보이는 모양 기준으로 가운데에 두므로 위아래를 같게 둠.
1691 top: 4,
1692 bottom: 4,
1693 }),
1694 )
1695 .show(root, |ui| {
1696 ui.horizontal(|ui| {
1697 ui.spacing_mut().item_spacing.x = 2.0;
1698 let idle = !self.model.busy()
1699 && self.model.close == Close::Open
1700 && self.picker.is_none();
1701 if theme::tool(ui, "열기", theme::OPEN, idle, false)
1702 .on_hover_text(&title)
1703 .clicked()
1704 {
1705 self.open_picker(Purpose::Open);
1706 }
1707 if theme::tool(
1708 ui,
1709 "미리보기",
1710 theme::PREVIEW,
1711 idle && self.can_preview() && !self.preview_open,
1712 false,
1713 )
1714 .on_disabled_hover_text(
1715 if self.model.list_id.as_ref().is_some_and(ListId::is_split) {
1716 "분할 압축파일은 미리보기를 지원하지 않습니다"
1717 } else {
1718 "일반 파일 하나를 선택하세요"
1719 },
1720 )
1721 .clicked()
1722 {
1723 self.begin_preview(ui.ctx());
1724 }
1725 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
1726 self.choose_zip_folder();
1727 }
1728 if theme::tool(
1729 ui,
1730 "압축해제",
1731 theme::EXTRACT,
1732 self.model.can_extract(),
1733 true,
1734 )
1735 .clicked()
1736 {
1737 self.open_picker(Purpose::Destination);
1738 }
1739 });
1740 });
1741 egui::Panel::bottom("archive-status")
1742 .exact_size(theme::STATUS_HEIGHT)
1743 .resizable(false)
1744 .frame(
1745 egui::Frame::new()
1746 .fill(theme::STRIPE)
1747 .inner_margin(egui::Margin::symmetric(16, 0)),
1748 )
1749 .show(root, |ui| {
1750 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1751 let selected = rows
1752 .iter()
1753 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
1754 .count();
1755 let rect = ui.max_rect();
1756 let half = (rect.width() - theme::SPACE) / 2.0;
1757 theme::status_text(
1758 ui,
1759 rect,
1760 &format!("{}개 항목", rows.len()),
1761 half,
1762 Align::Min,
1763 );
1764 theme::status_text(ui, rect, &format!("선택 {selected}개"), half, Align::Max);
1765 });
1766 if ctx.embed_viewports()
1767 && !self.work_in_parent
1768 && self.work_visible()
1769 && !self.limit_result_visible()
1770 {
1771 // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
1772 egui::Panel::bottom("archive-work")
1773 .frame(theme::panel(theme::PANEL).corner_radius(0))
1774 .show(root, |ui| self.work_area(ui));
1775 }
1776 egui::CentralPanel::default()
1777 .frame(
1778 theme::panel(theme::PANEL)
1779 .corner_radius(0)
1780 .inner_margin(egui::Margin::ZERO),
1781 )
1782 .show(root, |ui| {
1783 if let Some((_, warning)) = &self.recovery_warning {
1784 ui.colored_label(theme::WARNING, warning);
1785 }
1786 if self.model.archive.is_some() {
1787 self.archive_list(ui);
1788 } else {
1789 self.empty(ui);
1790 }
1791 });
1792 self.forget_password_history(&ctx);
1793 self.preview_dialog(&ctx);
1794 self.work_window(&ctx);
1795 self.limit_result_dialog(&ctx);
1796 self.create_window(&ctx);
1797 self.find_window(&ctx);
1798 if self.model.challenge.is_some() {
1799 self.password_dialog(&ctx, new_challenge);
1800 }
1801 self.resource_dialog(&ctx);
1802 if self.model.conflict.is_some() && self.model.close == Close::Open {
1803 self.conflict_dialog(&ctx);
1804 }
1805 self.close_dialog(&ctx);
1806 self.picker_notice(&ctx);
1807 self.handle_escape(&ctx, text_focused, main_search_focused, child_open);
1808 self.text_focus_before = (
1809 ctx.text_edit_focused(),
1810 ctx.memory(|m| m.has_focus(egui::Id::unique("archive-search"))),
1811 );
1812 if !preview_was_open
1813 && !self.preview_open
1814 && !self.model.busy()
1815 && let Some(id) = self.preview_return_focus.take()
1816 {
1817 ctx.memory_mut(|m| m.request_focus(id));
1818 }
1819 if self.custom_frame {
1820 window_frame::edges(&ctx, true);
1821 }
1822 if self.model.busy() {
1823 ctx.request_repaint_after(std::time::Duration::from_millis(30));
1824 }
1825 }
1826
1827 /// 메인 창 위에 자식 창(모달, 작업 창, 만들기 창, 찾기 창 등)이 떠 있는지.
1828 fn child_window_open(&self) -> bool {
1829 self.find.open
1830 || self.preview_open
1831 || self.create
1832 || self.picker.is_some()
1833 || self.model.challenge.is_some()
1834 || self.model.resource.is_some()
1835 || self.model.conflict.is_some()
1836 || self.model.close != Close::Open
1837 || self.work_visible()
1838 }
1839
1840 /// 다른 곳에서 처리하지 않은 Esc를 처리함. 자식 창이 떠 있으면 그 창을 닫고,
1841 /// 아무 창도 없으면 프로그램을 종료함(작업 중이면 기존 종료 확인을 거침).
1842 /// 암호 입력, 미리보기 등 모달은 Esc를 직접 받아 닫으므로 여기까지 오지 않음.
1843 fn handle_escape(
1844 &mut self,
1845 ctx: &egui::Context,
1846 text_focused: bool,
1847 main_search_focused: bool,
1848 child_open: bool,
1849 ) {
1850 if self.escape_handled
1851 || self.picker.is_some()
1852 || !ctx.input(|i| i.key_pressed(egui::Key::Escape))
1853 {
1854 return;
1855 }
1856 let consume = |ctx: &egui::Context| {
1857 ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
1858 };
1859 if child_open {
1860 if self.find.open && !main_search_focused {
1861 consume(ctx);
1862 crate::log_debug!("Esc: 찾기 창 닫기");
1863 self.close_find();
1864 } else if matches!(self.model.close, Close::Confirm | Close::Waiting) {
1865 consume(ctx);
1866 crate::log_debug!("Esc: 종료 확인 취소");
1867 self.model.keep_open();
1868 } else if self.create && !self.model.busy() {
1869 consume(ctx);
1870 crate::log_debug!("Esc: 만들기 창 닫기");
1871 self.close_create();
1872 } else if !self.model.busy() && self.work_visible() {
1873 consume(ctx);
1874 crate::log_debug!("Esc: 작업 결과 창 닫기");
1875 self.dismissed = true;
1876 self.ui_error = None;
1877 self.model.input_error = None;
1878 }
1879 // 진행 중인 작업 창은 Esc로 닫지 않음. 취소는 [취소] 버튼으로 함.
1880 return;
1881 }
1882 if text_focused {
1883 // 입력란에서 누른 Esc는 입력란 초점만 해제함.
1884 return;
1885 }
1886 consume(ctx);
1887 crate::log_info!("Esc: 프로그램 종료 요청");
1888 ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close);
1889 }
1890
1891 /// 찾기 창. 진행·결과 창처럼 부모 창을 따라가는 별도 창으로 띄우고,
1892 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 창으로 띄움.
1893 fn find_window(&mut self, ctx: &egui::Context) {
1894 if !self.find.open {
1895 return;
1896 }
1897 if self.model.archive.is_none() || self.model.list_id.is_none() {
1898 self.close_find();
1899 return;
1900 }
1901 if self.main_modal_open() || self.preview_open {
1902 // 암호 입력 등 모달을 가리지 않게 잠시 숨김.
1903 self.find.win.open = false;
1904 return;
1905 }
1906 let title = if self.find.whole_path {
1907 "전체 경로에서 찾기"
1908 } else {
1909 "찾기"
1910 };
1911 let mut chosen = None;
1912 let mut close = false;
1913 if ctx.embed_viewports() || self.work_in_parent {
1914 egui::Window::new(title)
1915 .id(egui::Id::unique("archive-find-in-parent"))
1916 .title_bar(false)
1917 .default_pos(ctx.content_rect().right_top() + egui::vec2(-FIND_WIDTH - 24.0, 24.0))
1918 .default_width(FIND_WIDTH)
1919 .min_width(FIND_WIDTH)
1920 .max_width(FIND_WIDTH)
1921 .collapsible(false)
1922 .resizable(false)
1923 .fade_in(false)
1924 .fade_out(false)
1925 .frame(
1926 egui::Frame::new()
1927 .fill(theme::PANEL)
1928 .stroke(egui::Stroke::new(1.0, theme::BORDER))
1929 .inner_margin(egui::Margin::ZERO)
1930 .corner_radius(0),
1931 )
1932 .show(ctx, |ui| {
1933 let spacing = ui.spacing().item_spacing.y;
1934 ui.spacing_mut().item_spacing.y = 0.0;
1935 close = window_frame::in_parent_title(ui, "find-in-parent", title, true);
1936 egui::Frame::new()
1937 .inner_margin(egui::Margin::same(theme::PAD))
1938 .show(ui, |ui| {
1939 ui.spacing_mut().item_spacing.y = spacing;
1940 ui.set_width(FIND_WIDTH - 2.0 * theme::PAD as f32);
1941 let list_height = (ctx.content_rect().height() - 260.0)
1942 .clamp(120.0, FIND_HEIGHT - 200.0);
1943 chosen = self.find_contents(ui, list_height, false);
1944 });
1945 });
1946 } else {
1947 let id = egui::ViewportId::from_hash_of("archive-find");
1948 let window_title = format!("{title} — Zipelo");
1949 let custom_frame = self.custom_frame;
1950 let builder = self.find.win.builder(
1951 ctx,
1952 id,
1953 egui::vec2(FIND_WIDTH, FIND_HEIGHT),
1954 &window_title,
1955 !custom_frame,
1956 self.picker.is_some(),
1957 );
1958 ctx.show_viewport_immediate(id, builder, |ui, class| {
1959 if ui.ctx().input(|i| i.viewport().close_requested()) {
1960 close = true;
1961 }
1962 if ui
1963 .ctx()
1964 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
1965 {
1966 crate::log_debug!("Esc: 찾기 창 닫기");
1967 close = true;
1968 }
1969 // 찾기 창 안에서도 단축키로 찾는 범위를 바꿀 수 있음.
1970 if ui.ctx().input_mut(|i| {
1971 i.consume_key(
1972 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1973 egui::Key::F,
1974 )
1975 }) {
1976 self.find.whole_path = true;
1977 self.find.base.clear();
1978 self.find.focus_query = true;
1979 } else if ui
1980 .ctx()
1981 .input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F))
1982 {
1983 self.find.whole_path = false;
1984 self.find.base = self.folder.clone();
1985 self.find.focus_query = true;
1986 }
1987 if class == egui::ViewportClass::EmbeddedWindow {
1988 ui.set_width(FIND_WIDTH);
1989 chosen = self.find_contents(ui, FIND_HEIGHT - 200.0, false);
1990 return;
1991 }
1992 if custom_frame {
1993 window_frame::title_bar(
1994 ui,
1995 "find",
1996 &window_title,
1997 window_frame::Buttons {
1998 minimize: false,
1999 maximize: false,
2000 },
2001 );
2002 window_frame::edges(ui.ctx(), false);
2003 }
2004 egui::CentralPanel::default()
2005 .frame(
2006 theme::panel(theme::PANEL)
2007 .corner_radius(0)
2008 .inner_margin(egui::Margin::same(theme::PAD)),
2009 )
2010 .show(ui, |ui| {
2011 chosen = self.find_contents(ui, 0.0, true);
2012 });
2013 });
2014 }
2015 if let Some(found) = chosen {
2016 self.go_to_found(&found);
2017 } else if close {
2018 self.close_find();
2019 }
2020 }
2021
2022 /// 찾기 창 내용: 위쪽 검색어 입력란과 그 아래 세로로 긴 결과 목록.
2023 /// `list_height`가 0이면 남은 높이를 모두 목록에 씀. `own_keyboard`가 true면
2024 /// 창 전체가 찾기 창이므로 입력란에 초점이 없어도 화살표와 Enter를 받음.
2025 /// 결과를 골랐으면(더블클릭 또는 Enter) 그 결과를 돌려줌.
2026 fn find_contents(
2027 &mut self,
2028 ui: &mut egui::Ui,
2029 list_height: f32,
2030 own_keyboard: bool,
2031 ) -> Option<browser::Found> {
2032 self.refresh_find();
2033 let scope = if self.find.whole_path {
2034 "압축파일 전체 경로에서 찾습니다".to_owned()
2035 } else {
2036 format!("/{} 아래 모든 폴더에서 이름으로 찾습니다", self.find.base)
2037 };
2038 let width = ui.available_width();
2039 ui.add(egui::Label::new(RichText::new(&scope).color(theme::MUTED)).truncate())
2040 .on_hover_text(&scope);
2041 ui.add_space(theme::SPACE / 2.0);
2042 let query_id = egui::Id::unique("archive-find-query");
2043 let edit = ui.add(
2044 egui::TextEdit::singleline(&mut self.find.query)
2045 .id(query_id)
2046 .char_limit(512)
2047 .desired_width(width)
2048 .hint_text(if self.find.whole_path {
2049 "찾을 경로 입력"
2050 } else {
2051 "찾을 이름 입력"
2052 }),
2053 );
2054 theme::focus(&edit);
2055 if std::mem::take(&mut self.find.focus_query) {
2056 edit.request_focus();
2057 }
2058 if edit.changed() {
2059 self.refresh_find();
2060 self.find.cursor = (!self.find.results.is_empty()).then_some(0);
2061 self.find.offset = 0.0;
2062 self.find.scroll_to_cursor = true;
2063 }
2064 // 결과를 한 번 누르면 입력란 대신 결과 목록이 초점을 가지므로, 목록에 초점이 있을
2065 // 때도 화살표와 Enter를 받음(부모 안 찾기 창에서도 결과를 고른 뒤 Enter로 이동).
2066 let list_id = egui::Id::unique("archive-find-results");
2067 let keyboard = own_keyboard
2068 || edit.has_focus()
2069 || edit.lost_focus()
2070 || ui.memory(|m| m.has_focus(list_id));
2071 let count = self.find.results.len();
2072 let mut chosen = None;
2073 if keyboard && count > 0 {
2074 let (down, up, enter) = ui.input(|i| {
2075 (
2076 i.key_pressed(egui::Key::ArrowDown),
2077 i.key_pressed(egui::Key::ArrowUp),
2078 i.key_pressed(egui::Key::Enter),
2079 )
2080 });
2081 if down || up {
2082 let index = match self.find.cursor {
2083 None => 0,
2084 Some(index) if down => (index + 1).min(count - 1),
2085 Some(index) => index.saturating_sub(1),
2086 };
2087 self.find.cursor = Some(index);
2088 self.find.scroll_to_cursor = true;
2089 }
2090 if enter {
2091 chosen = Some(self.find.cursor.unwrap_or(0));
2092 }
2093 }
2094 ui.add_space(theme::SPACE / 2.0);
2095 let status = if self.find.query.trim().is_empty() {
2096 "검색어를 입력하세요".to_owned()
2097 } else if count == 0 {
2098 "찾은 항목이 없습니다".to_owned()
2099 } else if self.find.truncated {
2100 format!("처음 {count}개만 표시합니다. 검색어를 더 구체적으로 입력하세요")
2101 } else {
2102 format!("{count}개 찾음 · 두 번 누르거나 Enter로 이동")
2103 };
2104 ui.add(
2105 egui::Label::new(
2106 RichText::new(status)
2107 .size(theme::FONT_SMALL)
2108 .color(theme::MUTED),
2109 )
2110 .truncate(),
2111 );
2112 ui.add_space(theme::SPACE / 2.0);
2113 let height = if list_height > 0.0 {
2114 list_height
2115 } else {
2116 ui.available_height().max(FIND_ROW)
2117 };
2118 let (frame_rect, _) =
2119 ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
2120 // 결과 목록 전체가 키보드 초점을 받는 목록 상자임. 행 누름은 위에 그리는 행이 받음.
2121 let list = ui.interact(frame_rect, list_id, egui::Sense::click());
2122 list.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, true, "찾기 결과"));
2123 if list.has_focus() {
2124 ui.memory_mut(|memory| {
2125 memory.set_focus_lock_filter(
2126 list_id,
2127 egui::EventFilter {
2128 vertical_arrows: true,
2129 ..Default::default()
2130 },
2131 )
2132 });
2133 }
2134 theme::boxed_field(ui, frame_rect);
2135 let mut list_ui = ui.new_child(
2136 egui::UiBuilder::new()
2137 .max_rect(frame_rect.shrink(1.0))
2138 .layout(Layout::top_down(Align::Min)),
2139 );
2140 let viewport_height = frame_rect.height() - 2.0;
2141 if self.find.scroll_to_cursor
2142 && let Some(index) = self.find.cursor
2143 {
2144 let top = index as f32 * FIND_ROW;
2145 if top < self.find.offset {
2146 self.find.offset = top;
2147 } else if top + FIND_ROW > self.find.offset + viewport_height {
2148 self.find.offset = top + FIND_ROW - viewport_height;
2149 }
2150 }
2151 let mut area = egui::ScrollArea::vertical()
2152 .id_salt("archive-find-results")
2153 .auto_shrink([false, false]);
2154 if std::mem::take(&mut self.find.scroll_to_cursor) {
2155 area = area.vertical_scroll_offset(self.find.offset);
2156 }
2157 let output = area.show_rows(&mut list_ui, FIND_ROW, count, |ui, range| {
2158 ui.spacing_mut().item_spacing.y = 0.0;
2159 let row_width = ui.available_width();
2160 for index in range {
2161 let found = &self.find.results[index];
2162 let (rect, response) =
2163 ui.allocate_exact_size(egui::vec2(row_width, FIND_ROW), egui::Sense::click());
2164 theme::pointer(&response);
2165 let parent = format!(
2166 "/{}",
2167 found.path.rsplit_once('/').map_or("", |(parent, _)| parent)
2168 );
2169 response.widget_info(|| {
2170 egui::WidgetInfo::selected(
2171 egui::Role::ListBoxOption,
2172 true,
2173 self.find.cursor == Some(index),
2174 &found.path,
2175 )
2176 });
2177 theme::row_background(
2178 ui,
2179 rect,
2180 self.find.cursor == Some(index),
2181 response.hovered(),
2182 );
2183 ui.scope_builder(
2184 egui::UiBuilder::new()
2185 .max_rect(rect.shrink2(egui::vec2(10.0, 4.0)))
2186 .layout(Layout::left_to_right(Align::Center)),
2187 |ui| {
2188 ui.style_mut().interaction.selectable_labels = false;
2189 theme::icon(
2190 ui,
2191 if found.directory {
2192 Icon::Folder
2193 } else {
2194 Icon::File
2195 },
2196 20.0,
2197 );
2198 ui.add_space(6.0);
2199 let text_width = ui.available_width();
2200 ui.vertical(|ui| {
2201 ui.spacing_mut().item_spacing.y = 0.0;
2202 theme::bounded_text_hover(ui, &found.name, &found.path, text_width);
2203 ui.add_sized(
2204 egui::vec2(text_width, 18.0),
2205 egui::Label::new(
2206 RichText::new(&parent)
2207 .size(theme::FONT_SMALL)
2208 .color(theme::MUTED),
2209 )
2210 .truncate(),
2211 );
2212 });
2213 },
2214 );
2215 if response.clicked() {
2216 self.find.cursor = Some(index);
2217 ui.memory_mut(|m| m.request_focus(list_id));
2218 }
2219 if response.double_clicked() {
2220 chosen = Some(index);
2221 }
2222 }
2223 });
2224 self.find.offset = output.state.clamped_offset().y;
2225 chosen.and_then(|index| self.find.results.get(index).cloned())
2226 }
2227
2228 // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
2229 fn picker_notice(&mut self, ctx: &egui::Context) {
2230 if self.picker.is_none() {
2231 return;
2232 }
2233 egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
2234 ui.set_width(360.0);
2235 ui.label("파일 선택 창에서 선택을 마쳐 주세요");
2236 });
2237 ctx.request_repaint_after(std::time::Duration::from_millis(100));
2238 }
2239
2240 fn empty(&mut self, ui: &mut egui::Ui) {
2241 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
2242 let width = (ui.available_width() * 0.60)
2243 .max(480.0)
2244 .min(ui.available_width());
2245 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
2246 ui.add_space(y);
2247 ui.vertical_centered(|ui| {
2248 let drop_frame = egui::Frame::new()
2249 .fill(if hovered { theme::DROP } else { theme::PANEL })
2250 .corner_radius(theme::DROP_RADIUS)
2251 .inner_margin(egui::Margin::same(theme::DROP_PAD))
2252 .show(ui, |ui| {
2253 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
2254 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
2255 ui.vertical_centered(|ui| {
2256 ui.add_space(theme::PAD as f32);
2257 theme::icon(ui, Icon::Archive, 48.0);
2258 ui.add_space(theme::PAD as f32);
2259 ui.label(
2260 RichText::new(if hovered {
2261 "놓으면 엽니다"
2262 } else {
2263 "압축파일을 여기에 끌어 놓으세요"
2264 })
2265 .size(theme::FONT_LARGE)
2266 .strong(),
2267 );
2268 ui.label("또는");
2269 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
2270 self.open_picker(Purpose::Open);
2271 }
2272 });
2273 });
2274 let rect = drop_frame.response.rect;
2275 if hovered {
2276 ui.painter().rect_stroke(
2277 rect,
2278 12,
2279 egui::Stroke::new(2.0, theme::BLUE),
2280 egui::StrokeKind::Inside,
2281 );
2282 } else {
2283 let stroke = egui::Stroke::new(2.0, theme::DASH);
2284 for (a, b) in [
2285 (rect.left_top(), rect.right_top()),
2286 (rect.right_top(), rect.right_bottom()),
2287 (rect.right_bottom(), rect.left_bottom()),
2288 (rect.left_bottom(), rect.left_top()),
2289 ] {
2290 let direction = (b - a).normalized();
2291 let mut distance = theme::DROP_RADIUS as f32;
2292 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
2293 ui.painter().line_segment(
2294 [
2295 a + direction * distance,
2296 a + direction
2297 * (distance + theme::SPACE)
2298 .min(a.distance(b) - theme::DROP_RADIUS as f32),
2299 ],
2300 stroke,
2301 );
2302 distance += theme::PAD as f32;
2303 }
2304 }
2305 }
2306 ui.add_space(theme::PAD as f32);
2307 ui.colored_label(
2308 theme::MUTED,
2309 "ZIP, 7z, TAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ 파일을 열 수 있습니다",
2310 );
2311 });
2312 }
2313
2314 fn archive_list(&mut self, ui: &mut egui::Ui) {
2315 // 경로 줄은 입력란 높이만 차지하고 창 너비 전체를 회색으로 채움.
2316 let path_row = egui::Frame::new()
2317 .fill(theme::STRIPE)
2318 .inner_margin(egui::Margin {
2319 left: 8,
2320 right: 12,
2321 top: 0,
2322 bottom: 0,
2323 })
2324 .show(ui, |ui| {
2325 ui.set_min_width(ui.available_width());
2326 ui.horizontal(|ui| {
2327 ui.set_height(theme::FIELD);
2328 // 간격은 아래에서 직접 넣어 위치가 흔들리지 않게 함.
2329 ui.spacing_mut().item_spacing.x = 0.0;
2330 let up = theme::flat_icon_button(
2331 ui,
2332 "위로",
2333 theme::UP,
2334 !self.folder.is_empty() && !self.model.busy(),
2335 egui::vec2(theme::FIELD, theme::FIELD),
2336 );
2337 if up.clicked() {
2338 let parent = self
2339 .folder
2340 .rsplit_once('/')
2341 .map_or("", |(parent, _)| parent)
2342 .to_owned();
2343 self.browse_folder(&parent);
2344 }
2345 ui.add_space(6.0);
2346 let path = format!("/{}", self.folder);
2347 let search_width = 240.0;
2348 let gap = 8.0;
2349 let path_width = (ui.available_width() - search_width - gap).max(0.0);
2350 // 두 입력란은 같은 높이의 칸을 받아 같은 세로 위치에 그림.
2351 let (path_rect, _) = ui.allocate_exact_size(
2352 egui::vec2(path_width, theme::FIELD),
2353 egui::Sense::hover(),
2354 );
2355 theme::field_frame(ui, path_rect, false);
2356 // 부모 배치에 영향을 주지 않는 하위 영역에 경로 글자를 그림.
2357 let mut text_ui = ui.new_child(
2358 egui::UiBuilder::new()
2359 .max_rect(path_rect.shrink2(egui::vec2(10.0, 0.0)))
2360 .layout(Layout::left_to_right(Align::Center)),
2361 );
2362 theme::bounded_text(&mut text_ui, &path, (path_width - 20.0).max(0.0));
2363 ui.add_space(gap);
2364 let (search_rect, _) = ui.allocate_exact_size(
2365 egui::vec2(search_width, theme::FIELD),
2366 egui::Sense::hover(),
2367 );
2368 let search_id = egui::Id::unique("archive-search");
2369 let focused = ui.memory(|m| m.has_focus(search_id));
2370 theme::field_frame(ui, search_rect, focused);
2371 let icon = egui::Rect::from_center_size(
2372 egui::pos2(search_rect.left() + 20.0, search_rect.center().y),
2373 egui::vec2(16.0, 16.0),
2374 );
2375 theme::svg_icon(ui.painter(), icon, theme::SEARCH, theme::MUTED);
2376 let search = ui.put(
2377 egui::Rect::from_min_max(
2378 egui::pos2(icon.right() + 8.0, search_rect.top() + 1.0),
2379 egui::pos2(search_rect.right() - 8.0, search_rect.bottom() - 1.0),
2380 ),
2381 egui::TextEdit::singleline(&mut self.search)
2382 .id(search_id)
2383 .frame(egui::Frame::NONE)
2384 .margin(egui::Margin::ZERO)
2385 .align(egui::Align2::LEFT_CENTER)
2386 .hint_text("파일 검색"),
2387 );
2388 if search.changed() {
2389 self.clear_list_selection();
2390 }
2391 });
2392 })
2393 .response
2394 .rect;
2395 // 경로 줄 아래 한 줄이 목록과의 경계이자 입력란의 아래 테두리 역할을 함.
2396 ui.painter().hline(
2397 path_row.x_range(),
2398 path_row.bottom() - 0.5,
2399 egui::Stroke::new(1.0, theme::BORDER),
2400 );
2401 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
2402
2403 // 열 제목 줄 없이 바로 목록을 보여 줌. 이름과 크기는 내용으로 구분됨.
2404 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 40.0).max(120.0);
2405 let active = !self.preview_open
2406 && !self.model.busy()
2407 && !self.create
2408 && self.model.challenge.is_none()
2409 && self.model.close == Close::Open;
2410 let list_id = egui::Id::unique("archive-list");
2411 let background = ui.interact(
2412 ui.available_rect_before_wrap(),
2413 list_id,
2414 if active {
2415 egui::Sense::click_and_drag()
2416 } else {
2417 egui::Sense::hover()
2418 },
2419 );
2420 background
2421 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
2422 if active && std::mem::take(&mut self.focus_list) {
2423 background.request_focus();
2424 }
2425 if background.has_focus() {
2426 ui.ctx().memory_mut(|memory| {
2427 memory.set_focus_lock_filter(
2428 list_id,
2429 egui::EventFilter {
2430 vertical_arrows: true,
2431 escape: true,
2432 ..Default::default()
2433 },
2434 )
2435 });
2436 }
2437 let mut focused = None;
2438 let mut open = None;
2439 let mut open_file = None;
2440 let mut menu_action = None;
2441 let mut drag_out = false;
2442 let mut next_offset = None;
2443 let output = egui::ScrollArea::vertical()
2444 .id_salt("archive-rows")
2445 .auto_shrink([false, false])
2446 .vertical_scroll_offset(self.list_offset)
2447 .show_viewport(ui, |ui, viewport| {
2448 let origin = ui.max_rect().min;
2449 let clip = ui.clip_rect();
2450 // 행을 누르는 영역은 오른쪽 24px을 비워 둠. 목록이 길어도 그 빈 곳에서
2451 // 끌어서 선택을 시작할 수 있음. 행 배경(선택, 마우스 올림)은 너비를 꽉 채움.
2452 let full_width = ui.available_width();
2453 let width = (full_width - 24.0).max(0.0);
2454 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
2455 let point = ui.input(|i| i.pointer.interact_pos());
2456 if active && let Some(point) = point {
2457 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
2458 let relative = press - origin;
2459 let in_row = relative.x >= 0.0
2460 && relative.x <= width
2461 && relative.y >= 0.0
2462 && relative.y < rows.len() as f32 * LIST_ROW;
2463 // 목록 위에 떠 있는 창(부모 안 작업 창 등)을 누른 경우는 목록 조작이 아님.
2464 let on_list = ui.ctx().layer_id_at(press) == Some(ui.layer_id());
2465 if clip.contains(press)
2466 && on_list
2467 && !in_row
2468 && ui.input(|i| i.pointer.primary_pressed())
2469 {
2470 background.request_focus();
2471 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
2472 self.marquee = Some(Marquee {
2473 origin: relative.to_pos2(),
2474 base: if ctrl {
2475 self.model.selected.clone()
2476 } else {
2477 BTreeSet::new()
2478 },
2479 moved: false,
2480 });
2481 if !ctrl {
2482 self.model.selected.clear();
2483 self.list_anchor = None;
2484 self.list_cursor = None;
2485 }
2486 }
2487 if let Some(drag) = &mut self.marquee {
2488 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
2489 drag.moved |= drag.origin.distance(end) > 3.0;
2490 if drag.moved {
2491 let rect = egui::Rect::from_two_pos(drag.origin, end);
2492 self.model.selected = drag.base.clone();
2493 if rect.left() < width && rect.right() > 0.0 {
2494 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
2495 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
2496 .min(rows.len());
2497 for row in rows.iter().take(last).skip(first) {
2498 self.model.selected.extend(&row.ids);
2499 }
2500 if first < last {
2501 self.list_anchor = Some(first);
2502 self.list_cursor = Some(last - 1);
2503 }
2504 }
2505 let speed = if point.y > clip.bottom() - 24.0 {
2506 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
2507 } else if point.y < clip.top() + 24.0 {
2508 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
2509 } else {
2510 0.0
2511 };
2512 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
2513 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
2514 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
2515 0.0,
2516 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
2517 ));
2518 ui.ctx().request_repaint();
2519 }
2520 }
2521 }
2522 }
2523 let first = (viewport.min.y / LIST_ROW).floor() as usize;
2524 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
2525 for index in first.min(rows.len())..last {
2526 let row = &rows[index];
2527 let rect = egui::Rect::from_min_size(
2528 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
2529 egui::vec2(width, LIST_ROW),
2530 );
2531 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
2532 let response = ui
2533 .interact(
2534 rect,
2535 egui::Id::unique(("archive-row", &row.path)),
2536 if active && self.drag_out.is_some() {
2537 // 선택한 항목을 창 밖으로 끌어 놓을 수 있게 끌기도 받음.
2538 egui::Sense::click_and_drag()
2539 } else if active {
2540 egui::Sense::click()
2541 } else {
2542 egui::Sense::hover()
2543 },
2544 )
2545 .on_hover_text(&row.name);
2546 theme::pointer(&response);
2547 response.widget_info(|| {
2548 egui::WidgetInfo::selected(
2549 egui::Role::ListBoxOption,
2550 active,
2551 selected,
2552 &row.name,
2553 )
2554 });
2555 if response.has_focus() {
2556 focused = Some(index);
2557 ui.ctx().memory_mut(|memory| {
2558 memory.set_focus_lock_filter(
2559 response.id,
2560 egui::EventFilter {
2561 vertical_arrows: true,
2562 escape: true,
2563 ..Default::default()
2564 },
2565 )
2566 });
2567 }
2568 theme::row_background(
2569 ui,
2570 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW)),
2571 selected,
2572 response.hovered(),
2573 );
2574 if response.clicked() {
2575 background.request_focus();
2576 let modifiers = ui.input(|i| i.modifiers);
2577 self.select_row(
2578 &rows,
2579 index,
2580 modifiers.ctrl || modifiers.command,
2581 modifiers.shift,
2582 );
2583 }
2584 // 오래 누르기만 해도 egui는 끌기로 보므로, 실제로 움직였을 때만 시작함.
2585 if active
2586 && self.drag_out.is_some()
2587 && !self.drag_out_fired
2588 && response.dragged()
2589 && ui.input(|i| {
2590 i.pointer
2591 .press_origin()
2592 .zip(i.pointer.interact_pos())
2593 .is_some_and(|(from, to)| from.distance(to) >= DRAG_OUT_DISTANCE)
2594 })
2595 {
2596 self.drag_out_fired = true;
2597 if !selected {
2598 // 선택하지 않은 행을 끌면 그 행만 선택한 뒤 끎.
2599 self.select_row(&rows, index, false, false);
2600 }
2601 drag_out = true;
2602 }
2603 if response.double_clicked() {
2604 if row.directory {
2605 open = Some(row.path.clone());
2606 } else if let [id] = row.ids.iter().copied().collect::<Vec<_>>()[..] {
2607 open_file = Some(id);
2608 }
2609 }
2610 if active && response.secondary_clicked() && !selected {
2611 // 선택하지 않은 행을 오른쪽 클릭하면 그 행만 선택한 뒤 메뉴를 엶.
2612 self.select_row(&rows, index, false, false);
2613 }
2614 if active {
2615 response.context_menu(|ui| {
2616 if ui
2617 .button("압축 파일명으로 새 폴더를 만들어 압축 풀기")
2618 .clicked()
2619 {
2620 menu_action = Some(MenuAction::NewFolder);
2621 }
2622 if ui.button("특정 폴더에 압축 풀기").clicked() {
2623 menu_action = Some(MenuAction::ChooseFolder);
2624 }
2625 });
2626 }
2627 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
2628 let name = if row.encrypted {
2629 format!("*{}", row.name)
2630 } else {
2631 row.name.clone()
2632 };
2633 Self::entry_cells(
2634 ui,
2635 rect,
2636 row.directory,
2637 &name,
2638 &row.name,
2639 row.bytes
2640 .map(present::bytes_text)
2641 .unwrap_or_else(|| "—".into()),
2642 name_width,
2643 );
2644 if active
2645 && self.list_cursor == Some(index)
2646 && (response.has_focus() || background.has_focus())
2647 {
2648 ui.painter().rect_stroke(
2649 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW))
2650 .shrink(1.0),
2651 0,
2652 egui::Stroke::new(1.0, theme::BLUE),
2653 egui::StrokeKind::Inside,
2654 );
2655 }
2656 }
2657 if rows.is_empty()
2658 && !(self.model.busy() && matches!(self.last_request, Some(Start::List { .. })))
2659 {
2660 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
2661 ui.centered_and_justified(|ui| {
2662 ui.label(if self.search.is_empty() {
2663 "이 폴더는 비어 있습니다"
2664 } else {
2665 "일치하는 항목이 없습니다"
2666 })
2667 });
2668 });
2669 }
2670 #[cfg(all(feature = "ui-fixture", debug_assertions))]
2671 if let Some(rect) = self.scenario_marquee {
2672 ui.painter().with_clip_rect(clip).rect(
2673 rect.translate(origin.to_vec2()),
2674 0,
2675 theme::BLUE.gamma_multiply(0.16),
2676 egui::Stroke::new(1.0, theme::BLUE),
2677 egui::StrokeKind::Inside,
2678 );
2679 }
2680 if let Some(drag) = &self.marquee
2681 && drag.moved
2682 && let Some(point) = point
2683 {
2684 let rect = egui::Rect::from_two_pos(
2685 origin + drag.origin.to_vec2(),
2686 point.clamp(clip.min, clip.max),
2687 );
2688 ui.painter().with_clip_rect(clip).rect(
2689 rect,
2690 0,
2691 theme::BLUE.gamma_multiply(0.16),
2692 egui::Stroke::new(1.0, theme::BLUE),
2693 egui::StrokeKind::Inside,
2694 );
2695 }
2696 });
2697 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
2698 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
2699 self.marquee = None;
2700 self.drag_out_fired = false;
2701 }
2702 let escape_from_list = self.list_focused
2703 && ui.ctx().memory(|memory| memory.focused()).is_none()
2704 && ui.input(|i| i.key_pressed(egui::Key::Escape));
2705 self.list_focused =
2706 active && (background.has_focus() || focused.is_some() || escape_from_list);
2707 if self.list_focused {
2708 if let Some(index) = focused {
2709 self.list_cursor = Some(index);
2710 }
2711 let modifiers = ui.input(|i| i.modifiers);
2712 let ctrl = modifiers.ctrl || modifiers.command;
2713 // 선택이 있으면 Esc는 선택만 해제함. 선택이 없으면 창 닫기로 넘김.
2714 if (!self.model.selected.is_empty() || self.marquee.is_some())
2715 && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
2716 {
2717 self.model.selected.clear();
2718 self.marquee = None;
2719 background.request_focus();
2720 self.escape_handled = true;
2721 }
2722 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
2723 self.model.selected = rows
2724 .iter()
2725 .flat_map(|row| row.ids.iter().copied())
2726 .collect();
2727 self.list_cursor = (!rows.is_empty()).then_some(0);
2728 self.list_anchor = self.list_cursor;
2729 }
2730 if !rows.is_empty() {
2731 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
2732 Some(1isize)
2733 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
2734 Some(-1)
2735 } else {
2736 None
2737 };
2738 if let Some(direction) = direction {
2739 let index = self.list_cursor.map_or(0, |index| {
2740 index.saturating_add_signed(direction).min(rows.len() - 1)
2741 });
2742 if ctrl && !modifiers.shift {
2743 self.list_cursor = Some(index);
2744 } else {
2745 self.select_row(&rows, index, ctrl, modifiers.shift);
2746 }
2747 background.request_focus();
2748 let top = index as f32 * LIST_ROW;
2749 if top < self.list_offset {
2750 self.list_offset = top;
2751 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
2752 self.list_offset = top + LIST_ROW - output.inner_rect.height();
2753 }
2754 ui.ctx().request_repaint();
2755 }
2756 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
2757 let index = self
2758 .list_cursor
2759 .or(focused)
2760 .unwrap_or(0)
2761 .min(rows.len() - 1);
2762 if rows[index].directory {
2763 open = Some(rows[index].path.clone());
2764 } else if let [id] = rows[index].ids.iter().copied().collect::<Vec<_>>()[..] {
2765 open_file = Some(id);
2766 }
2767 }
2768 }
2769 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
2770 open = Some(
2771 self.folder
2772 .rsplit_once('/')
2773 .map_or("", |(parent, _)| parent)
2774 .to_owned(),
2775 );
2776 }
2777 }
2778 // 마우스 옆 버튼(뒤로)을 목록 위에서 누르면 상위 폴더로 이동함.
2779 if active
2780 && !self.folder.is_empty()
2781 && ui.input(|i| {
2782 i.pointer.button_pressed(egui::PointerButton::Extra1)
2783 && i.pointer
2784 .interact_pos()
2785 .is_some_and(|pos| path_row.union(background.rect).contains(pos))
2786 })
2787 {
2788 open = Some(
2789 self.folder
2790 .rsplit_once('/')
2791 .map_or("", |(parent, _)| parent)
2792 .to_owned(),
2793 );
2794 }
2795 if let Some(folder) = open {
2796 self.browse_folder(&folder);
2797 background.request_focus();
2798 }
2799 if let Some(id) = open_file {
2800 self.open_entry(id);
2801 }
2802 if drag_out {
2803 self.begin_drag_out();
2804 }
2805 match menu_action {
2806 Some(MenuAction::NewFolder) => {
2807 self.extract_to_new_folder();
2808 }
2809 Some(MenuAction::ChooseFolder) => self.open_picker(Purpose::Destination),
2810 None => {}
2811 }
2812 }
2813
2814 fn clear_list_selection(&mut self) {
2815 self.model.selected.clear();
2816 self.list_anchor = None;
2817 self.list_cursor = None;
2818 self.list_offset = 0.0;
2819 self.marquee = None;
2820 }
2821
2822 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
2823 if shift {
2824 let anchor = self
2825 .list_anchor
2826 .unwrap_or(self.list_cursor.unwrap_or(index))
2827 .min(rows.len() - 1);
2828 if !ctrl {
2829 self.model.selected.clear();
2830 }
2831 for row in &rows[anchor.min(index)..=anchor.max(index)] {
2832 self.model.selected.extend(&row.ids);
2833 }
2834 self.list_anchor = Some(anchor);
2835 } else {
2836 if !ctrl {
2837 self.model.selected.clear();
2838 }
2839 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
2840 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
2841 self.model
2842 .selected
2843 .retain(|id| !rows[index].ids.contains(id));
2844 } else {
2845 self.model.selected.extend(&rows[index].ids);
2846 }
2847 self.list_anchor = Some(index);
2848 }
2849 self.list_cursor = Some(index);
2850 }
2851
2852 fn result_visible(&self) -> bool {
2853 !self.dismissed
2854 && !self
2855 .last_request
2856 .as_ref()
2857 .is_some_and(|r| matches!(r, Start::Preview { .. }))
2858 && !self.model.busy()
2859 && self.last_request.as_ref().is_some_and(|request| {
2860 !matches!(request, Start::List { .. })
2861 || self.model.error.is_some()
2862 || self
2863 .model
2864 .terminal
2865 .as_ref()
2866 .is_some_and(|t| t.outcome != Outcome::Completed)
2867 })
2868 }
2869
2870 fn can_preview(&self) -> bool {
2871 self.model.can_preview()
2872 && browser::rows(&self.model.entries, &self.folder, &self.search)
2873 .iter()
2874 .any(|row| !row.directory && row.ids == self.model.selected)
2875 }
2876
2877 fn begin_preview(&mut self, ctx: &egui::Context) {
2878 if !self.can_preview() || self.picker.is_some() {
2879 return;
2880 }
2881 self.preview_texture = None;
2882 self.preview_text.clear();
2883 self.preview_name = self
2884 .model
2885 .entries
2886 .iter()
2887 .find(|e| self.model.selected.contains(&e.id))
2888 .unwrap()
2889 .name
2890 .clone();
2891 self.preview_return_focus = Some(
2892 ctx.memory(|m| m.focused())
2893 .unwrap_or_else(|| egui::Id::unique("archive-list")),
2894 );
2895 self.preview_initial_focus = true;
2896 let request = Start::Preview {
2897 archive: self.model.archive.clone().unwrap(),
2898 entry_id: *self.model.selected.first().unwrap(),
2899 list_id: self.model.list_id.clone().unwrap(),
2900 };
2901 self.preview_open = true;
2902 self.start(request);
2903 }
2904
2905 fn close_preview(&mut self) {
2906 self.preview_open = false;
2907 self.model.dismiss_preview();
2908 self.preview_texture = None;
2909 self.preview_text.clear();
2910 self.dismissed = true;
2911 }
2912
2913 fn preview_dialog(&mut self, ctx: &egui::Context) {
2914 if !self.preview_open
2915 || self.model.challenge.is_some()
2916 || self.model.resource.is_some()
2917 || self.model.close != Close::Open
2918 {
2919 return;
2920 }
2921 if let Some(preview) = self.model.preview.as_mut()
2922 && (!preview.data.is_empty() || preview.info.total_bytes == 0)
2923 {
2924 match preview.info.format {
2925 PreviewFormat::Utf8Text => {
2926 self.preview_text =
2927 String::from_utf8(std::mem::take(&mut preview.data)).unwrap_or_default();
2928 }
2929 PreviewFormat::Rgba8 => {
2930 let width = preview.info.width as usize;
2931 let height = preview.info.height as usize;
2932 let limit = ctx.input(|i| i.max_texture_side).max(1);
2933 let step = width.div_ceil(limit).max(height.div_ceil(limit)).max(1);
2934 let size = [width.div_ceil(step), height.div_ceil(step)];
2935 let mut colors = Vec::with_capacity(size[0] * size[1]);
2936 for y in (0..height).step_by(step) {
2937 for x in (0..width).step_by(step) {
2938 let index = (y * width + x) * 4;
2939 colors.push(egui::Color32::from_rgba_unmultiplied(
2940 preview.data[index],
2941 preview.data[index + 1],
2942 preview.data[index + 2],
2943 preview.data[index + 3],
2944 ));
2945 }
2946 }
2947 let pixels = egui::ColorImage::new(size, colors);
2948 preview.data = Vec::new();
2949 self.preview_texture = Some(ctx.load_texture(
2950 "archive-preview",
2951 pixels,
2952 egui::TextureOptions::LINEAR,
2953 ));
2954 }
2955 }
2956 }
2957 let mut close = false;
2958 let modal = egui::Modal::new(egui::Id::unique("archive-preview")).show(ctx, |ui| {
2959 ui.set_width((ctx.content_rect().width() - 64.0).clamp(240.0, 760.0));
2960 ui.horizontal(|ui| {
2961 ui.heading("미리보기");
2962 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2963 let button = theme::flat_icon_button(
2964 ui,
2965 "미리보기 닫기",
2966 theme::CLOSE,
2967 true,
2968 egui::vec2(36.0, 36.0),
2969 );
2970 if self.preview_initial_focus {
2971 button.request_focus();
2972 self.preview_initial_focus = false;
2973 }
2974 close |= button.clicked();
2975 });
2976 });
2977 ui.add(egui::Label::new(&self.preview_name).truncate())
2978 .on_hover_text(&self.preview_name);
2979 let max_height = (ctx.content_rect().height() - 220.0).clamp(100.0, 560.0);
2980 if self.model.busy() {
2981 ui.label("미리보기를 불러오는 중입니다");
2982 if ui.button("취소").clicked() {
2983 close = true;
2984 }
2985 } else if let Some(error) = self.model.error.as_ref() {
2986 Self::error_notice(ui, error);
2987 } else if let Some(texture) = self.preview_texture.as_ref() {
2988 ui.add(
2989 egui::Image::new(texture)
2990 .max_size(egui::vec2(ui.available_width(), max_height))
2991 .shrink_to_fit(),
2992 );
2993 } else if self.model.preview.is_some() {
2994 egui::ScrollArea::both()
2995 .id_salt("preview-text")
2996 .max_height(max_height)
2997 .show(ui, |ui| {
2998 let mut text = self.preview_text.as_str();
2999 ui.add(
3000 egui::TextEdit::multiline(&mut text)
3001 .desired_width(ui.available_width())
3002 .desired_rows(12)
3003 .frame(egui::Frame::NONE),
3004 );
3005 });
3006 if self.preview_text.is_empty() {
3007 ui.label("빈 텍스트 파일입니다");
3008 }
3009 } else {
3010 let code = self.model.terminal.as_ref().and_then(|t| t.error);
3011 ui.label(match code {
3012 Some(ErrorCode::Limit) => "미리보기 크기 또는 처리 한도를 초과했습니다.",
3013 Some(ErrorCode::Integrity) => "파일이 손상됐거나 UTF-8 텍스트가 아닙니다.",
3014 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature) => {
3015 "이 파일 형식은 미리보기를 지원하지 않습니다."
3016 }
3017 Some(ErrorCode::SourceChanged) => "압축파일이 변경됐습니다. 다시 열어 주세요.",
3018 Some(ErrorCode::WrongPassword) => "암호가 올바르지 않습니다.",
3019 _ => "미리보기를 불러오지 못했습니다.",
3020 });
3021 ui.label("닫은 뒤 파일을 선택하고 [압축해제]를 사용할 수 있습니다.");
3022 }
3023 });
3024 if close || modal.should_close() {
3025 self.close_preview();
3026 }
3027 }
3028
3029 fn limit_result_visible(&self) -> bool {
3030 self.result_visible()
3031 && (self.model.volume_problem.is_some()
3032 || self.model.terminal.as_ref().is_some_and(|terminal| {
3033 terminal.error == Some(ErrorCode::Limit)
3034 || (matches!(
3035 terminal.error,
3036 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature)
3037 ) && self
3038 .model
3039 .archive
3040 .as_ref()
3041 .is_some_and(|p| present::excluded_split(p)))
3042 }))
3043 }
3044
3045 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
3046 if !self.limit_result_visible() || self.main_modal_open() {
3047 return;
3048 }
3049 egui::Modal::new(egui::Id::new("archive-limit-result")).show(ctx, |ui| {
3050 ui.set_width((ctx.content_rect().width() - 64.0).min(WORK_WIDTH));
3051 ui.heading("작업 결과");
3052 self.work_area(ui);
3053 });
3054 }
3055
3056 fn error_notice(ui: &mut egui::Ui, error: &str) {
3057 let response = theme::panel(theme::ERROR_BG)
3058 .show(ui, |ui| {
3059 ui.horizontal_wrapped(|ui| {
3060 theme::icon(ui, Icon::Error, 24.0);
3061 ui.colored_label(theme::ERROR, error);
3062 });
3063 })
3064 .response;
3065 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
3066 }
3067
3068 fn work_visible(&self) -> bool {
3069 !self
3070 .last_request
3071 .as_ref()
3072 .is_some_and(|r| matches!(r, Start::Preview { .. }))
3073 && (self.model.busy()
3074 || self.result_visible()
3075 || (self.ui_error.is_some() && !self.create))
3076 }
3077
3078 /// 메인 창 가운데에 모달(암호 입력, 종료 확인, 파일 선택 안내)이나 같은 자리에 뜨는
3079 /// ZIP 만들기 창이 떠 있는지. 닫기가 정해진 뒤(Allowed)에도 결과 창을 다시 띄우지 않음.
3080 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
3081 fn main_modal_open(&self) -> bool {
3082 (self.create && !self.model.busy())
3083 || self.picker.is_some()
3084 || self.model.challenge.is_some()
3085 || self.model.resource.is_some()
3086 || self.model.conflict.is_some()
3087 || self.model.close != Close::Open
3088 }
3089
3090 fn work_window(&mut self, ctx: &egui::Context) {
3091 if !self.work_visible() {
3092 self.work = WorkWindow::default();
3093 return;
3094 }
3095 if self.limit_result_visible() {
3096 self.work.open = false;
3097 return;
3098 }
3099 if ctx.embed_viewports() && !self.work_in_parent {
3100 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
3101 return;
3102 }
3103 if self.main_modal_open() {
3104 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
3105 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
3106 self.work.open = false;
3107 return;
3108 }
3109 let id = egui::ViewportId::from_hash_of("archive-work");
3110 let title = if self.model.busy() {
3111 present::activity_text(
3112 &self.model,
3113 matches!(
3114 self.last_request,
3115 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3116 ),
3117 )
3118 .to_owned()
3119 } else {
3120 "작업 결과".to_owned()
3121 };
3122 if self.work_in_parent {
3123 // Wayland는 창 올리기를 지원하지 않으므로 부모 안에서 같은 내용을 그림.
3124 // egui 기본 제목 줄의 닫기 버튼은 마우스를 올려도 모양이 바뀌지 않으므로
3125 // 제목 줄을 직접 그리고 별도 창과 같은 닫기 버튼을 씀.
3126 let mut close = false;
3127 let busy = self.model.busy();
3128 egui::Window::new(RichText::new(&title).size(theme::FONT_SMALL))
3129 .id(egui::Id::new("archive-work-in-parent"))
3130 .title_bar(false)
3131 .default_pos(
3132 ctx.content_rect().center() - egui::vec2(WORK_WIDTH, self.work.height) / 2.0,
3133 )
3134 .default_width(WORK_WIDTH)
3135 .min_width(WORK_WIDTH)
3136 .max_width(WORK_WIDTH)
3137 .max_height(WORK_MAX_HEIGHT)
3138 .collapsible(false)
3139 .resizable(false)
3140 .fade_in(false)
3141 .fade_out(false)
3142 .frame(
3143 egui::Frame::new()
3144 .fill(theme::PANEL)
3145 .stroke(egui::Stroke::new(1.0, theme::BORDER))
3146 .inner_margin(egui::Margin::ZERO)
3147 .corner_radius(0),
3148 )
3149 .show(ctx, |ui| {
3150 let spacing = ui.spacing().item_spacing.y;
3151 ui.spacing_mut().item_spacing.y = 0.0;
3152 close = window_frame::in_parent_title(ui, "work-in-parent", &title, !busy);
3153 egui::Frame::new()
3154 .inner_margin(egui::Margin::same(theme::PAD))
3155 .show(ui, |ui| {
3156 ui.spacing_mut().item_spacing.y = spacing;
3157 ui.set_width(WORK_WIDTH - 2.0 * theme::PAD as f32);
3158 self.work_area(ui)
3159 });
3160 });
3161 if close {
3162 self.dismissed = true;
3163 self.ui_error = None;
3164 self.model.input_error = None;
3165 }
3166 return;
3167 }
3168 let window_title = format!("{title} — Zipelo");
3169 let custom_frame = self.custom_frame;
3170 let size = egui::vec2(WORK_WIDTH, self.work.height);
3171 let builder = self.work.builder(
3172 ctx,
3173 id,
3174 size,
3175 &window_title,
3176 !custom_frame,
3177 self.picker.is_some(),
3178 );
3179 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
3180 // 끝난 작업의 결과 창은 Esc로 닫음. 진행 중에는 [취소] 버튼을 씀.
3181 if !self.model.busy()
3182 && ui
3183 .ctx()
3184 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
3185 {
3186 crate::log_debug!("Esc: 작업 결과 창 닫기");
3187 self.dismissed = true;
3188 self.ui_error = None;
3189 self.model.input_error = None;
3190 }
3191 if ui.ctx().input(|i| i.viewport().close_requested()) {
3192 if self.model.busy() {
3193 ui.ctx()
3194 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
3195 } else {
3196 self.dismissed = true;
3197 self.ui_error = None;
3198 self.model.input_error = None;
3199 }
3200 }
3201 if class == egui::ViewportClass::EmbeddedWindow {
3202 ui.set_width(WORK_WIDTH);
3203 self.work_area(ui);
3204 return None;
3205 }
3206 let mut chrome = 0.0;
3207 if custom_frame {
3208 window_frame::title_bar(
3209 ui,
3210 "work",
3211 &window_title,
3212 window_frame::Buttons {
3213 minimize: false,
3214 maximize: false,
3215 },
3216 );
3217 window_frame::edges(ui.ctx(), false);
3218 chrome = window_frame::TITLE_HEIGHT;
3219 }
3220 let margin = theme::PAD as f32;
3221 egui::CentralPanel::default()
3222 .frame(theme::panel(theme::PANEL).corner_radius(0))
3223 .show(ui, |ui| {
3224 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
3225 Some(content.height() + 2.0 * margin + chrome)
3226 })
3227 .inner
3228 });
3229 if let Some(height) = height {
3230 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
3231 if (height - self.work.height).abs() > 1.0 {
3232 self.work.height = height;
3233 }
3234 }
3235 }
3236
3237 fn work_area(&mut self, ui: &mut egui::Ui) {
3238 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
3239 let enabled = self.picker.is_none();
3240 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
3241 }
3242
3243 fn work_contents(&mut self, ui: &mut egui::Ui) {
3244 if self.model.busy() {
3245 self.progress(ui);
3246 } else if self.result_visible() {
3247 self.result(ui);
3248 }
3249 if !self.create
3250 && let Some(error) = &self.ui_error
3251 {
3252 Self::error_notice(ui, error);
3253 if error == present::FOLDER_ERROR
3254 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
3255 {
3256 self.open_picker(Purpose::Destination);
3257 }
3258 }
3259 if let Some(error) = &self.model.input_error {
3260 ui.colored_label(
3261 theme::ERROR,
3262 if error.starts_with("암호는") {
3263 error.as_str()
3264 } else {
3265 if matches!(
3266 self.last_request,
3267 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3268 ) {
3269 "저장 위치와 추가한 항목을 확인하세요"
3270 } else {
3271 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
3272 "원본과 다른 새 복구본 저장 위치를 선택하세요"
3273 } else {
3274 "풀 위치와 선택한 항목을 확인하세요"
3275 }
3276 }
3277 },
3278 );
3279 }
3280 }
3281
3282 fn progress(&mut self, ui: &mut egui::Ui) {
3283 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
3284 ui.strong("ZIP 복구 중");
3285 ui.label(if self.model.recovery_end.is_some() {
3286 "분석 완료 / 복구본 저장과 작업자 종료 확인 중"
3287 } else {
3288 "원본을 분석하고 있습니다. 전체 항목 수는 아직 알 수 없습니다."
3289 });
3290 ui.label(format!(
3291 "확인한 항목 {}개",
3292 self.model.recovery_entries.len()
3293 ));
3294 self.cancel_action(ui, false);
3295 return;
3296 }
3297 if self.model.resource.is_some() {
3298 ui.horizontal(|ui| {
3299 ui.label("사용자 허용을 기다리고 있습니다");
3300 self.cancel_action(ui, false);
3301 });
3302 return;
3303 }
3304 let creating = matches!(
3305 self.last_request,
3306 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3307 );
3308 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
3309 let title = present::activity_text(&self.model, creating);
3310 ui.strong(title);
3311 if let Some((stage, done, total, count)) = self.model.progress {
3312 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
3313 let processed = if stage == Stage::Read {
3314 String::new()
3315 } else {
3316 format!("{count}개 처리함, ")
3317 };
3318 if let Some(total) = total.filter(|n| *n > 0) {
3319 ui.scope(|ui| {
3320 ui.visuals_mut().extreme_bg_color = theme::BORDER;
3321 ui.add(
3322 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
3323 .fill(theme::BLUE)
3324 .desired_height(theme::SPACE * 2.0),
3325 );
3326 });
3327 ui.horizontal(|ui| {
3328 ui.label(format!(
3329 "{:.0}% / {processed}{} / {}",
3330 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
3331 present::bytes_text(done),
3332 present::bytes_text(total)
3333 ));
3334 self.cancel_action(ui, cancelling);
3335 });
3336 } else {
3337 theme::indeterminate(ui);
3338 ui.horizontal(|ui| {
3339 ui.label(format!("{processed}{}", present::bytes_text(done)));
3340 self.cancel_action(ui, cancelling);
3341 });
3342 }
3343 } else {
3344 theme::indeterminate(ui);
3345 ui.horizontal(|ui| {
3346 ui.label("작업을 진행하고 있습니다");
3347 self.cancel_action(ui, cancelling);
3348 });
3349 }
3350 }
3351
3352 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
3353 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3354 if theme::action(ui, "취소", false, !cancelling).clicked() {
3355 self.clear_password();
3356 self.model.cancel();
3357 }
3358 });
3359 }
3360
3361 fn recovery_result(&mut self, ui: &mut egui::Ui) {
3362 let t = self.model.terminal.as_ref();
3363 let summary = self.model.recovery_end.as_ref();
3364 let confirmed = self.model.confirmed && self.model.error.is_none();
3365 let saved = confirmed
3366 && t.is_some_and(|t| t.publication == Publication::Complete && t.created_count == 1)
3367 && summary.is_some_and(|s| s.verified_entries > 0);
3368 let partial = summary.is_some_and(|s| !s.complete());
3369 let title = if !confirmed {
3370 "복구 결과를 확정할 수 없음"
3371 } else if saved && partial {
3372 "일부 항목만 복구함"
3373 } else if saved && t.is_some_and(|t| t.outcome == Outcome::Completed) {
3374 "복구본 저장 완료"
3375 } else if t.is_some_and(|t| t.error == Some(ErrorCode::RecoveryImpossible)) {
3376 "복구 가능한 항목 없음"
3377 } else if t.is_some_and(|t| t.outcome == Outcome::Cancelled) {
3378 "복구를 취소했습니다"
3379 } else {
3380 "복구본 저장을 완료하지 못했습니다"
3381 };
3382 ui.heading(title);
3383 ui.label(
3384 "원본은 수정하지 않습니다. 검증 통과는 손상 전 내용과 동일하다는 보증이 아닙니다.",
3385 );
3386 let output = match &self.last_request {
3387 Some(Start::RecoverZip { output_file, .. }) => output_file.clone(),
3388 _ => return,
3389 };
3390 if saved
3391 || self
3392 .model
3393 .outputs
3394 .iter()
3395 .any(|(_, d)| matches!(d, Disposition::Created | Disposition::CommitUncertain))
3396 {
3397 theme::bounded_text(ui, &output.display().to_string(), ui.available_width());
3398 }
3399 for (name, _) in self
3400 .model
3401 .outputs
3402 .iter()
3403 .filter(|(_, d)| *d == Disposition::PartialRetained)
3404 {
3405 let retained = output.parent().unwrap_or(Path::new("")).join(name);
3406 theme::bounded_text(
3407 ui,
3408 &format!("남은 임시 파일: {}", retained.display()),
3409 ui.available_width(),
3410 );
3411 }
3412 if let Some(error) = &self.model.error {
3413 ui.colored_label(theme::WARNING, error);
3414 }
3415 if let Some(t) = t {
3416 if let Some(code) = t.error {
3417 ui.label(present::error_text(code));
3418 }
3419 for warning in present::publication_warnings(
3420 Some(t),
3421 self.model.confirmed,
3422 Some(&BTreeSet::from([output
3423 .file_name()
3424 .unwrap_or_default()
3425 .to_string_lossy()
3426 .into_owned()])),
3427 &BTreeSet::new(),
3428 &self.model.outputs,
3429 ) {
3430 ui.colored_label(theme::WARNING, warning);
3431 }
3432 if let Some(warning) = present::durability_warning(t.durability) {
3433 ui.colored_label(theme::WARNING, warning);
3434 }
3435 }
3436 let notice = summary.map(|s| {
3437 format!(
3438 "검증되어 포함됨 {}개 / 유실됨 {}개 / 무결성 미확인 {}개{}",
3439 s.verified_entries,
3440 s.lost_entries,
3441 s.unverified_entries,
3442 if s.unknown_loss {
3443 " / 전체 목록을 알 수 없어 추가 유실 여부를 확인할 수 없습니다"
3444 } else {
3445 ""
3446 }
3447 )
3448 });
3449 if let Some(notice) = &notice {
3450 ui.label(notice);
3451 }
3452 egui::ScrollArea::vertical()
3453 .id_salt("recovery-findings")
3454 .max_height(220.0)
3455 .show_rows(ui, 24.0, self.model.recovery_entries.len(), |ui, rows| {
3456 for entry in &self.model.recovery_entries[rows] {
3457 let status = match entry.status {
3458 RecoveryStatus::Verified => "검증되어 포함됨",
3459 RecoveryStatus::Lost => "유실됨",
3460 RecoveryStatus::Unverified => "무결성 미확인",
3461 };
3462 let reason = match entry.reason {
3463 RecoveryReason::None => "내용 검증 통과",
3464 RecoveryReason::HeaderRebuilt => "헤더 재구성",
3465 RecoveryReason::Truncated => "파일 절단",
3466 RecoveryReason::CrcMismatch => "CRC 불일치",
3467 RecoveryReason::DecodeFailure => "압축 데이터 손상",
3468 RecoveryReason::BoundaryUnknown => "항목 경계 불명",
3469 RecoveryReason::UnsupportedFeature => "지원하지 않는 기능",
3470 RecoveryReason::MetadataMissing => "메타정보 누락",
3471 };
3472 theme::bounded_text(
3473 ui,
3474 &format!(
3475 "{status} / {reason}: {}",
3476 entry.name.as_deref().unwrap_or("이름 확인 불가")
3477 ),
3478 ui.available_width(),
3479 );
3480 }
3481 });
3482 if saved && theme::action(ui, "복구본 열기", true, true).clicked() {
3483 self.recovery_warning = partial.then(|| (output.clone(), notice.unwrap_or_default()));
3484 self.open_path(output);
3485 }
3486 if self.model.can_retry_expanded()
3487 && theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked()
3488 {
3489 self.model.retry_expanded(self.factory.as_mut());
3490 }
3491 }
3492
3493 fn result(&mut self, ui: &mut egui::Ui) {
3494 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
3495 self.recovery_result(ui);
3496 return;
3497 }
3498 if self.model.confirmed
3499 && self.model.error.is_none()
3500 && self
3501 .model
3502 .terminal
3503 .as_ref()
3504 .is_some_and(|t| t.error == Some(ErrorCode::Integrity))
3505 && matches!(
3506 self.last_request,
3507 Some(Start::List { .. } | Start::Extract { .. })
3508 )
3509 {
3510 ui.label("원본을 바꾸지 않고 새 ZIP 복구본을 만듭니다. 일부 항목은 복구되지 않을 수 있습니다.");
3511 if theme::action(ui, "복구본 저장 위치 선택", true, true).clicked() {
3512 self.open_picker(Purpose::SaveRecoveryZip);
3513 }
3514 }
3515 let t = self.model.terminal.clone();
3516 let listing = matches!(self.last_request, Some(Start::List { .. }));
3517 let creating = matches!(
3518 self.last_request,
3519 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3520 );
3521 // 분할 7z는 작업자가 보고한 볼륨 수로 기대 이름(이름.7z.001…)을 정함.
3522 let split_targets = match (&self.last_request, t.as_ref()) {
3523 (
3524 Some(Start::CreateSevenZip {
3525 output_file,
3526 volume_size: Some(_),
3527 ..
3528 }),
3529 Some(t),
3530 ) => output_file.file_name().map(|name| {
3531 (1..=t.created_count.clamp(1, present::MAX_VOLUMES))
3532 .map(|index| format!("{}.{index:03}", name.to_string_lossy()))
3533 .collect::<BTreeSet<_>>()
3534 }),
3535 _ => None,
3536 };
3537 let resolved_targets = present::resolved_targets(
3538 split_targets.as_ref().or(self.targets.as_ref()),
3539 &self.model.entries,
3540 matches!(
3541 self.last_request,
3542 Some(Start::Extract {
3543 gzip_output_name: Some(_),
3544 ..
3545 })
3546 )
3547 .then_some(self.gzip_name.as_str()),
3548 &self.model.resolutions,
3549 );
3550 let skipped = self
3551 .model
3552 .resolutions
3553 .iter()
3554 .filter(|r| r.choice == ConflictChoice::Skip)
3555 .count();
3556 let created_names = self
3557 .model
3558 .outputs
3559 .iter()
3560 .filter(|(_, disposition)| *disposition == Disposition::Created)
3561 .map(|(name, _)| name.replace('\\', "/"))
3562 .collect::<BTreeSet<_>>();
3563 let warnings = if listing {
3564 Vec::new()
3565 } else {
3566 present::publication_warnings(
3567 t.as_ref(),
3568 self.model.confirmed,
3569 resolved_targets.as_ref(),
3570 &self.directories,
3571 &self.model.outputs,
3572 )
3573 };
3574 let success = self.model.confirmed
3575 && self.model.error.is_none()
3576 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
3577 && warnings
3578 .iter()
3579 .all(|warning| !creating && *warning == present::CLEANUP_WARNING);
3580 let durability_warning = t
3581 .as_ref()
3582 .filter(|_| self.model.confirmed && !listing)
3583 .and_then(|t| present::durability_warning(t.durability));
3584 let durability_in_details = success
3585 && t.as_ref()
3586 .is_some_and(|t| t.durability == Durability::Unconfirmed);
3587 let cancelled =
3588 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
3589 let title = if success {
3590 if creating {
3591 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3592 "7z 파일을 만들었습니다"
3593 } else {
3594 "ZIP 파일을 만들었습니다"
3595 }
3596 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
3597 "모든 파일을 건너뛰었습니다"
3598 } else {
3599 "압축을 풀었습니다"
3600 }
3601 } else if cancelled {
3602 "작업을 취소했습니다"
3603 } else if listing {
3604 "압축파일을 열지 못했습니다"
3605 } else if creating {
3606 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3607 "7z 파일을 만들지 못했습니다"
3608 } else {
3609 "ZIP 파일을 만들지 못했습니다"
3610 }
3611 } else {
3612 "압축을 풀지 못했습니다"
3613 };
3614 let fill = if success {
3615 theme::SUCCESS_BG
3616 } else if cancelled {
3617 theme::STRIPE
3618 } else {
3619 theme::ERROR_BG
3620 };
3621 let mut choose = false;
3622 let mut retry = false;
3623 let mut expand = false;
3624 let mut reopen = false;
3625 let mut folder = false;
3626 theme::panel(fill).show(ui, |ui| {
3627 ui.horizontal(|ui| {
3628 theme::icon(
3629 ui,
3630 if success {
3631 Icon::Success
3632 } else if cancelled {
3633 Icon::Warning
3634 } else {
3635 Icon::Error
3636 },
3637 24.0,
3638 );
3639 ui.strong(title);
3640 });
3641 let max_height = WORK_RESULT_MAX_HEIGHT;
3642 egui::ScrollArea::vertical()
3643 .id_salt("result-message")
3644 .max_height(max_height)
3645 .show(ui, |ui| {
3646 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
3647 let path = match self.last_request.as_ref() {
3648 Some(Start::CreateSevenZip {
3649 output_file,
3650 volume_size: Some(_),
3651 ..
3652 }) => present::volume_path(output_file, 1).display().to_string(),
3653 Some(
3654 Start::CreateZip { output_file, .. }
3655 | Start::CreateSevenZip { output_file, .. },
3656 ) => output_file.display().to_string(),
3657 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
3658 };
3659 theme::bounded_text(ui, &path, ui.available_width());
3660 if matches!(
3661 self.last_request,
3662 Some(Start::CreateSevenZip {
3663 volume_size: Some(_),
3664 ..
3665 })
3666 ) {
3667 ui.label(format!(
3668 "볼륨 {}개로 나누어 저장했습니다. 풀 때는 첫 볼륨(.001)을 여세요.",
3669 t.as_ref().map_or(0, |t| t.created_count)
3670 ));
3671 }
3672 } else if let Some(problem) = &self.model.volume_problem {
3673 ui.add(egui::Label::new(present::volume_problem_text(problem)).wrap());
3674 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
3675 ui.label(
3676 if matches!(
3677 code,
3678 ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature
3679 ) && self
3680 .model
3681 .archive
3682 .as_ref()
3683 .is_some_and(|p| present::excluded_split(p))
3684 {
3685 present::SPLIT_SUPPORT.to_owned()
3686 } else if creating && code == ErrorCode::SourceChanged {
3687 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
3688 .to_owned()
3689 } else if code == ErrorCode::Limit
3690 && matches!(
3691 self.last_request,
3692 Some(Start::CreateSevenZip {
3693 volume_size: Some(_),
3694 ..
3695 })
3696 )
3697 {
3698 present::VOLUME_LIMIT_ERROR.to_owned()
3699 } else {
3700 present::operation_text(present::error_text(code), creating)
3701 },
3702 );
3703 } else if let Some(error) = &self.model.error {
3704 ui.label(present::operation_text(
3705 present::client_error_text(error),
3706 creating,
3707 ));
3708 }
3709 if skipped > 0 {
3710 ui.label(format!("건너뛴 파일 {skipped}개"));
3711 }
3712 for resolution in self.model.resolutions.iter().filter(|r| {
3713 r.choice == ConflictChoice::Rename
3714 && created_names.contains(&r.relative_name.replace('\\', "/"))
3715 }) {
3716 theme::bounded_text(
3717 ui,
3718 &format!("이름 바꿔 저장: {}", resolution.relative_name),
3719 ui.available_width(),
3720 );
3721 }
3722 for warning in warnings
3723 .iter()
3724 .copied()
3725 .chain(durability_warning.filter(|_| !durability_in_details))
3726 {
3727 ui.horizontal_wrapped(|ui| {
3728 theme::icon(ui, Icon::Warning, 20.0);
3729 ui.colored_label(
3730 theme::WARNING,
3731 present::operation_text(warning, creating),
3732 );
3733 });
3734 }
3735 if !success
3736 && !listing
3737 && present::definitely_unsaved(
3738 t.as_ref(),
3739 self.model.confirmed,
3740 &self.model.outputs,
3741 )
3742 {
3743 ui.label(if creating {
3744 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3745 "7z 파일을 만들지 않았습니다"
3746 } else {
3747 "ZIP 파일을 만들지 않았습니다"
3748 }
3749 } else {
3750 "아무 파일도 풀지 않았습니다"
3751 });
3752 }
3753 if t.as_ref().is_some_and(|t| {
3754 t.error == Some(ErrorCode::Limit)
3755 && (t.created_count > 0
3756 || t.retained_partial_count > 0
3757 || t.publication != Publication::None)
3758 }) {
3759 ui.label(format!(
3760 "{}개 파일이 저장되었거나 일부 남아 있습니다. 저장 위치를 확인하세요.",
3761 t.as_ref().unwrap().created_count
3762 ));
3763 theme::bounded_text(
3764 ui,
3765 &self.destination.display().to_string(),
3766 ui.available_width(),
3767 );
3768 }
3769 if self.details {
3770 theme::panel(theme::STRIPE).show(ui, |ui| {
3771 if durability_in_details {
3772 if let Some(warning) = durability_warning {
3773 ui.label(present::operation_text(warning, creating));
3774 }
3775 }
3776 if let Some(t) = &t {
3777 for line in terminal_lines(t) {
3778 ui.label(line);
3779 }
3780 }
3781 if let Some(error) = &self.model.error {
3782 ui.label(error);
3783 }
3784 for (name, state) in &self.model.outputs {
3785 theme::bounded_text(
3786 ui,
3787 &format!("{name}: {}", disposition_label(*state)),
3788 ui.available_width(),
3789 );
3790 }
3791 });
3792 }
3793 });
3794 let conflict = t
3795 .as_ref()
3796 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
3797 && !creating;
3798 let uncertain = warnings.contains(&present::UNCERTAIN);
3799 if conflict && uncertain {
3800 let response = ui.checkbox(
3801 &mut self.checked_destination,
3802 "기존 풀 위치 폴더를 확인했습니다",
3803 );
3804 theme::pointer(&response);
3805 theme::focus(&response);
3806 }
3807 ui.horizontal(|ui| {
3808 if theme::action(
3809 ui,
3810 if self.details {
3811 "자세히 닫기"
3812 } else {
3813 "자세히 보기"
3814 },
3815 false,
3816 true,
3817 )
3818 .clicked()
3819 {
3820 self.details = !self.details;
3821 }
3822 let action = if success {
3823 Some(("폴더 열기", true))
3824 } else if conflict {
3825 Some((
3826 if self
3827 .model
3828 .list_id
3829 .as_ref()
3830 .is_some_and(|id| id.format == Format::Gzip)
3831 {
3832 "다른 이름으로 저장"
3833 } else {
3834 "다른 폴더에 풀기"
3835 },
3836 !uncertain || self.checked_destination,
3837 ))
3838 } else if t
3839 .as_ref()
3840 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
3841 {
3842 Some((
3843 if creating {
3844 "다시 만들기"
3845 } else {
3846 "압축파일 다시 열기"
3847 },
3848 true,
3849 ))
3850 } else if self.model.can_retry_expanded() {
3851 None
3852 } else if t
3853 .as_ref()
3854 .is_some_and(|t| t.error == Some(ErrorCode::Limit))
3855 {
3856 None
3857 } else if !cancelled && (!uncertain || listing) {
3858 Some(("다시 시도", true))
3859 } else {
3860 None
3861 };
3862 let (confirm, primary) = theme::action_pair(ui, "확인", action);
3863 if confirm {
3864 self.dismissed = true;
3865 self.ui_error = None;
3866 self.model.input_error = None;
3867 }
3868 if primary {
3869 match action.map(|(label, _)| label) {
3870 Some("폴더 열기") => folder = true,
3871 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
3872 choose = true
3873 }
3874 Some("압축파일 다시 열기") => reopen = true,
3875 Some("다시 시도" | "다시 만들기") => retry = true,
3876 _ => {}
3877 }
3878 }
3879 });
3880 if self.model.can_retry_expanded() {
3881 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3882 expand = theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked();
3883 });
3884 }
3885 });
3886 if choose {
3887 self.open_picker(Purpose::Retry);
3888 }
3889 if retry {
3890 self.retry();
3891 }
3892 if expand {
3893 let ready = if matches!(self.last_request, Some(Start::Extract { .. })) {
3894 match present::prepare_destination(&self.destination, self.automatic_destination) {
3895 Ok(created) => {
3896 self.owned_destination = created.then(|| self.destination.clone());
3897 true
3898 }
3899 Err(_) => {
3900 self.ui_error = Some(present::FOLDER_ERROR.into());
3901 false
3902 }
3903 }
3904 } else {
3905 true
3906 };
3907 if ready && self.model.retry_expanded(self.factory.as_mut()) {
3908 self.dismissed = false;
3909 self.details = false;
3910 self.ui_error = None;
3911 }
3912 }
3913 if reopen {
3914 if let Some(path) = self.model.archive.clone() {
3915 self.open_path(path);
3916 }
3917 }
3918 if folder {
3919 let path = match self.last_request.as_ref() {
3920 Some(
3921 Start::CreateZip { output_file, .. }
3922 | Start::CreateSevenZip { output_file, .. },
3923 ) => output_file.parent().unwrap_or(Path::new("/")),
3924 _ => self.destination.as_path(),
3925 };
3926 match present::folder_command(path).spawn() {
3927 Ok(mut child) => {
3928 std::thread::spawn(move || {
3929 let _ = child.wait();
3930 });
3931 }
3932 Err(_) => {
3933 self.ui_error = Some(
3934 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
3935 )
3936 }
3937 }
3938 }
3939 }
3940
3941 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
3942 fn entry_cells(
3943 ui: &mut egui::Ui,
3944 rect: egui::Rect,
3945 directory: bool,
3946 name: &str,
3947 hover: &str,
3948 size: String,
3949 name_width: f32,
3950 ) {
3951 ui.scope_builder(
3952 egui::UiBuilder::new()
3953 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
3954 .layout(Layout::left_to_right(Align::Center)),
3955 |ui| {
3956 ui.style_mut().interaction.selectable_labels = false;
3957 ui.add_space(16.0);
3958 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
3959 theme::bounded_text_hover(ui, name, hover, name_width);
3960 theme::column_label(ui, size, 96.0, Align::Max);
3961 },
3962 );
3963 }
3964
3965 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
3966 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
3967 fn create_window(&mut self, ctx: &egui::Context) {
3968 if !self.create || self.model.busy() {
3969 self.create_win = WorkWindow::default();
3970 return;
3971 }
3972 if ctx.embed_viewports() {
3973 let mut close = false;
3974 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
3975 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
3976 ui.horizontal(|ui| {
3977 ui.heading(if self.seven_zip {
3978 "7z 만들기"
3979 } else {
3980 "ZIP 만들기"
3981 });
3982 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3983 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
3984 close = button.clicked();
3985 });
3986 });
3987 close |= self.create_area(ui);
3988 ui.add_space(theme::SPACE);
3989 close |= self.create_actions(ui);
3990 });
3991 if close || modal.should_close() {
3992 self.close_create();
3993 }
3994 return;
3995 }
3996 let id = egui::ViewportId::from_hash_of("archive-create");
3997 let title = if self.seven_zip {
3998 "7z 만들기 — Zipelo"
3999 } else {
4000 "ZIP 만들기 — Zipelo"
4001 };
4002 let custom_frame = self.custom_frame;
4003 if !self.create_win.open {
4004 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
4005 }
4006 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
4007 let builder =
4008 self.create_win
4009 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
4010 let mut close = false;
4011 let picker_open = self.picker.is_some();
4012 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
4013 if ui.ctx().input(|i| i.viewport().close_requested()) {
4014 close = true;
4015 }
4016 if !picker_open
4017 && ui
4018 .ctx()
4019 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
4020 {
4021 crate::log_debug!("Esc: 만들기 창 닫기");
4022 close = true;
4023 }
4024 if class == egui::ViewportClass::EmbeddedWindow {
4025 ui.set_width(CREATE_WIDTH);
4026 close |= self.create_area(ui);
4027 close |= self.create_actions(ui);
4028 return None;
4029 }
4030 let mut chrome = 0.0;
4031 if custom_frame {
4032 window_frame::title_bar(
4033 ui,
4034 "create",
4035 title,
4036 window_frame::Buttons {
4037 minimize: false,
4038 maximize: false,
4039 },
4040 );
4041 window_frame::edges(ui.ctx(), false);
4042 chrome = window_frame::TITLE_HEIGHT;
4043 }
4044 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
4045 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
4046 .resizable(false)
4047 .show_separator_line(false)
4048 .frame(
4049 egui::Frame::new()
4050 .fill(theme::PANEL)
4051 .inner_margin(egui::Margin {
4052 left: theme::PAD,
4053 right: theme::PAD,
4054 top: 0,
4055 bottom: theme::PAD,
4056 }),
4057 )
4058 .show(ui, |ui| close |= self.create_actions(ui))
4059 .response
4060 .rect
4061 .height();
4062 let margin = theme::PAD as f32;
4063 egui::CentralPanel::default()
4064 .frame(theme::panel(theme::PANEL).corner_radius(0))
4065 .show(ui, |ui| {
4066 let content = ui
4067 .vertical(|ui| close |= self.create_area(ui))
4068 .response
4069 .rect;
4070 Some(content.height() + 2.0 * margin + chrome + actions)
4071 })
4072 .inner
4073 });
4074 if let Some(height) = height {
4075 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
4076 if (height - self.create_win.height).abs() > 1.0 {
4077 self.create_win.height = height;
4078 }
4079 }
4080 if close {
4081 self.close_create();
4082 }
4083 }
4084
4085 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
4086 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
4087 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
4088 let enabled = self.picker.is_none();
4089 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
4090 .inner
4091 }
4092
4093 fn set_seven_zip(&mut self, selected: bool) {
4094 if self.seven_zip == selected {
4095 return;
4096 }
4097 self.seven_zip = selected;
4098 self.aes256 = false;
4099 self.clear_zip_password();
4100 self.ui_error = None;
4101 let name = self.zip_name.clone();
4102 let lower = name.to_ascii_lowercase();
4103 let stem = if lower.ends_with(".zip") {
4104 &name[..name.len() - 4]
4105 } else if lower.ends_with(".7z") {
4106 &name[..name.len() - 3]
4107 } else {
4108 &name
4109 };
4110 self.zip_name = format!("{stem}{}", if selected { ".7z" } else { ".zip" });
4111 }
4112
4113 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
4114 let mut selected = self.seven_zip;
4115 ui.horizontal(|ui| {
4116 ui.label("형식");
4117 ui.selectable_value(&mut selected, false, "ZIP");
4118 ui.selectable_value(&mut selected, true, "7z");
4119 if selected {
4120 ui.label("LZMA2");
4121 }
4122 });
4123 self.set_seven_zip(selected);
4124
4125 let rows = self.create_rows();
4126 let root = self.create_root();
4127
4128 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
4129 ui.horizontal(|ui| {
4130 ui.set_height(theme::FIELD);
4131 ui.spacing_mut().item_spacing.x = 0.0;
4132 let up = theme::flat_icon_button(
4133 ui,
4134 "위로",
4135 theme::UP,
4136 !self.create_folder.is_empty(),
4137 egui::vec2(theme::FIELD, theme::FIELD),
4138 );
4139 if up.clicked() {
4140 self.create_folder = self
4141 .create_folder
4142 .rsplit_once('/')
4143 .map_or("", |(parent, _)| parent)
4144 .to_owned();
4145 self.create_selected = None;
4146 }
4147 ui.add_space(6.0);
4148 let path = match &root {
4149 Some(root) => {
4150 let name = root.file_name().unwrap_or_default().to_string_lossy();
4151 if self.create_folder.is_empty() {
4152 format!("/{name}")
4153 } else {
4154 format!("/{name}/{}", self.create_folder)
4155 }
4156 }
4157 None => "/".to_owned(),
4158 };
4159 let (rect, _) = ui.allocate_exact_size(
4160 egui::vec2(ui.available_width(), theme::FIELD),
4161 egui::Sense::hover(),
4162 );
4163 theme::boxed_field(ui, rect);
4164 theme::field_text(ui, rect, &path);
4165 });
4166 ui.add_space(theme::SPACE);
4167
4168 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
4169 let mut enter = None;
4170 egui::Frame::new()
4171 .stroke(egui::Stroke::new(1.0, theme::BORDER))
4172 .show(ui, |ui| {
4173 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
4174 ui.set_max_height(CREATE_LIST_HEIGHT);
4175 let message = match &rows {
4176 None => Some("폴더를 읽지 못했습니다"),
4177 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
4178 Some(_) => None,
4179 };
4180 if let Some(message) = message {
4181 ui.centered_and_justified(|ui| ui.label(message));
4182 return;
4183 }
4184 let rows = rows.unwrap();
4185 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
4186 egui::ScrollArea::vertical()
4187 .id_salt("create-rows")
4188 .auto_shrink([false, false])
4189 .max_height(CREATE_LIST_HEIGHT)
4190 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
4191 for row in &rows[range] {
4192 let (rect, response) = ui.allocate_exact_size(
4193 egui::vec2(ui.available_width(), LIST_ROW),
4194 egui::Sense::click(),
4195 );
4196 let response = response.on_hover_text(&row.name);
4197 theme::pointer(&response);
4198 response.widget_info(|| {
4199 egui::WidgetInfo::labeled(
4200 egui::Role::ListBoxOption,
4201 true,
4202 &row.name,
4203 )
4204 });
4205 if response.clicked() {
4206 self.create_selected = Some(row.name.clone());
4207 }
4208 theme::row_background(
4209 ui,
4210 rect,
4211 self.create_selected.as_deref() == Some(row.name.as_str()),
4212 response.hovered(),
4213 );
4214 if row.directory && root.is_some() && response.clicked() {
4215 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
4216 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
4217 let frame = ui.ctx().cumulative_frame_nr();
4218 let time = ui.input(|i| i.time);
4219 match &self.create_last_click {
4220 Some((name, last_frame, last_time))
4221 if name == &row.name
4222 && *last_frame != frame
4223 && time - last_time < 0.4 =>
4224 {
4225 enter = Some(row.name.clone());
4226 self.create_last_click = None;
4227 }
4228 Some((name, last_frame, _))
4229 if name == &row.name && *last_frame == frame => {}
4230 _ => {
4231 self.create_last_click =
4232 Some((row.name.clone(), frame, time));
4233 }
4234 }
4235 }
4236 Self::entry_cells(
4237 ui,
4238 rect,
4239 row.directory,
4240 &row.name,
4241 &row.name,
4242 row.bytes.map(present::bytes_text).unwrap_or_default(),
4243 name_width,
4244 );
4245 }
4246 });
4247 });
4248 if let Some(name) = enter {
4249 self.create_folder = if self.create_folder.is_empty() {
4250 name
4251 } else {
4252 format!("{}/{name}", self.create_folder)
4253 };
4254 self.create_selected = None;
4255 }
4256 ui.add_space(theme::SPACE);
4257
4258 if let Some(error) = &self.ui_error {
4259 Self::error_notice(ui, error);
4260 }
4261
4262 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
4263 if self.seven_zip {
4264 ui.label("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요");
4265 self.split_rows(ui);
4266 return false;
4267 }
4268 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
4269 theme::pointer(&check);
4270 theme::focus(&check);
4271 if self.aes256 {
4272 let label_width = 72.0;
4273 ui.horizontal(|ui| {
4274 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
4275 let toggle = if self.zip_password_visible {
4276 "숨기기"
4277 } else {
4278 "보기"
4279 };
4280 let toggle_width = 72.0;
4281 let edit = ui.add_sized(
4282 [
4283 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
4284 theme::FIELD,
4285 ],
4286 egui::TextEdit::singleline(&mut self.zip_password)
4287 .password(!self.zip_password_visible)
4288 .id(egui::Id::unique("zip-password-input"))
4289 .char_limit(1024)
4290 .align(egui::Align2::LEFT_CENTER),
4291 );
4292 theme::focus(&edit);
4293 if theme::action(ui, toggle, false, true).clicked() {
4294 self.zip_password_visible = !self.zip_password_visible;
4295 }
4296 });
4297 ui.horizontal(|ui| {
4298 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
4299 let edit = ui.add_sized(
4300 [
4301 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
4302 theme::FIELD,
4303 ],
4304 egui::TextEdit::singleline(&mut self.zip_password_confirm)
4305 .password(!self.zip_password_visible)
4306 .id(egui::Id::unique("zip-password-confirm"))
4307 .char_limit(1024)
4308 .align(egui::Align2::LEFT_CENTER),
4309 );
4310 theme::focus(&edit);
4311 });
4312 if self.zip_password.len() > 1024 {
4313 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
4314 } else if !self.zip_password_confirm.is_empty()
4315 && self.zip_password != self.zip_password_confirm
4316 {
4317 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
4318 }
4319 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
4320 } else if check.changed()
4321 || !self.zip_password.is_empty()
4322 || !self.zip_password_confirm.is_empty()
4323 {
4324 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
4325 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
4326 self.clear_zip_password();
4327 }
4328 false
4329 }
4330
4331 /// 쪼갤 용량: 체크하면 바로 아래에 볼륨 크기 칸과 MB/GB 선택을 보여 줌.
4332 fn split_rows(&mut self, ui: &mut egui::Ui) {
4333 let check = ui.checkbox(&mut self.split, "쪼갤 용량 설정");
4334 theme::pointer(&check);
4335 theme::focus(&check);
4336 if !self.split {
4337 return;
4338 }
4339 ui.horizontal(|ui| {
4340 ui.add_sized([72.0, theme::FIELD], egui::Label::new("볼륨 크기"));
4341 let edit = ui.add_sized(
4342 [120.0, theme::FIELD],
4343 egui::TextEdit::singleline(&mut self.split_amount)
4344 .id(egui::Id::unique("split-volume-size"))
4345 .char_limit(9)
4346 .align(egui::Align2::LEFT_CENTER),
4347 );
4348 theme::focus(&edit);
4349 for unit in [present::VolumeUnit::Mb, present::VolumeUnit::Gb] {
4350 let choice = ui.selectable_value(&mut self.split_unit, unit, unit.label());
4351 theme::pointer(&choice);
4352 }
4353 });
4354 match self.split_volume() {
4355 Err(error) => {
4356 ui.colored_label(theme::ERROR, error);
4357 }
4358 Ok(_) => {
4359 let name = if self.zip_name.is_empty() {
4360 "이름.7z"
4361 } else {
4362 &self.zip_name
4363 };
4364 ui.label(
4365 RichText::new(format!(
4366 "{name}.001, {name}.002 …로 나누어 저장합니다. 볼륨은 최대 {}개입니다.",
4367 present::MAX_VOLUMES
4368 ))
4369 .color(theme::MUTED),
4370 );
4371 }
4372 }
4373 }
4374
4375 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
4376 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
4377 let ready =
4378 !self.sources.is_empty() && self.zip_password_ready() && self.split_volume().is_ok();
4379 let enabled = self.picker.is_none();
4380 let (cancel, compress) = ui
4381 .add_enabled_ui(enabled, |ui| {
4382 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
4383 })
4384 .inner;
4385 if compress {
4386 self.open_picker(if self.seven_zip {
4387 Purpose::SaveSevenZip
4388 } else {
4389 Purpose::SaveZip
4390 });
4391 }
4392 cancel
4393 }
4394
4395 fn resource_dialog(&mut self, ctx: &egui::Context) {
4396 let Some(question) = self.model.resource.clone() else {
4397 return;
4398 };
4399 let Some(job) = self.model.job_id() else {
4400 return;
4401 };
4402 let mut allow = false;
4403 let mut cancel = false;
4404 let modal = egui::Modal::new(egui::Id::unique(("archive-resource", job, question.id)))
4405 .show(ctx, |ui| {
4406 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
4407 ui.heading(if question.scope.ratio {
4408 "압축률이 매우 높습니다"
4409 } else {
4410 "큰 작업을 허용할까요?"
4411 });
4412 ui.label(match question.action {
4413 ActionKind::List => "압축파일 목록 열기",
4414 ActionKind::Extract => "압축 해제",
4415 ActionKind::CreateZip => "ZIP 만들기",
4416 ActionKind::CreateSevenZip => "7z 만들기",
4417 ActionKind::RecoverZip => "ZIP 복구",
4418 ActionKind::Preview => "파일 미리보기",
4419 });
4420 if question.scope.ratio {
4421 ui.label("작은 압축파일도 많은 저장 공간을 사용할 수 있습니다.");
4422 }
4423 if question.scope.output {
4424 ui.label(format!(
4425 "총량 한도: {}에서 {}로",
4426 present::bytes_text(question.soft_limits.output),
4427 present::bytes_text(question.ceiling.output)
4428 ));
4429 }
4430 if question.scope.entries {
4431 ui.label(format!(
4432 "항목 한도: {}개에서 {}개로",
4433 question.soft_limits.entries, question.ceiling.entries
4434 ));
4435 }
4436 let mut u = question.usage;
4437 let estimated = self.model.estimated_usage();
4438 u.estimated_bytes = u.estimated_bytes.or(estimated.estimated_bytes);
4439 u.estimated_entries = u.estimated_entries.or(estimated.estimated_entries);
4440 let bytes = |value: Option<u64>| {
4441 value
4442 .map(present::bytes_text)
4443 .unwrap_or_else(|| "미확인".into())
4444 };
4445 let entries = |value: Option<u32>| {
4446 value
4447 .map(|n| format!("{n}개"))
4448 .unwrap_or_else(|| "미확인".into())
4449 };
4450 ui.label(format!(
4451 "예상 총량: {} / 실제 총량: {}",
4452 bytes(u.estimated_bytes),
4453 bytes(u.actual_bytes)
4454 ));
4455 ui.label(format!(
4456 "예상 항목: {} / 실제 항목: {}",
4457 entries(u.estimated_entries),
4458 entries(u.actual_entries)
4459 ));
4460 if question.scope.ratio {
4461 ui.label(format!(
4462 "압축 크기: {} / 풀린 크기: {}",
4463 bytes(u.compressed_bytes),
4464 bytes(u.ratio_output_bytes)
4465 ));
4466 }
4467 ui.label(format!(
4468 "확인한 저장 볼륨의 여유 공간: {}",
4469 bytes(u.available_bytes)
4470 ));
4471 ui.label(format!(
4472 "이 작업의 상한: {} / {}개",
4473 present::bytes_text(question.ceiling.output),
4474 question.ceiling.entries
4475 ));
4476 ui.label("이 작업에만 적용합니다. 공간 부족이나 자원 상한에 도달하면 중단합니다.");
4477 ui.horizontal(|ui| {
4478 cancel = theme::action(ui, "취소", false, true).clicked();
4479 allow = theme::action(ui, "이 작업 허용", true, true).clicked();
4480 });
4481 });
4482 if cancel || modal.should_close() {
4483 self.clear_password();
4484 self.model.cancel();
4485 } else if allow {
4486 self.model.resource_reply(job, question.id, true);
4487 }
4488 }
4489
4490 fn conflict_dialog(&mut self, ctx: &egui::Context) {
4491 let conflict = self.model.conflict.clone().unwrap();
4492 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
4493 if self.conflict_challenge != Some(question) {
4494 self.conflict_challenge = Some(question);
4495 self.conflict_apply = false;
4496 }
4497 let mut choice = None;
4498 let mut cancel = false;
4499 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
4500 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
4501 ui.heading("같은 이름의 파일이 있습니다");
4502 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
4503 ui.add_space(theme::SPACE);
4504 egui::Grid::new("conflict-sizes")
4505 .spacing([24.0, 8.0])
4506 .show(ui, |ui| {
4507 ui.label("기존 파일");
4508 ui.label(present::bytes_text(conflict.existing_size));
4509 ui.end_row();
4510 ui.label("압축파일 안의 파일");
4511 ui.label(present::bytes_text(conflict.incoming_size));
4512 ui.end_row();
4513 });
4514 ui.add_space(theme::SPACE);
4515 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
4516 ui.add_space(theme::SPACE);
4517 ui.horizontal_wrapped(|ui| {
4518 for (label, value) in [
4519 ("덮어쓰기", ConflictChoice::Overwrite),
4520 ("건너뛰기", ConflictChoice::Skip),
4521 ("이름 바꿔 저장", ConflictChoice::Rename),
4522 ] {
4523 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
4524 choice = Some(value);
4525 }
4526 }
4527 });
4528 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
4529 if let Some(error) = &self.model.error {
4530 Self::error_notice(ui, present::client_error_text(error));
4531 }
4532 cancel = theme::action(ui, "작업 취소", false, true).clicked();
4533 });
4534 if modal.should_close() || cancel {
4535 self.model.cancel();
4536 } else if let Some(choice) = choice {
4537 self.model.resolve_conflict(choice, self.conflict_apply);
4538 }
4539 }
4540
4541 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
4542 let (_, attempt, encrypt) = self.model.challenge.unwrap();
4543 let mut submit = false;
4544 let mut cancel = false;
4545 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
4546 id == egui::Id::unique("archive-password-input")
4547 || id == egui::Id::unique("archive-password-confirm")
4548 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
4549 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
4550 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
4551 ui.heading(if encrypt {
4552 "ZIP 암호 설정"
4553 } else {
4554 "암호가 필요합니다"
4555 });
4556 if encrypt {
4557 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
4558 } else if let Some(path) = &self.model.archive {
4559 ui.label(format!(
4560 "{}은 암호로 보호되어 있습니다.",
4561 present::middle_text(
4562 &path.file_name().unwrap_or_default().to_string_lossy(),
4563 24
4564 )
4565 ));
4566 }
4567 ui.horizontal(|ui| {
4568 ui.label("암호");
4569 let edit = ui.add(
4570 egui::TextEdit::singleline(&mut self.password)
4571 .password(!self.password_visible)
4572 .id(egui::Id::unique("archive-password-input"))
4573 .char_limit(1024)
4574 .desired_width(232.0),
4575 );
4576 theme::focus(&edit);
4577 if new_challenge {
4578 edit.request_focus();
4579 }
4580 if theme::action(
4581 ui,
4582 if self.password_visible {
4583 "숨기기"
4584 } else {
4585 "보기"
4586 },
4587 false,
4588 true,
4589 )
4590 .clicked()
4591 {
4592 self.password_visible = !self.password_visible;
4593 }
4594 });
4595 if encrypt {
4596 ui.horizontal(|ui| {
4597 ui.label("암호 확인");
4598 let edit = ui.add(
4599 egui::TextEdit::singleline(&mut self.password_confirm)
4600 .password(!self.password_visible)
4601 .id(egui::Id::unique("archive-password-confirm"))
4602 .char_limit(1024)
4603 .desired_width(232.0),
4604 );
4605 theme::focus(&edit);
4606 });
4607 if self.password != self.password_confirm {
4608 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
4609 }
4610 } else if attempt > 1 {
4611 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
4612 }
4613 if self.password.len() > 1024 {
4614 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
4615 }
4616 let valid = !self.password.is_empty()
4617 && self.password.len() <= 1024
4618 && (!encrypt || self.password == self.password_confirm);
4619 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
4620 cancel = actions.0;
4621 submit = actions.1 || (valid && password_enter);
4622 });
4623 if modal.should_close() || cancel {
4624 self.clear_password();
4625 self.model.cancel();
4626 } else if submit {
4627 let password = std::mem::take(&mut self.password);
4628 self.clear_password();
4629 self.model.password(password);
4630 }
4631 }
4632
4633 fn close_dialog(&mut self, ctx: &egui::Context) {
4634 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
4635 if matches!(
4636 self.model.close,
4637 Close::Open | Close::Allowed | Close::Review
4638 ) {
4639 return;
4640 }
4641 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
4642 ui.set_width(420.0);
4643 match self.model.close {
4644 Close::Confirm => {
4645 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
4646 let busy = self.model.busy();
4647 let (heading, text, keep, close) = if busy {
4648 (
4649 "작업 중 닫기",
4650 "작업을 취소하고 닫을까요?",
4651 "계속 작업",
4652 "취소하고 닫기",
4653 )
4654 } else {
4655 (
4656 "닫기",
4657 "작업이 끝났습니다. 창을 닫을까요?",
4658 "열어 두기",
4659 "닫기",
4660 )
4661 };
4662 ui.heading(heading);
4663 ui.label(text);
4664 ui.horizontal(|ui| {
4665 if theme::action(ui, keep, false, true).clicked() {
4666 self.model.keep_open();
4667 }
4668 if theme::action(ui, close, true, true).clicked() {
4669 self.clear_password();
4670 self.model.confirm_close();
4671 }
4672 });
4673 }
4674 Close::Waiting => {
4675 ui.heading("종료 확인 중");
4676 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
4677 if theme::action(ui, "닫기 취소", false, true).clicked() {
4678 self.model.keep_open();
4679 }
4680 }
4681 _ => {}
4682 }
4683 });
4684 }
4685}
4686
4687impl eframe::App for ArchiveApp {
4688 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
4689 self.show(root);
4690 }
4691
4692 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
4693 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
4694 if std::mem::take(&mut self.release_after_move) {
4695 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
4696 raw_input.events.insert(
4697 0,
4698 egui::Event::PointerButton {
4699 pos,
4700 button: egui::PointerButton::Primary,
4701 pressed: false,
4702 modifiers: ctx.input(|i| i.modifiers),
4703 },
4704 );
4705 }
4706 }
4707}
4708impl Drop for ArchiveApp {
4709 fn drop(&mut self) {
4710 self.clear_password();
4711 for (_, root) in self.open_roots.drain(..) {
4712 present::remove_open_root(root);
4713 }
4714 }
4715}