team-ljyzipelo

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