team-ljyzipelo

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