team-ljyzipelo

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