team-ljyzipelo

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