team-ljyzipelo

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