team-ljyzipelo

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