team-ljyzipelo

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