team-ljyzipelo

공개
1,326줄54 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() - 344.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(12)
422 .inner_margin(egui::Margin::same(24))
423 .show(ui, |ui| {
424 ui.set_width(width - 48.0);
425 ui.set_min_height(232.0);
426 ui.vertical_centered(|ui| {
427 ui.add_space(16.0);
428 theme::icon(ui, Icon::Archive, 48.0);
429 ui.add_space(16.0);
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 = 12.0;
463 while distance < a.distance(b) - 12.0 {
464 ui.painter().line_segment(
465 [
466 a + direction * distance,
467 a + direction * (distance + 8.0).min(a.distance(b) - 12.0),
468 ],
469 stroke,
470 );
471 distance += 16.0;
472 }
473 }
474 }
475 ui.add_space(16.0);
476 ui.colored_label(
477 theme::MUTED,
478 "ZIP, 7z, TAR, GZ, TAR.GZ 파일을 열 수 있습니다",
479 );
480 });
481 }
482
483 fn archive_list(&mut self, ui: &mut egui::Ui) {
484 let archive = self.model.archive.as_ref().unwrap().clone();
485 ui.horizontal(|ui| {
486 theme::icon(ui, Icon::Archive, 32.0);
487 let name = archive.file_name().unwrap_or_default().to_string_lossy();
488 let limit = ((ui.available_width() - 144.0) / theme::TITLE).max(10.0) as usize;
489 ui.heading(present::middle_text(&name, limit))
490 .on_hover_text(archive.display().to_string());
491 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
492 if theme::action(ui, "다른 파일", false, !self.model.busy()).clicked() {
493 self.open_picker(Purpose::Open);
494 }
495 });
496 });
497 let bytes = self
498 .model
499 .entries
500 .iter()
501 .filter_map(|entry| entry.bytes)
502 .sum();
503 ui.colored_label(
504 theme::MUTED,
505 format!(
506 "항목 {}개, {}",
507 self.model.entries.len(),
508 present::bytes_text(bytes)
509 ),
510 );
511 ui.add_space(theme::SPACE);
512 let selectable = self
513 .model
514 .entries
515 .iter()
516 .filter(|e| matches!(e.kind, Kind::File | Kind::Directory))
517 .map(|e| e.id)
518 .collect::<BTreeSet<_>>();
519 let mut all = !selectable.is_empty() && selectable.is_subset(&self.model.selected);
520 let widths =
521 (ui.available_width() - 32.0 - 96.0 - 64.0 - theme::SPACE * 4.0 - 32.0).max(160.0);
522 theme::panel(theme::PANEL)
523 .inner_margin(egui::Margin::symmetric(8, 0))
524 .show(ui, |ui| {
525 ui.horizontal(|ui| {
526 let response = ui
527 .add_enabled(
528 !self.model.busy() && !selectable.is_empty(),
529 egui::Checkbox::without_text(&mut all),
530 )
531 .on_hover_text("전체 선택");
532 response.widget_info(|| {
533 egui::WidgetInfo::selected(
534 egui::Role::CheckBox,
535 !self.model.busy(),
536 all,
537 "전체 선택",
538 )
539 });
540 theme::focus(&response);
541 if response.changed() {
542 self.model.selected = if all {
543 selectable.clone()
544 } else {
545 BTreeSet::new()
546 };
547 }
548 theme::column_label(ui, RichText::new("이름").strong(), widths, Align::Min);
549 theme::column_label(ui, "크기", 96.0, Align::Max);
550 theme::column_label(ui, "암호", 64.0, Align::Min);
551 });
552 ui.separator();
553 if self.model.entries.is_empty() {
554 ui.vertical_centered(|ui| {
555 ui.add_space(64.0);
556 ui.label(if self.model.list_id.is_some() {
557 "이 압축파일은 비어 있습니다"
558 } else {
559 "압축파일을 읽는 중"
560 });
561 });
562 } else {
563 egui::ScrollArea::vertical()
564 .id_salt("archive-rows")
565 .auto_shrink([false, false])
566 .show_rows(ui, theme::ROW, self.model.entries.len(), |ui, rows| {
567 for index in rows {
568 let entry = &self.model.entries[index];
569 let enabled = !self.model.busy()
570 && matches!(entry.kind, Kind::File | Kind::Directory);
571 let mut selected = self.model.selected.contains(&entry.id);
572 let width = ui.available_width();
573 let (rect, row) = ui.allocate_exact_size(
574 egui::vec2(width, theme::ROW),
575 if enabled {
576 egui::Sense::click()
577 } else {
578 egui::Sense::hover()
579 },
580 );
581 ui.painter().rect_filled(
582 rect,
583 0,
584 if selected {
585 theme::SELECTED
586 } else if index % 2 == 0 {
587 theme::PANEL
588 } else {
589 theme::STRIPE
590 },
591 );
592 let mut changed = false;
593 ui.scope_builder(
594 egui::UiBuilder::new()
595 .max_rect(rect)
596 .layout(Layout::left_to_right(Align::Center)),
597 |ui| {
598 let check = ui.add_enabled(
599 enabled,
600 egui::Checkbox::without_text(&mut selected),
601 );
602 check.widget_info(|| {
603 egui::WidgetInfo::selected(
604 egui::Role::CheckBox,
605 enabled,
606 selected,
607 &entry.name,
608 )
609 });
610 theme::focus(&check);
611 changed = check.changed();
612 ui.allocate_ui_with_layout(
613 egui::vec2(widths, theme::ROW),
614 Layout::left_to_right(Align::Center),
615 |ui| {
616 ui.set_min_width(widths);
617 theme::icon(
618 ui,
619 if entry.kind == Kind::Directory {
620 Icon::Folder
621 } else {
622 Icon::File
623 },
624 20.0,
625 );
626 let name = if matches!(
627 entry.kind,
628 Kind::Link | Kind::Other
629 ) {
630 format!("{} (링크)", entry.name)
631 } else {
632 entry.name.clone()
633 };
634 let limit = ((widths - 32.0) / theme::BODY).max(8.0)
635 as usize;
636 ui.label(present::middle_text(&name, limit));
637 },
638 );
639 ui.allocate_ui_with_layout(
640 egui::vec2(96.0, theme::ROW),
641 Layout::right_to_left(Align::Center),
642 |ui| {
643 ui.set_min_width(96.0);
644 ui.label(entry.bytes.map_or_else(
645 || "알 수 없음".into(),
646 present::bytes_text,
647 ));
648 },
649 );
650 ui.allocate_ui_with_layout(
651 egui::vec2(64.0, theme::ROW),
652 Layout::left_to_right(Align::Center),
653 |ui| {
654 ui.set_min_width(64.0);
655 if entry.encrypted {
656 theme::icon(ui, Icon::Lock, 16.0);
657 ui.label("있음");
658 }
659 },
660 );
661 },
662 );
663 row.widget_info(|| {
664 egui::WidgetInfo::selected(
665 egui::Role::Button,
666 enabled,
667 selected,
668 &entry.name,
669 )
670 });
671 row.clone().on_hover_text(&entry.name);
672 theme::focus(&row);
673 if enabled && !changed && row.clicked() {
674 selected = !selected;
675 changed = true;
676 }
677 if changed {
678 if selected {
679 self.model.selected.insert(entry.id);
680 } else {
681 self.model.selected.remove(&entry.id);
682 }
683 }
684 }
685 });
686 }
687 });
688 }
689
690 fn result_visible(&self) -> bool {
691 !self.dismissed
692 && !self.model.busy()
693 && self.last_request.as_ref().is_some_and(|request| {
694 !matches!(request, Start::List { .. })
695 || self.model.error.is_some()
696 || self
697 .model
698 .terminal
699 .as_ref()
700 .is_some_and(|t| t.outcome != Outcome::Completed)
701 })
702 }
703
704 fn work_area(&mut self, ui: &mut egui::Ui) {
705 if self.model.busy() {
706 self.progress(ui);
707 } else if self.result_visible() {
708 self.result(ui);
709 } else if self.model.list_id.is_some() {
710 ui.horizontal(|ui| {
711 ui.strong("풀 위치");
712 let width = ui.available_width() - 136.0;
713 theme::column_label(
714 ui,
715 present::middle_text(
716 &self.destination.display().to_string(),
717 (width / theme::BODY).max(10.0) as usize,
718 ),
719 width,
720 Align::Min,
721 )
722 .on_hover_text(self.destination.display().to_string());
723 if theme::action(ui, "폴더 바꾸기", false, true).clicked() {
724 self.open_picker(Purpose::Destination);
725 }
726 });
727 if self
728 .model
729 .list_id
730 .as_ref()
731 .is_some_and(|id| id.format == Format::Gzip)
732 {
733 ui.horizontal(|ui| {
734 ui.label("저장할 파일 이름");
735 let edit = ui.add(
736 egui::TextEdit::singleline(&mut self.gzip_name)
737 .id(egui::Id::unique("gzip-name")),
738 );
739 theme::focus(&edit);
740 });
741 }
742 ui.horizontal(|ui| {
743 let response = ui.checkbox(&mut self.selected_only, "선택한 항목만 풀기");
744 theme::focus(&response);
745 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
746 let enabled = self.model.can_extract()
747 && (!self.selected_only || !self.model.selected.is_empty());
748 if theme::action(ui, "풀기", true, enabled)
749 .on_disabled_hover_text("풀 항목을 선택하세요")
750 .clicked()
751 || (enabled
752 && !self.create
753 && self.picker.is_none()
754 && ui.input(|i| i.key_pressed(egui::Key::Enter)))
755 {
756 self.begin_extract();
757 }
758 });
759 });
760 }
761 if let Some(error) = &self.ui_error {
762 ui.colored_label(theme::ERROR, error);
763 if error == present::FOLDER_ERROR
764 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
765 {
766 self.open_picker(Purpose::Destination);
767 }
768 }
769 if let Some(error) = &self.model.input_error {
770 ui.colored_label(
771 theme::ERROR,
772 if error.starts_with("암호는") {
773 error.as_str()
774 } else {
775 "풀 위치와 선택한 항목을 확인하세요"
776 },
777 );
778 }
779 }
780
781 fn progress(&mut self, ui: &mut egui::Ui) {
782 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
783 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
784 let title = present::activity_text(&self.model, creating);
785 ui.strong(title);
786 if let Some((_, done, total, count)) = self.model.progress {
787 if let Some(total) = total.filter(|n| *n > 0) {
788 ui.scope(|ui| {
789 ui.visuals_mut().extreme_bg_color = theme::BORDER;
790 ui.add(
791 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
792 .fill(theme::BLUE)
793 .desired_height(theme::SPACE * 2.0),
794 );
795 });
796 ui.horizontal(|ui| {
797 ui.label(format!(
798 "{:.0}% / {count}개 처리함, {} / {}",
799 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
800 present::bytes_text(done),
801 present::bytes_text(total)
802 ));
803 self.cancel_action(ui, cancelling);
804 });
805 } else {
806 theme::indeterminate(ui);
807 ui.horizontal(|ui| {
808 ui.label(format!("{count}개 처리함, {}", present::bytes_text(done)));
809 self.cancel_action(ui, cancelling);
810 });
811 }
812 } else {
813 theme::indeterminate(ui);
814 ui.horizontal(|ui| {
815 ui.label("작업을 진행하고 있습니다");
816 self.cancel_action(ui, cancelling);
817 });
818 }
819 }
820
821 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
822 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
823 if theme::action(ui, "취소", false, !cancelling).clicked() {
824 self.clear_password();
825 self.model.cancel();
826 }
827 });
828 }
829
830 fn result(&mut self, ui: &mut egui::Ui) {
831 let t = self.model.terminal.clone();
832 let listing = matches!(self.last_request, Some(Start::List { .. }));
833 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
834 let warnings = if listing {
835 Vec::new()
836 } else {
837 present::warnings(
838 t.as_ref(),
839 self.model.confirmed,
840 self.targets.as_ref(),
841 &self.model.outputs,
842 )
843 };
844 let success = self.model.confirmed
845 && self.model.error.is_none()
846 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
847 && warnings.is_empty();
848 let cancelled =
849 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
850 let title = if success {
851 if creating {
852 "ZIP 파일을 만들었습니다"
853 } else {
854 "압축을 풀었습니다"
855 }
856 } else if cancelled {
857 "작업을 취소했습니다"
858 } else if listing {
859 "압축파일을 열지 못했습니다"
860 } else if creating {
861 "ZIP 파일을 만들지 못했습니다"
862 } else {
863 "압축을 풀지 못했습니다"
864 };
865 let fill = if success {
866 theme::SUCCESS_BG
867 } else if cancelled {
868 theme::STRIPE
869 } else {
870 theme::ERROR_BG
871 };
872 let mut choose = false;
873 let mut retry = false;
874 let mut reopen = false;
875 let mut folder = false;
876 theme::panel(fill).show(ui, |ui| {
877 ui.horizontal(|ui| {
878 theme::icon(
879 ui,
880 if success {
881 Icon::Success
882 } else if cancelled {
883 Icon::Warning
884 } else {
885 Icon::Error
886 },
887 24.0,
888 );
889 ui.strong(title);
890 });
891 let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
892 egui::ScrollArea::vertical()
893 .id_salt("result-message")
894 .max_height(max_height)
895 .show(ui, |ui| {
896 if success {
897 ui.label(match self.last_request.as_ref() {
898 Some(Start::CreateZip { output_file, .. }) => {
899 output_file.display().to_string()
900 }
901 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
902 });
903 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
904 ui.label(present::error_text(code));
905 } else if let Some(error) = &self.model.error {
906 ui.label(present::client_error_text(error));
907 }
908 for warning in &warnings {
909 ui.horizontal_wrapped(|ui| {
910 theme::icon(ui, Icon::Warning, 20.0);
911 ui.colored_label(theme::WARNING, *warning);
912 });
913 }
914 if !success
915 && !listing
916 && present::definitely_unsaved(
917 t.as_ref(),
918 self.model.confirmed,
919 &self.model.outputs,
920 )
921 {
922 ui.label("아무 파일도 풀지 않았습니다");
923 }
924 if self.details {
925 theme::panel(theme::STRIPE).show(ui, |ui| {
926 if let Some(t) = &t {
927 for line in terminal_lines(t) {
928 ui.label(line);
929 }
930 }
931 if let Some(error) = &self.model.error {
932 ui.label(error);
933 }
934 for (name, state) in &self.model.outputs {
935 ui.label(format!("{name}: {}", disposition_label(*state)));
936 }
937 });
938 }
939 });
940 let conflict = t
941 .as_ref()
942 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
943 && !creating;
944 let uncertain = warnings.contains(&present::UNCERTAIN);
945 if conflict && uncertain {
946 let response = ui.checkbox(
947 &mut self.checked_destination,
948 "기존 풀 위치 폴더를 확인했습니다",
949 );
950 theme::focus(&response);
951 }
952 ui.horizontal(|ui| {
953 if theme::action(
954 ui,
955 if self.details {
956 "자세히 닫기"
957 } else {
958 "자세히 보기"
959 },
960 false,
961 true,
962 )
963 .clicked()
964 {
965 self.details = !self.details;
966 }
967 let action = if success {
968 Some(("폴더 열기", true))
969 } else if conflict {
970 Some(("다른 폴더에 풀기", !uncertain || self.checked_destination))
971 } else if t
972 .as_ref()
973 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
974 {
975 Some(("압축파일 다시 열기", true))
976 } else if !cancelled && (!uncertain || listing) {
977 Some(("다시 시도", true))
978 } else {
979 None
980 };
981 let (confirm, primary) = theme::action_pair(ui, "확인", action);
982 if confirm {
983 self.dismissed = true;
984 self.ui_error = None;
985 self.model.input_error = None;
986 }
987 if primary {
988 match action.map(|(label, _)| label) {
989 Some("폴더 열기") => folder = true,
990 Some("다른 폴더에 풀기") => choose = true,
991 Some("압축파일 다시 열기") => reopen = true,
992 Some("다시 시도") => retry = true,
993 _ => {}
994 }
995 }
996 });
997 });
998 if choose {
999 self.open_picker(Purpose::Retry);
1000 }
1001 if retry {
1002 self.retry();
1003 }
1004 if reopen {
1005 if let Some(path) = self.model.archive.clone() {
1006 self.open_path(path);
1007 }
1008 }
1009 if folder {
1010 let path = match self.last_request.as_ref() {
1011 Some(Start::CreateZip { output_file, .. }) => {
1012 output_file.parent().unwrap_or(Path::new("/"))
1013 }
1014 _ => self.destination.as_path(),
1015 };
1016 match present::folder_command(path).spawn() {
1017 Ok(mut child) => {
1018 std::thread::spawn(move || {
1019 let _ = child.wait();
1020 });
1021 }
1022 Err(_) => {
1023 self.ui_error = Some(
1024 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1025 )
1026 }
1027 }
1028 }
1029 }
1030
1031 fn create_dialog(&mut self, ctx: &egui::Context) {
1032 let mut create = false;
1033 let mut pick = None;
1034 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1035 ui.set_width((ctx.content_rect().width() - 64.0).min(560.0));
1036 ui.heading("ZIP 만들기");
1037 egui::ScrollArea::vertical()
1038 .id_salt("create-fields")
1039 .scroll_bar_visibility(if ctx.content_rect().height() < 600.0 {
1040 egui::scroll_area::ScrollBarVisibility::AlwaysVisible
1041 } else {
1042 egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded
1043 })
1044 .max_height((ctx.content_rect().height() - 200.0).max(240.0))
1045 .show(ui, |ui| {
1046 ui.strong("1. 묶을 파일과 폴더");
1047 let mut remove = None;
1048 theme::panel(theme::STRIPE).show(ui, |ui| {
1049 egui::ScrollArea::vertical()
1050 .id_salt("zip-sources")
1051 .max_height(128.0)
1052 .show(ui, |ui| {
1053 if self.sources.is_empty() {
1054 ui.label("여기에 파일이나 폴더를 끌어 놓으세요");
1055 }
1056 for (index, path) in self.sources.iter().enumerate() {
1057 ui.horizontal(|ui| {
1058 theme::icon(
1059 ui,
1060 if path.is_dir() {
1061 Icon::Folder
1062 } else {
1063 Icon::File
1064 },
1065 20.0,
1066 );
1067 theme::column_label(
1068 ui,
1069 present::middle_text(
1070 &path
1071 .file_name()
1072 .unwrap_or_default()
1073 .to_string_lossy(),
1074 28,
1075 ),
1076 ui.available_width() - 80.0,
1077 Align::Min,
1078 )
1079 .on_hover_text(path.display().to_string());
1080 if theme::action(ui, "빼기", false, true).clicked() {
1081 remove = Some(index);
1082 }
1083 });
1084 }
1085 });
1086 });
1087 if let Some(index) = remove {
1088 self.sources.remove(index);
1089 }
1090 ui.horizontal(|ui| {
1091 if theme::action(ui, "파일 추가", false, true).clicked() {
1092 pick = Some(Purpose::Files);
1093 }
1094 if theme::action(ui, "폴더 추가", false, true).clicked() {
1095 pick = Some(Purpose::Folder);
1096 }
1097 });
1098 ui.add_space(theme::SPACE);
1099 ui.strong("2. 저장 위치");
1100 ui.horizontal(|ui| {
1101 ui.label("이름");
1102 let edit = ui.add(
1103 egui::TextEdit::singleline(&mut self.zip_name)
1104 .id(egui::Id::unique("zip-name"))
1105 .desired_width(ui.available_width()),
1106 );
1107 theme::focus(&edit);
1108 });
1109 if let Some(error) = &self.ui_error {
1110 ui.colored_label(theme::ERROR, error);
1111 }
1112 ui.horizontal(|ui| {
1113 ui.label("폴더");
1114 theme::column_label(
1115 ui,
1116 present::middle_text(&self.zip_folder.display().to_string(), 30),
1117 ui.available_width() - 136.0,
1118 Align::Min,
1119 )
1120 .on_hover_text(self.zip_folder.display().to_string());
1121 if theme::action(ui, "폴더 바꾸기", false, true).clicked() {
1122 pick = Some(Purpose::ZipFolder);
1123 }
1124 });
1125 ui.add_space(theme::SPACE);
1126 ui.strong("3. 보호");
1127 let response = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1128 theme::focus(&response);
1129 ui.collapsing("자세한 설정", |ui| {
1130 ui.radio_value(&mut self.method, Method::Deflate, "작게 압축(기본)");
1131 ui.radio_value(&mut self.method, Method::Store, "빠르게 묶기");
1132 });
1133 });
1134 ui.separator();
1135 let can_create = !self.sources.is_empty() && !self.zip_name.is_empty();
1136 let (cancel, confirm) = theme::action_pair(ui, "취소", Some(("만들기", can_create)));
1137 create = confirm
1138 || (can_create
1139 && self.picker.is_none()
1140 && ui.input(|i| i.key_pressed(egui::Key::Enter)));
1141 if cancel {
1142 self.create = false;
1143 self.ui_error = None;
1144 }
1145 });
1146 if modal.should_close() {
1147 self.create = false;
1148 }
1149 if let Some(purpose) = pick {
1150 self.open_picker(purpose);
1151 }
1152 if create {
1153 self.begin_zip();
1154 }
1155 }
1156
1157 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1158 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1159 let mut submit = false;
1160 let mut cancel = false;
1161 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1162 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1163 ui.heading(if encrypt {
1164 "ZIP 암호 설정"
1165 } else {
1166 "암호가 필요합니다"
1167 });
1168 if encrypt {
1169 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1170 } else if let Some(path) = &self.model.archive {
1171 ui.label(format!(
1172 "{}은 암호로 보호되어 있습니다.",
1173 present::middle_text(
1174 &path.file_name().unwrap_or_default().to_string_lossy(),
1175 24
1176 )
1177 ));
1178 }
1179 ui.horizontal(|ui| {
1180 ui.label("암호");
1181 let edit = ui.add(
1182 egui::TextEdit::singleline(&mut self.password)
1183 .password(!self.password_visible)
1184 .id(egui::Id::unique("archive-password-input"))
1185 .char_limit(1024)
1186 .desired_width(232.0),
1187 );
1188 theme::focus(&edit);
1189 if new_challenge {
1190 edit.request_focus();
1191 }
1192 if theme::action(
1193 ui,
1194 if self.password_visible {
1195 "숨기기"
1196 } else {
1197 "보기"
1198 },
1199 false,
1200 true,
1201 )
1202 .clicked()
1203 {
1204 self.password_visible = !self.password_visible;
1205 }
1206 });
1207 if encrypt {
1208 ui.horizontal(|ui| {
1209 ui.label("암호 확인");
1210 let edit = ui.add(
1211 egui::TextEdit::singleline(&mut self.password_confirm)
1212 .password(!self.password_visible)
1213 .id(egui::Id::unique("archive-password-confirm"))
1214 .char_limit(1024)
1215 .desired_width(232.0),
1216 );
1217 theme::focus(&edit);
1218 });
1219 if self.password != self.password_confirm {
1220 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1221 }
1222 } else if attempt > 1 {
1223 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1224 }
1225 if self.password.len() > 1024 {
1226 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1227 }
1228 let valid = !self.password.is_empty()
1229 && self.password.len() <= 1024
1230 && (!encrypt || self.password == self.password_confirm);
1231 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1232 cancel = actions.0;
1233 submit = actions.1 || (valid && ui.input(|i| i.key_pressed(egui::Key::Enter)));
1234 });
1235 if modal.should_close() || cancel {
1236 self.clear_password();
1237 self.model.cancel();
1238 } else if submit {
1239 let password = std::mem::take(&mut self.password);
1240 self.clear_password();
1241 self.model.password(password);
1242 }
1243 }
1244
1245 fn close_dialog(&mut self, ctx: &egui::Context) {
1246 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1247 return;
1248 }
1249 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1250 ui.set_width(420.0);
1251 match self.model.close {
1252 Close::Confirm => {
1253 ui.heading("작업 중 닫기");
1254 ui.label("작업을 취소하고 닫을까요?");
1255 ui.horizontal(|ui| {
1256 if theme::action(ui, "계속 작업", false, true).clicked() {
1257 self.model.keep_open();
1258 }
1259 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1260 self.clear_password();
1261 self.model.confirm_close();
1262 }
1263 });
1264 }
1265 Close::Waiting => {
1266 ui.heading("종료 확인 중");
1267 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
1268 if theme::action(ui, "닫기 취소", false, true).clicked() {
1269 self.model.keep_open();
1270 }
1271 }
1272 Close::Review => {
1273 ui.heading("결과 확인 후 닫기");
1274 let wrote = self
1275 .last_request
1276 .as_ref()
1277 .is_some_and(|request| !matches!(request, Start::List { .. }));
1278 ui.label(if !wrote {
1279 "프로그램을 닫을까요?"
1280 } else if self.model.confirmed {
1281 "작업 결과를 확인한 뒤 닫으세요"
1282 } else {
1283 present::UNCERTAIN
1284 });
1285 egui::ScrollArea::vertical()
1286 .max_height(160.0)
1287 .show(ui, |ui| {
1288 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
1289 ui.colored_label(theme::ERROR, present::error_text(code));
1290 }
1291 if wrote {
1292 for warning in present::warnings(
1293 self.model.terminal.as_ref(),
1294 self.model.confirmed,
1295 self.targets.as_ref(),
1296 &self.model.outputs,
1297 ) {
1298 ui.colored_label(theme::WARNING, warning);
1299 }
1300 }
1301 });
1302 ui.horizontal(|ui| {
1303 if theme::action(ui, "계속 작업", false, true).clicked() {
1304 self.model.keep_open();
1305 }
1306 if theme::action(ui, "닫기", true, true).clicked() {
1307 self.model.acknowledge_close();
1308 }
1309 });
1310 }
1311 _ => {}
1312 }
1313 });
1314 }
1315}
1316
1317impl eframe::App for ArchiveApp {
1318 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1319 self.show(root);
1320 }
1321}
1322impl Drop for ArchiveApp {
1323 fn drop(&mut self) {
1324 self.clear_password();
1325 }
1326}