team-ljyzipelo

공개
2,059줄82 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 /// 메인 창 가운데에 모달(ZIP 만들기, 암호 입력, 종료 확인, 파일 선택 안내)이 떠 있는지.
1237 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
1238 fn main_modal_open(&self) -> bool {
1239 (self.create && !self.model.busy())
1240 || self.picker.is_some()
1241 || self.model.challenge.is_some()
1242 || self.model.close != Close::Open
1243 }
1244
1245 fn work_window(&mut self, ctx: &egui::Context) {
1246 if !self.work_visible() {
1247 self.work = WorkWindow::default();
1248 return;
1249 }
1250 if ctx.embed_viewports() {
1251 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1252 return;
1253 }
1254 if self.main_modal_open() {
1255 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
1256 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1257 self.work.open = false;
1258 return;
1259 }
1260 let id = egui::ViewportId::from_hash_of("archive-work");
1261 let (parent, parent_focused, now) = ctx.input(|i| {
1262 (
1263 i.viewport().outer_rect,
1264 i.viewport().focused.unwrap_or(false),
1265 i.time,
1266 )
1267 });
1268 let (child, child_focused) = ctx.input(|i| {
1269 i.raw.viewports.get(&id).map_or((None, false), |v| {
1270 (v.outer_rect, v.focused.unwrap_or(false))
1271 })
1272 });
1273 let size = egui::vec2(WORK_WIDTH, self.work.height);
1274 if !self.work.open {
1275 // 처음 열 때 부모 창 가운데에 둠. 암호 입력 뒤 다시 열 때는 기억한 위치에 둠.
1276 // Wayland처럼 위치를 알 수 없으면 창 관리자에 맡김.
1277 self.work.open = true;
1278 self.work.initial = parent.map(|p| match self.work.offset {
1279 Some(offset) => (p.min + offset).round(),
1280 None => (p.center() - size / 2.0).round(),
1281 });
1282 self.work.offset = self.work.initial.zip(parent).map(|(c, p)| c - p.min);
1283 self.work.parent = parent.map(|p| p.min);
1284 self.work.expected = self.work.initial;
1285 self.work.settle_until = now + 0.5;
1286 }
1287 if let (Some(parent), Some(child)) = (parent, child) {
1288 let parent_moved = self
1289 .work
1290 .parent
1291 .is_some_and(|p| (p - parent.min).length() > 0.5);
1292 let settled = self
1293 .work
1294 .expected
1295 .is_some_and(|e| (child.min - e).length() <= 2.0);
1296 if settled || now >= self.work.settle_until {
1297 self.work.settle_until = 0.0;
1298 }
1299 if parent_moved {
1300 if let Some(offset) = self.work.offset {
1301 let target = (parent.min + offset).round();
1302 ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
1303 self.work.expected = Some(target);
1304 self.work.settle_until = now + 0.5;
1305 }
1306 } else if self.work.settle_until == 0.0 && !settled {
1307 // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
1308 self.work.offset = Some(child.min - parent.min);
1309 self.work.expected = Some(child.min);
1310 }
1311 self.work.parent = Some(parent.min);
1312 }
1313 let title = if self.model.busy() {
1314 present::activity_text(
1315 &self.model,
1316 matches!(self.last_request, Some(Start::CreateZip { .. })),
1317 )
1318 .to_owned()
1319 } else {
1320 "작업 결과".to_owned()
1321 };
1322 let window_title = format!("{title} — Zipelo");
1323 let custom_frame = self.custom_frame;
1324 let mut builder = egui::ViewportBuilder::default()
1325 .with_title(window_title.clone())
1326 .with_decorations(!custom_frame)
1327 .with_inner_size(size)
1328 .with_resizable(false)
1329 .with_minimize_button(false)
1330 .with_maximize_button(false)
1331 .with_taskbar(false)
1332 // 앱을 쓰는 동안에만 부모 창 위에 유지함.
1333 .with_window_level(if parent_focused || child_focused {
1334 egui::WindowLevel::AlwaysOnTop
1335 } else {
1336 egui::WindowLevel::Normal
1337 });
1338 if let Some(position) = self.work.initial {
1339 builder = builder.with_position(position);
1340 }
1341 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1342 if ui.ctx().input(|i| i.viewport().close_requested()) {
1343 if self.model.busy() {
1344 ui.ctx()
1345 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1346 } else {
1347 self.dismissed = true;
1348 self.ui_error = None;
1349 self.model.input_error = None;
1350 }
1351 }
1352 if class == egui::ViewportClass::EmbeddedWindow {
1353 ui.set_width(WORK_WIDTH);
1354 self.work_area(ui);
1355 return None;
1356 }
1357 let mut chrome = 0.0;
1358 if custom_frame {
1359 window_frame::title_bar(
1360 ui,
1361 "work",
1362 &window_title,
1363 window_frame::Buttons {
1364 minimize: false,
1365 maximize: false,
1366 },
1367 );
1368 window_frame::edges(ui.ctx(), false);
1369 chrome = window_frame::TITLE_HEIGHT;
1370 }
1371 let margin = theme::PAD as f32;
1372 egui::CentralPanel::default()
1373 .frame(theme::panel(theme::PANEL).corner_radius(0))
1374 .show(ui, |ui| {
1375 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1376 Some(content.height() + 2.0 * margin + chrome)
1377 })
1378 .inner
1379 });
1380 if let Some(height) = height {
1381 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1382 if (height - self.work.height).abs() > 1.0 {
1383 self.work.height = height;
1384 }
1385 }
1386 }
1387
1388 fn work_area(&mut self, ui: &mut egui::Ui) {
1389 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
1390 let enabled = self.picker.is_none();
1391 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
1392 }
1393
1394 fn work_contents(&mut self, ui: &mut egui::Ui) {
1395 if self.model.busy() {
1396 self.progress(ui);
1397 } else if self.result_visible() {
1398 self.result(ui);
1399 }
1400 if !self.create
1401 && let Some(error) = &self.ui_error
1402 {
1403 Self::error_notice(ui, error);
1404 if error == present::FOLDER_ERROR
1405 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
1406 {
1407 self.open_picker(Purpose::Destination);
1408 }
1409 }
1410 if let Some(error) = &self.model.input_error {
1411 ui.colored_label(
1412 theme::ERROR,
1413 if error.starts_with("암호는") {
1414 error.as_str()
1415 } else {
1416 if matches!(self.last_request, Some(Start::CreateZip { .. })) {
1417 "저장 위치와 추가한 항목을 확인하세요"
1418 } else {
1419 "풀 위치와 선택한 항목을 확인하세요"
1420 }
1421 },
1422 );
1423 }
1424 }
1425
1426 fn progress(&mut self, ui: &mut egui::Ui) {
1427 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1428 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
1429 let title = present::activity_text(&self.model, creating);
1430 ui.strong(title);
1431 if let Some((stage, done, total, count)) = self.model.progress {
1432 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
1433 let processed = if stage == Stage::Read {
1434 String::new()
1435 } else {
1436 format!("{count}개 처리함, ")
1437 };
1438 if let Some(total) = total.filter(|n| *n > 0) {
1439 ui.scope(|ui| {
1440 ui.visuals_mut().extreme_bg_color = theme::BORDER;
1441 ui.add(
1442 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
1443 .fill(theme::BLUE)
1444 .desired_height(theme::SPACE * 2.0),
1445 );
1446 });
1447 ui.horizontal(|ui| {
1448 ui.label(format!(
1449 "{:.0}% / {processed}{} / {}",
1450 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
1451 present::bytes_text(done),
1452 present::bytes_text(total)
1453 ));
1454 self.cancel_action(ui, cancelling);
1455 });
1456 } else {
1457 theme::indeterminate(ui);
1458 ui.horizontal(|ui| {
1459 ui.label(format!("{processed}{}", present::bytes_text(done)));
1460 self.cancel_action(ui, cancelling);
1461 });
1462 }
1463 } else {
1464 theme::indeterminate(ui);
1465 ui.horizontal(|ui| {
1466 ui.label("작업을 진행하고 있습니다");
1467 self.cancel_action(ui, cancelling);
1468 });
1469 }
1470 }
1471
1472 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
1473 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1474 if theme::action(ui, "취소", false, !cancelling).clicked() {
1475 self.clear_password();
1476 self.model.cancel();
1477 }
1478 });
1479 }
1480
1481 fn result(&mut self, ui: &mut egui::Ui) {
1482 let t = self.model.terminal.clone();
1483 let listing = matches!(self.last_request, Some(Start::List { .. }));
1484 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1485 let warnings = if listing {
1486 Vec::new()
1487 } else {
1488 present::publication_warnings(
1489 t.as_ref(),
1490 self.model.confirmed,
1491 self.targets.as_ref(),
1492 &self.directories,
1493 &self.model.outputs,
1494 )
1495 };
1496 let success = self.model.confirmed
1497 && self.model.error.is_none()
1498 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
1499 && warnings.is_empty();
1500 let durability_warning = t
1501 .as_ref()
1502 .filter(|_| self.model.confirmed && !listing)
1503 .and_then(|t| present::durability_warning(t.durability));
1504 let durability_in_details = success
1505 && t.as_ref()
1506 .is_some_and(|t| t.durability == Durability::Unconfirmed);
1507 let cancelled =
1508 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
1509 let title = if success {
1510 if creating {
1511 "ZIP 파일을 만들었습니다"
1512 } else {
1513 "압축을 풀었습니다"
1514 }
1515 } else if cancelled {
1516 "작업을 취소했습니다"
1517 } else if listing {
1518 "압축파일을 열지 못했습니다"
1519 } else if creating {
1520 "ZIP 파일을 만들지 못했습니다"
1521 } else {
1522 "압축을 풀지 못했습니다"
1523 };
1524 let fill = if success {
1525 theme::SUCCESS_BG
1526 } else if cancelled {
1527 theme::STRIPE
1528 } else {
1529 theme::ERROR_BG
1530 };
1531 let mut choose = false;
1532 let mut retry = false;
1533 let mut reopen = false;
1534 let mut folder = false;
1535 theme::panel(fill).show(ui, |ui| {
1536 ui.horizontal(|ui| {
1537 theme::icon(
1538 ui,
1539 if success {
1540 Icon::Success
1541 } else if cancelled {
1542 Icon::Warning
1543 } else {
1544 Icon::Error
1545 },
1546 24.0,
1547 );
1548 ui.strong(title);
1549 });
1550 let max_height = WORK_RESULT_MAX_HEIGHT;
1551 egui::ScrollArea::vertical()
1552 .id_salt("result-message")
1553 .max_height(max_height)
1554 .show(ui, |ui| {
1555 if success {
1556 let path = match self.last_request.as_ref() {
1557 Some(Start::CreateZip { output_file, .. }) => {
1558 output_file.display().to_string()
1559 }
1560 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
1561 };
1562 theme::bounded_text(ui, &path, ui.available_width());
1563 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
1564 ui.label(if creating && code == ErrorCode::SourceChanged {
1565 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요".to_owned()
1566 } else {
1567 present::operation_text(present::error_text(code), creating)
1568 });
1569 } else if let Some(error) = &self.model.error {
1570 ui.label(present::operation_text(
1571 present::client_error_text(error),
1572 creating,
1573 ));
1574 }
1575 for warning in warnings
1576 .iter()
1577 .copied()
1578 .chain(durability_warning.filter(|_| !durability_in_details))
1579 {
1580 ui.horizontal_wrapped(|ui| {
1581 theme::icon(ui, Icon::Warning, 20.0);
1582 ui.colored_label(
1583 theme::WARNING,
1584 present::operation_text(warning, creating),
1585 );
1586 });
1587 }
1588 if !success
1589 && !listing
1590 && present::definitely_unsaved(
1591 t.as_ref(),
1592 self.model.confirmed,
1593 &self.model.outputs,
1594 )
1595 {
1596 ui.label(if creating {
1597 "ZIP 파일을 만들지 않았습니다"
1598 } else {
1599 "아무 파일도 풀지 않았습니다"
1600 });
1601 }
1602 if self.details {
1603 theme::panel(theme::STRIPE).show(ui, |ui| {
1604 if durability_in_details {
1605 if let Some(warning) = durability_warning {
1606 ui.label(present::operation_text(warning, creating));
1607 }
1608 }
1609 if let Some(t) = &t {
1610 for line in terminal_lines(t) {
1611 ui.label(line);
1612 }
1613 }
1614 if let Some(error) = &self.model.error {
1615 ui.label(error);
1616 }
1617 for (name, state) in &self.model.outputs {
1618 theme::bounded_text(
1619 ui,
1620 &format!("{name}: {}", disposition_label(*state)),
1621 ui.available_width(),
1622 );
1623 }
1624 });
1625 }
1626 });
1627 let conflict = t
1628 .as_ref()
1629 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
1630 && !creating;
1631 let uncertain = warnings.contains(&present::UNCERTAIN);
1632 if conflict && uncertain {
1633 let response = ui.checkbox(
1634 &mut self.checked_destination,
1635 "기존 풀 위치 폴더를 확인했습니다",
1636 );
1637 theme::focus(&response);
1638 }
1639 ui.horizontal(|ui| {
1640 if theme::action(
1641 ui,
1642 if self.details {
1643 "자세히 닫기"
1644 } else {
1645 "자세히 보기"
1646 },
1647 false,
1648 true,
1649 )
1650 .clicked()
1651 {
1652 self.details = !self.details;
1653 }
1654 let action = if success {
1655 Some(("폴더 열기", true))
1656 } else if conflict {
1657 Some((
1658 if self
1659 .model
1660 .list_id
1661 .as_ref()
1662 .is_some_and(|id| id.format == Format::Gzip)
1663 {
1664 "다른 이름으로 저장"
1665 } else {
1666 "다른 폴더에 풀기"
1667 },
1668 !uncertain || self.checked_destination,
1669 ))
1670 } else if t
1671 .as_ref()
1672 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1673 {
1674 Some((
1675 if creating {
1676 "다시 만들기"
1677 } else {
1678 "압축파일 다시 열기"
1679 },
1680 true,
1681 ))
1682 } else if !cancelled && (!uncertain || listing) {
1683 Some(("다시 시도", true))
1684 } else {
1685 None
1686 };
1687 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1688 if confirm {
1689 self.dismissed = true;
1690 self.ui_error = None;
1691 self.model.input_error = None;
1692 }
1693 if primary {
1694 match action.map(|(label, _)| label) {
1695 Some("폴더 열기") => folder = true,
1696 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
1697 choose = true
1698 }
1699 Some("압축파일 다시 열기") => reopen = true,
1700 Some("다시 시도" | "다시 만들기") => retry = true,
1701 _ => {}
1702 }
1703 }
1704 });
1705 });
1706 if choose {
1707 self.open_picker(Purpose::Retry);
1708 }
1709 if retry {
1710 self.retry();
1711 }
1712 if reopen {
1713 if let Some(path) = self.model.archive.clone() {
1714 self.open_path(path);
1715 }
1716 }
1717 if folder {
1718 let path = match self.last_request.as_ref() {
1719 Some(Start::CreateZip { output_file, .. }) => {
1720 output_file.parent().unwrap_or(Path::new("/"))
1721 }
1722 _ => self.destination.as_path(),
1723 };
1724 match present::folder_command(path).spawn() {
1725 Ok(mut child) => {
1726 std::thread::spawn(move || {
1727 let _ = child.wait();
1728 });
1729 }
1730 Err(_) => {
1731 self.ui_error = Some(
1732 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1733 )
1734 }
1735 }
1736 }
1737 }
1738
1739 fn create_dialog(&mut self, ctx: &egui::Context) {
1740 let mut compress = false;
1741 let mut pick = None;
1742 let mut cancel = false;
1743 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1744 ui.set_width((ctx.content_rect().width() - 64.0).min(600.0));
1745 ui.horizontal(|ui| {
1746 ui.heading("ZIP 만들기");
1747 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1748 let close = theme::icon_button(ui, "닫기", theme::CLOSE, true);
1749 theme::focus(&close);
1750 cancel = close.clicked();
1751 });
1752 });
1753 if let Some(error) = &self.ui_error {
1754 Self::error_notice(ui, error);
1755 }
1756 egui::ScrollArea::vertical()
1757 .id_salt("create-fields")
1758 .max_height(
1759 (ctx.content_rect().height()
1760 - 180.0
1761 - if self.ui_error.is_some() { 96.0 } else { 0.0 })
1762 .max(120.0),
1763 )
1764 .show(ui, |ui| {
1765 ui.add_space(16.0);
1766 let frame = theme::panel(theme::STRIPE)
1767 .stroke(egui::Stroke::new(1.0, theme::DASH))
1768 .inner_margin(egui::Margin::same(24));
1769 let area = frame
1770 .show(ui, |ui| {
1771 ui.set_min_size(egui::vec2(ui.available_width(), 144.0));
1772 ui.vertical_centered(|ui| {
1773 theme::icon(ui, Icon::File, 44.0);
1774 ui.add_space(16.0);
1775 ui.label(
1776 RichText::new("파일이나 폴더를 여기에 끌어 놓으세요")
1777 .size(18.0),
1778 );
1779 });
1780 })
1781 .response;
1782 let drop = ui.interact(
1783 area.rect,
1784 egui::Id::unique("zip-source-drop"),
1785 egui::Sense::click(),
1786 );
1787 theme::focus(&drop);
1788 drop.widget_info(|| {
1789 egui::WidgetInfo::labeled(egui::Role::Button, true, "파일 추가")
1790 });
1791 if drop.clicked() {
1792 pick = Some(Purpose::Files);
1793 }
1794 egui::ScrollArea::vertical()
1795 .id_salt("zip-sources")
1796 .max_height(86.0)
1797 .show(ui, |ui| {
1798 let mut remove = None;
1799 for (index, path) in self.sources.iter().enumerate() {
1800 ui.horizontal(|ui| {
1801 theme::icon(
1802 ui,
1803 if path.is_dir() {
1804 Icon::Folder
1805 } else {
1806 Icon::File
1807 },
1808 20.0,
1809 );
1810 let name =
1811 path.file_name().unwrap_or_default().to_string_lossy();
1812 theme::bounded_text(
1813 ui,
1814 &name,
1815 (ui.available_width() - 72.0).max(0.0),
1816 )
1817 .on_hover_text(path.display().to_string());
1818 if ui.button("빼기").clicked() {
1819 remove = Some(index);
1820 }
1821 });
1822 }
1823 if let Some(index) = remove {
1824 self.sources.remove(index);
1825 }
1826 });
1827 ui.horizontal(|ui| {
1828 if theme::action(ui, "파일 추가", false, true).clicked() {
1829 pick = Some(Purpose::Files);
1830 }
1831 if theme::action(ui, "폴더 추가", false, true).clicked() {
1832 pick = Some(Purpose::Folder);
1833 }
1834 });
1835 ui.add_space(16.0);
1836 ui.horizontal(|ui| {
1837 theme::icon(ui, Icon::Lock, 24.0);
1838 ui.strong("암호화");
1839 });
1840 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1841 theme::focus(&check);
1842 ui.add_space(16.0);
1843 });
1844 let (dismiss, confirm) =
1845 theme::action_pair(ui, "취소", Some(("압축하기", !self.sources.is_empty())));
1846 cancel |= dismiss;
1847 compress = confirm;
1848 });
1849 if cancel || modal.should_close() {
1850 self.create = false;
1851 self.ui_error = None;
1852 return;
1853 }
1854 if let Some(purpose) = pick {
1855 self.open_picker(purpose);
1856 }
1857 if compress {
1858 self.open_picker(Purpose::SaveZip);
1859 }
1860 }
1861
1862 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1863 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1864 let mut submit = false;
1865 let mut cancel = false;
1866 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
1867 id == egui::Id::unique("archive-password-input")
1868 || id == egui::Id::unique("archive-password-confirm")
1869 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
1870 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1871 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1872 ui.heading(if encrypt {
1873 "ZIP 암호 설정"
1874 } else {
1875 "암호가 필요합니다"
1876 });
1877 if encrypt {
1878 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1879 } else if let Some(path) = &self.model.archive {
1880 ui.label(format!(
1881 "{}은 암호로 보호되어 있습니다.",
1882 present::middle_text(
1883 &path.file_name().unwrap_or_default().to_string_lossy(),
1884 24
1885 )
1886 ));
1887 }
1888 ui.horizontal(|ui| {
1889 ui.label("암호");
1890 let edit = ui.add(
1891 egui::TextEdit::singleline(&mut self.password)
1892 .password(!self.password_visible)
1893 .id(egui::Id::unique("archive-password-input"))
1894 .char_limit(1024)
1895 .desired_width(232.0),
1896 );
1897 theme::focus(&edit);
1898 if new_challenge {
1899 edit.request_focus();
1900 }
1901 if theme::action(
1902 ui,
1903 if self.password_visible {
1904 "숨기기"
1905 } else {
1906 "보기"
1907 },
1908 false,
1909 true,
1910 )
1911 .clicked()
1912 {
1913 self.password_visible = !self.password_visible;
1914 }
1915 });
1916 if encrypt {
1917 ui.horizontal(|ui| {
1918 ui.label("암호 확인");
1919 let edit = ui.add(
1920 egui::TextEdit::singleline(&mut self.password_confirm)
1921 .password(!self.password_visible)
1922 .id(egui::Id::unique("archive-password-confirm"))
1923 .char_limit(1024)
1924 .desired_width(232.0),
1925 );
1926 theme::focus(&edit);
1927 });
1928 if self.password != self.password_confirm {
1929 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1930 }
1931 } else if attempt > 1 {
1932 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1933 }
1934 if self.password.len() > 1024 {
1935 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1936 }
1937 let valid = !self.password.is_empty()
1938 && self.password.len() <= 1024
1939 && (!encrypt || self.password == self.password_confirm);
1940 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1941 cancel = actions.0;
1942 submit = actions.1 || (valid && password_enter);
1943 });
1944 if modal.should_close() || cancel {
1945 self.clear_password();
1946 self.model.cancel();
1947 } else if submit {
1948 let password = std::mem::take(&mut self.password);
1949 self.clear_password();
1950 self.model.password(password);
1951 }
1952 }
1953
1954 fn close_dialog(&mut self, ctx: &egui::Context) {
1955 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1956 return;
1957 }
1958 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1959 ui.set_width(420.0);
1960 match self.model.close {
1961 Close::Confirm => {
1962 ui.heading("작업 중 닫기");
1963 ui.label("작업을 취소하고 닫을까요?");
1964 ui.horizontal(|ui| {
1965 if theme::action(ui, "계속 작업", false, true).clicked() {
1966 self.model.keep_open();
1967 }
1968 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1969 self.clear_password();
1970 self.model.confirm_close();
1971 }
1972 });
1973 }
1974 Close::Waiting => {
1975 ui.heading("종료 확인 중");
1976 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
1977 if theme::action(ui, "닫기 취소", false, true).clicked() {
1978 self.model.keep_open();
1979 }
1980 }
1981 Close::Review => {
1982 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1983 ui.heading("결과 확인 후 닫기");
1984 let wrote = self
1985 .last_request
1986 .as_ref()
1987 .is_some_and(|request| !matches!(request, Start::List { .. }));
1988 ui.label(if !wrote {
1989 "프로그램을 닫을까요?".to_owned()
1990 } else if self.model.confirmed {
1991 "작업 결과를 확인한 뒤 닫으세요".to_owned()
1992 } else {
1993 present::operation_text(present::UNCERTAIN, creating)
1994 });
1995 egui::ScrollArea::vertical()
1996 .max_height(160.0)
1997 .show(ui, |ui| {
1998 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
1999 ui.colored_label(
2000 theme::ERROR,
2001 present::operation_text(present::error_text(code), creating),
2002 );
2003 }
2004 if wrote {
2005 for warning in present::warnings(
2006 self.model.terminal.as_ref(),
2007 self.model.confirmed,
2008 self.targets.as_ref(),
2009 &self.directories,
2010 &self.model.outputs,
2011 ) {
2012 ui.colored_label(
2013 theme::WARNING,
2014 present::operation_text(warning, creating),
2015 );
2016 }
2017 }
2018 });
2019 ui.horizontal(|ui| {
2020 if theme::action(ui, "계속 작업", false, true).clicked() {
2021 self.model.keep_open();
2022 }
2023 if theme::action(ui, "닫기", true, true).clicked() {
2024 self.model.acknowledge_close();
2025 }
2026 });
2027 }
2028 _ => {}
2029 }
2030 });
2031 }
2032}
2033
2034impl eframe::App for ArchiveApp {
2035 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
2036 self.show(root);
2037 }
2038
2039 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
2040 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
2041 if std::mem::take(&mut self.release_after_move) {
2042 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
2043 raw_input.events.insert(
2044 0,
2045 egui::Event::PointerButton {
2046 pos,
2047 button: egui::PointerButton::Primary,
2048 pressed: false,
2049 modifiers: ctx.input(|i| i.modifiers),
2050 },
2051 );
2052 }
2053 }
2054}
2055impl Drop for ArchiveApp {
2056 fn drop(&mut self) {
2057 self.clear_password();
2058 }
2059}