team-ljyzipelo

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