team-ljyzipelo

공개
1,378줄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 self.model.selected.retain(|id| !visible.contains(id));
659 }
660 }
661 theme::focus(&check);
662 theme::column_label(ui, RichText::new("이름").strong(), name_width, Align::Min);
663 theme::column_label(ui, "크기", 96.0, Align::Max);
664 theme::column_label(ui, "암호", 64.0, Align::Min);
665 });
666 ui.separator();
667 egui::ScrollArea::vertical()
668 .id_salt("archive-rows")
669 .auto_shrink([false, false])
670 .show_rows(ui, 38.0, rows.len(), |ui, range| {
671 for index in range {
672 let row = &rows[index];
673 let mut selected =
674 !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
675 let response = ui
676 .horizontal(|ui| {
677 ui.set_min_height(36.0);
678 ui.add_space(16.0);
679 let check = ui.add_enabled(
680 !self.model.busy() && !row.ids.is_empty(),
681 egui::Checkbox::without_text(&mut selected),
682 );
683 check.widget_info(|| {
684 egui::WidgetInfo::selected(
685 egui::Role::CheckBox,
686 !self.model.busy(),
687 selected,
688 &row.name,
689 )
690 });
691 theme::focus(&check);
692 if check.changed() {
693 if selected {
694 self.model.selected.extend(&row.ids);
695 } else {
696 self.model.selected.retain(|id| !row.ids.contains(id));
697 }
698 }
699 theme::icon(
700 ui,
701 if row.directory {
702 Icon::Folder
703 } else {
704 Icon::File
705 },
706 20.0,
707 );
708 let label = ui
709 .allocate_ui_with_layout(
710 egui::vec2(name_width - 28.0, 34.0),
711 Layout::left_to_right(Align::Center),
712 |ui| {
713 ui.set_min_width(name_width - 28.0);
714 ui.add_enabled(
715 !self.model.busy(),
716 egui::Button::new(&row.name)
717 .selected(selected)
718 .frame(false)
719 .min_size(egui::vec2(0.0, 34.0)),
720 )
721 },
722 )
723 .inner;
724 theme::focus(&label);
725 let enter =
726 label.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
727 if row.directory && (label.double_clicked() || enter) {
728 self.browse_folder(&row.path);
729 } else if !row.directory && label.clicked() {
730 if selected {
731 self.model.selected.retain(|id| !row.ids.contains(id));
732 } else {
733 self.model.selected.extend(&row.ids);
734 }
735 }
736 theme::column_label(
737 ui,
738 if row.directory {
739 "0 B".into()
740 } else {
741 row.bytes
742 .map(present::bytes_text)
743 .unwrap_or_else(|| "—".into())
744 },
745 96.0,
746 Align::Max,
747 );
748 if row.encrypted {
749 theme::icon(ui, Icon::Lock, 16.0);
750 }
751 })
752 .response;
753 ui.painter().hline(
754 response.rect.x_range(),
755 response.rect.bottom(),
756 egui::Stroke::new(1.0, theme::BORDER),
757 );
758 }
759 });
760 if rows.is_empty() {
761 ui.centered_and_justified(|ui| {
762 ui.label(if self.search.is_empty() {
763 "이 폴더는 비어 있습니다"
764 } else {
765 "일치하는 항목이 없습니다"
766 });
767 });
768 }
769 }
770
771 fn result_visible(&self) -> bool {
772 !self.dismissed
773 && !self.model.busy()
774 && self.last_request.as_ref().is_some_and(|request| {
775 !matches!(request, Start::List { .. })
776 || self.model.error.is_some()
777 || self
778 .model
779 .terminal
780 .as_ref()
781 .is_some_and(|t| t.outcome != Outcome::Completed)
782 })
783 }
784
785 fn work_area(&mut self, ui: &mut egui::Ui) {
786 if self.model.busy() {
787 self.progress(ui);
788 } else if self.result_visible() {
789 self.result(ui);
790 }
791 if let Some(error) = &self.ui_error {
792 ui.colored_label(theme::ERROR, error);
793 if error == present::FOLDER_ERROR
794 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
795 {
796 self.open_picker(Purpose::Destination);
797 }
798 }
799 if let Some(error) = &self.model.input_error {
800 ui.colored_label(
801 theme::ERROR,
802 if error.starts_with("암호는") {
803 error.as_str()
804 } else {
805 "풀 위치와 선택한 항목을 확인하세요"
806 },
807 );
808 }
809 }
810
811 fn progress(&mut self, ui: &mut egui::Ui) {
812 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
813 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
814 let title = present::activity_text(&self.model, creating);
815 ui.strong(title);
816 if let Some((_, done, total, count)) = self.model.progress {
817 if let Some(total) = total.filter(|n| *n > 0) {
818 ui.scope(|ui| {
819 ui.visuals_mut().extreme_bg_color = theme::BORDER;
820 ui.add(
821 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
822 .fill(theme::BLUE)
823 .desired_height(theme::SPACE * 2.0),
824 );
825 });
826 ui.horizontal(|ui| {
827 ui.label(format!(
828 "{:.0}% / {count}개 처리함, {} / {}",
829 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
830 present::bytes_text(done),
831 present::bytes_text(total)
832 ));
833 self.cancel_action(ui, cancelling);
834 });
835 } else {
836 theme::indeterminate(ui);
837 ui.horizontal(|ui| {
838 ui.label(format!("{count}개 처리함, {}", present::bytes_text(done)));
839 self.cancel_action(ui, cancelling);
840 });
841 }
842 } else {
843 theme::indeterminate(ui);
844 ui.horizontal(|ui| {
845 ui.label("작업을 진행하고 있습니다");
846 self.cancel_action(ui, cancelling);
847 });
848 }
849 }
850
851 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
852 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
853 if theme::action(ui, "취소", false, !cancelling).clicked() {
854 self.clear_password();
855 self.model.cancel();
856 }
857 });
858 }
859
860 fn result(&mut self, ui: &mut egui::Ui) {
861 let t = self.model.terminal.clone();
862 let listing = matches!(self.last_request, Some(Start::List { .. }));
863 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
864 let warnings = if listing {
865 Vec::new()
866 } else {
867 present::publication_warnings(
868 t.as_ref(),
869 self.model.confirmed,
870 self.targets.as_ref(),
871 &self.directories,
872 &self.model.outputs,
873 )
874 };
875 let success = self.model.confirmed
876 && self.model.error.is_none()
877 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
878 && warnings.is_empty();
879 let durability_warning = t
880 .as_ref()
881 .filter(|_| self.model.confirmed && !listing)
882 .and_then(|t| present::durability_warning(t.durability));
883 let durability_in_details = success
884 && t.as_ref()
885 .is_some_and(|t| t.durability == Durability::Unconfirmed);
886 let cancelled =
887 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
888 let title = if success {
889 if creating {
890 "ZIP 파일을 만들었습니다"
891 } else {
892 "압축을 풀었습니다"
893 }
894 } else if cancelled {
895 "작업을 취소했습니다"
896 } else if listing {
897 "압축파일을 열지 못했습니다"
898 } else if creating {
899 "ZIP 파일을 만들지 못했습니다"
900 } else {
901 "압축을 풀지 못했습니다"
902 };
903 let fill = if success {
904 theme::SUCCESS_BG
905 } else if cancelled {
906 theme::STRIPE
907 } else {
908 theme::ERROR_BG
909 };
910 let mut choose = false;
911 let mut retry = false;
912 let mut reopen = false;
913 let mut folder = false;
914 theme::panel(fill).show(ui, |ui| {
915 ui.horizontal(|ui| {
916 theme::icon(
917 ui,
918 if success {
919 Icon::Success
920 } else if cancelled {
921 Icon::Warning
922 } else {
923 Icon::Error
924 },
925 24.0,
926 );
927 ui.strong(title);
928 });
929 let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
930 egui::ScrollArea::vertical()
931 .id_salt("result-message")
932 .max_height(max_height)
933 .show(ui, |ui| {
934 if success {
935 ui.label(match self.last_request.as_ref() {
936 Some(Start::CreateZip { output_file, .. }) => {
937 output_file.display().to_string()
938 }
939 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
940 });
941 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
942 ui.label(if creating && code == ErrorCode::SourceChanged {
943 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
944 } else {
945 present::error_text(code)
946 });
947 } else if let Some(error) = &self.model.error {
948 ui.label(present::client_error_text(error));
949 }
950 for warning in warnings
951 .iter()
952 .copied()
953 .chain(durability_warning.filter(|_| !durability_in_details))
954 {
955 ui.horizontal_wrapped(|ui| {
956 theme::icon(ui, Icon::Warning, 20.0);
957 ui.colored_label(theme::WARNING, warning);
958 });
959 }
960 if !success
961 && !listing
962 && present::definitely_unsaved(
963 t.as_ref(),
964 self.model.confirmed,
965 &self.model.outputs,
966 )
967 {
968 ui.label("아무 파일도 풀지 않았습니다");
969 }
970 if self.details {
971 theme::panel(theme::STRIPE).show(ui, |ui| {
972 if durability_in_details {
973 if let Some(warning) = durability_warning {
974 ui.label(warning);
975 }
976 }
977 if let Some(t) = &t {
978 for line in terminal_lines(t) {
979 ui.label(line);
980 }
981 }
982 if let Some(error) = &self.model.error {
983 ui.label(error);
984 }
985 for (name, state) in &self.model.outputs {
986 ui.label(format!("{name}: {}", disposition_label(*state)));
987 }
988 });
989 }
990 });
991 let conflict = t
992 .as_ref()
993 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
994 && !creating;
995 let uncertain = warnings.contains(&present::UNCERTAIN);
996 if conflict && uncertain {
997 let response = ui.checkbox(
998 &mut self.checked_destination,
999 "기존 풀 위치 폴더를 확인했습니다",
1000 );
1001 theme::focus(&response);
1002 }
1003 ui.horizontal(|ui| {
1004 if theme::action(
1005 ui,
1006 if self.details {
1007 "자세히 닫기"
1008 } else {
1009 "자세히 보기"
1010 },
1011 false,
1012 true,
1013 )
1014 .clicked()
1015 {
1016 self.details = !self.details;
1017 }
1018 let action = if success {
1019 Some(("폴더 열기", true))
1020 } else if conflict {
1021 Some(("다른 폴더에 풀기", !uncertain || self.checked_destination))
1022 } else if t
1023 .as_ref()
1024 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1025 {
1026 Some((
1027 if creating {
1028 "다시 만들기"
1029 } else {
1030 "압축파일 다시 열기"
1031 },
1032 true,
1033 ))
1034 } else if !cancelled && (!uncertain || listing) {
1035 Some(("다시 시도", true))
1036 } else {
1037 None
1038 };
1039 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1040 if confirm {
1041 self.dismissed = true;
1042 self.ui_error = None;
1043 self.model.input_error = None;
1044 }
1045 if primary {
1046 match action.map(|(label, _)| label) {
1047 Some("폴더 열기") => folder = true,
1048 Some("다른 폴더에 풀기") => choose = true,
1049 Some("압축파일 다시 열기") => reopen = true,
1050 Some("다시 시도" | "다시 만들기") => retry = true,
1051 _ => {}
1052 }
1053 }
1054 });
1055 });
1056 if choose {
1057 self.open_picker(Purpose::Retry);
1058 }
1059 if retry {
1060 self.retry();
1061 }
1062 if reopen {
1063 if let Some(path) = self.model.archive.clone() {
1064 self.open_path(path);
1065 }
1066 }
1067 if folder {
1068 let path = match self.last_request.as_ref() {
1069 Some(Start::CreateZip { output_file, .. }) => {
1070 output_file.parent().unwrap_or(Path::new("/"))
1071 }
1072 _ => self.destination.as_path(),
1073 };
1074 match present::folder_command(path).spawn() {
1075 Ok(mut child) => {
1076 std::thread::spawn(move || {
1077 let _ = child.wait();
1078 });
1079 }
1080 Err(_) => {
1081 self.ui_error = Some(
1082 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1083 )
1084 }
1085 }
1086 }
1087 }
1088
1089 fn create_dialog(&mut self, ctx: &egui::Context) {
1090 let mut compress = false;
1091 let mut pick = None;
1092 let mut cancel = false;
1093 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1094 ui.set_width((ctx.content_rect().width() - 64.0).min(600.0));
1095 ui.horizontal(|ui| {
1096 ui.heading("ZIP 만들기");
1097 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1098 let close = theme::icon_button(ui, "닫기", theme::CLOSE, true);
1099 theme::focus(&close);
1100 cancel = close.clicked();
1101 });
1102 });
1103 egui::ScrollArea::vertical()
1104 .id_salt("create-fields")
1105 .max_height((ctx.content_rect().height() - 180.0).max(180.0))
1106 .show(ui, |ui| {
1107 ui.add_space(16.0);
1108 let frame = theme::panel(theme::STRIPE)
1109 .stroke(egui::Stroke::new(1.0, theme::DASH))
1110 .inner_margin(egui::Margin::same(24));
1111 let area = frame
1112 .show(ui, |ui| {
1113 ui.set_min_size(egui::vec2(ui.available_width(), 144.0));
1114 ui.vertical_centered(|ui| {
1115 theme::icon(ui, Icon::File, 44.0);
1116 ui.add_space(16.0);
1117 ui.label(
1118 RichText::new("파일이나 폴더를 여기에 끌어 놓으세요")
1119 .size(18.0),
1120 );
1121 });
1122 })
1123 .response;
1124 let drop = ui.interact(
1125 area.rect,
1126 egui::Id::unique("zip-source-drop"),
1127 egui::Sense::click(),
1128 );
1129 theme::focus(&drop);
1130 drop.widget_info(|| {
1131 egui::WidgetInfo::labeled(egui::Role::Button, true, "파일 추가")
1132 });
1133 if drop.clicked() {
1134 pick = Some(Purpose::Files);
1135 }
1136 egui::ScrollArea::vertical()
1137 .id_salt("zip-sources")
1138 .max_height(86.0)
1139 .show(ui, |ui| {
1140 let mut remove = None;
1141 for (index, path) in self.sources.iter().enumerate() {
1142 ui.horizontal(|ui| {
1143 theme::icon(
1144 ui,
1145 if path.is_dir() {
1146 Icon::Folder
1147 } else {
1148 Icon::File
1149 },
1150 20.0,
1151 );
1152 ui.label(present::middle_text(
1153 &path.file_name().unwrap_or_default().to_string_lossy(),
1154 36,
1155 ))
1156 .on_hover_text(path.display().to_string());
1157 if ui.button("빼기").clicked() {
1158 remove = Some(index);
1159 }
1160 });
1161 }
1162 if let Some(index) = remove {
1163 self.sources.remove(index);
1164 }
1165 });
1166 ui.horizontal(|ui| {
1167 if theme::action(ui, "파일 추가", false, true).clicked() {
1168 pick = Some(Purpose::Files);
1169 }
1170 if theme::action(ui, "폴더 추가", false, true).clicked() {
1171 pick = Some(Purpose::Folder);
1172 }
1173 });
1174 ui.add_space(16.0);
1175 ui.horizontal(|ui| {
1176 theme::icon(ui, Icon::Lock, 24.0);
1177 ui.strong("암호화");
1178 });
1179 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1180 theme::focus(&check);
1181 if let Some(error) = &self.ui_error {
1182 ui.colored_label(theme::ERROR, error);
1183 }
1184 ui.add_space(16.0);
1185 });
1186 let (dismiss, confirm) =
1187 theme::action_pair(ui, "취소", Some(("압축하기", !self.sources.is_empty())));
1188 cancel |= dismiss;
1189 compress = confirm;
1190 });
1191 if cancel || modal.should_close() {
1192 self.create = false;
1193 self.ui_error = None;
1194 return;
1195 }
1196 if let Some(purpose) = pick {
1197 self.open_picker(purpose);
1198 }
1199 if compress {
1200 self.open_picker(Purpose::SaveZip);
1201 }
1202 }
1203
1204 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1205 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1206 let mut submit = false;
1207 let mut cancel = false;
1208 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
1209 id == egui::Id::unique("archive-password-input")
1210 || id == egui::Id::unique("archive-password-confirm")
1211 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
1212 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1213 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1214 ui.heading(if encrypt {
1215 "ZIP 암호 설정"
1216 } else {
1217 "암호가 필요합니다"
1218 });
1219 if encrypt {
1220 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1221 } else if let Some(path) = &self.model.archive {
1222 ui.label(format!(
1223 "{}은 암호로 보호되어 있습니다.",
1224 present::middle_text(
1225 &path.file_name().unwrap_or_default().to_string_lossy(),
1226 24
1227 )
1228 ));
1229 }
1230 ui.horizontal(|ui| {
1231 ui.label("암호");
1232 let edit = ui.add(
1233 egui::TextEdit::singleline(&mut self.password)
1234 .password(!self.password_visible)
1235 .id(egui::Id::unique("archive-password-input"))
1236 .char_limit(1024)
1237 .desired_width(232.0),
1238 );
1239 theme::focus(&edit);
1240 if new_challenge {
1241 edit.request_focus();
1242 }
1243 if theme::action(
1244 ui,
1245 if self.password_visible {
1246 "숨기기"
1247 } else {
1248 "보기"
1249 },
1250 false,
1251 true,
1252 )
1253 .clicked()
1254 {
1255 self.password_visible = !self.password_visible;
1256 }
1257 });
1258 if encrypt {
1259 ui.horizontal(|ui| {
1260 ui.label("암호 확인");
1261 let edit = ui.add(
1262 egui::TextEdit::singleline(&mut self.password_confirm)
1263 .password(!self.password_visible)
1264 .id(egui::Id::unique("archive-password-confirm"))
1265 .char_limit(1024)
1266 .desired_width(232.0),
1267 );
1268 theme::focus(&edit);
1269 });
1270 if self.password != self.password_confirm {
1271 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1272 }
1273 } else if attempt > 1 {
1274 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1275 }
1276 if self.password.len() > 1024 {
1277 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1278 }
1279 let valid = !self.password.is_empty()
1280 && self.password.len() <= 1024
1281 && (!encrypt || self.password == self.password_confirm);
1282 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1283 cancel = actions.0;
1284 submit = actions.1 || (valid && password_enter);
1285 });
1286 if modal.should_close() || cancel {
1287 self.clear_password();
1288 self.model.cancel();
1289 } else if submit {
1290 let password = std::mem::take(&mut self.password);
1291 self.clear_password();
1292 self.model.password(password);
1293 }
1294 }
1295
1296 fn close_dialog(&mut self, ctx: &egui::Context) {
1297 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1298 return;
1299 }
1300 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1301 ui.set_width(420.0);
1302 match self.model.close {
1303 Close::Confirm => {
1304 ui.heading("작업 중 닫기");
1305 ui.label("작업을 취소하고 닫을까요?");
1306 ui.horizontal(|ui| {
1307 if theme::action(ui, "계속 작업", false, true).clicked() {
1308 self.model.keep_open();
1309 }
1310 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1311 self.clear_password();
1312 self.model.confirm_close();
1313 }
1314 });
1315 }
1316 Close::Waiting => {
1317 ui.heading("종료 확인 중");
1318 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
1319 if theme::action(ui, "닫기 취소", false, true).clicked() {
1320 self.model.keep_open();
1321 }
1322 }
1323 Close::Review => {
1324 ui.heading("결과 확인 후 닫기");
1325 let wrote = self
1326 .last_request
1327 .as_ref()
1328 .is_some_and(|request| !matches!(request, Start::List { .. }));
1329 ui.label(if !wrote {
1330 "프로그램을 닫을까요?"
1331 } else if self.model.confirmed {
1332 "작업 결과를 확인한 뒤 닫으세요"
1333 } else {
1334 present::UNCERTAIN
1335 });
1336 egui::ScrollArea::vertical()
1337 .max_height(160.0)
1338 .show(ui, |ui| {
1339 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
1340 ui.colored_label(theme::ERROR, present::error_text(code));
1341 }
1342 if wrote {
1343 for warning in present::warnings(
1344 self.model.terminal.as_ref(),
1345 self.model.confirmed,
1346 self.targets.as_ref(),
1347 &self.directories,
1348 &self.model.outputs,
1349 ) {
1350 ui.colored_label(theme::WARNING, warning);
1351 }
1352 }
1353 });
1354 ui.horizontal(|ui| {
1355 if theme::action(ui, "계속 작업", false, true).clicked() {
1356 self.model.keep_open();
1357 }
1358 if theme::action(ui, "닫기", true, true).clicked() {
1359 self.model.acknowledge_close();
1360 }
1361 });
1362 }
1363 _ => {}
1364 }
1365 });
1366 }
1367}
1368
1369impl eframe::App for ArchiveApp {
1370 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1371 self.show(root);
1372 }
1373}
1374impl Drop for ArchiveApp {
1375 fn drop(&mut self) {
1376 self.clear_password();
1377 }
1378}