team-ljyzipelo

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