team-ljyzipelo

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