team-ljyzipelo

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