team-ljyzipelo

공개
2,088줄83 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 {
618 left: 12,
619 right: 12,
620 // 버튼 안 내용은 보이는 모양 기준으로 가운데에 두므로 위아래를 같게 둠.
621 top: 4,
622 bottom: 4,
623 }),
624 )
625 .show(root, |ui| {
626 ui.horizontal(|ui| {
627 ui.spacing_mut().item_spacing.x = 2.0;
628 let idle = !self.model.busy()
629 && self.model.close == Close::Open
630 && self.picker.is_none();
631 if theme::tool(ui, "열기", theme::OPEN, idle, false)
632 .on_hover_text(&title)
633 .clicked()
634 {
635 self.open_picker(Purpose::Open);
636 }
637 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
638 self.show_create(false);
639 }
640 if theme::tool(
641 ui,
642 "압축해제",
643 theme::EXTRACT,
644 self.model.can_extract(),
645 true,
646 )
647 .clicked()
648 {
649 self.open_picker(Purpose::Destination);
650 }
651 });
652 });
653 egui::Panel::bottom("archive-status")
654 .exact_size(theme::STATUS_HEIGHT)
655 .resizable(false)
656 .frame(
657 egui::Frame::new()
658 .fill(theme::STRIPE)
659 .inner_margin(egui::Margin::symmetric(16, 0)),
660 )
661 .show(root, |ui| {
662 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
663 let selected = rows
664 .iter()
665 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
666 .count();
667 let rect = ui.max_rect();
668 let half = (rect.width() - theme::SPACE) / 2.0;
669 theme::status_text(
670 ui,
671 rect,
672 &format!("{}개 항목", rows.len()),
673 half,
674 Align::Min,
675 );
676 theme::status_text(ui, rect, &format!("선택 {selected}개"), half, Align::Max);
677 });
678 if ctx.embed_viewports() && self.work_visible() {
679 // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
680 egui::Panel::bottom("archive-work")
681 .frame(theme::panel(theme::PANEL).corner_radius(0))
682 .show(root, |ui| self.work_area(ui));
683 }
684 egui::CentralPanel::default()
685 .frame(
686 theme::panel(theme::PANEL)
687 .corner_radius(0)
688 .inner_margin(egui::Margin::ZERO),
689 )
690 .show(root, |ui| {
691 if self.model.archive.is_some() {
692 self.archive_list(ui);
693 } else {
694 self.empty(ui);
695 }
696 });
697 self.work_window(&ctx);
698 if self.create && !self.model.busy() {
699 self.create_dialog(&ctx);
700 }
701 if self.model.challenge.is_some() {
702 self.password_dialog(&ctx, new_challenge);
703 }
704 self.close_dialog(&ctx);
705 self.picker_notice(&ctx);
706 if self.custom_frame {
707 window_frame::edges(&ctx, true);
708 }
709 if self.model.busy() {
710 ctx.request_repaint_after(std::time::Duration::from_millis(30));
711 }
712 }
713
714 // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
715 fn picker_notice(&mut self, ctx: &egui::Context) {
716 if self.picker.is_none() {
717 return;
718 }
719 egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
720 ui.set_width(360.0);
721 ui.label("파일 선택 창에서 선택을 마쳐 주세요");
722 });
723 ctx.request_repaint_after(std::time::Duration::from_millis(100));
724 }
725
726 fn empty(&mut self, ui: &mut egui::Ui) {
727 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
728 let width = (ui.available_width() * 0.60)
729 .max(480.0)
730 .min(ui.available_width());
731 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
732 ui.add_space(y);
733 ui.vertical_centered(|ui| {
734 let drop_frame = egui::Frame::new()
735 .fill(if hovered { theme::DROP } else { theme::PANEL })
736 .corner_radius(theme::DROP_RADIUS)
737 .inner_margin(egui::Margin::same(theme::DROP_PAD))
738 .show(ui, |ui| {
739 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
740 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
741 ui.vertical_centered(|ui| {
742 ui.add_space(theme::PAD as f32);
743 theme::icon(ui, Icon::Archive, 48.0);
744 ui.add_space(theme::PAD as f32);
745 ui.label(
746 RichText::new(if hovered {
747 "놓으면 엽니다"
748 } else {
749 "압축파일을 여기에 끌어 놓으세요"
750 })
751 .size(theme::FONT_LARGE)
752 .strong(),
753 );
754 ui.label("또는");
755 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
756 self.open_picker(Purpose::Open);
757 }
758 });
759 });
760 let rect = drop_frame.response.rect;
761 if hovered {
762 ui.painter().rect_stroke(
763 rect,
764 12,
765 egui::Stroke::new(2.0, theme::BLUE),
766 egui::StrokeKind::Inside,
767 );
768 } else {
769 let stroke = egui::Stroke::new(2.0, theme::DASH);
770 for (a, b) in [
771 (rect.left_top(), rect.right_top()),
772 (rect.right_top(), rect.right_bottom()),
773 (rect.right_bottom(), rect.left_bottom()),
774 (rect.left_bottom(), rect.left_top()),
775 ] {
776 let direction = (b - a).normalized();
777 let mut distance = theme::DROP_RADIUS as f32;
778 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
779 ui.painter().line_segment(
780 [
781 a + direction * distance,
782 a + direction
783 * (distance + theme::SPACE)
784 .min(a.distance(b) - theme::DROP_RADIUS as f32),
785 ],
786 stroke,
787 );
788 distance += theme::PAD as f32;
789 }
790 }
791 }
792 ui.add_space(theme::PAD as f32);
793 ui.colored_label(
794 theme::MUTED,
795 "ZIP, 7z, TAR, GZ, TAR.GZ 파일을 열 수 있습니다",
796 );
797 });
798 }
799
800 fn archive_list(&mut self, ui: &mut egui::Ui) {
801 // 경로 줄은 입력란 높이만 차지하고 창 너비 전체를 회색으로 채움.
802 egui::Frame::new()
803 .fill(theme::STRIPE)
804 .inner_margin(egui::Margin {
805 left: 8,
806 right: 12,
807 top: 0,
808 bottom: 0,
809 })
810 .show(ui, |ui| {
811 ui.set_min_width(ui.available_width());
812 ui.horizontal(|ui| {
813 ui.set_height(theme::FIELD);
814 // 간격은 아래에서 직접 넣어 위치가 흔들리지 않게 함.
815 ui.spacing_mut().item_spacing.x = 0.0;
816 let up = theme::flat_icon_button(
817 ui,
818 "위로",
819 theme::UP,
820 !self.folder.is_empty() && !self.model.busy(),
821 egui::vec2(theme::FIELD, theme::FIELD),
822 );
823 if up.clicked() {
824 let parent = self
825 .folder
826 .rsplit_once('/')
827 .map_or("", |(parent, _)| parent)
828 .to_owned();
829 self.browse_folder(&parent);
830 }
831 ui.add_space(6.0);
832 let path = format!("/{}", self.folder);
833 let search_width = 240.0;
834 let gap = 8.0;
835 let path_width = (ui.available_width() - search_width - gap).max(0.0);
836 // 두 입력란은 같은 높이의 칸을 받아 같은 세로 위치에 그림.
837 let (path_rect, _) = ui.allocate_exact_size(
838 egui::vec2(path_width, theme::FIELD),
839 egui::Sense::hover(),
840 );
841 theme::field_frame(ui, path_rect, false);
842 // 부모 배치에 영향을 주지 않는 하위 영역에 경로 글자를 그림.
843 let mut text_ui = ui.new_child(
844 egui::UiBuilder::new()
845 .max_rect(path_rect.shrink2(egui::vec2(10.0, 0.0)))
846 .layout(Layout::left_to_right(Align::Center)),
847 );
848 theme::bounded_text(&mut text_ui, &path, (path_width - 20.0).max(0.0));
849 ui.add_space(gap);
850 let (search_rect, _) = ui.allocate_exact_size(
851 egui::vec2(search_width, theme::FIELD),
852 egui::Sense::hover(),
853 );
854 let search_id = egui::Id::unique("archive-search");
855 let focused = ui.memory(|m| m.has_focus(search_id));
856 theme::field_frame(ui, search_rect, focused);
857 let icon = egui::Rect::from_center_size(
858 egui::pos2(search_rect.left() + 20.0, search_rect.center().y),
859 egui::vec2(16.0, 16.0),
860 );
861 theme::svg_icon(ui.painter(), icon, theme::SEARCH, theme::MUTED);
862 let search = ui.put(
863 egui::Rect::from_min_max(
864 egui::pos2(icon.right() + 8.0, search_rect.top() + 1.0),
865 egui::pos2(search_rect.right() - 8.0, search_rect.bottom() - 1.0),
866 ),
867 egui::TextEdit::singleline(&mut self.search)
868 .id(search_id)
869 .frame(egui::Frame::NONE)
870 .margin(egui::Margin::ZERO)
871 .align(egui::Align2::LEFT_CENTER)
872 .hint_text("파일 검색"),
873 );
874 if search.changed() {
875 self.clear_list_selection();
876 }
877 });
878 });
879 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
880
881 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 40.0).max(120.0);
882 ui.horizontal(|ui| {
883 ui.add_space(16.0 + 28.0);
884 theme::column_label(ui, RichText::new("이름").strong(), name_width, Align::Min);
885 theme::column_label(ui, "크기", 96.0, Align::Max);
886 });
887 ui.separator();
888 let active = !self.model.busy()
889 && !self.create
890 && self.model.challenge.is_none()
891 && self.model.close == Close::Open;
892 let list_id = egui::Id::unique("archive-list");
893 let background = ui.interact(
894 ui.available_rect_before_wrap(),
895 list_id,
896 if active {
897 egui::Sense::click_and_drag()
898 } else {
899 egui::Sense::hover()
900 },
901 );
902 background
903 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
904 if background.has_focus() {
905 ui.ctx().memory_mut(|memory| {
906 memory.set_focus_lock_filter(
907 list_id,
908 egui::EventFilter {
909 vertical_arrows: true,
910 escape: true,
911 ..Default::default()
912 },
913 )
914 });
915 }
916 let mut focused = None;
917 let mut open = None;
918 let mut next_offset = None;
919 let output = egui::ScrollArea::vertical()
920 .id_salt("archive-rows")
921 .auto_shrink([false, false])
922 .vertical_scroll_offset(self.list_offset)
923 .show_viewport(ui, |ui, viewport| {
924 let origin = ui.max_rect().min;
925 let clip = ui.clip_rect();
926 let width = (ui.available_width() - 24.0).max(0.0);
927 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
928 let point = ui.input(|i| i.pointer.interact_pos());
929 if active && let Some(point) = point {
930 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
931 let relative = press - origin;
932 let in_row = relative.x >= 0.0
933 && relative.x <= width
934 && relative.y >= 0.0
935 && relative.y < rows.len() as f32 * LIST_ROW;
936 if clip.contains(press) && !in_row && ui.input(|i| i.pointer.primary_pressed())
937 {
938 background.request_focus();
939 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
940 self.marquee = Some(Marquee {
941 origin: relative.to_pos2(),
942 base: if ctrl {
943 self.model.selected.clone()
944 } else {
945 BTreeSet::new()
946 },
947 moved: false,
948 });
949 if !ctrl {
950 self.model.selected.clear();
951 self.list_anchor = None;
952 self.list_cursor = None;
953 }
954 }
955 if let Some(drag) = &mut self.marquee {
956 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
957 drag.moved |= drag.origin.distance(end) > 3.0;
958 if drag.moved {
959 let rect = egui::Rect::from_two_pos(drag.origin, end);
960 self.model.selected = drag.base.clone();
961 if rect.left() < width && rect.right() > 0.0 {
962 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
963 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
964 .min(rows.len());
965 for row in rows.iter().take(last).skip(first) {
966 self.model.selected.extend(&row.ids);
967 }
968 if first < last {
969 self.list_anchor = Some(first);
970 self.list_cursor = Some(last - 1);
971 }
972 }
973 let speed = if point.y > clip.bottom() - 24.0 {
974 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
975 } else if point.y < clip.top() + 24.0 {
976 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
977 } else {
978 0.0
979 };
980 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
981 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
982 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
983 0.0,
984 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
985 ));
986 ui.ctx().request_repaint();
987 }
988 }
989 }
990 }
991 let first = (viewport.min.y / LIST_ROW).floor() as usize;
992 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
993 for index in first.min(rows.len())..last {
994 let row = &rows[index];
995 let rect = egui::Rect::from_min_size(
996 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
997 egui::vec2(width, LIST_ROW),
998 );
999 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
1000 let response = ui
1001 .interact(
1002 rect,
1003 egui::Id::unique(("archive-row", &row.path)),
1004 if active {
1005 egui::Sense::click()
1006 } else {
1007 egui::Sense::hover()
1008 },
1009 )
1010 .on_hover_text(&row.name);
1011 response.widget_info(|| {
1012 egui::WidgetInfo::selected(
1013 egui::Role::ListBoxOption,
1014 active,
1015 selected,
1016 &row.name,
1017 )
1018 });
1019 if response.has_focus() {
1020 focused = Some(index);
1021 ui.ctx().memory_mut(|memory| {
1022 memory.set_focus_lock_filter(
1023 response.id,
1024 egui::EventFilter {
1025 vertical_arrows: true,
1026 escape: true,
1027 ..Default::default()
1028 },
1029 )
1030 });
1031 }
1032 if selected {
1033 ui.painter().rect_filled(rect, 0, theme::SELECTED);
1034 }
1035 if response.clicked() {
1036 background.request_focus();
1037 let modifiers = ui.input(|i| i.modifiers);
1038 self.select_row(
1039 &rows,
1040 index,
1041 modifiers.ctrl || modifiers.command,
1042 modifiers.shift,
1043 );
1044 }
1045 if row.directory && response.double_clicked() {
1046 open = Some(row.path.clone());
1047 }
1048 ui.scope_builder(
1049 egui::UiBuilder::new()
1050 .max_rect(rect.shrink2(egui::vec2(0.0, 4.0)))
1051 .layout(Layout::left_to_right(Align::Center)),
1052 |ui| {
1053 ui.style_mut().interaction.selectable_labels = false;
1054 ui.add_space(16.0);
1055 theme::icon(
1056 ui,
1057 if row.directory {
1058 Icon::Folder
1059 } else {
1060 Icon::File
1061 },
1062 20.0,
1063 );
1064 // 암호가 걸린 항목은 이름 앞에 *를 붙여 표시함.
1065 let name = if row.encrypted {
1066 format!("*{}", row.name)
1067 } else {
1068 row.name.clone()
1069 };
1070 // 툴팁은 표시용 *를 빼고 실제 이름을 보여 줌.
1071 theme::bounded_text_hover(ui, &name, &row.name, name_width);
1072 theme::column_label(
1073 ui,
1074 if row.directory {
1075 "0 B".into()
1076 } else {
1077 row.bytes
1078 .map(present::bytes_text)
1079 .unwrap_or_else(|| "—".into())
1080 },
1081 96.0,
1082 Align::Max,
1083 );
1084 },
1085 );
1086 if active
1087 && self.list_cursor == Some(index)
1088 && (response.has_focus() || background.has_focus())
1089 {
1090 ui.painter().rect_stroke(
1091 rect.shrink(1.0),
1092 0,
1093 egui::Stroke::new(1.0, theme::BLUE),
1094 egui::StrokeKind::Inside,
1095 );
1096 }
1097 }
1098 if rows.is_empty() {
1099 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
1100 ui.centered_and_justified(|ui| {
1101 ui.label(if self.search.is_empty() {
1102 "이 폴더는 비어 있습니다"
1103 } else {
1104 "일치하는 항목이 없습니다"
1105 })
1106 });
1107 });
1108 }
1109 if let Some(drag) = &self.marquee
1110 && drag.moved
1111 && let Some(point) = point
1112 {
1113 let rect = egui::Rect::from_two_pos(
1114 origin + drag.origin.to_vec2(),
1115 point.clamp(clip.min, clip.max),
1116 );
1117 ui.painter().with_clip_rect(clip).rect(
1118 rect,
1119 0,
1120 theme::BLUE.gamma_multiply(0.16),
1121 egui::Stroke::new(1.0, theme::BLUE),
1122 egui::StrokeKind::Inside,
1123 );
1124 }
1125 });
1126 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
1127 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
1128 self.marquee = None;
1129 }
1130 let escape_from_list = self.list_focused
1131 && ui.ctx().memory(|memory| memory.focused()).is_none()
1132 && ui.input(|i| i.key_pressed(egui::Key::Escape));
1133 self.list_focused =
1134 active && (background.has_focus() || focused.is_some() || escape_from_list);
1135 if self.list_focused {
1136 if let Some(index) = focused {
1137 self.list_cursor = Some(index);
1138 }
1139 let modifiers = ui.input(|i| i.modifiers);
1140 let ctrl = modifiers.ctrl || modifiers.command;
1141 if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
1142 self.model.selected.clear();
1143 self.marquee = None;
1144 background.request_focus();
1145 }
1146 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
1147 self.model.selected = rows
1148 .iter()
1149 .flat_map(|row| row.ids.iter().copied())
1150 .collect();
1151 self.list_cursor = (!rows.is_empty()).then_some(0);
1152 self.list_anchor = self.list_cursor;
1153 }
1154 if !rows.is_empty() {
1155 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
1156 Some(1isize)
1157 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
1158 Some(-1)
1159 } else {
1160 None
1161 };
1162 if let Some(direction) = direction {
1163 let index = self.list_cursor.map_or(0, |index| {
1164 index.saturating_add_signed(direction).min(rows.len() - 1)
1165 });
1166 if ctrl && !modifiers.shift {
1167 self.list_cursor = Some(index);
1168 } else {
1169 self.select_row(&rows, index, ctrl, modifiers.shift);
1170 }
1171 background.request_focus();
1172 let top = index as f32 * LIST_ROW;
1173 if top < self.list_offset {
1174 self.list_offset = top;
1175 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
1176 self.list_offset = top + LIST_ROW - output.inner_rect.height();
1177 }
1178 ui.ctx().request_repaint();
1179 }
1180 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1181 let index = self
1182 .list_cursor
1183 .or(focused)
1184 .unwrap_or(0)
1185 .min(rows.len() - 1);
1186 if rows[index].directory {
1187 open = Some(rows[index].path.clone());
1188 }
1189 }
1190 }
1191 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
1192 open = Some(
1193 self.folder
1194 .rsplit_once('/')
1195 .map_or("", |(parent, _)| parent)
1196 .to_owned(),
1197 );
1198 }
1199 }
1200 if let Some(folder) = open {
1201 self.browse_folder(&folder);
1202 background.request_focus();
1203 }
1204 }
1205
1206 fn clear_list_selection(&mut self) {
1207 self.model.selected.clear();
1208 self.list_anchor = None;
1209 self.list_cursor = None;
1210 self.list_offset = 0.0;
1211 self.marquee = None;
1212 }
1213
1214 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
1215 if shift {
1216 let anchor = self
1217 .list_anchor
1218 .unwrap_or(self.list_cursor.unwrap_or(index))
1219 .min(rows.len() - 1);
1220 if !ctrl {
1221 self.model.selected.clear();
1222 }
1223 for row in &rows[anchor.min(index)..=anchor.max(index)] {
1224 self.model.selected.extend(&row.ids);
1225 }
1226 self.list_anchor = Some(anchor);
1227 } else {
1228 if !ctrl {
1229 self.model.selected.clear();
1230 }
1231 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
1232 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
1233 self.model
1234 .selected
1235 .retain(|id| !rows[index].ids.contains(id));
1236 } else {
1237 self.model.selected.extend(&rows[index].ids);
1238 }
1239 self.list_anchor = Some(index);
1240 }
1241 self.list_cursor = Some(index);
1242 }
1243
1244 fn result_visible(&self) -> bool {
1245 !self.dismissed
1246 && !self.model.busy()
1247 && self.last_request.as_ref().is_some_and(|request| {
1248 !matches!(request, Start::List { .. })
1249 || self.model.error.is_some()
1250 || self
1251 .model
1252 .terminal
1253 .as_ref()
1254 .is_some_and(|t| t.outcome != Outcome::Completed)
1255 })
1256 }
1257
1258 fn error_notice(ui: &mut egui::Ui, error: &str) {
1259 let response = theme::panel(theme::ERROR_BG)
1260 .show(ui, |ui| {
1261 ui.horizontal_wrapped(|ui| {
1262 theme::icon(ui, Icon::Error, 24.0);
1263 ui.colored_label(theme::ERROR, error);
1264 });
1265 })
1266 .response;
1267 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
1268 }
1269
1270 fn work_visible(&self) -> bool {
1271 self.model.busy() || self.result_visible() || (self.ui_error.is_some() && !self.create)
1272 }
1273
1274 fn work_window(&mut self, ctx: &egui::Context) {
1275 if !self.work_visible() {
1276 self.work = WorkWindow::default();
1277 return;
1278 }
1279 if ctx.embed_viewports() {
1280 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1281 return;
1282 }
1283 if self.model.challenge.is_some() {
1284 // 암호 입력 창은 메인 창 가운데에 뜨므로, 위에 떠 있는 진행 창이 입력란을
1285 // 가리지 않게 그동안 진행 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1286 self.work.open = false;
1287 return;
1288 }
1289 let id = egui::ViewportId::from_hash_of("archive-work");
1290 let (parent, parent_focused, now) = ctx.input(|i| {
1291 (
1292 i.viewport().outer_rect,
1293 i.viewport().focused.unwrap_or(false),
1294 i.time,
1295 )
1296 });
1297 let (child, child_focused) = ctx.input(|i| {
1298 i.raw.viewports.get(&id).map_or((None, false), |v| {
1299 (v.outer_rect, v.focused.unwrap_or(false))
1300 })
1301 });
1302 let size = egui::vec2(WORK_WIDTH, self.work.height);
1303 if !self.work.open {
1304 // 처음 열 때 부모 창 가운데에 둠. 암호 입력 뒤 다시 열 때는 기억한 위치에 둠.
1305 // Wayland처럼 위치를 알 수 없으면 창 관리자에 맡김.
1306 self.work.open = true;
1307 self.work.initial = parent.map(|p| match self.work.offset {
1308 Some(offset) => (p.min + offset).round(),
1309 None => (p.center() - size / 2.0).round(),
1310 });
1311 self.work.offset = self.work.initial.zip(parent).map(|(c, p)| c - p.min);
1312 self.work.parent = parent.map(|p| p.min);
1313 self.work.expected = self.work.initial;
1314 self.work.settle_until = now + 0.5;
1315 }
1316 if let (Some(parent), Some(child)) = (parent, child) {
1317 let parent_moved = self
1318 .work
1319 .parent
1320 .is_some_and(|p| (p - parent.min).length() > 0.5);
1321 let settled = self
1322 .work
1323 .expected
1324 .is_some_and(|e| (child.min - e).length() <= 2.0);
1325 if settled || now >= self.work.settle_until {
1326 self.work.settle_until = 0.0;
1327 }
1328 if parent_moved {
1329 if let Some(offset) = self.work.offset {
1330 let target = (parent.min + offset).round();
1331 ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
1332 self.work.expected = Some(target);
1333 self.work.settle_until = now + 0.5;
1334 }
1335 } else if self.work.settle_until == 0.0 && !settled {
1336 // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
1337 self.work.offset = Some(child.min - parent.min);
1338 self.work.expected = Some(child.min);
1339 }
1340 self.work.parent = Some(parent.min);
1341 }
1342 let title = if self.model.busy() {
1343 present::activity_text(
1344 &self.model,
1345 matches!(self.last_request, Some(Start::CreateZip { .. })),
1346 )
1347 .to_owned()
1348 } else {
1349 "작업 결과".to_owned()
1350 };
1351 let window_title = format!("{title} — Zipelo");
1352 let custom_frame = self.custom_frame;
1353 let mut builder = egui::ViewportBuilder::default()
1354 .with_title(window_title.clone())
1355 .with_decorations(!custom_frame)
1356 .with_inner_size(size)
1357 .with_resizable(false)
1358 .with_minimize_button(false)
1359 .with_maximize_button(false)
1360 .with_taskbar(false)
1361 // 앱을 쓰는 동안에만 부모 창 위에 유지함.
1362 .with_window_level(if parent_focused || child_focused {
1363 egui::WindowLevel::AlwaysOnTop
1364 } else {
1365 egui::WindowLevel::Normal
1366 });
1367 if let Some(position) = self.work.initial {
1368 builder = builder.with_position(position);
1369 }
1370 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1371 if ui.ctx().input(|i| i.viewport().close_requested()) {
1372 if self.model.busy() {
1373 ui.ctx()
1374 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1375 } else {
1376 self.dismissed = true;
1377 self.ui_error = None;
1378 self.model.input_error = None;
1379 }
1380 }
1381 if class == egui::ViewportClass::EmbeddedWindow {
1382 ui.set_width(WORK_WIDTH);
1383 self.work_area(ui);
1384 return None;
1385 }
1386 let mut chrome = 0.0;
1387 if custom_frame {
1388 window_frame::title_bar(
1389 ui,
1390 "work",
1391 &window_title,
1392 window_frame::Buttons {
1393 minimize: false,
1394 maximize: false,
1395 },
1396 );
1397 window_frame::edges(ui.ctx(), false);
1398 chrome = window_frame::TITLE_HEIGHT;
1399 }
1400 let margin = theme::PAD as f32;
1401 egui::CentralPanel::default()
1402 .frame(theme::panel(theme::PANEL).corner_radius(0))
1403 .show(ui, |ui| {
1404 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1405 Some(content.height() + 2.0 * margin + chrome)
1406 })
1407 .inner
1408 });
1409 if let Some(height) = height {
1410 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1411 if (height - self.work.height).abs() > 1.0 {
1412 self.work.height = height;
1413 }
1414 }
1415 }
1416
1417 fn work_area(&mut self, ui: &mut egui::Ui) {
1418 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
1419 let enabled = self.picker.is_none();
1420 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
1421 }
1422
1423 fn work_contents(&mut self, ui: &mut egui::Ui) {
1424 if self.model.busy() {
1425 self.progress(ui);
1426 } else if self.result_visible() {
1427 self.result(ui);
1428 }
1429 if !self.create
1430 && let Some(error) = &self.ui_error
1431 {
1432 Self::error_notice(ui, error);
1433 if error == present::FOLDER_ERROR
1434 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
1435 {
1436 self.open_picker(Purpose::Destination);
1437 }
1438 }
1439 if let Some(error) = &self.model.input_error {
1440 ui.colored_label(
1441 theme::ERROR,
1442 if error.starts_with("암호는") {
1443 error.as_str()
1444 } else {
1445 if matches!(self.last_request, Some(Start::CreateZip { .. })) {
1446 "저장 위치와 추가한 항목을 확인하세요"
1447 } else {
1448 "풀 위치와 선택한 항목을 확인하세요"
1449 }
1450 },
1451 );
1452 }
1453 }
1454
1455 fn progress(&mut self, ui: &mut egui::Ui) {
1456 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1457 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
1458 let title = present::activity_text(&self.model, creating);
1459 ui.strong(title);
1460 if let Some((stage, done, total, count)) = self.model.progress {
1461 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
1462 let processed = if stage == Stage::Read {
1463 String::new()
1464 } else {
1465 format!("{count}개 처리함, ")
1466 };
1467 if let Some(total) = total.filter(|n| *n > 0) {
1468 ui.scope(|ui| {
1469 ui.visuals_mut().extreme_bg_color = theme::BORDER;
1470 ui.add(
1471 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
1472 .fill(theme::BLUE)
1473 .desired_height(theme::SPACE * 2.0),
1474 );
1475 });
1476 ui.horizontal(|ui| {
1477 ui.label(format!(
1478 "{:.0}% / {processed}{} / {}",
1479 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
1480 present::bytes_text(done),
1481 present::bytes_text(total)
1482 ));
1483 self.cancel_action(ui, cancelling);
1484 });
1485 } else {
1486 theme::indeterminate(ui);
1487 ui.horizontal(|ui| {
1488 ui.label(format!("{processed}{}", present::bytes_text(done)));
1489 self.cancel_action(ui, cancelling);
1490 });
1491 }
1492 } else {
1493 theme::indeterminate(ui);
1494 ui.horizontal(|ui| {
1495 ui.label("작업을 진행하고 있습니다");
1496 self.cancel_action(ui, cancelling);
1497 });
1498 }
1499 }
1500
1501 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
1502 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1503 if theme::action(ui, "취소", false, !cancelling).clicked() {
1504 self.clear_password();
1505 self.model.cancel();
1506 }
1507 });
1508 }
1509
1510 fn result(&mut self, ui: &mut egui::Ui) {
1511 let t = self.model.terminal.clone();
1512 let listing = matches!(self.last_request, Some(Start::List { .. }));
1513 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1514 let warnings = if listing {
1515 Vec::new()
1516 } else {
1517 present::publication_warnings(
1518 t.as_ref(),
1519 self.model.confirmed,
1520 self.targets.as_ref(),
1521 &self.directories,
1522 &self.model.outputs,
1523 )
1524 };
1525 let success = self.model.confirmed
1526 && self.model.error.is_none()
1527 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
1528 && warnings.is_empty();
1529 let durability_warning = t
1530 .as_ref()
1531 .filter(|_| self.model.confirmed && !listing)
1532 .and_then(|t| present::durability_warning(t.durability));
1533 let durability_in_details = success
1534 && t.as_ref()
1535 .is_some_and(|t| t.durability == Durability::Unconfirmed);
1536 let cancelled =
1537 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
1538 let title = if success {
1539 if creating {
1540 "ZIP 파일을 만들었습니다"
1541 } else {
1542 "압축을 풀었습니다"
1543 }
1544 } else if cancelled {
1545 "작업을 취소했습니다"
1546 } else if listing {
1547 "압축파일을 열지 못했습니다"
1548 } else if creating {
1549 "ZIP 파일을 만들지 못했습니다"
1550 } else {
1551 "압축을 풀지 못했습니다"
1552 };
1553 let fill = if success {
1554 theme::SUCCESS_BG
1555 } else if cancelled {
1556 theme::STRIPE
1557 } else {
1558 theme::ERROR_BG
1559 };
1560 let mut choose = false;
1561 let mut retry = false;
1562 let mut reopen = false;
1563 let mut folder = false;
1564 theme::panel(fill).show(ui, |ui| {
1565 ui.horizontal(|ui| {
1566 theme::icon(
1567 ui,
1568 if success {
1569 Icon::Success
1570 } else if cancelled {
1571 Icon::Warning
1572 } else {
1573 Icon::Error
1574 },
1575 24.0,
1576 );
1577 ui.strong(title);
1578 });
1579 let max_height = WORK_RESULT_MAX_HEIGHT;
1580 egui::ScrollArea::vertical()
1581 .id_salt("result-message")
1582 .max_height(max_height)
1583 .show(ui, |ui| {
1584 if success {
1585 let path = match self.last_request.as_ref() {
1586 Some(Start::CreateZip { output_file, .. }) => {
1587 output_file.display().to_string()
1588 }
1589 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
1590 };
1591 theme::bounded_text(ui, &path, ui.available_width());
1592 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
1593 ui.label(if creating && code == ErrorCode::SourceChanged {
1594 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요".to_owned()
1595 } else {
1596 present::operation_text(present::error_text(code), creating)
1597 });
1598 } else if let Some(error) = &self.model.error {
1599 ui.label(present::operation_text(
1600 present::client_error_text(error),
1601 creating,
1602 ));
1603 }
1604 for warning in warnings
1605 .iter()
1606 .copied()
1607 .chain(durability_warning.filter(|_| !durability_in_details))
1608 {
1609 ui.horizontal_wrapped(|ui| {
1610 theme::icon(ui, Icon::Warning, 20.0);
1611 ui.colored_label(
1612 theme::WARNING,
1613 present::operation_text(warning, creating),
1614 );
1615 });
1616 }
1617 if !success
1618 && !listing
1619 && present::definitely_unsaved(
1620 t.as_ref(),
1621 self.model.confirmed,
1622 &self.model.outputs,
1623 )
1624 {
1625 ui.label(if creating {
1626 "ZIP 파일을 만들지 않았습니다"
1627 } else {
1628 "아무 파일도 풀지 않았습니다"
1629 });
1630 }
1631 if self.details {
1632 theme::panel(theme::STRIPE).show(ui, |ui| {
1633 if durability_in_details {
1634 if let Some(warning) = durability_warning {
1635 ui.label(present::operation_text(warning, creating));
1636 }
1637 }
1638 if let Some(t) = &t {
1639 for line in terminal_lines(t) {
1640 ui.label(line);
1641 }
1642 }
1643 if let Some(error) = &self.model.error {
1644 ui.label(error);
1645 }
1646 for (name, state) in &self.model.outputs {
1647 theme::bounded_text(
1648 ui,
1649 &format!("{name}: {}", disposition_label(*state)),
1650 ui.available_width(),
1651 );
1652 }
1653 });
1654 }
1655 });
1656 let conflict = t
1657 .as_ref()
1658 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
1659 && !creating;
1660 let uncertain = warnings.contains(&present::UNCERTAIN);
1661 if conflict && uncertain {
1662 let response = ui.checkbox(
1663 &mut self.checked_destination,
1664 "기존 풀 위치 폴더를 확인했습니다",
1665 );
1666 theme::focus(&response);
1667 }
1668 ui.horizontal(|ui| {
1669 if theme::action(
1670 ui,
1671 if self.details {
1672 "자세히 닫기"
1673 } else {
1674 "자세히 보기"
1675 },
1676 false,
1677 true,
1678 )
1679 .clicked()
1680 {
1681 self.details = !self.details;
1682 }
1683 let action = if success {
1684 Some(("폴더 열기", true))
1685 } else if conflict {
1686 Some((
1687 if self
1688 .model
1689 .list_id
1690 .as_ref()
1691 .is_some_and(|id| id.format == Format::Gzip)
1692 {
1693 "다른 이름으로 저장"
1694 } else {
1695 "다른 폴더에 풀기"
1696 },
1697 !uncertain || self.checked_destination,
1698 ))
1699 } else if t
1700 .as_ref()
1701 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1702 {
1703 Some((
1704 if creating {
1705 "다시 만들기"
1706 } else {
1707 "압축파일 다시 열기"
1708 },
1709 true,
1710 ))
1711 } else if !cancelled && (!uncertain || listing) {
1712 Some(("다시 시도", true))
1713 } else {
1714 None
1715 };
1716 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1717 if confirm {
1718 self.dismissed = true;
1719 self.ui_error = None;
1720 self.model.input_error = None;
1721 }
1722 if primary {
1723 match action.map(|(label, _)| label) {
1724 Some("폴더 열기") => folder = true,
1725 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
1726 choose = true
1727 }
1728 Some("압축파일 다시 열기") => reopen = true,
1729 Some("다시 시도" | "다시 만들기") => retry = true,
1730 _ => {}
1731 }
1732 }
1733 });
1734 });
1735 if choose {
1736 self.open_picker(Purpose::Retry);
1737 }
1738 if retry {
1739 self.retry();
1740 }
1741 if reopen {
1742 if let Some(path) = self.model.archive.clone() {
1743 self.open_path(path);
1744 }
1745 }
1746 if folder {
1747 let path = match self.last_request.as_ref() {
1748 Some(Start::CreateZip { output_file, .. }) => {
1749 output_file.parent().unwrap_or(Path::new("/"))
1750 }
1751 _ => self.destination.as_path(),
1752 };
1753 match present::folder_command(path).spawn() {
1754 Ok(mut child) => {
1755 std::thread::spawn(move || {
1756 let _ = child.wait();
1757 });
1758 }
1759 Err(_) => {
1760 self.ui_error = Some(
1761 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1762 )
1763 }
1764 }
1765 }
1766 }
1767
1768 fn create_dialog(&mut self, ctx: &egui::Context) {
1769 let mut compress = false;
1770 let mut pick = None;
1771 let mut cancel = false;
1772 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1773 ui.set_width((ctx.content_rect().width() - 64.0).min(600.0));
1774 ui.horizontal(|ui| {
1775 ui.heading("ZIP 만들기");
1776 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1777 let close = theme::icon_button(ui, "닫기", theme::CLOSE, true);
1778 theme::focus(&close);
1779 cancel = close.clicked();
1780 });
1781 });
1782 if let Some(error) = &self.ui_error {
1783 Self::error_notice(ui, error);
1784 }
1785 egui::ScrollArea::vertical()
1786 .id_salt("create-fields")
1787 .max_height(
1788 (ctx.content_rect().height()
1789 - 180.0
1790 - if self.ui_error.is_some() { 96.0 } else { 0.0 })
1791 .max(120.0),
1792 )
1793 .show(ui, |ui| {
1794 ui.add_space(16.0);
1795 let frame = theme::panel(theme::STRIPE)
1796 .stroke(egui::Stroke::new(1.0, theme::DASH))
1797 .inner_margin(egui::Margin::same(24));
1798 let area = frame
1799 .show(ui, |ui| {
1800 ui.set_min_size(egui::vec2(ui.available_width(), 144.0));
1801 ui.vertical_centered(|ui| {
1802 theme::icon(ui, Icon::File, 44.0);
1803 ui.add_space(16.0);
1804 ui.label(
1805 RichText::new("파일이나 폴더를 여기에 끌어 놓으세요")
1806 .size(theme::FONT_BODY),
1807 );
1808 });
1809 })
1810 .response;
1811 let drop = ui.interact(
1812 area.rect,
1813 egui::Id::unique("zip-source-drop"),
1814 egui::Sense::click(),
1815 );
1816 theme::focus(&drop);
1817 drop.widget_info(|| {
1818 egui::WidgetInfo::labeled(egui::Role::Button, true, "파일 추가")
1819 });
1820 if drop.clicked() {
1821 pick = Some(Purpose::Files);
1822 }
1823 egui::ScrollArea::vertical()
1824 .id_salt("zip-sources")
1825 .max_height(86.0)
1826 .show(ui, |ui| {
1827 let mut remove = None;
1828 for (index, path) in self.sources.iter().enumerate() {
1829 ui.horizontal(|ui| {
1830 theme::icon(
1831 ui,
1832 if path.is_dir() {
1833 Icon::Folder
1834 } else {
1835 Icon::File
1836 },
1837 20.0,
1838 );
1839 let name =
1840 path.file_name().unwrap_or_default().to_string_lossy();
1841 theme::bounded_text(
1842 ui,
1843 &name,
1844 (ui.available_width() - 72.0).max(0.0),
1845 )
1846 .on_hover_text(path.display().to_string());
1847 if ui.button("빼기").clicked() {
1848 remove = Some(index);
1849 }
1850 });
1851 }
1852 if let Some(index) = remove {
1853 self.sources.remove(index);
1854 }
1855 });
1856 ui.horizontal(|ui| {
1857 if theme::action(ui, "파일 추가", false, true).clicked() {
1858 pick = Some(Purpose::Files);
1859 }
1860 if theme::action(ui, "폴더 추가", false, true).clicked() {
1861 pick = Some(Purpose::Folder);
1862 }
1863 });
1864 ui.add_space(16.0);
1865 ui.horizontal(|ui| {
1866 theme::icon(ui, Icon::Lock, 24.0);
1867 ui.strong("암호화");
1868 });
1869 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
1870 theme::focus(&check);
1871 ui.add_space(16.0);
1872 });
1873 let (dismiss, confirm) =
1874 theme::action_pair(ui, "취소", Some(("압축하기", !self.sources.is_empty())));
1875 cancel |= dismiss;
1876 compress = confirm;
1877 });
1878 if cancel || modal.should_close() {
1879 self.create = false;
1880 self.ui_error = None;
1881 return;
1882 }
1883 if let Some(purpose) = pick {
1884 self.open_picker(purpose);
1885 }
1886 if compress {
1887 self.open_picker(Purpose::SaveZip);
1888 }
1889 }
1890
1891 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
1892 let (_, attempt, encrypt) = self.model.challenge.unwrap();
1893 let mut submit = false;
1894 let mut cancel = false;
1895 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
1896 id == egui::Id::unique("archive-password-input")
1897 || id == egui::Id::unique("archive-password-confirm")
1898 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
1899 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
1900 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
1901 ui.heading(if encrypt {
1902 "ZIP 암호 설정"
1903 } else {
1904 "암호가 필요합니다"
1905 });
1906 if encrypt {
1907 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
1908 } else if let Some(path) = &self.model.archive {
1909 ui.label(format!(
1910 "{}은 암호로 보호되어 있습니다.",
1911 present::middle_text(
1912 &path.file_name().unwrap_or_default().to_string_lossy(),
1913 24
1914 )
1915 ));
1916 }
1917 ui.horizontal(|ui| {
1918 ui.label("암호");
1919 let edit = ui.add(
1920 egui::TextEdit::singleline(&mut self.password)
1921 .password(!self.password_visible)
1922 .id(egui::Id::unique("archive-password-input"))
1923 .char_limit(1024)
1924 .desired_width(232.0),
1925 );
1926 theme::focus(&edit);
1927 if new_challenge {
1928 edit.request_focus();
1929 }
1930 if theme::action(
1931 ui,
1932 if self.password_visible {
1933 "숨기기"
1934 } else {
1935 "보기"
1936 },
1937 false,
1938 true,
1939 )
1940 .clicked()
1941 {
1942 self.password_visible = !self.password_visible;
1943 }
1944 });
1945 if encrypt {
1946 ui.horizontal(|ui| {
1947 ui.label("암호 확인");
1948 let edit = ui.add(
1949 egui::TextEdit::singleline(&mut self.password_confirm)
1950 .password(!self.password_visible)
1951 .id(egui::Id::unique("archive-password-confirm"))
1952 .char_limit(1024)
1953 .desired_width(232.0),
1954 );
1955 theme::focus(&edit);
1956 });
1957 if self.password != self.password_confirm {
1958 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
1959 }
1960 } else if attempt > 1 {
1961 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
1962 }
1963 if self.password.len() > 1024 {
1964 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
1965 }
1966 let valid = !self.password.is_empty()
1967 && self.password.len() <= 1024
1968 && (!encrypt || self.password == self.password_confirm);
1969 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
1970 cancel = actions.0;
1971 submit = actions.1 || (valid && password_enter);
1972 });
1973 if modal.should_close() || cancel {
1974 self.clear_password();
1975 self.model.cancel();
1976 } else if submit {
1977 let password = std::mem::take(&mut self.password);
1978 self.clear_password();
1979 self.model.password(password);
1980 }
1981 }
1982
1983 fn close_dialog(&mut self, ctx: &egui::Context) {
1984 if self.model.close == Close::Open || self.model.close == Close::Allowed {
1985 return;
1986 }
1987 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
1988 ui.set_width(420.0);
1989 match self.model.close {
1990 Close::Confirm => {
1991 ui.heading("작업 중 닫기");
1992 ui.label("작업을 취소하고 닫을까요?");
1993 ui.horizontal(|ui| {
1994 if theme::action(ui, "계속 작업", false, true).clicked() {
1995 self.model.keep_open();
1996 }
1997 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
1998 self.clear_password();
1999 self.model.confirm_close();
2000 }
2001 });
2002 }
2003 Close::Waiting => {
2004 ui.heading("종료 확인 중");
2005 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
2006 if theme::action(ui, "닫기 취소", false, true).clicked() {
2007 self.model.keep_open();
2008 }
2009 }
2010 Close::Review => {
2011 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
2012 ui.heading("결과 확인 후 닫기");
2013 let wrote = self
2014 .last_request
2015 .as_ref()
2016 .is_some_and(|request| !matches!(request, Start::List { .. }));
2017 ui.label(if !wrote {
2018 "프로그램을 닫을까요?".to_owned()
2019 } else if self.model.confirmed {
2020 "작업 결과를 확인한 뒤 닫으세요".to_owned()
2021 } else {
2022 present::operation_text(present::UNCERTAIN, creating)
2023 });
2024 egui::ScrollArea::vertical()
2025 .max_height(160.0)
2026 .show(ui, |ui| {
2027 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
2028 ui.colored_label(
2029 theme::ERROR,
2030 present::operation_text(present::error_text(code), creating),
2031 );
2032 }
2033 if wrote {
2034 for warning in present::warnings(
2035 self.model.terminal.as_ref(),
2036 self.model.confirmed,
2037 self.targets.as_ref(),
2038 &self.directories,
2039 &self.model.outputs,
2040 ) {
2041 ui.colored_label(
2042 theme::WARNING,
2043 present::operation_text(warning, creating),
2044 );
2045 }
2046 }
2047 });
2048 ui.horizontal(|ui| {
2049 if theme::action(ui, "계속 작업", false, true).clicked() {
2050 self.model.keep_open();
2051 }
2052 if theme::action(ui, "닫기", true, true).clicked() {
2053 self.model.acknowledge_close();
2054 }
2055 });
2056 }
2057 _ => {}
2058 }
2059 });
2060 }
2061}
2062
2063impl eframe::App for ArchiveApp {
2064 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
2065 self.show(root);
2066 }
2067
2068 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
2069 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
2070 if std::mem::take(&mut self.release_after_move) {
2071 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
2072 raw_input.events.insert(
2073 0,
2074 egui::Event::PointerButton {
2075 pos,
2076 button: egui::PointerButton::Primary,
2077 pressed: false,
2078 modifiers: ctx.input(|i| i.modifiers),
2079 },
2080 );
2081 }
2082 }
2083}
2084impl Drop for ArchiveApp {
2085 fn drop(&mut self) {
2086 self.clear_password();
2087 }
2088}