team-ljyzipelo

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