team-ljyzipelo

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