team-ljyzipelo

공개
1,768줄70 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
14struct Marquee {
15 // 스크롤 중에도 시작점을 목록 좌표로 유지함.
16 origin: egui::Pos2,
17 base: BTreeSet<u32>,
18 moved: bool,
19}
20
21const LIST_ROW: f32 = 44.0;
22
23pub struct ArchiveApp {
24 pub model: Model,
25 factory: Box<dyn Factory>,
26 destination: PathBuf,
27 automatic_destination: bool,
28 owned_destination: Option<PathBuf>,
29 gzip_name: String,
30 sources: Vec<PathBuf>,
31 zip_folder: PathBuf,
32 zip_name: String,
33 password: String,
34 password_confirm: String,
35 password_visible: bool,
36 password_challenge: Option<u64>,
37 aes256: bool,
38 create: bool,
39 selected_only: bool,
40 method: Method,
41 dialogs: Box<dyn Dialogs>,
42 folder: String,
43 search: String,
44 list_anchor: Option<usize>,
45 list_cursor: Option<usize>,
46 list_offset: f32,
47 list_focused: bool,
48 marquee: Option<Marquee>,
49 last_request: Option<Start>,
50 targets: Option<BTreeSet<String>>,
51 directories: BTreeSet<String>,
52 dismissed: bool,
53 details: bool,
54 checked_destination: bool,
55 ui_error: Option<String>,
56 initialized: bool,
57}
58
59impl ArchiveApp {
60 pub fn new(factory: Box<dyn Factory>, startup: Option<PathBuf>, _fixture: bool) -> Self {
61 let mut app = Self {
62 model: Model::default(),
63 factory,
64 destination: PathBuf::new(),
65 automatic_destination: true,
66 owned_destination: None,
67 gzip_name: String::new(),
68 sources: Vec::new(),
69 zip_folder: present::home_directory(),
70 zip_name: String::new(),
71 password: String::new(),
72 password_confirm: String::new(),
73 password_visible: false,
74 password_challenge: None,
75 aes256: false,
76 create: false,
77 selected_only: false,
78 method: Method::Deflate,
79 dialogs: Box::new(NativeDialogs),
80 folder: String::new(),
81 search: String::new(),
82 list_anchor: None,
83 list_cursor: None,
84 list_offset: 0.0,
85 list_focused: false,
86 marquee: None,
87 last_request: None,
88 targets: None,
89 directories: BTreeSet::new(),
90 dismissed: false,
91 details: false,
92 checked_destination: false,
93 ui_error: None,
94 initialized: false,
95 };
96 if let Some(path) = startup {
97 app.open_path(path);
98 }
99 app
100 }
101
102 pub fn set_dialogs(&mut self, dialogs: Box<dyn Dialogs>) {
103 self.dialogs = dialogs;
104 }
105
106 pub fn browse_folder(&mut self, folder: &str) {
107 self.folder = folder.trim_matches('/').to_owned();
108 self.search.clear();
109 self.clear_list_selection();
110 }
111
112 pub fn show_create(&mut self, encrypted: bool) {
113 if !self.model.busy() {
114 self.create = true;
115 self.aes256 = encrypted;
116 self.ui_error = None;
117 }
118 }
119
120 fn clear_password(&mut self) {
121 for value in [&mut self.password, &mut self.password_confirm] {
122 let mut bytes = std::mem::take(value).into_bytes();
123 bytes.fill(0);
124 }
125 self.password_visible = false;
126 }
127
128 pub fn open_path(&mut self, archive: PathBuf) {
129 if self.model.busy() {
130 return;
131 }
132 self.clear_password();
133 self.destination = present::default_destination(&archive);
134 self.automatic_destination = true;
135 self.gzip_name = present::gzip_output_name(&archive);
136 self.selected_only = false;
137 self.folder.clear();
138 self.search.clear();
139 self.clear_list_selection();
140 self.targets = None;
141 self.directories.clear();
142 self.start(Start::List { archive });
143 }
144
145 fn start(&mut self, request: Start) -> bool {
146 self.last_request = Some(request.clone());
147 self.dismissed = false;
148 self.details = false;
149 self.checked_destination = false;
150 self.ui_error = None;
151 self.model.begin(request, self.factory.as_mut())
152 }
153
154 pub fn choose_destination(&mut self, path: PathBuf) {
155 self.destination = path;
156 self.automatic_destination = false;
157 self.ui_error = None;
158 }
159
160 pub fn add_sources(&mut self, paths: Vec<PathBuf>) {
161 if self.model.busy() {
162 return;
163 }
164 let mut validated = Vec::new();
165 for path in paths {
166 let Ok(metadata) = std::fs::symlink_metadata(&path) else {
167 self.ui_error = Some("파일이나 폴더를 찾지 못했습니다. 다시 선택하세요".into());
168 return;
169 };
170 if metadata.file_type().is_symlink() || !(metadata.is_file() || metadata.is_dir()) {
171 self.ui_error = Some("일반 파일과 폴더만 추가할 수 있습니다".into());
172 return;
173 }
174 let Ok(path) = path.canonicalize() else {
175 return;
176 };
177 if path.to_str().is_none()
178 || !path
179 .file_name()
180 .and_then(|name| name.to_str())
181 .is_some_and(valid_leaf)
182 {
183 self.ui_error = Some("파일이나 폴더의 이름을 확인하세요".into());
184 return;
185 }
186 validated.push(crate::archive_path::worker_path(&path));
187 }
188 let paths = validated;
189 if self.sources.is_empty() {
190 if let Some(first) = paths.first() {
191 self.zip_folder = first.parent().unwrap_or(Path::new("/")).to_path_buf();
192 let name = if first.is_dir() {
193 first.file_name()
194 } else {
195 first.file_stem()
196 };
197 self.zip_name = format!("{}.zip", name.unwrap_or_default().to_string_lossy());
198 }
199 }
200 for path in paths {
201 if !self.sources.contains(&path) {
202 self.sources.push(path);
203 }
204 }
205 self.create = true;
206 }
207
208 pub fn begin_extract(&mut self) -> bool {
209 self.selected_only = !self.model.selected.is_empty();
210 let selection = if self.selected_only {
211 Selection::EntryIds(
212 browser::expand_selection(&self.model.entries, &self.model.selected)
213 .into_iter()
214 .collect(),
215 )
216 } else {
217 Selection::All
218 };
219 self.extract_selection(selection)
220 }
221
222 fn extract_selection(&mut self, selection: Selection) -> bool {
223 if !self.model.can_extract()
224 || matches!(&selection, Selection::EntryIds(ids) if ids.is_empty())
225 {
226 return false;
227 }
228 self.selected_only = matches!(&selection, Selection::EntryIds(_));
229 match present::prepare_destination(&self.destination, self.automatic_destination) {
230 Ok(true) => self.owned_destination = Some(self.destination.clone()),
231 Ok(false) => self.owned_destination = None,
232 Err(_) => {
233 self.ui_error = Some(present::FOLDER_ERROR.into());
234 return false;
235 }
236 }
237 let gzip = self
238 .model
239 .list_id
240 .as_ref()
241 .is_some_and(|id| id.format == Format::Gzip);
242 self.targets = present::target_files(
243 &self.model.entries,
244 &selection,
245 gzip.then_some(self.gzip_name.as_str()),
246 );
247 self.directories = if gzip {
248 BTreeSet::new()
249 } else {
250 present::target_directories(&self.model.entries, &selection)
251 };
252 let request = Start::Extract {
253 archive: self.model.archive.clone().unwrap(),
254 destination: self.destination.clone(),
255 selection,
256 list_id: self.model.list_id.clone().unwrap(),
257 gzip_output_name: gzip.then(|| self.gzip_name.clone()),
258 };
259 if self.start(request) {
260 true
261 } else {
262 if let Some(path) = self.owned_destination.take() {
263 present::remove_owned_empty(&path);
264 }
265 false
266 }
267 }
268
269 fn begin_zip(&mut self) {
270 if self.sources.is_empty() {
271 return;
272 }
273 if !self.zip_name.to_ascii_lowercase().ends_with(".zip") {
274 self.zip_name.push_str(".zip");
275 }
276 if !valid_leaf(&self.zip_name) {
277 self.ui_error = Some("ZIP 파일 이름을 확인하세요".into());
278 return;
279 }
280 let output_file = self.zip_folder.join(&self.zip_name);
281 if std::fs::symlink_metadata(&output_file).is_ok() {
282 self.ui_error = Some("같은 이름의 파일이 이미 있습니다. 다른 이름을 입력하세요".into());
283 return;
284 }
285 let mut sources = Vec::new();
286 for path in &self.sources {
287 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
288 self.ui_error = Some(
289 "이름을 읽을 수 없는 파일이 있습니다. 파일 이름을 바꾼 뒤 다시 추가하세요"
290 .into(),
291 );
292 return;
293 };
294 sources.push((path.clone(), name.to_owned()));
295 }
296 self.targets = Some([self.zip_name.clone()].into_iter().collect());
297 self.directories.clear();
298 if self.start(Start::CreateZip {
299 sources,
300 output_file,
301 method: self.method,
302 aes256: self.aes256,
303 }) {
304 self.create = false;
305 }
306 }
307
308 fn open_picker(&mut self, purpose: Purpose) {
309 if self.model.busy() {
310 return;
311 }
312 let gzip = self
313 .model
314 .list_id
315 .as_ref()
316 .is_some_and(|id| id.format == Format::Gzip);
317 let purpose = match (purpose, gzip) {
318 (Purpose::Destination, true) => Purpose::SaveGzip,
319 (Purpose::Retry, true) => Purpose::RetryGzip,
320 _ => purpose,
321 };
322 let directory = match purpose {
323 Purpose::SaveZip => self.zip_folder.clone(),
324 Purpose::Destination | Purpose::SaveGzip => self
325 .model
326 .archive
327 .as_ref()
328 .and_then(|path| path.parent())
329 .map(Path::to_path_buf)
330 .unwrap_or_else(present::home_directory),
331 Purpose::Retry | Purpose::RetryGzip => self.destination.clone(),
332 _ => self
333 .sources
334 .last()
335 .and_then(|path| path.parent())
336 .map(Path::to_path_buf)
337 .unwrap_or_else(present::home_directory),
338 };
339 let request = DialogRequest {
340 purpose,
341 directory,
342 file_name: if matches!(purpose, Purpose::SaveGzip | Purpose::RetryGzip) {
343 self.gzip_name.clone()
344 } else {
345 self.zip_name.clone()
346 },
347 };
348 let answer = self.dialogs.choose(request);
349 if answer.is_ok()
350 && self.ui_error.as_deref() == Some(crate::archive_dialog::DIALOG_UNAVAILABLE)
351 {
352 self.ui_error = None;
353 }
354 match answer {
355 Ok(Some(paths)) if !paths.is_empty() => {
356 let path = paths[0].clone();
357 match purpose {
358 Purpose::Open => {
359 if std::fs::symlink_metadata(&path)
360 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
361 {
362 self.open_path(path);
363 } else {
364 self.ui_error = Some("일반 압축파일을 선택하세요".into());
365 }
366 }
367 Purpose::Files | Purpose::Folder => self.add_sources(paths),
368 Purpose::Destination | Purpose::Retry => {
369 self.choose_destination(path);
370 self.selected_only = !self.model.selected.is_empty();
371 if purpose == Purpose::Retry {
372 self.retry();
373 } else {
374 self.begin_extract();
375 }
376 }
377 Purpose::SaveGzip | Purpose::RetryGzip => {
378 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
379 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
380 return;
381 };
382 if !present::valid_output_leaf(name) {
383 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
384 return;
385 }
386 let name = name.to_owned();
387 self.choose_destination(
388 path.parent().unwrap_or(Path::new("/")).to_path_buf(),
389 );
390 self.gzip_name = name.clone();
391 self.selected_only = !self.model.selected.is_empty();
392 if purpose == Purpose::RetryGzip {
393 if let Some(Start::Extract {
394 gzip_output_name, ..
395 }) = &mut self.last_request
396 {
397 *gzip_output_name = Some(name);
398 }
399 self.retry();
400 } else {
401 self.begin_extract();
402 }
403 }
404 Purpose::SaveZip => {
405 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
406 self.zip_name = name.to_owned();
407 self.zip_folder = path.parent().unwrap_or(Path::new("/")).to_path_buf();
408 self.begin_zip();
409 }
410 }
411 }
412 }
413 Ok(_) => {}
414 Err(error) => self.ui_error = Some(error),
415 }
416 }
417
418 fn retry(&mut self) {
419 if let Some(request) = self.last_request.clone() {
420 match request {
421 Start::List { archive } => self.open_path(archive),
422 Start::Extract {
423 selection,
424 gzip_output_name,
425 ..
426 } => {
427 if let Some(name) = gzip_output_name {
428 self.gzip_name = name;
429 }
430 self.extract_selection(selection);
431 }
432 Start::CreateZip { .. } => {
433 self.create = true;
434 self.begin_zip();
435 }
436 }
437 }
438 }
439
440 fn on_drop(&mut self, paths: Vec<PathBuf>) {
441 if self.model.busy() || paths.is_empty() {
442 return;
443 }
444 if paths.len() == 1 && !self.create && !paths[0].is_dir() {
445 if std::fs::symlink_metadata(&paths[0])
446 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
447 {
448 self.open_path(paths[0].clone());
449 } else {
450 self.ui_error = Some("일반 압축파일을 선택하세요".into());
451 }
452 } else {
453 self.add_sources(paths);
454 }
455 }
456
457 fn poll(&mut self) {
458 let busy = self.model.busy();
459 self.model.poll();
460 if busy && !self.model.busy() {
461 if let Some(path) = self.owned_destination.take() {
462 if !self.model.confirmed
463 || self
464 .model
465 .terminal
466 .as_ref()
467 .is_none_or(|t| t.outcome != Outcome::Completed)
468 {
469 present::remove_owned_empty(&path);
470 }
471 }
472 }
473 }
474
475 pub fn show(&mut self, root: &mut egui::Ui) {
476 let ctx = root.ctx().clone();
477 if !self.initialized {
478 theme::apply(&ctx);
479 self.initialized = true;
480 }
481 self.poll();
482 let challenge = self.model.challenge.map(|(id, _, _)| id);
483 let new_challenge = challenge != self.password_challenge;
484 if new_challenge || challenge.is_none() {
485 self.clear_password();
486 }
487 self.password_challenge = challenge;
488 self.on_drop(ctx.input(|i| {
489 i.raw
490 .dropped_files
491 .iter()
492 .map(|file| file.path().to_path_buf())
493 .collect()
494 }));
495 if ctx.input(|i| i.viewport().close_requested()) {
496 self.model.request_close();
497 if self.model.close != Close::Allowed {
498 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
499 }
500 }
501 if self.model.close == Close::Allowed {
502 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
503 }
504 let title = self
505 .model
506 .archive
507 .as_ref()
508 .map(|path| {
509 let full = if path.is_absolute() {
510 path.clone()
511 } else {
512 std::env::current_dir().unwrap_or_default().join(path)
513 };
514 format!("{} — Zipelo", full.display())
515 })
516 .unwrap_or_else(|| "Zipelo".into());
517 let short_title = if let Some(path) = title.strip_suffix(" — Zipelo") {
518 format!(
519 "{} — Zipelo",
520 theme::window_title(root, path, ctx.content_rect().width() - 300.0)
521 )
522 } else {
523 title.clone()
524 };
525 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
526 egui::Panel::top("archive-actions")
527 .frame(
528 theme::panel(theme::PANEL)
529 .corner_radius(0)
530 .inner_margin(egui::Margin::symmetric(16, 4)),
531 )
532 .show(root, |ui| {
533 ui.horizontal(|ui| {
534 let idle = !self.model.busy() && self.model.close == Close::Open;
535 if theme::tool(ui, "열기", theme::OPEN, idle, false)
536 .on_hover_text(&title)
537 .clicked()
538 {
539 self.open_picker(Purpose::Open);
540 }
541 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
542 self.show_create(false);
543 }
544 if theme::tool(
545 ui,
546 "압축해제",
547 theme::EXTRACT,
548 self.model.can_extract(),
549 true,
550 )
551 .clicked()
552 {
553 self.open_picker(Purpose::Destination);
554 }
555 });
556 });
557 egui::Panel::bottom("archive-status")
558 .frame(
559 theme::panel(theme::STRIPE)
560 .corner_radius(0)
561 .inner_margin(egui::Margin::symmetric(16, 8)),
562 )
563 .show(root, |ui| {
564 ui.horizontal(|ui| {
565 let width = (ui.available_width() - ui.spacing().item_spacing.x) / 2.0;
566 theme::bounded_text(
567 ui,
568 &format!(
569 "{}개 항목",
570 browser::rows(&self.model.entries, &self.folder, &self.search).len()
571 ),
572 width,
573 );
574 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
575 theme::bounded_text(
576 ui,
577 &format!(
578 "선택 {}개",
579 browser::rows(&self.model.entries, &self.folder, &self.search)
580 .iter()
581 .filter(|row| !row.ids.is_empty()
582 && row.ids.is_subset(&self.model.selected))
583 .count()
584 ),
585 width,
586 );
587 });
588 });
589 });
590 if self.model.busy() || self.result_visible() || (self.ui_error.is_some() && !self.create) {
591 egui::Panel::bottom("archive-work")
592 .frame(theme::panel(theme::PANEL).corner_radius(0))
593 .show(root, |ui| self.work_area(ui));
594 }
595 egui::CentralPanel::default()
596 .frame(
597 theme::panel(theme::PANEL)
598 .corner_radius(0)
599 .inner_margin(egui::Margin::ZERO),
600 )
601 .show(root, |ui| {
602 if self.model.archive.is_some() {
603 self.archive_list(ui);
604 } else {
605 self.empty(ui);
606 }
607 });
608 if self.create && !self.model.busy() {
609 self.create_dialog(&ctx);
610 }
611 if self.model.challenge.is_some() {
612 self.password_dialog(&ctx, new_challenge);
613 }
614 self.close_dialog(&ctx);
615 if self.model.busy() {
616 ctx.request_repaint_after(std::time::Duration::from_millis(30));
617 }
618 }
619
620 fn empty(&mut self, ui: &mut egui::Ui) {
621 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
622 let width = (ui.available_width() * 0.60)
623 .max(480.0)
624 .min(ui.available_width());
625 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
626 ui.add_space(y);
627 ui.vertical_centered(|ui| {
628 let drop_frame = egui::Frame::new()
629 .fill(if hovered { theme::DROP } else { theme::PANEL })
630 .corner_radius(theme::DROP_RADIUS)
631 .inner_margin(egui::Margin::same(theme::DROP_PAD))
632 .show(ui, |ui| {
633 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
634 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
635 ui.vertical_centered(|ui| {
636 ui.add_space(theme::PAD as f32);
637 theme::icon(ui, Icon::Archive, 48.0);
638 ui.add_space(theme::PAD as f32);
639 ui.label(
640 RichText::new(if hovered {
641 "놓으면 엽니다"
642 } else {
643 "압축파일을 여기에 끌어 놓으세요"
644 })
645 .size(20.0)
646 .strong(),
647 );
648 ui.label("또는");
649 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
650 self.open_picker(Purpose::Open);
651 }
652 });
653 });
654 let rect = drop_frame.response.rect;
655 if hovered {
656 ui.painter().rect_stroke(
657 rect,
658 12,
659 egui::Stroke::new(2.0, theme::BLUE),
660 egui::StrokeKind::Inside,
661 );
662 } else {
663 let stroke = egui::Stroke::new(2.0, theme::DASH);
664 for (a, b) in [
665 (rect.left_top(), rect.right_top()),
666 (rect.right_top(), rect.right_bottom()),
667 (rect.right_bottom(), rect.left_bottom()),
668 (rect.left_bottom(), rect.left_top()),
669 ] {
670 let direction = (b - a).normalized();
671 let mut distance = theme::DROP_RADIUS as f32;
672 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
673 ui.painter().line_segment(
674 [
675 a + direction * distance,
676 a + direction
677 * (distance + theme::SPACE)
678 .min(a.distance(b) - theme::DROP_RADIUS as f32),
679 ],
680 stroke,
681 );
682 distance += theme::PAD as f32;
683 }
684 }
685 }
686 ui.add_space(theme::PAD as f32);
687 ui.colored_label(
688 theme::MUTED,
689 "ZIP, 7z, TAR, GZ, TAR.GZ 파일을 열 수 있습니다",
690 );
691 });
692 }
693
694 fn archive_list(&mut self, ui: &mut egui::Ui) {
695 theme::panel(theme::STRIPE).corner_radius(0).show(ui, |ui| {
696 ui.horizontal(|ui| {
697 let up = theme::icon_button(
698 ui,
699 "위로",
700 theme::UP,
701 !self.folder.is_empty() && !self.model.busy(),
702 );
703 if up.clicked() {
704 let parent = self
705 .folder
706 .rsplit_once('/')
707 .map_or("", |(parent, _)| parent)
708 .to_owned();
709 self.browse_folder(&parent);
710 }
711 ui.label("현재 경로");
712 let path = format!("/{}", self.folder);
713 let width = (ui.available_width() - 270.0).max(0.0);
714 egui::Frame::new()
715 .fill(theme::PANEL)
716 .stroke(egui::Stroke::new(1.0, theme::BORDER))
717 .corner_radius(6)
718 .inner_margin(egui::Margin::symmetric(8, 7))
719 .show(ui, |ui| {
720 theme::bounded_text(ui, &path, (width - 18.0).max(0.0));
721 });
722 let (rect, _) =
723 ui.allocate_exact_size(egui::vec2(20.0, 20.0), egui::Sense::hover());
724 theme::svg_icon(ui.painter(), rect, theme::SEARCH, theme::MUTED);
725 let search = ui.add_sized(
726 [220.0, 36.0],
727 egui::TextEdit::singleline(&mut self.search)
728 .id(egui::Id::unique("archive-search"))
729 .hint_text("파일 찾기"),
730 );
731 theme::focus(&search);
732 if search.changed() {
733 self.clear_list_selection();
734 }
735 });
736 });
737 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
738
739 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 64.0 - 40.0).max(120.0);
740 ui.horizontal(|ui| {
741 ui.add_space(16.0 + 28.0);
742 theme::column_label(ui, RichText::new("이름").strong(), name_width, Align::Min);
743 theme::column_label(ui, "크기", 96.0, Align::Max);
744 theme::column_label(ui, "암호", 64.0, Align::Min);
745 });
746 ui.separator();
747 let active = !self.model.busy()
748 && !self.create
749 && self.model.challenge.is_none()
750 && self.model.close == Close::Open;
751 let list_id = egui::Id::unique("archive-list");
752 let background = ui.interact(
753 ui.available_rect_before_wrap(),
754 list_id,
755 if active {
756 egui::Sense::click_and_drag()
757 } else {
758 egui::Sense::hover()
759 },
760 );
761 background
762 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
763 if background.has_focus() {
764 ui.ctx().memory_mut(|memory| {
765 memory.set_focus_lock_filter(
766 list_id,
767 egui::EventFilter {
768 vertical_arrows: true,
769 escape: true,
770 ..Default::default()
771 },
772 )
773 });
774 }
775 let mut focused = None;
776 let mut open = None;
777 let mut next_offset = None;
778 let output = egui::ScrollArea::vertical()
779 .id_salt("archive-rows")
780 .auto_shrink([false, false])
781 .vertical_scroll_offset(self.list_offset)
782 .show_viewport(ui, |ui, viewport| {
783 let origin = ui.max_rect().min;
784 let clip = ui.clip_rect();
785 let width = (ui.available_width() - 24.0).max(0.0);
786 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
787 let point = ui.input(|i| i.pointer.interact_pos());
788 if active && let Some(point) = point {
789 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
790 let relative = press - origin;
791 let in_row = relative.x >= 0.0
792 && relative.x <= width
793 && relative.y >= 0.0
794 && relative.y < rows.len() as f32 * LIST_ROW;
795 if clip.contains(press) && !in_row && ui.input(|i| i.pointer.primary_pressed())
796 {
797 background.request_focus();
798 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
799 self.marquee = Some(Marquee {
800 origin: relative.to_pos2(),
801 base: if ctrl {
802 self.model.selected.clone()
803 } else {
804 BTreeSet::new()
805 },
806 moved: false,
807 });
808 if !ctrl {
809 self.model.selected.clear();
810 self.list_anchor = None;
811 self.list_cursor = None;
812 }
813 }
814 if let Some(drag) = &mut self.marquee {
815 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
816 drag.moved |= drag.origin.distance(end) > 3.0;
817 if drag.moved {
818 let rect = egui::Rect::from_two_pos(drag.origin, end);
819 self.model.selected = drag.base.clone();
820 if rect.left() < width && rect.right() > 0.0 {
821 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
822 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
823 .min(rows.len());
824 for row in rows.iter().take(last).skip(first) {
825 self.model.selected.extend(&row.ids);
826 }
827 if first < last {
828 self.list_anchor = Some(first);
829 self.list_cursor = Some(last - 1);
830 }
831 }
832 let speed = if point.y > clip.bottom() - 24.0 {
833 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
834 } else if point.y < clip.top() + 24.0 {
835 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
836 } else {
837 0.0
838 };
839 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
840 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
841 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
842 0.0,
843 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
844 ));
845 ui.ctx().request_repaint();
846 }
847 }
848 }
849 }
850 let first = (viewport.min.y / LIST_ROW).floor() as usize;
851 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
852 for index in first.min(rows.len())..last {
853 let row = &rows[index];
854 let rect = egui::Rect::from_min_size(
855 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
856 egui::vec2(width, LIST_ROW),
857 );
858 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
859 let response = ui
860 .interact(
861 rect,
862 egui::Id::unique(("archive-row", &row.path)),
863 if active {
864 egui::Sense::click()
865 } else {
866 egui::Sense::hover()
867 },
868 )
869 .on_hover_text(&row.name);
870 response.widget_info(|| {
871 egui::WidgetInfo::selected(
872 egui::Role::ListBoxOption,
873 active,
874 selected,
875 &row.name,
876 )
877 });
878 if response.has_focus() {
879 focused = Some(index);
880 ui.ctx().memory_mut(|memory| {
881 memory.set_focus_lock_filter(
882 response.id,
883 egui::EventFilter {
884 vertical_arrows: true,
885 escape: true,
886 ..Default::default()
887 },
888 )
889 });
890 }
891 if selected {
892 ui.painter().rect_filled(rect, 0, theme::SELECTED);
893 }
894 if response.clicked() {
895 background.request_focus();
896 let modifiers = ui.input(|i| i.modifiers);
897 self.select_row(
898 &rows,
899 index,
900 modifiers.ctrl || modifiers.command,
901 modifiers.shift,
902 );
903 }
904 if row.directory && response.double_clicked() {
905 open = Some(row.path.clone());
906 }
907 ui.scope_builder(
908 egui::UiBuilder::new()
909 .max_rect(rect.shrink2(egui::vec2(0.0, 4.0)))
910 .layout(Layout::left_to_right(Align::Center)),
911 |ui| {
912 ui.style_mut().interaction.selectable_labels = false;
913 ui.add_space(16.0);
914 theme::icon(
915 ui,
916 if row.directory {
917 Icon::Folder
918 } else {
919 Icon::File
920 },
921 20.0,
922 );
923 theme::bounded_text(ui, &row.name, name_width);
924 theme::column_label(
925 ui,
926 if row.directory {
927 "0 B".into()
928 } else {
929 row.bytes
930 .map(present::bytes_text)
931 .unwrap_or_else(|| "—".into())
932 },
933 96.0,
934 Align::Max,
935 );
936 if row.encrypted {
937 theme::icon(ui, Icon::Lock, 16.0);
938 }
939 },
940 );
941 if active
942 && self.list_cursor == Some(index)
943 && (response.has_focus() || background.has_focus())
944 {
945 ui.painter().rect_stroke(
946 rect.shrink(1.0),
947 0,
948 egui::Stroke::new(1.0, theme::BLUE),
949 egui::StrokeKind::Inside,
950 );
951 }
952 }
953 if rows.is_empty() {
954 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
955 ui.centered_and_justified(|ui| {
956 ui.label(if self.search.is_empty() {
957 "이 폴더는 비어 있습니다"
958 } else {
959 "일치하는 항목이 없습니다"
960 })
961 });
962 });
963 }
964 if let Some(drag) = &self.marquee
965 && drag.moved
966 && let Some(point) = point
967 {
968 let rect = egui::Rect::from_two_pos(
969 origin + drag.origin.to_vec2(),
970 point.clamp(clip.min, clip.max),
971 );
972 ui.painter().with_clip_rect(clip).rect(
973 rect,
974 0,
975 theme::BLUE.gamma_multiply(0.16),
976 egui::Stroke::new(1.0, theme::BLUE),
977 egui::StrokeKind::Inside,
978 );
979 }
980 });
981 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
982 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
983 self.marquee = None;
984 }
985 let escape_from_list = self.list_focused
986 && ui.ctx().memory(|memory| memory.focused()).is_none()
987 && ui.input(|i| i.key_pressed(egui::Key::Escape));
988 self.list_focused =
989 active && (background.has_focus() || focused.is_some() || escape_from_list);
990 if self.list_focused {
991 if let Some(index) = focused {
992 self.list_cursor = Some(index);
993 }
994 let modifiers = ui.input(|i| i.modifiers);
995 let ctrl = modifiers.ctrl || modifiers.command;
996 if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
997 self.model.selected.clear();
998 self.marquee = None;
999 background.request_focus();
1000 }
1001 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
1002 self.model.selected = rows
1003 .iter()
1004 .flat_map(|row| row.ids.iter().copied())
1005 .collect();
1006 self.list_cursor = (!rows.is_empty()).then_some(0);
1007 self.list_anchor = self.list_cursor;
1008 }
1009 if !rows.is_empty() {
1010 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
1011 Some(1isize)
1012 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
1013 Some(-1)
1014 } else {
1015 None
1016 };
1017 if let Some(direction) = direction {
1018 let index = self.list_cursor.map_or(0, |index| {
1019 index.saturating_add_signed(direction).min(rows.len() - 1)
1020 });
1021 if ctrl && !modifiers.shift {
1022 self.list_cursor = Some(index);
1023 } else {
1024 self.select_row(&rows, index, ctrl, modifiers.shift);
1025 }
1026 background.request_focus();
1027 let top = index as f32 * LIST_ROW;
1028 if top < self.list_offset {
1029 self.list_offset = top;
1030 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
1031 self.list_offset = top + LIST_ROW - output.inner_rect.height();
1032 }
1033 ui.ctx().request_repaint();
1034 }
1035 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1036 let index = self
1037 .list_cursor
1038 .or(focused)
1039 .unwrap_or(0)
1040 .min(rows.len() - 1);
1041 if rows[index].directory {
1042 open = Some(rows[index].path.clone());
1043 }
1044 }
1045 }
1046 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
1047 open = Some(
1048 self.folder
1049 .rsplit_once('/')
1050 .map_or("", |(parent, _)| parent)
1051 .to_owned(),
1052 );
1053 }
1054 }
1055 if let Some(folder) = open {
1056 self.browse_folder(&folder);
1057 background.request_focus();
1058 }
1059 }
1060
1061 fn clear_list_selection(&mut self) {
1062 self.model.selected.clear();
1063 self.list_anchor = None;
1064 self.list_cursor = None;
1065 self.list_offset = 0.0;
1066 self.marquee = None;
1067 }
1068
1069 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
1070 if shift {
1071 let anchor = self
1072 .list_anchor
1073 .unwrap_or(self.list_cursor.unwrap_or(index))
1074 .min(rows.len() - 1);
1075 if !ctrl {
1076 self.model.selected.clear();
1077 }
1078 for row in &rows[anchor.min(index)..=anchor.max(index)] {
1079 self.model.selected.extend(&row.ids);
1080 }
1081 self.list_anchor = Some(anchor);
1082 } else {
1083 if !ctrl {
1084 self.model.selected.clear();
1085 }
1086 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
1087 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
1088 self.model
1089 .selected
1090 .retain(|id| !rows[index].ids.contains(id));
1091 } else {
1092 self.model.selected.extend(&rows[index].ids);
1093 }
1094 self.list_anchor = Some(index);
1095 }
1096 self.list_cursor = Some(index);
1097 }
1098
1099 fn result_visible(&self) -> bool {
1100 !self.dismissed
1101 && !self.model.busy()
1102 && self.last_request.as_ref().is_some_and(|request| {
1103 !matches!(request, Start::List { .. })
1104 || self.model.error.is_some()
1105 || self
1106 .model
1107 .terminal
1108 .as_ref()
1109 .is_some_and(|t| t.outcome != Outcome::Completed)
1110 })
1111 }
1112
1113 fn error_notice(ui: &mut egui::Ui, error: &str) {
1114 let response = theme::panel(theme::ERROR_BG)
1115 .show(ui, |ui| {
1116 ui.horizontal_wrapped(|ui| {
1117 theme::icon(ui, Icon::Error, 24.0);
1118 ui.colored_label(theme::ERROR, error);
1119 });
1120 })
1121 .response;
1122 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
1123 }
1124
1125 fn work_area(&mut self, ui: &mut egui::Ui) {
1126 if self.model.busy() {
1127 self.progress(ui);
1128 } else if self.result_visible() {
1129 self.result(ui);
1130 }
1131 if !self.create
1132 && let Some(error) = &self.ui_error
1133 {
1134 Self::error_notice(ui, error);
1135 if error == present::FOLDER_ERROR
1136 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
1137 {
1138 self.open_picker(Purpose::Destination);
1139 }
1140 }
1141 if let Some(error) = &self.model.input_error {
1142 ui.colored_label(
1143 theme::ERROR,
1144 if error.starts_with("암호는") {
1145 error.as_str()
1146 } else {
1147 if matches!(self.last_request, Some(Start::CreateZip { .. })) {
1148 "저장 위치와 추가한 항목을 확인하세요"
1149 } else {
1150 "풀 위치와 선택한 항목을 확인하세요"
1151 }
1152 },
1153 );
1154 }
1155 }
1156
1157 fn progress(&mut self, ui: &mut egui::Ui) {
1158 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1159 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
1160 let title = present::activity_text(&self.model, creating);
1161 ui.strong(title);
1162 if let Some((_, done, total, count)) = self.model.progress {
1163 if let Some(total) = total.filter(|n| *n > 0) {
1164 ui.scope(|ui| {
1165 ui.visuals_mut().extreme_bg_color = theme::BORDER;
1166 ui.add(
1167 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
1168 .fill(theme::BLUE)
1169 .desired_height(theme::SPACE * 2.0),
1170 );
1171 });
1172 ui.horizontal(|ui| {
1173 ui.label(format!(
1174 "{:.0}% / {count}개 처리함, {} / {}",
1175 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
1176 present::bytes_text(done),
1177 present::bytes_text(total)
1178 ));
1179 self.cancel_action(ui, cancelling);
1180 });
1181 } else {
1182 theme::indeterminate(ui);
1183 ui.horizontal(|ui| {
1184 ui.label(format!("{count}개 처리함, {}", present::bytes_text(done)));
1185 self.cancel_action(ui, cancelling);
1186 });
1187 }
1188 } else {
1189 theme::indeterminate(ui);
1190 ui.horizontal(|ui| {
1191 ui.label("작업을 진행하고 있습니다");
1192 self.cancel_action(ui, cancelling);
1193 });
1194 }
1195 }
1196
1197 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
1198 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1199 if theme::action(ui, "취소", false, !cancelling).clicked() {
1200 self.clear_password();
1201 self.model.cancel();
1202 }
1203 });
1204 }
1205
1206 fn result(&mut self, ui: &mut egui::Ui) {
1207 let t = self.model.terminal.clone();
1208 let listing = matches!(self.last_request, Some(Start::List { .. }));
1209 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1210 let warnings = if listing {
1211 Vec::new()
1212 } else {
1213 present::publication_warnings(
1214 t.as_ref(),
1215 self.model.confirmed,
1216 self.targets.as_ref(),
1217 &self.directories,
1218 &self.model.outputs,
1219 )
1220 };
1221 let success = self.model.confirmed
1222 && self.model.error.is_none()
1223 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
1224 && warnings.is_empty();
1225 let durability_warning = t
1226 .as_ref()
1227 .filter(|_| self.model.confirmed && !listing)
1228 .and_then(|t| present::durability_warning(t.durability));
1229 let durability_in_details = success
1230 && t.as_ref()
1231 .is_some_and(|t| t.durability == Durability::Unconfirmed);
1232 let cancelled =
1233 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
1234 let title = if success {
1235 if creating {
1236 "ZIP 파일을 만들었습니다"
1237 } else {
1238 "압축을 풀었습니다"
1239 }
1240 } else if cancelled {
1241 "작업을 취소했습니다"
1242 } else if listing {
1243 "압축파일을 열지 못했습니다"
1244 } else if creating {
1245 "ZIP 파일을 만들지 못했습니다"
1246 } else {
1247 "압축을 풀지 못했습니다"
1248 };
1249 let fill = if success {
1250 theme::SUCCESS_BG
1251 } else if cancelled {
1252 theme::STRIPE
1253 } else {
1254 theme::ERROR_BG
1255 };
1256 let mut choose = false;
1257 let mut retry = false;
1258 let mut reopen = false;
1259 let mut folder = false;
1260 theme::panel(fill).show(ui, |ui| {
1261 ui.horizontal(|ui| {
1262 theme::icon(
1263 ui,
1264 if success {
1265 Icon::Success
1266 } else if cancelled {
1267 Icon::Warning
1268 } else {
1269 Icon::Error
1270 },
1271 24.0,
1272 );
1273 ui.strong(title);
1274 });
1275 let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
1276 egui::ScrollArea::vertical()
1277 .id_salt("result-message")
1278 .max_height(max_height)
1279 .show(ui, |ui| {
1280 if success {
1281 let path = match self.last_request.as_ref() {
1282 Some(Start::CreateZip { output_file, .. }) => {
1283 output_file.display().to_string()
1284 }
1285 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
1286 };
1287 theme::bounded_text(ui, &path, ui.available_width());
1288 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
1289 ui.label(if creating && code == ErrorCode::SourceChanged {
1290 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요".to_owned()
1291 } else {
1292 present::operation_text(present::error_text(code), creating)
1293 });
1294 } else if let Some(error) = &self.model.error {
1295 ui.label(present::operation_text(
1296 present::client_error_text(error),
1297 creating,
1298 ));
1299 }
1300 for warning in warnings
1301 .iter()
1302 .copied()
1303 .chain(durability_warning.filter(|_| !durability_in_details))
1304 {
1305 ui.horizontal_wrapped(|ui| {
1306 theme::icon(ui, Icon::Warning, 20.0);
1307 ui.colored_label(
1308 theme::WARNING,
1309 present::operation_text(warning, creating),
1310 );
1311 });
1312 }
1313 if !success
1314 && !listing
1315 && present::definitely_unsaved(
1316 t.as_ref(),
1317 self.model.confirmed,
1318 &self.model.outputs,
1319 )
1320 {
1321 ui.label(if creating {
1322 "ZIP 파일을 만들지 않았습니다"
1323 } else {
1324 "아무 파일도 풀지 않았습니다"
1325 });
1326 }
1327 if self.details {
1328 theme::panel(theme::STRIPE).show(ui, |ui| {
1329 if durability_in_details {
1330 if let Some(warning) = durability_warning {
1331 ui.label(present::operation_text(warning, creating));
1332 }
1333 }
1334 if let Some(t) = &t {
1335 for line in terminal_lines(t) {
1336 ui.label(line);
1337 }
1338 }
1339 if let Some(error) = &self.model.error {
1340 ui.label(error);
1341 }
1342 for (name, state) in &self.model.outputs {
1343 theme::bounded_text(
1344 ui,
1345 &format!("{name}: {}", disposition_label(*state)),
1346 ui.available_width(),
1347 );
1348 }
1349 });
1350 }
1351 });
1352 let conflict = t
1353 .as_ref()
1354 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
1355 && !creating;
1356 let uncertain = warnings.contains(&present::UNCERTAIN);
1357 if conflict && uncertain {
1358 let response = ui.checkbox(
1359 &mut self.checked_destination,
1360 "기존 풀 위치 폴더를 확인했습니다",
1361 );
1362 theme::focus(&response);
1363 }
1364 ui.horizontal(|ui| {
1365 if theme::action(
1366 ui,
1367 if self.details {
1368 "자세히 닫기"
1369 } else {
1370 "자세히 보기"
1371 },
1372 false,
1373 true,
1374 )
1375 .clicked()
1376 {
1377 self.details = !self.details;
1378 }
1379 let action = if success {
1380 Some(("폴더 열기", true))
1381 } else if conflict {
1382 Some((
1383 if self
1384 .model
1385 .list_id
1386 .as_ref()
1387 .is_some_and(|id| id.format == Format::Gzip)
1388 {
1389 "다른 이름으로 저장"
1390 } else {
1391 "다른 폴더에 풀기"
1392 },
1393 !uncertain || self.checked_destination,
1394 ))
1395 } else if t
1396 .as_ref()
1397 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1398 {
1399 Some((
1400 if creating {
1401 "다시 만들기"
1402 } else {
1403 "압축파일 다시 열기"
1404 },
1405 true,
1406 ))
1407 } else if !cancelled && (!uncertain || listing) {
1408 Some(("다시 시도", true))
1409 } else {
1410 None
1411 };
1412 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1413 if confirm {
1414 self.dismissed = true;
1415 self.ui_error = None;
1416 self.model.input_error = None;
1417 }
1418 if primary {
1419 match action.map(|(label, _)| label) {
1420 Some("폴더 열기") => folder = true,
1421 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
1422 choose = true
1423 }
1424 Some("압축파일 다시 열기") => reopen = true,
1425 Some("다시 시도" | "다시 만들기") => retry = true,
1426 _ => {}
1427 }
1428 }
1429 });
1430 });
1431 if choose {
1432 self.open_picker(Purpose::Retry);
1433 }
1434 if retry {
1435 self.retry();
1436 }
1437 if reopen {
1438 if let Some(path) = self.model.archive.clone() {
1439 self.open_path(path);
1440 }
1441 }
1442 if folder {
1443 let path = match self.last_request.as_ref() {
1444 Some(Start::CreateZip { output_file, .. }) => {
1445 output_file.parent().unwrap_or(Path::new("/"))
1446 }
1447 _ => self.destination.as_path(),
1448 };
1449 match present::folder_command(path).spawn() {
1450 Ok(mut child) => {
1451 std::thread::spawn(move || {
1452 let _ = child.wait();
1453 });
1454 }
1455 Err(_) => {
1456 self.ui_error = Some(
1457 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1458 )
1459 }
1460 }
1461 }
1462 }
1463
1464 fn create_dialog(&mut self, ctx: &egui::Context) {
1465 let mut compress = false;
1466 let mut pick = None;
1467 let mut cancel = false;
1468 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1469 ui.set_width((ctx.content_rect().width() - 64.0).min(600.0));
1470 ui.horizontal(|ui| {
1471 ui.heading("ZIP 만들기");
1472 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1473 let close = theme::icon_button(ui, "닫기", theme::CLOSE, true);
1474 theme::focus(&close);
1475 cancel = close.clicked();
1476 });
1477 });
1478 if let Some(error) = &self.ui_error {
1479 Self::error_notice(ui, error);
1480 }
1481 egui::ScrollArea::vertical()
1482 .id_salt("create-fields")
1483 .max_height(
1484 (ctx.content_rect().height()
1485 - 180.0
1486 - if self.ui_error.is_some() { 96.0 } else { 0.0 })
1487 .max(120.0),
1488 )
1489 .show(ui, |ui| {
1490 ui.add_space(16.0);
1491 let frame = theme::panel(theme::STRIPE)
1492 .stroke(egui::Stroke::new(1.0, theme::DASH))
1493 .inner_margin(egui::Margin::same(24));
1494 let area = frame
1495 .show(ui, |ui| {
1496 ui.set_min_size(egui::vec2(ui.available_width(), 144.0));
1497 ui.vertical_centered(|ui| {
1498 theme::icon(ui, Icon::File, 44.0);
1499 ui.add_space(16.0);
1500 ui.label(
1501 RichText::new("파일이나 폴더를 여기에 끌어 놓으세요")
1502 .size(18.0),
1503 );
1504 });
1505 })
1506 .response;
1507 let drop = ui.interact(
1508 area.rect,
1509 egui::Id::unique("zip-source-drop"),
1510 egui::Sense::click(),
1511 );
1512 theme::focus(&drop);
1513 drop.widget_info(|| {
1514 egui::WidgetInfo::labeled(egui::Role::Button, true, "파일 추가")
1515 });
1516 if drop.clicked() {
1517 pick = Some(Purpose::Files);
1518 }
1519 egui::ScrollArea::vertical()
1520 .id_salt("zip-sources")
1521 .max_height(86.0)
1522 .show(ui, |ui| {
1523 let mut remove = None;
1524 for (index, path) in self.sources.iter().enumerate() {
1525 ui.horizontal(|ui| {
1526 theme::icon(
1527 ui,
1528 if path.is_dir() {
1529 Icon::Folder
1530 } else {
1531 Icon::File
1532 },
1533 20.0,
1534 );
1535 let name =
1536 path.file_name().unwrap_or_default().to_string_lossy();
1537 theme::bounded_text(
1538 ui,
1539 &name,
1540 (ui.available_width() - 72.0).max(0.0),
1541 )
1542 .on_hover_text(path.display().to_string());
1543 if ui.button("빼기").clicked() {
1544 remove = Some(index);
1545 }
1546 });
1547 }
1548 if let Some(index) = remove {
1549 self.sources.remove(index);
1550 }
1551 });
1552 ui.horizontal(|ui| {
1553 if theme::action(ui, "파일 추가", false, true).clicked() {
1554 pick = Some(Purpose::Files);
1555 }
1556 if theme::action(ui, "폴더 추가", false, true).clicked() {
1557 pick = Some(Purpose::Folder);
1558 }
1559 });
1560 ui.add_space(16.0);
1561 ui.horizontal(|ui| {
1562 theme::icon(ui, Icon::Lock, 24.0);
1563 ui.strong("암호화");
1564 });
1565 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1566 theme::focus(&check);
1567 ui.add_space(16.0);
1568 });
1569 let (dismiss, confirm) =
1570 theme::action_pair(ui, "취소", Some(("압축하기", !self.sources.is_empty())));
1571 cancel |= dismiss;
1572 compress = confirm;
1573 });
1574 if cancel || modal.should_close() {
1575 self.create = false;
1576 self.ui_error = None;
1577 return;
1578 }
1579 if let Some(purpose) = pick {
1580 self.open_picker(purpose);
1581 }
1582 if compress {
1583 self.open_picker(Purpose::SaveZip);
1584 }
1585 }
1586
1587 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1588 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1589 let mut submit = false;
1590 let mut cancel = false;
1591 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
1592 id == egui::Id::unique("archive-password-input")
1593 || id == egui::Id::unique("archive-password-confirm")
1594 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
1595 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1596 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1597 ui.heading(if encrypt {
1598 "ZIP 암호 설정"
1599 } else {
1600 "암호가 필요합니다"
1601 });
1602 if encrypt {
1603 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1604 } else if let Some(path) = &self.model.archive {
1605 ui.label(format!(
1606 "{}은 암호로 보호되어 있습니다.",
1607 present::middle_text(
1608 &path.file_name().unwrap_or_default().to_string_lossy(),
1609 24
1610 )
1611 ));
1612 }
1613 ui.horizontal(|ui| {
1614 ui.label("암호");
1615 let edit = ui.add(
1616 egui::TextEdit::singleline(&mut self.password)
1617 .password(!self.password_visible)
1618 .id(egui::Id::unique("archive-password-input"))
1619 .char_limit(1024)
1620 .desired_width(232.0),
1621 );
1622 theme::focus(&edit);
1623 if new_challenge {
1624 edit.request_focus();
1625 }
1626 if theme::action(
1627 ui,
1628 if self.password_visible {
1629 "숨기기"
1630 } else {
1631 "보기"
1632 },
1633 false,
1634 true,
1635 )
1636 .clicked()
1637 {
1638 self.password_visible = !self.password_visible;
1639 }
1640 });
1641 if encrypt {
1642 ui.horizontal(|ui| {
1643 ui.label("암호 확인");
1644 let edit = ui.add(
1645 egui::TextEdit::singleline(&mut self.password_confirm)
1646 .password(!self.password_visible)
1647 .id(egui::Id::unique("archive-password-confirm"))
1648 .char_limit(1024)
1649 .desired_width(232.0),
1650 );
1651 theme::focus(&edit);
1652 });
1653 if self.password != self.password_confirm {
1654 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1655 }
1656 } else if attempt > 1 {
1657 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1658 }
1659 if self.password.len() > 1024 {
1660 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1661 }
1662 let valid = !self.password.is_empty()
1663 && self.password.len() <= 1024
1664 && (!encrypt || self.password == self.password_confirm);
1665 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1666 cancel = actions.0;
1667 submit = actions.1 || (valid && password_enter);
1668 });
1669 if modal.should_close() || cancel {
1670 self.clear_password();
1671 self.model.cancel();
1672 } else if submit {
1673 let password = std::mem::take(&mut self.password);
1674 self.clear_password();
1675 self.model.password(password);
1676 }
1677 }
1678
1679 fn close_dialog(&mut self, ctx: &egui::Context) {
1680 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1681 return;
1682 }
1683 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1684 ui.set_width(420.0);
1685 match self.model.close {
1686 Close::Confirm => {
1687 ui.heading("작업 중 닫기");
1688 ui.label("작업을 취소하고 닫을까요?");
1689 ui.horizontal(|ui| {
1690 if theme::action(ui, "계속 작업", false, true).clicked() {
1691 self.model.keep_open();
1692 }
1693 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1694 self.clear_password();
1695 self.model.confirm_close();
1696 }
1697 });
1698 }
1699 Close::Waiting => {
1700 ui.heading("종료 확인 중");
1701 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
1702 if theme::action(ui, "닫기 취소", false, true).clicked() {
1703 self.model.keep_open();
1704 }
1705 }
1706 Close::Review => {
1707 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1708 ui.heading("결과 확인 후 닫기");
1709 let wrote = self
1710 .last_request
1711 .as_ref()
1712 .is_some_and(|request| !matches!(request, Start::List { .. }));
1713 ui.label(if !wrote {
1714 "프로그램을 닫을까요?".to_owned()
1715 } else if self.model.confirmed {
1716 "작업 결과를 확인한 뒤 닫으세요".to_owned()
1717 } else {
1718 present::operation_text(present::UNCERTAIN, creating)
1719 });
1720 egui::ScrollArea::vertical()
1721 .max_height(160.0)
1722 .show(ui, |ui| {
1723 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
1724 ui.colored_label(
1725 theme::ERROR,
1726 present::operation_text(present::error_text(code), creating),
1727 );
1728 }
1729 if wrote {
1730 for warning in present::warnings(
1731 self.model.terminal.as_ref(),
1732 self.model.confirmed,
1733 self.targets.as_ref(),
1734 &self.directories,
1735 &self.model.outputs,
1736 ) {
1737 ui.colored_label(
1738 theme::WARNING,
1739 present::operation_text(warning, creating),
1740 );
1741 }
1742 }
1743 });
1744 ui.horizontal(|ui| {
1745 if theme::action(ui, "계속 작업", false, true).clicked() {
1746 self.model.keep_open();
1747 }
1748 if theme::action(ui, "닫기", true, true).clicked() {
1749 self.model.acknowledge_close();
1750 }
1751 });
1752 }
1753 _ => {}
1754 }
1755 });
1756 }
1757}
1758
1759impl eframe::App for ArchiveApp {
1760 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1761 self.show(root);
1762 }
1763}
1764impl Drop for ArchiveApp {
1765 fn drop(&mut self) {
1766 self.clear_password();
1767 }
1768}