team-ljyzipelo

공개
1,377줄56 KB
1use crate::{
2 archive_picker::{Choice, Picker, Purpose},
3 archive_present as present,
4 archive_theme::{self as theme, Icon},
5 archive_ui::*,
6};
7use eframe::egui::{self, Align, Layout, RichText};
8use std::{
9 collections::BTreeSet,
10 path::{Path, PathBuf},
11};
12
13pub struct ArchiveApp {
14 pub model: Model,
15 factory: Box<dyn Factory>,
16 destination: PathBuf,
17 automatic_destination: bool,
18 owned_destination: Option<PathBuf>,
19 gzip_name: String,
20 sources: Vec<PathBuf>,
21 zip_folder: PathBuf,
22 zip_name: String,
23 password: String,
24 password_confirm: String,
25 password_visible: bool,
26 password_challenge: Option<u64>,
27 aes256: bool,
28 create: bool,
29 selected_only: bool,
30 method: Method,
31 fixture: bool,
32 picker: Option<Picker>,
33 last_request: Option<Start>,
34 targets: Option<BTreeSet<String>>,
35 directories: BTreeSet<String>,
36 dismissed: bool,
37 details: bool,
38 checked_destination: bool,
39 ui_error: Option<String>,
40 initialized: bool,
41}
42
43impl ArchiveApp {
44 pub fn new(factory: Box<dyn Factory>, startup: Option<PathBuf>, fixture: bool) -> Self {
45 let mut app = Self {
46 model: Model::default(),
47 factory,
48 destination: PathBuf::new(),
49 automatic_destination: true,
50 owned_destination: None,
51 gzip_name: String::new(),
52 sources: Vec::new(),
53 zip_folder: present::home_directory(),
54 zip_name: String::new(),
55 password: String::new(),
56 password_confirm: String::new(),
57 password_visible: false,
58 password_challenge: None,
59 aes256: false,
60 create: false,
61 selected_only: false,
62 method: Method::Deflate,
63 fixture,
64 picker: None,
65 last_request: None,
66 targets: None,
67 directories: BTreeSet::new(),
68 dismissed: false,
69 details: false,
70 checked_destination: false,
71 ui_error: None,
72 initialized: false,
73 };
74 if let Some(path) = startup {
75 app.open_path(path);
76 }
77 app
78 }
79
80 fn clear_password(&mut self) {
81 for value in [&mut self.password, &mut self.password_confirm] {
82 let mut bytes = std::mem::take(value).into_bytes();
83 bytes.fill(0);
84 }
85 self.password_visible = false;
86 }
87
88 pub fn open_path(&mut self, archive: PathBuf) {
89 if self.model.busy() {
90 return;
91 }
92 self.clear_password();
93 self.destination = present::default_destination(&archive);
94 self.automatic_destination = true;
95 self.gzip_name = archive
96 .file_name()
97 .unwrap_or_default()
98 .to_string_lossy()
99 .strip_suffix(".gz")
100 .unwrap_or("압축 해제 파일")
101 .into();
102 self.selected_only = false;
103 self.targets = None;
104 self.directories.clear();
105 self.start(Start::List { archive });
106 }
107
108 fn start(&mut self, request: Start) -> bool {
109 self.last_request = Some(request.clone());
110 self.dismissed = false;
111 self.details = false;
112 self.checked_destination = false;
113 self.ui_error = None;
114 self.model.begin(request, self.factory.as_mut())
115 }
116
117 pub fn choose_destination(&mut self, path: PathBuf) {
118 self.destination = path;
119 self.automatic_destination = false;
120 self.ui_error = None;
121 }
122
123 pub fn add_sources(&mut self, paths: Vec<PathBuf>) {
124 if self.model.busy() {
125 return;
126 }
127 if self.sources.is_empty() {
128 if let Some(first) = paths.first() {
129 self.zip_folder = first.parent().unwrap_or(Path::new("/")).to_path_buf();
130 let name = if first.is_dir() {
131 first.file_name()
132 } else {
133 first.file_stem()
134 };
135 self.zip_name = format!("{}.zip", name.unwrap_or_default().to_string_lossy());
136 }
137 }
138 for path in paths {
139 if !self.sources.contains(&path) {
140 self.sources.push(path);
141 }
142 }
143 self.create = true;
144 }
145
146 pub fn begin_extract(&mut self) -> bool {
147 if !self.model.can_extract() || (self.selected_only && self.model.selected.is_empty()) {
148 return false;
149 }
150 match present::prepare_destination(&self.destination, self.automatic_destination) {
151 Ok(true) => self.owned_destination = Some(self.destination.clone()),
152 Ok(false) => self.owned_destination = None,
153 Err(_) => {
154 self.ui_error = Some(present::FOLDER_ERROR.into());
155 return false;
156 }
157 }
158 let gzip = self
159 .model
160 .list_id
161 .as_ref()
162 .is_some_and(|id| id.format == Format::Gzip);
163 let selection = if self.selected_only {
164 Selection::EntryIds(self.model.selected.iter().copied().collect())
165 } else {
166 Selection::All
167 };
168 self.targets = present::target_files(
169 &self.model.entries,
170 &selection,
171 gzip.then_some(self.gzip_name.as_str()),
172 );
173 self.directories = if gzip {
174 BTreeSet::new()
175 } else {
176 present::target_directories(&self.model.entries, &selection)
177 };
178 let request = Start::Extract {
179 archive: self.model.archive.clone().unwrap(),
180 destination: self.destination.clone(),
181 selection,
182 list_id: self.model.list_id.clone().unwrap(),
183 gzip_output_name: gzip.then(|| self.gzip_name.clone()),
184 };
185 if self.start(request) {
186 true
187 } else {
188 if let Some(path) = self.owned_destination.take() {
189 present::remove_owned_empty(&path);
190 }
191 false
192 }
193 }
194
195 fn begin_zip(&mut self) {
196 if self.sources.is_empty() {
197 return;
198 }
199 if !self.zip_name.to_ascii_lowercase().ends_with(".zip") {
200 self.zip_name.push_str(".zip");
201 }
202 if !valid_leaf(&self.zip_name) {
203 self.ui_error = Some("ZIP 파일 이름을 확인하세요".into());
204 return;
205 }
206 let output_file = self.zip_folder.join(&self.zip_name);
207 if std::fs::symlink_metadata(&output_file).is_ok() {
208 self.ui_error = Some("같은 이름의 파일이 이미 있습니다. 다른 이름을 입력하세요".into());
209 return;
210 }
211 let mut sources = Vec::new();
212 for path in &self.sources {
213 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
214 self.ui_error = Some(
215 "이름을 읽을 수 없는 파일이 있습니다. 파일 이름을 바꾼 뒤 다시 추가하세요"
216 .into(),
217 );
218 return;
219 };
220 sources.push((path.clone(), name.to_owned()));
221 }
222 self.targets = Some([self.zip_name.clone()].into_iter().collect());
223 self.directories.clear();
224 if self.start(Start::CreateZip {
225 sources,
226 output_file,
227 method: self.method,
228 aes256: self.aes256,
229 }) {
230 self.create = false;
231 }
232 }
233
234 fn open_picker(&mut self, purpose: Purpose) {
235 let start = match purpose {
236 Purpose::Destination | Purpose::Retry => self.destination.clone(),
237 Purpose::ZipFolder => self.zip_folder.clone(),
238 Purpose::Open => self
239 .model
240 .archive
241 .as_deref()
242 .and_then(Path::parent)
243 .map(Path::to_path_buf)
244 .unwrap_or_else(present::home_directory),
245 _ => self
246 .sources
247 .last()
248 .and_then(|p| p.parent())
249 .map(Path::to_path_buf)
250 .unwrap_or_else(present::home_directory),
251 };
252 self.picker = Some(Picker::new(purpose, &start));
253 }
254
255 fn retry(&mut self) {
256 if let Some(request) = self.last_request.clone() {
257 match request {
258 Start::List { archive } => self.open_path(archive),
259 Start::Extract {
260 selection,
261 gzip_output_name,
262 ..
263 } => {
264 self.selected_only = matches!(selection, Selection::EntryIds(_));
265 if let Selection::EntryIds(ids) = selection {
266 self.model.selected = ids.into_iter().collect();
267 }
268 if let Some(name) = gzip_output_name {
269 self.gzip_name = name;
270 }
271 self.begin_extract();
272 }
273 Start::CreateZip { .. } => {
274 self.create = true;
275 self.begin_zip();
276 }
277 }
278 }
279 }
280
281 fn show_picker(&mut self, ctx: &egui::Context) {
282 let answer = self.picker.as_mut().and_then(|picker| picker.show(ctx));
283 if let Some(answer) = answer {
284 let purpose = self.picker.take().unwrap().purpose;
285 if let Choice::Paths(paths) = answer {
286 if let Some(path) = paths.first() {
287 match purpose {
288 Purpose::Open => self.open_path(path.clone()),
289 Purpose::Destination | Purpose::Retry => {
290 self.choose_destination(path.clone());
291 if purpose == Purpose::Retry {
292 self.retry();
293 }
294 }
295 Purpose::ZipFolder => self.zip_folder = path.clone(),
296 Purpose::Files | Purpose::Folder => self.add_sources(paths),
297 }
298 }
299 }
300 }
301 }
302
303 fn on_drop(&mut self, paths: Vec<PathBuf>) {
304 if self.model.busy() || paths.is_empty() || self.picker.is_some() {
305 return;
306 }
307 if paths.len() == 1 && !self.create && !paths[0].is_dir() {
308 self.open_path(paths[0].clone());
309 } else {
310 self.add_sources(paths);
311 }
312 }
313
314 fn poll(&mut self) {
315 let busy = self.model.busy();
316 self.model.poll();
317 if busy && !self.model.busy() {
318 if let Some(path) = self.owned_destination.take() {
319 if !self.model.confirmed
320 || self
321 .model
322 .terminal
323 .as_ref()
324 .is_none_or(|t| t.outcome != Outcome::Completed)
325 {
326 present::remove_owned_empty(&path);
327 }
328 }
329 }
330 }
331
332 pub fn show(&mut self, root: &mut egui::Ui) {
333 let ctx = root.ctx().clone();
334 if !self.initialized {
335 theme::apply(&ctx);
336 self.initialized = true;
337 }
338 self.poll();
339 let challenge = self.model.challenge.map(|(id, _, _)| id);
340 let new_challenge = challenge != self.password_challenge;
341 if new_challenge || challenge.is_none() {
342 self.clear_password();
343 }
344 self.password_challenge = challenge;
345 self.on_drop(ctx.input(|i| {
346 i.raw
347 .dropped_files
348 .iter()
349 .map(|file| file.path().to_path_buf())
350 .collect()
351 }));
352 if ctx.input(|i| i.viewport().close_requested()) {
353 self.model.request_close();
354 if self.model.close != Close::Allowed {
355 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
356 }
357 }
358 if self.model.close == Close::Allowed {
359 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
360 }
361 egui::Panel::top("archive-actions")
362 .frame(theme::panel(theme::PANEL).corner_radius(0))
363 .show(root, |ui| {
364 ui.horizontal(|ui| {
365 theme::icon(ui, Icon::Archive, 24.0);
366 ui.heading("Zipelo");
367 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
368 if theme::action(
369 ui,
370 "ZIP 만들기",
371 false,
372 !self.model.busy() && self.model.close == Close::Open,
373 )
374 .on_disabled_hover_text("작업이 끝나면 ZIP을 만들 수 있습니다")
375 .clicked()
376 {
377 self.create = true;
378 self.ui_error = None;
379 }
380 });
381 });
382 if self.fixture {
383 ui.colored_label(
384 theme::WARNING,
385 "화면 시험 모드 / 파일을 읽거나 저장하지 않습니다",
386 );
387 }
388 });
389 if self.model.archive.is_some()
390 || self.model.busy()
391 || self.result_visible()
392 || self.ui_error.is_some()
393 {
394 egui::Panel::bottom("archive-work")
395 .frame(theme::panel(theme::PANEL).corner_radius(0))
396 .show(root, |ui| self.work_area(ui));
397 }
398 egui::CentralPanel::default()
399 .frame(theme::panel(theme::BACKGROUND))
400 .show(root, |ui| {
401 if self.model.archive.is_some() {
402 self.archive_list(ui);
403 } else {
404 self.empty(ui);
405 }
406 });
407 if self.create && !self.model.busy() {
408 self.create_dialog(&ctx);
409 }
410 self.show_picker(&ctx);
411 if self.model.challenge.is_some() {
412 self.password_dialog(&ctx, new_challenge);
413 }
414 self.close_dialog(&ctx);
415 if self.model.busy() {
416 ctx.request_repaint_after(std::time::Duration::from_millis(30));
417 }
418 }
419
420 fn empty(&mut self, ui: &mut egui::Ui) {
421 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
422 let width = (ui.available_width() * 0.60)
423 .max(480.0)
424 .min(ui.available_width());
425 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
426 ui.add_space(y);
427 ui.vertical_centered(|ui| {
428 let drop_frame = egui::Frame::new()
429 .fill(if hovered { theme::DROP } else { theme::PANEL })
430 .corner_radius(theme::DROP_RADIUS)
431 .inner_margin(egui::Margin::same(theme::DROP_PAD))
432 .show(ui, |ui| {
433 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
434 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
435 ui.vertical_centered(|ui| {
436 ui.add_space(theme::PAD as f32);
437 theme::icon(ui, Icon::Archive, 48.0);
438 ui.add_space(theme::PAD as f32);
439 ui.label(
440 RichText::new(if hovered {
441 "놓으면 엽니다"
442 } else {
443 "압축파일을 여기에 끌어 놓으세요"
444 })
445 .size(20.0)
446 .strong(),
447 );
448 ui.label("또는");
449 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
450 self.open_picker(Purpose::Open);
451 }
452 });
453 });
454 let rect = drop_frame.response.rect;
455 if hovered {
456 ui.painter().rect_stroke(
457 rect,
458 12,
459 egui::Stroke::new(2.0, theme::BLUE),
460 egui::StrokeKind::Inside,
461 );
462 } else {
463 let stroke = egui::Stroke::new(2.0, theme::DASH);
464 for (a, b) in [
465 (rect.left_top(), rect.right_top()),
466 (rect.right_top(), rect.right_bottom()),
467 (rect.right_bottom(), rect.left_bottom()),
468 (rect.left_bottom(), rect.left_top()),
469 ] {
470 let direction = (b - a).normalized();
471 let mut distance = theme::DROP_RADIUS as f32;
472 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
473 ui.painter().line_segment(
474 [
475 a + direction * distance,
476 a + direction
477 * (distance + theme::SPACE)
478 .min(a.distance(b) - theme::DROP_RADIUS as f32),
479 ],
480 stroke,
481 );
482 distance += theme::PAD as f32;
483 }
484 }
485 }
486 ui.add_space(theme::PAD as f32);
487 ui.colored_label(
488 theme::MUTED,
489 "ZIP, 7z, TAR, GZ, TAR.GZ 파일을 열 수 있습니다",
490 );
491 });
492 }
493
494 fn archive_list(&mut self, ui: &mut egui::Ui) {
495 let archive = self.model.archive.as_ref().unwrap().clone();
496 ui.horizontal(|ui| {
497 theme::icon(ui, Icon::Archive, 32.0);
498 let name = archive.file_name().unwrap_or_default().to_string_lossy();
499 let limit = ((ui.available_width() - 144.0) / theme::TITLE).max(10.0) as usize;
500 ui.heading(present::middle_text(&name, limit))
501 .on_hover_text(archive.display().to_string());
502 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
503 if theme::action(ui, "다른 파일", false, !self.model.busy()).clicked() {
504 self.open_picker(Purpose::Open);
505 }
506 });
507 });
508 let bytes = self
509 .model
510 .entries
511 .iter()
512 .filter_map(|entry| entry.bytes)
513 .sum();
514 ui.colored_label(
515 theme::MUTED,
516 format!(
517 "항목 {}개, {}",
518 self.model.entries.len(),
519 present::bytes_text(bytes)
520 ),
521 );
522 ui.add_space(theme::SPACE);
523 let selectable = self
524 .model
525 .entries
526 .iter()
527 .filter(|e| matches!(e.kind, Kind::File | Kind::Directory))
528 .map(|e| e.id)
529 .collect::<BTreeSet<_>>();
530 let mut all = !selectable.is_empty() && selectable.is_subset(&self.model.selected);
531 let widths =
532 (ui.available_width() - 32.0 - 96.0 - 64.0 - theme::SPACE * 4.0 - 32.0).max(160.0);
533 theme::panel(theme::PANEL)
534 .inner_margin(egui::Margin::symmetric(theme::SPACE as i8, 0))
535 .show(ui, |ui| {
536 ui.horizontal(|ui| {
537 let response = ui
538 .add_enabled(
539 !self.model.busy() && !selectable.is_empty(),
540 egui::Checkbox::without_text(&mut all),
541 )
542 .on_hover_text("전체 선택");
543 response.widget_info(|| {
544 egui::WidgetInfo::selected(
545 egui::Role::CheckBox,
546 !self.model.busy(),
547 all,
548 "전체 선택",
549 )
550 });
551 theme::focus(&response);
552 if response.changed() {
553 self.model.selected = if all {
554 selectable.clone()
555 } else {
556 BTreeSet::new()
557 };
558 }
559 theme::column_label(ui, RichText::new("이름").strong(), widths, Align::Min);
560 theme::column_label(ui, "크기", 96.0, Align::Max);
561 theme::column_label(ui, "암호", 64.0, Align::Min);
562 });
563 ui.separator();
564 if self.model.entries.is_empty() {
565 ui.vertical_centered(|ui| {
566 ui.add_space(theme::SPACE * 8.0);
567 ui.label(if self.model.list_id.is_some() {
568 "이 압축파일은 비어 있습니다"
569 } else {
570 "압축파일을 읽는 중"
571 });
572 });
573 } else {
574 egui::ScrollArea::vertical()
575 .id_salt("archive-rows")
576 .auto_shrink([false, false])
577 .show_rows(ui, theme::ROW, self.model.entries.len(), |ui, rows| {
578 for index in rows {
579 let entry = &self.model.entries[index];
580 let enabled = !self.model.busy()
581 && matches!(entry.kind, Kind::File | Kind::Directory);
582 let mut selected = self.model.selected.contains(&entry.id);
583 let width = ui.available_width();
584 let (rect, row) = ui.allocate_exact_size(
585 egui::vec2(width, theme::ROW),
586 if enabled {
587 egui::Sense::click()
588 } else {
589 egui::Sense::hover()
590 },
591 );
592 ui.painter().rect_filled(
593 rect,
594 0,
595 if selected {
596 theme::SELECTED
597 } else if index % 2 == 0 {
598 theme::PANEL
599 } else {
600 theme::STRIPE
601 },
602 );
603 let mut changed = false;
604 ui.scope_builder(
605 egui::UiBuilder::new()
606 .max_rect(rect)
607 .layout(Layout::left_to_right(Align::Center)),
608 |ui| {
609 let check = ui.add_enabled(
610 enabled,
611 egui::Checkbox::without_text(&mut selected),
612 );
613 check.widget_info(|| {
614 egui::WidgetInfo::selected(
615 egui::Role::CheckBox,
616 enabled,
617 selected,
618 &entry.name,
619 )
620 });
621 theme::focus(&check);
622 changed = check.changed();
623 ui.allocate_ui_with_layout(
624 egui::vec2(widths, theme::ROW),
625 Layout::left_to_right(Align::Center),
626 |ui| {
627 ui.set_min_width(widths);
628 theme::icon(
629 ui,
630 if entry.kind == Kind::Directory {
631 Icon::Folder
632 } else {
633 Icon::File
634 },
635 20.0,
636 );
637 let name = if matches!(
638 entry.kind,
639 Kind::Link | Kind::Other
640 ) {
641 format!("{} (링크)", entry.name)
642 } else {
643 entry.name.clone()
644 };
645 let limit = ((widths - 32.0) / theme::BODY).max(8.0)
646 as usize;
647 ui.label(present::middle_text(&name, limit));
648 },
649 );
650 ui.allocate_ui_with_layout(
651 egui::vec2(96.0, theme::ROW),
652 Layout::right_to_left(Align::Center),
653 |ui| {
654 ui.set_min_width(96.0);
655 ui.label(entry.bytes.map_or_else(
656 || "알 수 없음".into(),
657 present::bytes_text,
658 ));
659 },
660 );
661 ui.allocate_ui_with_layout(
662 egui::vec2(64.0, theme::ROW),
663 Layout::left_to_right(Align::Center),
664 |ui| {
665 ui.set_min_width(64.0);
666 if entry.encrypted {
667 theme::icon(ui, Icon::Lock, 16.0);
668 ui.label("있음");
669 }
670 },
671 );
672 },
673 );
674 row.widget_info(|| {
675 egui::WidgetInfo::selected(
676 egui::Role::Button,
677 enabled,
678 selected,
679 &entry.name,
680 )
681 });
682 row.clone().on_hover_text(&entry.name);
683 theme::focus(&row);
684 let content = ui.interact(
685 egui::Rect::from_min_max(
686 rect.min + egui::vec2(32.0, 0.0),
687 rect.max,
688 ),
689 row.id.with("content"),
690 if enabled {
691 egui::Sense::CLICK
692 } else {
693 egui::Sense::hover()
694 },
695 );
696 if enabled && !changed && (row.clicked() || content.clicked()) {
697 selected = !selected;
698 changed = true;
699 }
700 if changed {
701 if selected {
702 self.model.selected.insert(entry.id);
703 } else {
704 self.model.selected.remove(&entry.id);
705 }
706 }
707 }
708 });
709 }
710 });
711 }
712
713 fn result_visible(&self) -> bool {
714 !self.dismissed
715 && !self.model.busy()
716 && self.last_request.as_ref().is_some_and(|request| {
717 !matches!(request, Start::List { .. })
718 || self.model.error.is_some()
719 || self
720 .model
721 .terminal
722 .as_ref()
723 .is_some_and(|t| t.outcome != Outcome::Completed)
724 })
725 }
726
727 fn work_area(&mut self, ui: &mut egui::Ui) {
728 if self.model.busy() {
729 self.progress(ui);
730 } else if self.result_visible() {
731 self.result(ui);
732 } else if self.model.list_id.is_some() {
733 ui.horizontal(|ui| {
734 ui.strong("풀 위치");
735 let width = ui.available_width() - 136.0;
736 theme::column_label(
737 ui,
738 present::middle_text(
739 &self.destination.display().to_string(),
740 (width / theme::BODY).max(10.0) as usize,
741 ),
742 width,
743 Align::Min,
744 )
745 .on_hover_text(self.destination.display().to_string());
746 if theme::action(ui, "폴더 바꾸기", false, true).clicked() {
747 self.open_picker(Purpose::Destination);
748 }
749 });
750 if self
751 .model
752 .list_id
753 .as_ref()
754 .is_some_and(|id| id.format == Format::Gzip)
755 {
756 ui.horizontal(|ui| {
757 ui.label("저장할 파일 이름");
758 let edit = ui.add(
759 egui::TextEdit::singleline(&mut self.gzip_name)
760 .id(egui::Id::unique("gzip-name")),
761 );
762 theme::focus(&edit);
763 });
764 }
765 ui.horizontal(|ui| {
766 let response = ui.checkbox(&mut self.selected_only, "선택한 항목만 풀기");
767 theme::focus(&response);
768 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
769 let enabled = self.model.can_extract()
770 && (!self.selected_only || !self.model.selected.is_empty());
771 if theme::action(ui, "풀기", true, enabled)
772 .on_disabled_hover_text("풀 항목을 선택하세요")
773 .clicked()
774 {
775 self.begin_extract();
776 }
777 });
778 });
779 }
780 if let Some(error) = &self.ui_error {
781 ui.colored_label(theme::ERROR, error);
782 if error == present::FOLDER_ERROR
783 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
784 {
785 self.open_picker(Purpose::Destination);
786 }
787 }
788 if let Some(error) = &self.model.input_error {
789 ui.colored_label(
790 theme::ERROR,
791 if error.starts_with("암호는") {
792 error.as_str()
793 } else {
794 "풀 위치와 선택한 항목을 확인하세요"
795 },
796 );
797 }
798 }
799
800 fn progress(&mut self, ui: &mut egui::Ui) {
801 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
802 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
803 let title = present::activity_text(&self.model, creating);
804 ui.strong(title);
805 if let Some((_, done, total, count)) = self.model.progress {
806 if let Some(total) = total.filter(|n| *n > 0) {
807 ui.scope(|ui| {
808 ui.visuals_mut().extreme_bg_color = theme::BORDER;
809 ui.add(
810 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
811 .fill(theme::BLUE)
812 .desired_height(theme::SPACE * 2.0),
813 );
814 });
815 ui.horizontal(|ui| {
816 ui.label(format!(
817 "{:.0}% / {count}개 처리함, {} / {}",
818 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
819 present::bytes_text(done),
820 present::bytes_text(total)
821 ));
822 self.cancel_action(ui, cancelling);
823 });
824 } else {
825 theme::indeterminate(ui);
826 ui.horizontal(|ui| {
827 ui.label(format!("{count}개 처리함, {}", present::bytes_text(done)));
828 self.cancel_action(ui, cancelling);
829 });
830 }
831 } else {
832 theme::indeterminate(ui);
833 ui.horizontal(|ui| {
834 ui.label("작업을 진행하고 있습니다");
835 self.cancel_action(ui, cancelling);
836 });
837 }
838 }
839
840 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
841 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
842 if theme::action(ui, "취소", false, !cancelling).clicked() {
843 self.clear_password();
844 self.model.cancel();
845 }
846 });
847 }
848
849 fn result(&mut self, ui: &mut egui::Ui) {
850 let t = self.model.terminal.clone();
851 let listing = matches!(self.last_request, Some(Start::List { .. }));
852 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
853 let warnings = if listing {
854 Vec::new()
855 } else {
856 present::publication_warnings(
857 t.as_ref(),
858 self.model.confirmed,
859 self.targets.as_ref(),
860 &self.directories,
861 &self.model.outputs,
862 )
863 };
864 let success = self.model.confirmed
865 && self.model.error.is_none()
866 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
867 && warnings.is_empty();
868 let durability_warning = t
869 .as_ref()
870 .filter(|_| self.model.confirmed && !listing)
871 .and_then(|t| present::durability_warning(t.durability));
872 let durability_in_details = success
873 && t.as_ref()
874 .is_some_and(|t| t.durability == Durability::Unconfirmed);
875 let cancelled =
876 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
877 let title = if success {
878 if creating {
879 "ZIP 파일을 만들었습니다"
880 } else {
881 "압축을 풀었습니다"
882 }
883 } else if cancelled {
884 "작업을 취소했습니다"
885 } else if listing {
886 "압축파일을 열지 못했습니다"
887 } else if creating {
888 "ZIP 파일을 만들지 못했습니다"
889 } else {
890 "압축을 풀지 못했습니다"
891 };
892 let fill = if success {
893 theme::SUCCESS_BG
894 } else if cancelled {
895 theme::STRIPE
896 } else {
897 theme::ERROR_BG
898 };
899 let mut choose = false;
900 let mut retry = false;
901 let mut reopen = false;
902 let mut folder = false;
903 theme::panel(fill).show(ui, |ui| {
904 ui.horizontal(|ui| {
905 theme::icon(
906 ui,
907 if success {
908 Icon::Success
909 } else if cancelled {
910 Icon::Warning
911 } else {
912 Icon::Error
913 },
914 24.0,
915 );
916 ui.strong(title);
917 });
918 let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
919 egui::ScrollArea::vertical()
920 .id_salt("result-message")
921 .max_height(max_height)
922 .show(ui, |ui| {
923 if success {
924 ui.label(match self.last_request.as_ref() {
925 Some(Start::CreateZip { output_file, .. }) => {
926 output_file.display().to_string()
927 }
928 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
929 });
930 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
931 ui.label(if creating && code == ErrorCode::SourceChanged {
932 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
933 } else {
934 present::error_text(code)
935 });
936 } else if let Some(error) = &self.model.error {
937 ui.label(present::client_error_text(error));
938 }
939 for warning in warnings
940 .iter()
941 .copied()
942 .chain(durability_warning.filter(|_| !durability_in_details))
943 {
944 ui.horizontal_wrapped(|ui| {
945 theme::icon(ui, Icon::Warning, 20.0);
946 ui.colored_label(theme::WARNING, warning);
947 });
948 }
949 if !success
950 && !listing
951 && present::definitely_unsaved(
952 t.as_ref(),
953 self.model.confirmed,
954 &self.model.outputs,
955 )
956 {
957 ui.label("아무 파일도 풀지 않았습니다");
958 }
959 if self.details {
960 theme::panel(theme::STRIPE).show(ui, |ui| {
961 if durability_in_details {
962 if let Some(warning) = durability_warning {
963 ui.label(warning);
964 }
965 }
966 if let Some(t) = &t {
967 for line in terminal_lines(t) {
968 ui.label(line);
969 }
970 }
971 if let Some(error) = &self.model.error {
972 ui.label(error);
973 }
974 for (name, state) in &self.model.outputs {
975 ui.label(format!("{name}: {}", disposition_label(*state)));
976 }
977 });
978 }
979 });
980 let conflict = t
981 .as_ref()
982 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
983 && !creating;
984 let uncertain = warnings.contains(&present::UNCERTAIN);
985 if conflict && uncertain {
986 let response = ui.checkbox(
987 &mut self.checked_destination,
988 "기존 풀 위치 폴더를 확인했습니다",
989 );
990 theme::focus(&response);
991 }
992 ui.horizontal(|ui| {
993 if theme::action(
994 ui,
995 if self.details {
996 "자세히 닫기"
997 } else {
998 "자세히 보기"
999 },
1000 false,
1001 true,
1002 )
1003 .clicked()
1004 {
1005 self.details = !self.details;
1006 }
1007 let action = if success {
1008 Some(("폴더 열기", true))
1009 } else if conflict {
1010 Some(("다른 폴더에 풀기", !uncertain || self.checked_destination))
1011 } else if t
1012 .as_ref()
1013 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1014 {
1015 Some((
1016 if creating {
1017 "다시 만들기"
1018 } else {
1019 "압축파일 다시 열기"
1020 },
1021 true,
1022 ))
1023 } else if !cancelled && (!uncertain || listing) {
1024 Some(("다시 시도", true))
1025 } else {
1026 None
1027 };
1028 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1029 if confirm {
1030 self.dismissed = true;
1031 self.ui_error = None;
1032 self.model.input_error = None;
1033 }
1034 if primary {
1035 match action.map(|(label, _)| label) {
1036 Some("폴더 열기") => folder = true,
1037 Some("다른 폴더에 풀기") => choose = true,
1038 Some("압축파일 다시 열기") => reopen = true,
1039 Some("다시 시도" | "다시 만들기") => retry = true,
1040 _ => {}
1041 }
1042 }
1043 });
1044 });
1045 if choose {
1046 self.open_picker(Purpose::Retry);
1047 }
1048 if retry {
1049 self.retry();
1050 }
1051 if reopen {
1052 if let Some(path) = self.model.archive.clone() {
1053 self.open_path(path);
1054 }
1055 }
1056 if folder {
1057 let path = match self.last_request.as_ref() {
1058 Some(Start::CreateZip { output_file, .. }) => {
1059 output_file.parent().unwrap_or(Path::new("/"))
1060 }
1061 _ => self.destination.as_path(),
1062 };
1063 match present::folder_command(path).spawn() {
1064 Ok(mut child) => {
1065 std::thread::spawn(move || {
1066 let _ = child.wait();
1067 });
1068 }
1069 Err(_) => {
1070 self.ui_error = Some(
1071 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1072 )
1073 }
1074 }
1075 }
1076 }
1077
1078 fn create_dialog(&mut self, ctx: &egui::Context) {
1079 let mut create = false;
1080 let mut pick = None;
1081 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1082 ui.set_width((ctx.content_rect().width() - 64.0).min(560.0));
1083 ui.heading("ZIP 만들기");
1084 egui::ScrollArea::vertical()
1085 .id_salt("create-fields")
1086 .scroll_bar_visibility(if ctx.content_rect().height() < 600.0 {
1087 egui::scroll_area::ScrollBarVisibility::AlwaysVisible
1088 } else {
1089 egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded
1090 })
1091 .max_height((ctx.content_rect().height() - 200.0).max(240.0))
1092 .show(ui, |ui| {
1093 ui.strong("1. 묶을 파일과 폴더");
1094 let mut remove = None;
1095 theme::panel(theme::STRIPE).show(ui, |ui| {
1096 egui::ScrollArea::vertical()
1097 .id_salt("zip-sources")
1098 .max_height(128.0)
1099 .show(ui, |ui| {
1100 if self.sources.is_empty() {
1101 ui.label("여기에 파일이나 폴더를 끌어 놓으세요");
1102 }
1103 for (index, path) in self.sources.iter().enumerate() {
1104 ui.horizontal(|ui| {
1105 theme::icon(
1106 ui,
1107 if path.is_dir() {
1108 Icon::Folder
1109 } else {
1110 Icon::File
1111 },
1112 20.0,
1113 );
1114 theme::column_label(
1115 ui,
1116 present::middle_text(
1117 &path
1118 .file_name()
1119 .unwrap_or_default()
1120 .to_string_lossy(),
1121 28,
1122 ),
1123 ui.available_width() - 80.0,
1124 Align::Min,
1125 )
1126 .on_hover_text(path.display().to_string());
1127 if theme::action(ui, "빼기", false, true).clicked() {
1128 remove = Some(index);
1129 }
1130 });
1131 }
1132 });
1133 });
1134 if let Some(index) = remove {
1135 self.sources.remove(index);
1136 }
1137 ui.horizontal(|ui| {
1138 if theme::action(ui, "파일 추가", false, true).clicked() {
1139 pick = Some(Purpose::Files);
1140 }
1141 if theme::action(ui, "폴더 추가", false, true).clicked() {
1142 pick = Some(Purpose::Folder);
1143 }
1144 });
1145 ui.add_space(theme::SPACE);
1146 ui.strong("2. 저장 위치");
1147 ui.horizontal(|ui| {
1148 ui.label("이름");
1149 let edit = ui.add(
1150 egui::TextEdit::singleline(&mut self.zip_name)
1151 .id(egui::Id::unique("zip-name"))
1152 .desired_width(ui.available_width()),
1153 );
1154 theme::focus(&edit);
1155 });
1156 if let Some(error) = &self.ui_error {
1157 ui.colored_label(theme::ERROR, error);
1158 }
1159 ui.horizontal(|ui| {
1160 ui.label("폴더");
1161 theme::column_label(
1162 ui,
1163 present::middle_text(&self.zip_folder.display().to_string(), 30),
1164 ui.available_width() - 136.0,
1165 Align::Min,
1166 )
1167 .on_hover_text(self.zip_folder.display().to_string());
1168 if theme::action(ui, "폴더 바꾸기", false, true).clicked() {
1169 pick = Some(Purpose::ZipFolder);
1170 }
1171 });
1172 ui.add_space(theme::SPACE);
1173 ui.strong("3. 보호");
1174 let response = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1175 theme::focus(&response);
1176 ui.collapsing("자세한 설정", |ui| {
1177 ui.radio_value(&mut self.method, Method::Deflate, "작게 압축(기본)");
1178 ui.radio_value(&mut self.method, Method::Store, "빠르게 묶기");
1179 });
1180 });
1181 ui.separator();
1182 let can_create = !self.sources.is_empty() && !self.zip_name.is_empty();
1183 let (cancel, confirm) = theme::action_pair(ui, "취소", Some(("만들기", can_create)));
1184 if cancel {
1185 self.create = false;
1186 self.ui_error = None;
1187 return;
1188 }
1189 create = confirm;
1190 });
1191 if !self.create || modal.should_close() {
1192 self.create = false;
1193 return;
1194 }
1195 if let Some(purpose) = pick {
1196 self.open_picker(purpose);
1197 }
1198 if create {
1199 self.begin_zip();
1200 }
1201 }
1202
1203 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1204 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1205 let mut submit = false;
1206 let mut cancel = false;
1207 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
1208 id == egui::Id::unique("archive-password-input")
1209 || id == egui::Id::unique("archive-password-confirm")
1210 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
1211 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1212 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1213 ui.heading(if encrypt {
1214 "ZIP 암호 설정"
1215 } else {
1216 "암호가 필요합니다"
1217 });
1218 if encrypt {
1219 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1220 } else if let Some(path) = &self.model.archive {
1221 ui.label(format!(
1222 "{}은 암호로 보호되어 있습니다.",
1223 present::middle_text(
1224 &path.file_name().unwrap_or_default().to_string_lossy(),
1225 24
1226 )
1227 ));
1228 }
1229 ui.horizontal(|ui| {
1230 ui.label("암호");
1231 let edit = ui.add(
1232 egui::TextEdit::singleline(&mut self.password)
1233 .password(!self.password_visible)
1234 .id(egui::Id::unique("archive-password-input"))
1235 .char_limit(1024)
1236 .desired_width(232.0),
1237 );
1238 theme::focus(&edit);
1239 if new_challenge {
1240 edit.request_focus();
1241 }
1242 if theme::action(
1243 ui,
1244 if self.password_visible {
1245 "숨기기"
1246 } else {
1247 "보기"
1248 },
1249 false,
1250 true,
1251 )
1252 .clicked()
1253 {
1254 self.password_visible = !self.password_visible;
1255 }
1256 });
1257 if encrypt {
1258 ui.horizontal(|ui| {
1259 ui.label("암호 확인");
1260 let edit = ui.add(
1261 egui::TextEdit::singleline(&mut self.password_confirm)
1262 .password(!self.password_visible)
1263 .id(egui::Id::unique("archive-password-confirm"))
1264 .char_limit(1024)
1265 .desired_width(232.0),
1266 );
1267 theme::focus(&edit);
1268 });
1269 if self.password != self.password_confirm {
1270 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1271 }
1272 } else if attempt > 1 {
1273 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1274 }
1275 if self.password.len() > 1024 {
1276 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1277 }
1278 let valid = !self.password.is_empty()
1279 && self.password.len() <= 1024
1280 && (!encrypt || self.password == self.password_confirm);
1281 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1282 cancel = actions.0;
1283 submit = actions.1 || (valid && password_enter);
1284 });
1285 if modal.should_close() || cancel {
1286 self.clear_password();
1287 self.model.cancel();
1288 } else if submit {
1289 let password = std::mem::take(&mut self.password);
1290 self.clear_password();
1291 self.model.password(password);
1292 }
1293 }
1294
1295 fn close_dialog(&mut self, ctx: &egui::Context) {
1296 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1297 return;
1298 }
1299 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1300 ui.set_width(420.0);
1301 match self.model.close {
1302 Close::Confirm => {
1303 ui.heading("작업 중 닫기");
1304 ui.label("작업을 취소하고 닫을까요?");
1305 ui.horizontal(|ui| {
1306 if theme::action(ui, "계속 작업", false, true).clicked() {
1307 self.model.keep_open();
1308 }
1309 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1310 self.clear_password();
1311 self.model.confirm_close();
1312 }
1313 });
1314 }
1315 Close::Waiting => {
1316 ui.heading("종료 확인 중");
1317 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
1318 if theme::action(ui, "닫기 취소", false, true).clicked() {
1319 self.model.keep_open();
1320 }
1321 }
1322 Close::Review => {
1323 ui.heading("결과 확인 후 닫기");
1324 let wrote = self
1325 .last_request
1326 .as_ref()
1327 .is_some_and(|request| !matches!(request, Start::List { .. }));
1328 ui.label(if !wrote {
1329 "프로그램을 닫을까요?"
1330 } else if self.model.confirmed {
1331 "작업 결과를 확인한 뒤 닫으세요"
1332 } else {
1333 present::UNCERTAIN
1334 });
1335 egui::ScrollArea::vertical()
1336 .max_height(160.0)
1337 .show(ui, |ui| {
1338 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
1339 ui.colored_label(theme::ERROR, present::error_text(code));
1340 }
1341 if wrote {
1342 for warning in present::warnings(
1343 self.model.terminal.as_ref(),
1344 self.model.confirmed,
1345 self.targets.as_ref(),
1346 &self.directories,
1347 &self.model.outputs,
1348 ) {
1349 ui.colored_label(theme::WARNING, warning);
1350 }
1351 }
1352 });
1353 ui.horizontal(|ui| {
1354 if theme::action(ui, "계속 작업", false, true).clicked() {
1355 self.model.keep_open();
1356 }
1357 if theme::action(ui, "닫기", true, true).clicked() {
1358 self.model.acknowledge_close();
1359 }
1360 });
1361 }
1362 _ => {}
1363 }
1364 });
1365 }
1366}
1367
1368impl eframe::App for ArchiveApp {
1369 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1370 self.show(root);
1371 }
1372}
1373impl Drop for ArchiveApp {
1374 fn drop(&mut self) {
1375 self.clear_password();
1376 }
1377}