team-ljyzipelo

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