team-ljyzipelo

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