team-ljyzipelo

공개
1,369줄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::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
868 .iter()
869 .all(|warning| *warning == present::SYNC_WARNING);
870 let cancelled =
871 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
872 let title = if success {
873 if creating {
874 "ZIP 파일을 만들었습니다"
875 } else {
876 "압축을 풀었습니다"
877 }
878 } else if cancelled {
879 "작업을 취소했습니다"
880 } else if listing {
881 "압축파일을 열지 못했습니다"
882 } else if creating {
883 "ZIP 파일을 만들지 못했습니다"
884 } else {
885 "압축을 풀지 못했습니다"
886 };
887 let fill = if success {
888 theme::SUCCESS_BG
889 } else if cancelled {
890 theme::STRIPE
891 } else {
892 theme::ERROR_BG
893 };
894 let mut choose = false;
895 let mut retry = false;
896 let mut reopen = false;
897 let mut folder = false;
898 theme::panel(fill).show(ui, |ui| {
899 ui.horizontal(|ui| {
900 theme::icon(
901 ui,
902 if success {
903 Icon::Success
904 } else if cancelled {
905 Icon::Warning
906 } else {
907 Icon::Error
908 },
909 24.0,
910 );
911 ui.strong(title);
912 });
913 let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
914 egui::ScrollArea::vertical()
915 .id_salt("result-message")
916 .max_height(max_height)
917 .show(ui, |ui| {
918 if success {
919 ui.label(match self.last_request.as_ref() {
920 Some(Start::CreateZip { output_file, .. }) => {
921 output_file.display().to_string()
922 }
923 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
924 });
925 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
926 ui.label(if creating && code == ErrorCode::SourceChanged {
927 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
928 } else {
929 present::error_text(code)
930 });
931 } else if let Some(error) = &self.model.error {
932 ui.label(present::client_error_text(error));
933 }
934 for warning in warnings
935 .iter()
936 .filter(|warning| **warning != present::SYNC_WARNING)
937 {
938 ui.horizontal_wrapped(|ui| {
939 theme::icon(ui, Icon::Warning, 20.0);
940 ui.colored_label(theme::WARNING, *warning);
941 });
942 }
943 if !success
944 && !listing
945 && present::definitely_unsaved(
946 t.as_ref(),
947 self.model.confirmed,
948 &self.model.outputs,
949 )
950 {
951 ui.label("아무 파일도 풀지 않았습니다");
952 }
953 if self.details {
954 theme::panel(theme::STRIPE).show(ui, |ui| {
955 if warnings.contains(&present::SYNC_WARNING) {
956 ui.label(present::SYNC_WARNING);
957 }
958 if let Some(t) = &t {
959 for line in terminal_lines(t) {
960 ui.label(line);
961 }
962 }
963 if let Some(error) = &self.model.error {
964 ui.label(error);
965 }
966 for (name, state) in &self.model.outputs {
967 ui.label(format!("{name}: {}", disposition_label(*state)));
968 }
969 });
970 }
971 });
972 let conflict = t
973 .as_ref()
974 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
975 && !creating;
976 let uncertain = warnings.contains(&present::UNCERTAIN);
977 if conflict && uncertain {
978 let response = ui.checkbox(
979 &mut self.checked_destination,
980 "기존 풀 위치 폴더를 확인했습니다",
981 );
982 theme::focus(&response);
983 }
984 ui.horizontal(|ui| {
985 if theme::action(
986 ui,
987 if self.details {
988 "자세히 닫기"
989 } else {
990 "자세히 보기"
991 },
992 false,
993 true,
994 )
995 .clicked()
996 {
997 self.details = !self.details;
998 }
999 let action = if success {
1000 Some(("폴더 열기", true))
1001 } else if conflict {
1002 Some(("다른 폴더에 풀기", !uncertain || self.checked_destination))
1003 } else if t
1004 .as_ref()
1005 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1006 {
1007 Some((
1008 if creating {
1009 "다시 만들기"
1010 } else {
1011 "압축파일 다시 열기"
1012 },
1013 true,
1014 ))
1015 } else if !cancelled && (!uncertain || listing) {
1016 Some(("다시 시도", true))
1017 } else {
1018 None
1019 };
1020 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1021 if confirm {
1022 self.dismissed = true;
1023 self.ui_error = None;
1024 self.model.input_error = None;
1025 }
1026 if primary {
1027 match action.map(|(label, _)| label) {
1028 Some("폴더 열기") => folder = true,
1029 Some("다른 폴더에 풀기") => choose = true,
1030 Some("압축파일 다시 열기") => reopen = true,
1031 Some("다시 시도" | "다시 만들기") => retry = true,
1032 _ => {}
1033 }
1034 }
1035 });
1036 });
1037 if choose {
1038 self.open_picker(Purpose::Retry);
1039 }
1040 if retry {
1041 self.retry();
1042 }
1043 if reopen {
1044 if let Some(path) = self.model.archive.clone() {
1045 self.open_path(path);
1046 }
1047 }
1048 if folder {
1049 let path = match self.last_request.as_ref() {
1050 Some(Start::CreateZip { output_file, .. }) => {
1051 output_file.parent().unwrap_or(Path::new("/"))
1052 }
1053 _ => self.destination.as_path(),
1054 };
1055 match present::folder_command(path).spawn() {
1056 Ok(mut child) => {
1057 std::thread::spawn(move || {
1058 let _ = child.wait();
1059 });
1060 }
1061 Err(_) => {
1062 self.ui_error = Some(
1063 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1064 )
1065 }
1066 }
1067 }
1068 }
1069
1070 fn create_dialog(&mut self, ctx: &egui::Context) {
1071 let mut create = false;
1072 let mut pick = None;
1073 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1074 ui.set_width((ctx.content_rect().width() - 64.0).min(560.0));
1075 ui.heading("ZIP 만들기");
1076 egui::ScrollArea::vertical()
1077 .id_salt("create-fields")
1078 .scroll_bar_visibility(if ctx.content_rect().height() < 600.0 {
1079 egui::scroll_area::ScrollBarVisibility::AlwaysVisible
1080 } else {
1081 egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded
1082 })
1083 .max_height((ctx.content_rect().height() - 200.0).max(240.0))
1084 .show(ui, |ui| {
1085 ui.strong("1. 묶을 파일과 폴더");
1086 let mut remove = None;
1087 theme::panel(theme::STRIPE).show(ui, |ui| {
1088 egui::ScrollArea::vertical()
1089 .id_salt("zip-sources")
1090 .max_height(128.0)
1091 .show(ui, |ui| {
1092 if self.sources.is_empty() {
1093 ui.label("여기에 파일이나 폴더를 끌어 놓으세요");
1094 }
1095 for (index, path) in self.sources.iter().enumerate() {
1096 ui.horizontal(|ui| {
1097 theme::icon(
1098 ui,
1099 if path.is_dir() {
1100 Icon::Folder
1101 } else {
1102 Icon::File
1103 },
1104 20.0,
1105 );
1106 theme::column_label(
1107 ui,
1108 present::middle_text(
1109 &path
1110 .file_name()
1111 .unwrap_or_default()
1112 .to_string_lossy(),
1113 28,
1114 ),
1115 ui.available_width() - 80.0,
1116 Align::Min,
1117 )
1118 .on_hover_text(path.display().to_string());
1119 if theme::action(ui, "빼기", false, true).clicked() {
1120 remove = Some(index);
1121 }
1122 });
1123 }
1124 });
1125 });
1126 if let Some(index) = remove {
1127 self.sources.remove(index);
1128 }
1129 ui.horizontal(|ui| {
1130 if theme::action(ui, "파일 추가", false, true).clicked() {
1131 pick = Some(Purpose::Files);
1132 }
1133 if theme::action(ui, "폴더 추가", false, true).clicked() {
1134 pick = Some(Purpose::Folder);
1135 }
1136 });
1137 ui.add_space(theme::SPACE);
1138 ui.strong("2. 저장 위치");
1139 ui.horizontal(|ui| {
1140 ui.label("이름");
1141 let edit = ui.add(
1142 egui::TextEdit::singleline(&mut self.zip_name)
1143 .id(egui::Id::unique("zip-name"))
1144 .desired_width(ui.available_width()),
1145 );
1146 theme::focus(&edit);
1147 });
1148 if let Some(error) = &self.ui_error {
1149 ui.colored_label(theme::ERROR, error);
1150 }
1151 ui.horizontal(|ui| {
1152 ui.label("폴더");
1153 theme::column_label(
1154 ui,
1155 present::middle_text(&self.zip_folder.display().to_string(), 30),
1156 ui.available_width() - 136.0,
1157 Align::Min,
1158 )
1159 .on_hover_text(self.zip_folder.display().to_string());
1160 if theme::action(ui, "폴더 바꾸기", false, true).clicked() {
1161 pick = Some(Purpose::ZipFolder);
1162 }
1163 });
1164 ui.add_space(theme::SPACE);
1165 ui.strong("3. 보호");
1166 let response = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1167 theme::focus(&response);
1168 ui.collapsing("자세한 설정", |ui| {
1169 ui.radio_value(&mut self.method, Method::Deflate, "작게 압축(기본)");
1170 ui.radio_value(&mut self.method, Method::Store, "빠르게 묶기");
1171 });
1172 });
1173 ui.separator();
1174 let can_create = !self.sources.is_empty() && !self.zip_name.is_empty();
1175 let (cancel, confirm) = theme::action_pair(ui, "취소", Some(("만들기", can_create)));
1176 if cancel {
1177 self.create = false;
1178 self.ui_error = None;
1179 return;
1180 }
1181 create = confirm;
1182 });
1183 if !self.create || modal.should_close() {
1184 self.create = false;
1185 return;
1186 }
1187 if let Some(purpose) = pick {
1188 self.open_picker(purpose);
1189 }
1190 if create {
1191 self.begin_zip();
1192 }
1193 }
1194
1195 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1196 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1197 let mut submit = false;
1198 let mut cancel = false;
1199 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
1200 id == egui::Id::unique("archive-password-input")
1201 || id == egui::Id::unique("archive-password-confirm")
1202 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
1203 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1204 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1205 ui.heading(if encrypt {
1206 "ZIP 암호 설정"
1207 } else {
1208 "암호가 필요합니다"
1209 });
1210 if encrypt {
1211 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1212 } else if let Some(path) = &self.model.archive {
1213 ui.label(format!(
1214 "{}은 암호로 보호되어 있습니다.",
1215 present::middle_text(
1216 &path.file_name().unwrap_or_default().to_string_lossy(),
1217 24
1218 )
1219 ));
1220 }
1221 ui.horizontal(|ui| {
1222 ui.label("암호");
1223 let edit = ui.add(
1224 egui::TextEdit::singleline(&mut self.password)
1225 .password(!self.password_visible)
1226 .id(egui::Id::unique("archive-password-input"))
1227 .char_limit(1024)
1228 .desired_width(232.0),
1229 );
1230 theme::focus(&edit);
1231 if new_challenge {
1232 edit.request_focus();
1233 }
1234 if theme::action(
1235 ui,
1236 if self.password_visible {
1237 "숨기기"
1238 } else {
1239 "보기"
1240 },
1241 false,
1242 true,
1243 )
1244 .clicked()
1245 {
1246 self.password_visible = !self.password_visible;
1247 }
1248 });
1249 if encrypt {
1250 ui.horizontal(|ui| {
1251 ui.label("암호 확인");
1252 let edit = ui.add(
1253 egui::TextEdit::singleline(&mut self.password_confirm)
1254 .password(!self.password_visible)
1255 .id(egui::Id::unique("archive-password-confirm"))
1256 .char_limit(1024)
1257 .desired_width(232.0),
1258 );
1259 theme::focus(&edit);
1260 });
1261 if self.password != self.password_confirm {
1262 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1263 }
1264 } else if attempt > 1 {
1265 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1266 }
1267 if self.password.len() > 1024 {
1268 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1269 }
1270 let valid = !self.password.is_empty()
1271 && self.password.len() <= 1024
1272 && (!encrypt || self.password == self.password_confirm);
1273 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1274 cancel = actions.0;
1275 submit = actions.1 || (valid && password_enter);
1276 });
1277 if modal.should_close() || cancel {
1278 self.clear_password();
1279 self.model.cancel();
1280 } else if submit {
1281 let password = std::mem::take(&mut self.password);
1282 self.clear_password();
1283 self.model.password(password);
1284 }
1285 }
1286
1287 fn close_dialog(&mut self, ctx: &egui::Context) {
1288 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1289 return;
1290 }
1291 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1292 ui.set_width(420.0);
1293 match self.model.close {
1294 Close::Confirm => {
1295 ui.heading("작업 중 닫기");
1296 ui.label("작업을 취소하고 닫을까요?");
1297 ui.horizontal(|ui| {
1298 if theme::action(ui, "계속 작업", false, true).clicked() {
1299 self.model.keep_open();
1300 }
1301 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1302 self.clear_password();
1303 self.model.confirm_close();
1304 }
1305 });
1306 }
1307 Close::Waiting => {
1308 ui.heading("종료 확인 중");
1309 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
1310 if theme::action(ui, "닫기 취소", false, true).clicked() {
1311 self.model.keep_open();
1312 }
1313 }
1314 Close::Review => {
1315 ui.heading("결과 확인 후 닫기");
1316 let wrote = self
1317 .last_request
1318 .as_ref()
1319 .is_some_and(|request| !matches!(request, Start::List { .. }));
1320 ui.label(if !wrote {
1321 "프로그램을 닫을까요?"
1322 } else if self.model.confirmed {
1323 "작업 결과를 확인한 뒤 닫으세요"
1324 } else {
1325 present::UNCERTAIN
1326 });
1327 egui::ScrollArea::vertical()
1328 .max_height(160.0)
1329 .show(ui, |ui| {
1330 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
1331 ui.colored_label(theme::ERROR, present::error_text(code));
1332 }
1333 if wrote {
1334 for warning in present::warnings(
1335 self.model.terminal.as_ref(),
1336 self.model.confirmed,
1337 self.targets.as_ref(),
1338 &self.directories,
1339 &self.model.outputs,
1340 ) {
1341 ui.colored_label(theme::WARNING, warning);
1342 }
1343 }
1344 });
1345 ui.horizontal(|ui| {
1346 if theme::action(ui, "계속 작업", false, true).clicked() {
1347 self.model.keep_open();
1348 }
1349 if theme::action(ui, "닫기", true, true).clicked() {
1350 self.model.acknowledge_close();
1351 }
1352 });
1353 }
1354 _ => {}
1355 }
1356 });
1357 }
1358}
1359
1360impl eframe::App for ArchiveApp {
1361 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1362 self.show(root);
1363 }
1364}
1365impl Drop for ArchiveApp {
1366 fn drop(&mut self) {
1367 self.clear_password();
1368 }
1369}