team-ljyzipelo

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