team-ljyzipelo

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