team-ljyzipelo

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