team-ljyzipelo

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