team-ljyzipelo

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