team-ljyzipelo

공개
1,747줄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 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 "풀 위치와 선택한 항목을 확인하세요"
1148 },
1149 );
1150 }
1151 }
1152
1153 fn progress(&mut self, ui: &mut egui::Ui) {
1154 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1155 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
1156 let title = present::activity_text(&self.model, creating);
1157 ui.strong(title);
1158 if let Some((_, done, total, count)) = self.model.progress {
1159 if let Some(total) = total.filter(|n| *n > 0) {
1160 ui.scope(|ui| {
1161 ui.visuals_mut().extreme_bg_color = theme::BORDER;
1162 ui.add(
1163 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
1164 .fill(theme::BLUE)
1165 .desired_height(theme::SPACE * 2.0),
1166 );
1167 });
1168 ui.horizontal(|ui| {
1169 ui.label(format!(
1170 "{:.0}% / {count}개 처리함, {} / {}",
1171 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
1172 present::bytes_text(done),
1173 present::bytes_text(total)
1174 ));
1175 self.cancel_action(ui, cancelling);
1176 });
1177 } else {
1178 theme::indeterminate(ui);
1179 ui.horizontal(|ui| {
1180 ui.label(format!("{count}개 처리함, {}", present::bytes_text(done)));
1181 self.cancel_action(ui, cancelling);
1182 });
1183 }
1184 } else {
1185 theme::indeterminate(ui);
1186 ui.horizontal(|ui| {
1187 ui.label("작업을 진행하고 있습니다");
1188 self.cancel_action(ui, cancelling);
1189 });
1190 }
1191 }
1192
1193 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
1194 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1195 if theme::action(ui, "취소", false, !cancelling).clicked() {
1196 self.clear_password();
1197 self.model.cancel();
1198 }
1199 });
1200 }
1201
1202 fn result(&mut self, ui: &mut egui::Ui) {
1203 let t = self.model.terminal.clone();
1204 let listing = matches!(self.last_request, Some(Start::List { .. }));
1205 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1206 let warnings = if listing {
1207 Vec::new()
1208 } else {
1209 present::publication_warnings(
1210 t.as_ref(),
1211 self.model.confirmed,
1212 self.targets.as_ref(),
1213 &self.directories,
1214 &self.model.outputs,
1215 )
1216 };
1217 let success = self.model.confirmed
1218 && self.model.error.is_none()
1219 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
1220 && warnings.is_empty();
1221 let durability_warning = t
1222 .as_ref()
1223 .filter(|_| self.model.confirmed && !listing)
1224 .and_then(|t| present::durability_warning(t.durability));
1225 let durability_in_details = success
1226 && t.as_ref()
1227 .is_some_and(|t| t.durability == Durability::Unconfirmed);
1228 let cancelled =
1229 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
1230 let title = if success {
1231 if creating {
1232 "ZIP 파일을 만들었습니다"
1233 } else {
1234 "압축을 풀었습니다"
1235 }
1236 } else if cancelled {
1237 "작업을 취소했습니다"
1238 } else if listing {
1239 "압축파일을 열지 못했습니다"
1240 } else if creating {
1241 "ZIP 파일을 만들지 못했습니다"
1242 } else {
1243 "압축을 풀지 못했습니다"
1244 };
1245 let fill = if success {
1246 theme::SUCCESS_BG
1247 } else if cancelled {
1248 theme::STRIPE
1249 } else {
1250 theme::ERROR_BG
1251 };
1252 let mut choose = false;
1253 let mut retry = false;
1254 let mut reopen = false;
1255 let mut folder = false;
1256 theme::panel(fill).show(ui, |ui| {
1257 ui.horizontal(|ui| {
1258 theme::icon(
1259 ui,
1260 if success {
1261 Icon::Success
1262 } else if cancelled {
1263 Icon::Warning
1264 } else {
1265 Icon::Error
1266 },
1267 24.0,
1268 );
1269 ui.strong(title);
1270 });
1271 let max_height = (ui.ctx().content_rect().height() * 0.24).max(80.0);
1272 egui::ScrollArea::vertical()
1273 .id_salt("result-message")
1274 .max_height(max_height)
1275 .show(ui, |ui| {
1276 if success {
1277 let path = match self.last_request.as_ref() {
1278 Some(Start::CreateZip { output_file, .. }) => {
1279 output_file.display().to_string()
1280 }
1281 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
1282 };
1283 theme::bounded_text(ui, &path, ui.available_width());
1284 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
1285 ui.label(if creating && code == ErrorCode::SourceChanged {
1286 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
1287 } else {
1288 present::error_text(code)
1289 });
1290 } else if let Some(error) = &self.model.error {
1291 ui.label(present::client_error_text(error));
1292 }
1293 for warning in warnings
1294 .iter()
1295 .copied()
1296 .chain(durability_warning.filter(|_| !durability_in_details))
1297 {
1298 ui.horizontal_wrapped(|ui| {
1299 theme::icon(ui, Icon::Warning, 20.0);
1300 ui.colored_label(theme::WARNING, warning);
1301 });
1302 }
1303 if !success
1304 && !listing
1305 && present::definitely_unsaved(
1306 t.as_ref(),
1307 self.model.confirmed,
1308 &self.model.outputs,
1309 )
1310 {
1311 ui.label("아무 파일도 풀지 않았습니다");
1312 }
1313 if self.details {
1314 theme::panel(theme::STRIPE).show(ui, |ui| {
1315 if durability_in_details {
1316 if let Some(warning) = durability_warning {
1317 ui.label(warning);
1318 }
1319 }
1320 if let Some(t) = &t {
1321 for line in terminal_lines(t) {
1322 ui.label(line);
1323 }
1324 }
1325 if let Some(error) = &self.model.error {
1326 ui.label(error);
1327 }
1328 for (name, state) in &self.model.outputs {
1329 theme::bounded_text(
1330 ui,
1331 &format!("{name}: {}", disposition_label(*state)),
1332 ui.available_width(),
1333 );
1334 }
1335 });
1336 }
1337 });
1338 let conflict = t
1339 .as_ref()
1340 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
1341 && !creating;
1342 let uncertain = warnings.contains(&present::UNCERTAIN);
1343 if conflict && uncertain {
1344 let response = ui.checkbox(
1345 &mut self.checked_destination,
1346 "기존 풀 위치 폴더를 확인했습니다",
1347 );
1348 theme::focus(&response);
1349 }
1350 ui.horizontal(|ui| {
1351 if theme::action(
1352 ui,
1353 if self.details {
1354 "자세히 닫기"
1355 } else {
1356 "자세히 보기"
1357 },
1358 false,
1359 true,
1360 )
1361 .clicked()
1362 {
1363 self.details = !self.details;
1364 }
1365 let action = if success {
1366 Some(("폴더 열기", true))
1367 } else if conflict {
1368 Some((
1369 if self
1370 .model
1371 .list_id
1372 .as_ref()
1373 .is_some_and(|id| id.format == Format::Gzip)
1374 {
1375 "다른 이름으로 저장"
1376 } else {
1377 "다른 폴더에 풀기"
1378 },
1379 !uncertain || self.checked_destination,
1380 ))
1381 } else if t
1382 .as_ref()
1383 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1384 {
1385 Some((
1386 if creating {
1387 "다시 만들기"
1388 } else {
1389 "압축파일 다시 열기"
1390 },
1391 true,
1392 ))
1393 } else if !cancelled && (!uncertain || listing) {
1394 Some(("다시 시도", true))
1395 } else {
1396 None
1397 };
1398 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1399 if confirm {
1400 self.dismissed = true;
1401 self.ui_error = None;
1402 self.model.input_error = None;
1403 }
1404 if primary {
1405 match action.map(|(label, _)| label) {
1406 Some("폴더 열기") => folder = true,
1407 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
1408 choose = true
1409 }
1410 Some("압축파일 다시 열기") => reopen = true,
1411 Some("다시 시도" | "다시 만들기") => retry = true,
1412 _ => {}
1413 }
1414 }
1415 });
1416 });
1417 if choose {
1418 self.open_picker(Purpose::Retry);
1419 }
1420 if retry {
1421 self.retry();
1422 }
1423 if reopen {
1424 if let Some(path) = self.model.archive.clone() {
1425 self.open_path(path);
1426 }
1427 }
1428 if folder {
1429 let path = match self.last_request.as_ref() {
1430 Some(Start::CreateZip { output_file, .. }) => {
1431 output_file.parent().unwrap_or(Path::new("/"))
1432 }
1433 _ => self.destination.as_path(),
1434 };
1435 match present::folder_command(path).spawn() {
1436 Ok(mut child) => {
1437 std::thread::spawn(move || {
1438 let _ = child.wait();
1439 });
1440 }
1441 Err(_) => {
1442 self.ui_error = Some(
1443 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1444 )
1445 }
1446 }
1447 }
1448 }
1449
1450 fn create_dialog(&mut self, ctx: &egui::Context) {
1451 let mut compress = false;
1452 let mut pick = None;
1453 let mut cancel = false;
1454 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1455 ui.set_width((ctx.content_rect().width() - 64.0).min(600.0));
1456 ui.horizontal(|ui| {
1457 ui.heading("ZIP 만들기");
1458 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1459 let close = theme::icon_button(ui, "닫기", theme::CLOSE, true);
1460 theme::focus(&close);
1461 cancel = close.clicked();
1462 });
1463 });
1464 if let Some(error) = &self.ui_error {
1465 Self::error_notice(ui, error);
1466 }
1467 egui::ScrollArea::vertical()
1468 .id_salt("create-fields")
1469 .max_height(
1470 (ctx.content_rect().height()
1471 - 180.0
1472 - if self.ui_error.is_some() { 96.0 } else { 0.0 })
1473 .max(120.0),
1474 )
1475 .show(ui, |ui| {
1476 ui.add_space(16.0);
1477 let frame = theme::panel(theme::STRIPE)
1478 .stroke(egui::Stroke::new(1.0, theme::DASH))
1479 .inner_margin(egui::Margin::same(24));
1480 let area = frame
1481 .show(ui, |ui| {
1482 ui.set_min_size(egui::vec2(ui.available_width(), 144.0));
1483 ui.vertical_centered(|ui| {
1484 theme::icon(ui, Icon::File, 44.0);
1485 ui.add_space(16.0);
1486 ui.label(
1487 RichText::new("파일이나 폴더를 여기에 끌어 놓으세요")
1488 .size(18.0),
1489 );
1490 });
1491 })
1492 .response;
1493 let drop = ui.interact(
1494 area.rect,
1495 egui::Id::unique("zip-source-drop"),
1496 egui::Sense::click(),
1497 );
1498 theme::focus(&drop);
1499 drop.widget_info(|| {
1500 egui::WidgetInfo::labeled(egui::Role::Button, true, "파일 추가")
1501 });
1502 if drop.clicked() {
1503 pick = Some(Purpose::Files);
1504 }
1505 egui::ScrollArea::vertical()
1506 .id_salt("zip-sources")
1507 .max_height(86.0)
1508 .show(ui, |ui| {
1509 let mut remove = None;
1510 for (index, path) in self.sources.iter().enumerate() {
1511 ui.horizontal(|ui| {
1512 theme::icon(
1513 ui,
1514 if path.is_dir() {
1515 Icon::Folder
1516 } else {
1517 Icon::File
1518 },
1519 20.0,
1520 );
1521 let name =
1522 path.file_name().unwrap_or_default().to_string_lossy();
1523 theme::bounded_text(
1524 ui,
1525 &name,
1526 (ui.available_width() - 72.0).max(0.0),
1527 )
1528 .on_hover_text(path.display().to_string());
1529 if ui.button("빼기").clicked() {
1530 remove = Some(index);
1531 }
1532 });
1533 }
1534 if let Some(index) = remove {
1535 self.sources.remove(index);
1536 }
1537 });
1538 ui.horizontal(|ui| {
1539 if theme::action(ui, "파일 추가", false, true).clicked() {
1540 pick = Some(Purpose::Files);
1541 }
1542 if theme::action(ui, "폴더 추가", false, true).clicked() {
1543 pick = Some(Purpose::Folder);
1544 }
1545 });
1546 ui.add_space(16.0);
1547 ui.horizontal(|ui| {
1548 theme::icon(ui, Icon::Lock, 24.0);
1549 ui.strong("암호화");
1550 });
1551 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1552 theme::focus(&check);
1553 ui.add_space(16.0);
1554 });
1555 let (dismiss, confirm) =
1556 theme::action_pair(ui, "취소", Some(("압축하기", !self.sources.is_empty())));
1557 cancel |= dismiss;
1558 compress = confirm;
1559 });
1560 if cancel || modal.should_close() {
1561 self.create = false;
1562 self.ui_error = None;
1563 return;
1564 }
1565 if let Some(purpose) = pick {
1566 self.open_picker(purpose);
1567 }
1568 if compress {
1569 self.open_picker(Purpose::SaveZip);
1570 }
1571 }
1572
1573 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1574 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1575 let mut submit = false;
1576 let mut cancel = false;
1577 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
1578 id == egui::Id::unique("archive-password-input")
1579 || id == egui::Id::unique("archive-password-confirm")
1580 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
1581 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1582 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1583 ui.heading(if encrypt {
1584 "ZIP 암호 설정"
1585 } else {
1586 "암호가 필요합니다"
1587 });
1588 if encrypt {
1589 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1590 } else if let Some(path) = &self.model.archive {
1591 ui.label(format!(
1592 "{}은 암호로 보호되어 있습니다.",
1593 present::middle_text(
1594 &path.file_name().unwrap_or_default().to_string_lossy(),
1595 24
1596 )
1597 ));
1598 }
1599 ui.horizontal(|ui| {
1600 ui.label("암호");
1601 let edit = ui.add(
1602 egui::TextEdit::singleline(&mut self.password)
1603 .password(!self.password_visible)
1604 .id(egui::Id::unique("archive-password-input"))
1605 .char_limit(1024)
1606 .desired_width(232.0),
1607 );
1608 theme::focus(&edit);
1609 if new_challenge {
1610 edit.request_focus();
1611 }
1612 if theme::action(
1613 ui,
1614 if self.password_visible {
1615 "숨기기"
1616 } else {
1617 "보기"
1618 },
1619 false,
1620 true,
1621 )
1622 .clicked()
1623 {
1624 self.password_visible = !self.password_visible;
1625 }
1626 });
1627 if encrypt {
1628 ui.horizontal(|ui| {
1629 ui.label("암호 확인");
1630 let edit = ui.add(
1631 egui::TextEdit::singleline(&mut self.password_confirm)
1632 .password(!self.password_visible)
1633 .id(egui::Id::unique("archive-password-confirm"))
1634 .char_limit(1024)
1635 .desired_width(232.0),
1636 );
1637 theme::focus(&edit);
1638 });
1639 if self.password != self.password_confirm {
1640 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1641 }
1642 } else if attempt > 1 {
1643 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1644 }
1645 if self.password.len() > 1024 {
1646 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1647 }
1648 let valid = !self.password.is_empty()
1649 && self.password.len() <= 1024
1650 && (!encrypt || self.password == self.password_confirm);
1651 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1652 cancel = actions.0;
1653 submit = actions.1 || (valid && password_enter);
1654 });
1655 if modal.should_close() || cancel {
1656 self.clear_password();
1657 self.model.cancel();
1658 } else if submit {
1659 let password = std::mem::take(&mut self.password);
1660 self.clear_password();
1661 self.model.password(password);
1662 }
1663 }
1664
1665 fn close_dialog(&mut self, ctx: &egui::Context) {
1666 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1667 return;
1668 }
1669 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1670 ui.set_width(420.0);
1671 match self.model.close {
1672 Close::Confirm => {
1673 ui.heading("작업 중 닫기");
1674 ui.label("작업을 취소하고 닫을까요?");
1675 ui.horizontal(|ui| {
1676 if theme::action(ui, "계속 작업", false, true).clicked() {
1677 self.model.keep_open();
1678 }
1679 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1680 self.clear_password();
1681 self.model.confirm_close();
1682 }
1683 });
1684 }
1685 Close::Waiting => {
1686 ui.heading("종료 확인 중");
1687 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
1688 if theme::action(ui, "닫기 취소", false, true).clicked() {
1689 self.model.keep_open();
1690 }
1691 }
1692 Close::Review => {
1693 ui.heading("결과 확인 후 닫기");
1694 let wrote = self
1695 .last_request
1696 .as_ref()
1697 .is_some_and(|request| !matches!(request, Start::List { .. }));
1698 ui.label(if !wrote {
1699 "프로그램을 닫을까요?"
1700 } else if self.model.confirmed {
1701 "작업 결과를 확인한 뒤 닫으세요"
1702 } else {
1703 present::UNCERTAIN
1704 });
1705 egui::ScrollArea::vertical()
1706 .max_height(160.0)
1707 .show(ui, |ui| {
1708 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
1709 ui.colored_label(theme::ERROR, present::error_text(code));
1710 }
1711 if wrote {
1712 for warning in present::warnings(
1713 self.model.terminal.as_ref(),
1714 self.model.confirmed,
1715 self.targets.as_ref(),
1716 &self.directories,
1717 &self.model.outputs,
1718 ) {
1719 ui.colored_label(theme::WARNING, warning);
1720 }
1721 }
1722 });
1723 ui.horizontal(|ui| {
1724 if theme::action(ui, "계속 작업", false, true).clicked() {
1725 self.model.keep_open();
1726 }
1727 if theme::action(ui, "닫기", true, true).clicked() {
1728 self.model.acknowledge_close();
1729 }
1730 });
1731 }
1732 _ => {}
1733 }
1734 });
1735 }
1736}
1737
1738impl eframe::App for ArchiveApp {
1739 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
1740 self.show(root);
1741 }
1742}
1743impl Drop for ArchiveApp {
1744 fn drop(&mut self) {
1745 self.clear_password();
1746 }
1747}