team-ljyzipelo

공개
3,430줄139 KB
1#[cfg(all(feature = "ui-fixture", debug_assertions))]
2#[path = "../../../tests/rust-app-ui/scenarios.rs"]
3pub mod scenarios;
4
5use crate::{
6 archive_browser as browser,
7 archive_dialog::{
8 DIALOG_UNAVAILABLE, DialogAnswer, DialogRequest, Dialogs, NativeDialogs, PendingDialog,
9 Purpose,
10 },
11 archive_present as present,
12 archive_theme::{self as theme, Icon},
13 archive_ui::*,
14 window_frame,
15};
16use eframe::egui::{self, Align, Layout, RichText};
17use std::{
18 collections::BTreeSet,
19 path::{Path, PathBuf},
20};
21
22const WORK_WIDTH: f32 = 480.0;
23const CREATE_WIDTH: f32 = 560.0;
24/// 처음 열 때의 높이. 그다음부터는 내용 높이에 맞춤.
25const CREATE_MIN_HEIGHT: f32 = 560.0;
26const CREATE_LIST_HEIGHT: f32 = 288.0;
27
28/// ZIP 만들기 창 목록의 한 행. 디스크에서 읽은 파일이나 폴더임.
29#[derive(Clone)]
30struct SourceRow {
31 name: String,
32 directory: bool,
33 bytes: Option<u64>,
34}
35
36fn source_row(path: &Path) -> SourceRow {
37 let metadata = std::fs::symlink_metadata(path).ok();
38 SourceRow {
39 name: path
40 .file_name()
41 .map(|name| name.to_string_lossy().into_owned())
42 .unwrap_or_default(),
43 // 심볼릭 링크는 따라가지 않으므로 폴더로 보이지 않음.
44 directory: metadata.as_ref().is_some_and(|m| m.is_dir()),
45 bytes: metadata.filter(|m| m.is_file()).map(|m| m.len()),
46 }
47}
48
49/// 폴더 안 항목을 메인 목록과 같은 순서(폴더 먼저, 이름순)로 읽음. 읽지 못하면 None.
50fn read_source_dir(dir: &Path) -> Option<std::rc::Rc<Vec<SourceRow>>> {
51 let mut rows = std::fs::read_dir(dir)
52 .ok()?
53 .filter_map(Result::ok)
54 .map(|entry| source_row(&entry.path()))
55 .collect::<Vec<_>>();
56 rows.sort_by(|a, b| {
57 b.directory
58 .cmp(&a.directory)
59 .then_with(|| a.name.cmp(&b.name))
60 });
61 Some(std::rc::Rc::new(rows))
62}
63
64/// 덮어쓴 뒤 버려 메모리에 암호가 남지 않게 함.
65fn wipe(value: &mut String) {
66 let mut bytes = std::mem::take(value).into_bytes();
67 bytes.fill(0);
68}
69const WORK_MIN_HEIGHT: f32 = 96.0;
70const WORK_MAX_HEIGHT: f32 = 520.0;
71const WORK_RESULT_MAX_HEIGHT: f32 = 220.0;
72
73/// 작업 진행·결과를 보여주는 자식 창의 위치 상태.
74/// 부모 창 기준 상대 위치를 기억해 두고, 부모 창이 움직이면 같은 상대 위치로 따라감.
75struct WorkWindow {
76 open: bool,
77 initial: Option<egui::Pos2>,
78 offset: Option<egui::Vec2>,
79 parent: Option<egui::Pos2>,
80 expected: Option<egui::Pos2>,
81 settle_until: f64,
82 height: f32,
83}
84
85impl Default for WorkWindow {
86 fn default() -> Self {
87 Self {
88 open: false,
89 initial: None,
90 offset: None,
91 parent: None,
92 expected: None,
93 settle_until: 0.0,
94 height: 168.0,
95 }
96 }
97}
98
99impl WorkWindow {
100 /// 부모 창 가운데에 열고, 사용자가 옮긴 상대 위치를 유지한 채 부모 창을 따라가게 함.
101 /// 앱을 쓰는 동안에만 부모 위에 두고, 처음 위치를 담은 ViewportBuilder를 돌려줌.
102 /// Wayland처럼 창 위치를 알 수 없으면 위치는 창 관리자에 맡김.
103 fn builder(
104 &mut self,
105 ctx: &egui::Context,
106 id: egui::ViewportId,
107 size: egui::Vec2,
108 title: &str,
109 decorations: bool,
110 native_dialog_open: bool,
111 ) -> egui::ViewportBuilder {
112 let (parent, parent_focused, now) = ctx.input(|i| {
113 (
114 i.viewport().outer_rect,
115 i.viewport().focused.unwrap_or(false),
116 i.time,
117 )
118 });
119 let (child, child_focused) = ctx.input(|i| {
120 i.raw.viewports.get(&id).map_or((None, false), |v| {
121 (v.outer_rect, v.focused.unwrap_or(false))
122 })
123 });
124 let opening = !self.open;
125 if opening {
126 // 처음 열 때 부모 창 가운데에 둠. 닫혔다 다시 열 때는 기억한 위치에 둠.
127 self.open = true;
128 self.initial = parent.map(|p| match self.offset {
129 Some(offset) => (p.min + offset).round(),
130 None => (p.center() - size / 2.0).round(),
131 });
132 self.offset = self.initial.zip(parent).map(|(c, p)| c - p.min);
133 self.parent = parent.map(|p| p.min);
134 self.expected = self.initial;
135 self.settle_until = now + 0.5;
136 }
137 if let (Some(parent), Some(child)) = (parent, child) {
138 let parent_moved = self.parent.is_some_and(|p| (p - parent.min).length() > 0.5);
139 let settled = self
140 .expected
141 .is_some_and(|e| (child.min - e).length() <= 2.0);
142 if settled || now >= self.settle_until {
143 self.settle_until = 0.0;
144 }
145 if parent_moved {
146 if let Some(offset) = self.offset {
147 let target = (parent.min + offset).round();
148 ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
149 self.expected = Some(target);
150 self.settle_until = now + 0.5;
151 }
152 } else if self.settle_until == 0.0 && !settled {
153 // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
154 self.offset = Some(child.min - parent.min);
155 self.expected = Some(child.min);
156 }
157 self.parent = Some(parent.min);
158 }
159 let mut builder = egui::ViewportBuilder::default()
160 .with_title(title)
161 .with_icon(crate::app_icon::load())
162 .with_decorations(decorations)
163 .with_inner_size(size)
164 .with_resizable(false)
165 .with_minimize_button(false)
166 .with_maximize_button(false)
167 .with_taskbar(false)
168 .with_window_level(
169 if !native_dialog_open && (opening || parent_focused || child_focused) {
170 egui::WindowLevel::AlwaysOnTop
171 } else {
172 egui::WindowLevel::Normal
173 },
174 );
175 if let Some(position) = self.initial {
176 builder = builder.with_position(position);
177 }
178 builder
179 }
180}
181
182struct Marquee {
183 // 스크롤 중에도 시작점을 목록 좌표로 유지함.
184 origin: egui::Pos2,
185 base: BTreeSet<u32>,
186 moved: bool,
187}
188
189/// 파일 목록 한 행의 높이. 행 안의 크기 칸(theme::ROW)이 위아래 2px 여백으로 들어감.
190const LIST_ROW: f32 = 36.0;
191
192pub struct ArchiveApp {
193 pub model: Model,
194 factory: Box<dyn Factory>,
195 destination: PathBuf,
196 automatic_destination: bool,
197 owned_destination: Option<PathBuf>,
198 gzip_name: String,
199 sources: Vec<PathBuf>,
200 zip_folder: PathBuf,
201 zip_name: String,
202 password: String,
203 password_confirm: String,
204 password_visible: bool,
205 password_challenge: Option<u64>,
206 conflict_challenge: Option<(u64, u64)>,
207 conflict_apply: bool,
208 aes256: bool,
209 create: bool,
210 selected_only: bool,
211 method: Method,
212 seven_zip: bool,
213 dialogs: Box<dyn Dialogs>,
214 picker: Option<(Purpose, std::sync::mpsc::Receiver<DialogAnswer>)>,
215 preview_open: bool,
216 preview_name: String,
217 preview_text: String,
218 preview_texture: Option<egui::TextureHandle>,
219 preview_return_focus: Option<egui::Id>,
220 preview_initial_focus: bool,
221 work: WorkWindow,
222 work_in_parent: bool,
223 create_win: WorkWindow,
224 /// ZIP 만들기 창에서 보고 있는 폴더 (고른 폴더 기준 상대 경로, 비어 있으면 최상위).
225 create_folder: String,
226 create_listing: Option<(PathBuf, Option<std::rc::Rc<Vec<SourceRow>>>)>,
227 /// 마지막으로 누른 폴더 행 (이름, 프레임 번호, 시각). 두 번 누름을 직접 판단할 때 씀.
228 create_last_click: Option<(String, u64, f64)>,
229 /// ZIP 만들기 목록에서 한 번 눌러 선택한 항목 이름. 보고 있는 폴더가 바뀌면 지움.
230 create_selected: Option<String>,
231 zip_password: String,
232 zip_password_confirm: String,
233 zip_password_visible: bool,
234 /// 암호를 지웠으면 입력창의 실행 취소 기록도 다음 그리기 전에 지움.
235 forget_password_history: Vec<&'static str>,
236 /// 작업을 시작한 뒤 작업자가 암호를 요청하면 넘길 암호. 넘기거나 작업이 끝나면 지움.
237 pending_zip_password: Option<String>,
238 custom_frame: bool,
239 release_after_move: bool,
240 folder: String,
241 search: String,
242 list_anchor: Option<usize>,
243 list_cursor: Option<usize>,
244 list_offset: f32,
245 list_focused: bool,
246 marquee: Option<Marquee>,
247 last_request: Option<Start>,
248 recovery_warning: Option<(PathBuf, String)>,
249 targets: Option<BTreeSet<String>>,
250 directories: BTreeSet<String>,
251 dismissed: bool,
252 details: bool,
253 checked_destination: bool,
254 ui_error: Option<String>,
255 initialized: bool,
256 #[cfg(all(feature = "ui-fixture", debug_assertions))]
257 scenario_marquee: Option<egui::Rect>,
258 #[cfg(all(feature = "ui-fixture", debug_assertions))]
259 scenario_sources: Option<std::rc::Rc<Vec<SourceRow>>>,
260}
261
262impl ArchiveApp {
263 pub fn new(factory: Box<dyn Factory>, startup: Option<PathBuf>, _fixture: bool) -> Self {
264 let mut app = Self {
265 model: Model::default(),
266 factory,
267 destination: PathBuf::new(),
268 automatic_destination: true,
269 owned_destination: None,
270 gzip_name: String::new(),
271 sources: Vec::new(),
272 zip_folder: present::home_directory(),
273 zip_name: String::new(),
274 password: String::new(),
275 password_confirm: String::new(),
276 password_visible: false,
277 password_challenge: None,
278 conflict_challenge: None,
279 conflict_apply: false,
280 aes256: false,
281 create: false,
282 selected_only: false,
283 method: Method::Deflate,
284 seven_zip: false,
285 dialogs: Box::new(NativeDialogs),
286 picker: None,
287 preview_open: false,
288 preview_name: String::new(),
289 preview_text: String::new(),
290 preview_texture: None,
291 preview_return_focus: None,
292 preview_initial_focus: false,
293 work: WorkWindow::default(),
294 work_in_parent: false,
295 create_win: WorkWindow::default(),
296 create_folder: String::new(),
297 create_listing: None,
298 create_last_click: None,
299 create_selected: None,
300 zip_password: String::new(),
301 zip_password_confirm: String::new(),
302 zip_password_visible: false,
303 forget_password_history: Vec::new(),
304 pending_zip_password: None,
305 custom_frame: false,
306 release_after_move: false,
307 folder: String::new(),
308 search: String::new(),
309 list_anchor: None,
310 list_cursor: None,
311 list_offset: 0.0,
312 list_focused: false,
313 marquee: None,
314 last_request: None,
315 recovery_warning: None,
316 targets: None,
317 directories: BTreeSet::new(),
318 dismissed: false,
319 details: false,
320 checked_destination: false,
321 ui_error: None,
322 initialized: false,
323 #[cfg(all(feature = "ui-fixture", debug_assertions))]
324 scenario_marquee: None,
325 #[cfg(all(feature = "ui-fixture", debug_assertions))]
326 scenario_sources: None,
327 };
328 if let Some(path) = startup {
329 app.open_path(path);
330 }
331 app
332 }
333
334 pub fn set_dialogs(&mut self, dialogs: Box<dyn Dialogs>) {
335 self.dialogs = dialogs;
336 }
337
338 /// 창 순서를 지정할 수 없는 환경에서는 부모 안에 작업 화면을 그림.
339 pub fn set_work_window_in_parent(&mut self, enabled: bool) {
340 self.work_in_parent = enabled;
341 }
342
343 /// 운영체제가 창 테두리를 그려 주지 않을 때(GNOME Wayland) 제목 표시줄을 직접 그림.
344 pub fn set_custom_frame(&mut self, custom: bool) {
345 self.custom_frame = custom;
346 }
347
348 pub fn browse_folder(&mut self, folder: &str) {
349 self.folder = folder.trim_matches('/').to_owned();
350 self.search.clear();
351 self.clear_list_selection();
352 }
353
354 pub fn show_create(&mut self, encrypted: bool) {
355 if !self.model.busy() {
356 self.create = true;
357 self.aes256 = encrypted && !self.seven_zip;
358 self.ui_error = None;
359 }
360 }
361
362 fn clear_password(&mut self) {
363 for value in [&mut self.password, &mut self.password_confirm] {
364 let mut bytes = std::mem::take(value).into_bytes();
365 bytes.fill(0);
366 }
367 self.password_visible = false;
368 // 이 함수는 암호 요청이 없는 동안 매 프레임 불리므로, 암호 창을 쓴 뒤에만 기록을 지움.
369 if self.password_challenge.is_some() {
370 self.forget_password_history
371 .extend(["archive-password-input", "archive-password-confirm"]);
372 }
373 }
374
375 /// 지운 암호가 입력창의 실행 취소(Ctrl+Z)로 되살아나지 않게 egui가 보관하는
376 /// 입력창 상태(실행 취소 기록 포함)를 지움.
377 fn forget_password_history(&mut self, ctx: &egui::Context) {
378 if self.forget_password_history.is_empty() {
379 return;
380 }
381 let names = std::mem::take(&mut self.forget_password_history);
382 ctx.data_mut(|data| {
383 for name in names {
384 data.remove::<egui::text_edit::TextEditState>(egui::Id::unique(name));
385 }
386 });
387 }
388
389 fn clear_zip_password(&mut self) {
390 wipe(&mut self.zip_password);
391 wipe(&mut self.zip_password_confirm);
392 if let Some(mut pending) = self.pending_zip_password.take() {
393 wipe(&mut pending);
394 }
395 self.zip_password_visible = false;
396 self.forget_password_history
397 .extend(["zip-password-input", "zip-password-confirm"]);
398 }
399
400 /// 암호로 보호하지 않거나, 두 암호가 같고 1~1024바이트이면 만들 수 있음.
401 fn zip_password_ready(&self) -> bool {
402 !self.aes256
403 || (!self.zip_password.is_empty()
404 && self.zip_password.len() <= 1024
405 && self.zip_password == self.zip_password_confirm)
406 }
407
408 fn close_create(&mut self) {
409 self.create = false;
410 self.ui_error = None;
411 self.clear_zip_password();
412 self.create_win = WorkWindow::default();
413 }
414
415 /// 압축하기: 묶을 폴더를 운영체제 폴더 선택 창에서 고른 뒤 ZIP 만들기 창을 엶.
416 fn choose_zip_folder(&mut self) {
417 if self.model.busy() || self.picker.is_some() {
418 return;
419 }
420 // 이미 열린 ZIP 만들기 창의 목록과 암호 설정은 새 폴더를 실제로 고른 뒤에만 바꿈.
421 // 선택을 취소하면 그대로 남음(apply_picker의 Purpose::Folder).
422 self.open_picker(Purpose::Folder);
423 }
424
425 /// 폴더 하나를 골랐으면 그 폴더 안을 목록으로 보여 줌. 여러 항목이면 그 항목들을 보여 줌.
426 fn create_root(&self) -> Option<PathBuf> {
427 (self.sources.len() == 1 && self.sources[0].is_dir()).then(|| self.sources[0].clone())
428 }
429
430 fn create_rows(&mut self) -> Option<std::rc::Rc<Vec<SourceRow>>> {
431 #[cfg(all(feature = "ui-fixture", debug_assertions))]
432 if let Some(rows) = &self.scenario_sources {
433 return Some(rows.clone());
434 }
435 let Some(root) = self.create_root() else {
436 return Some(std::rc::Rc::new(
437 self.sources.iter().map(|path| source_row(path)).collect(),
438 ));
439 };
440 let dir = if self.create_folder.is_empty() {
441 root
442 } else {
443 root.join(&self.create_folder)
444 };
445 // 프레임마다 디스크를 읽지 않도록 보고 있는 폴더가 바뀔 때만 다시 읽음.
446 if self
447 .create_listing
448 .as_ref()
449 .is_none_or(|(path, _)| path != &dir)
450 {
451 let rows = read_source_dir(&dir);
452 self.create_listing = Some((dir, rows));
453 }
454 self.create_listing
455 .as_ref()
456 .and_then(|(_, rows)| rows.clone())
457 }
458
459 pub fn open_path(&mut self, archive: PathBuf) {
460 if self.model.busy() {
461 return;
462 }
463 if self
464 .recovery_warning
465 .as_ref()
466 .is_some_and(|(path, _)| path != &archive)
467 {
468 self.recovery_warning = None;
469 }
470 self.clear_password();
471 self.destination = present::default_destination(&archive);
472 self.automatic_destination = true;
473 self.gzip_name = present::gzip_output_name(&archive);
474 self.selected_only = false;
475 self.folder.clear();
476 self.search.clear();
477 self.clear_list_selection();
478 self.targets = None;
479 self.directories.clear();
480 self.start(Start::List { archive });
481 }
482
483 fn start(&mut self, request: Start) -> bool {
484 // 파일 선택 창이 응답을 기다리는 동안에는 어느 창에서도 새 작업을 시작하지 않음.
485 if self.picker.is_some() {
486 return false;
487 }
488 if matches!(request, Start::RecoverZip { .. }) {
489 self.work = WorkWindow {
490 height: 480.0,
491 ..WorkWindow::default()
492 };
493 }
494 self.last_request = Some(request.clone());
495 self.dismissed = false;
496 self.details = false;
497 self.checked_destination = false;
498 self.ui_error = None;
499 self.model.begin(request, self.factory.as_mut())
500 }
501
502 pub fn choose_destination(&mut self, path: PathBuf) {
503 self.destination = path;
504 self.automatic_destination = false;
505 self.ui_error = None;
506 }
507
508 pub fn add_sources(&mut self, paths: Vec<PathBuf>) {
509 if self.model.busy() {
510 return;
511 }
512 let mut validated = Vec::new();
513 for path in paths {
514 let Ok(metadata) = std::fs::symlink_metadata(&path) else {
515 self.ui_error = Some("파일이나 폴더를 찾지 못했습니다. 다시 선택하세요".into());
516 return;
517 };
518 if metadata.file_type().is_symlink() || !(metadata.is_file() || metadata.is_dir()) {
519 self.ui_error = Some("일반 파일과 폴더만 추가할 수 있습니다".into());
520 return;
521 }
522 let Ok(path) = path.canonicalize() else {
523 return;
524 };
525 if path.to_str().is_none()
526 || !path
527 .file_name()
528 .and_then(|name| name.to_str())
529 .is_some_and(valid_leaf)
530 {
531 self.ui_error = Some("파일이나 폴더의 이름을 확인하세요".into());
532 return;
533 }
534 validated.push(crate::archive_path::worker_path(&path));
535 }
536 let paths = validated;
537 if self.sources.is_empty() {
538 if let Some(first) = paths.first() {
539 self.zip_folder = first.parent().unwrap_or(Path::new("/")).to_path_buf();
540 let name = if first.is_dir() {
541 first.file_name()
542 } else {
543 first.file_stem()
544 };
545 self.zip_name = format!(
546 "{}.{}",
547 name.unwrap_or_default().to_string_lossy(),
548 if self.seven_zip { "7z" } else { "zip" }
549 );
550 }
551 }
552 for path in paths {
553 if !self.sources.contains(&path) {
554 self.sources.push(path);
555 }
556 }
557 self.create_folder.clear();
558 self.create_listing = None;
559 self.create_selected = None;
560 self.create = true;
561 }
562
563 pub fn begin_extract(&mut self) -> bool {
564 self.selected_only = !self.model.selected.is_empty();
565 let selection = if self.selected_only {
566 Selection::EntryIds(
567 browser::expand_selection(&self.model.entries, &self.model.selected)
568 .into_iter()
569 .collect(),
570 )
571 } else {
572 Selection::All
573 };
574 self.extract_selection(selection)
575 }
576
577 fn extract_selection(&mut self, selection: Selection) -> bool {
578 if !self.model.can_extract()
579 || matches!(&selection, Selection::EntryIds(ids) if ids.is_empty())
580 {
581 return false;
582 }
583 self.selected_only = matches!(&selection, Selection::EntryIds(_));
584 match present::prepare_destination(&self.destination, self.automatic_destination) {
585 Ok(true) => self.owned_destination = Some(self.destination.clone()),
586 Ok(false) => self.owned_destination = None,
587 Err(_) => {
588 self.ui_error = Some(present::FOLDER_ERROR.into());
589 return false;
590 }
591 }
592 let gzip = self
593 .model
594 .list_id
595 .as_ref()
596 .is_some_and(|id| id.format == Format::Gzip);
597 self.targets = present::target_files(
598 &self.model.entries,
599 &selection,
600 gzip.then_some(self.gzip_name.as_str()),
601 );
602 self.directories = if gzip {
603 BTreeSet::new()
604 } else {
605 present::target_directories(&self.model.entries, &selection)
606 };
607 let request = Start::Extract {
608 archive: self.model.archive.clone().unwrap(),
609 destination: self.destination.clone(),
610 selection,
611 list_id: self.model.list_id.clone().unwrap(),
612 gzip_output_name: gzip.then(|| self.gzip_name.clone()),
613 };
614 if self.start(request) {
615 true
616 } else {
617 if let Some(path) = self.owned_destination.take() {
618 present::remove_owned_empty(&path);
619 }
620 false
621 }
622 }
623
624 fn begin_zip(&mut self) {
625 if self.sources.is_empty() {
626 return;
627 }
628 let extension = if self.seven_zip { ".7z" } else { ".zip" };
629 if !self.zip_name.to_ascii_lowercase().ends_with(extension) {
630 self.zip_name.push_str(extension);
631 }
632 if !valid_leaf(&self.zip_name) {
633 self.ui_error = Some("압축파일 이름을 확인하세요".into());
634 return;
635 }
636 let output_file = self.zip_folder.join(&self.zip_name);
637 if std::fs::symlink_metadata(&output_file).is_ok() {
638 self.ui_error = Some("같은 이름의 파일이 이미 있습니다. 다른 이름을 입력하세요".into());
639 return;
640 }
641 let mut sources = Vec::new();
642 for path in &self.sources {
643 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
644 self.ui_error = Some(
645 "이름을 읽을 수 없는 파일이 있습니다. 파일 이름을 바꾼 뒤 다시 추가하세요"
646 .into(),
647 );
648 return;
649 };
650 sources.push((path.clone(), name.to_owned()));
651 }
652 if self.seven_zip
653 && (self.aes256
654 || !self.zip_password.is_empty()
655 || !self.zip_password_confirm.is_empty())
656 {
657 self.ui_error =
658 Some("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요".into());
659 return;
660 }
661 if !self.zip_password_ready() {
662 self.ui_error = Some("두 암호가 같은지 확인하세요".into());
663 return;
664 }
665 self.targets = Some([self.zip_name.clone()].into_iter().collect());
666 self.directories.clear();
667 // 암호는 ZIP 만들기 창에서 받아 두었다가 작업자가 요청하면 넘김.
668 let password = self.aes256.then(|| std::mem::take(&mut self.zip_password));
669 let request = if self.seven_zip {
670 Start::CreateSevenZip {
671 sources,
672 output_file,
673 }
674 } else {
675 Start::CreateZip {
676 sources,
677 output_file,
678 method: self.method,
679 aes256: self.aes256,
680 }
681 };
682 if self.start(request) {
683 self.create = false;
684 self.create_win = WorkWindow::default();
685 self.clear_zip_password();
686 self.pending_zip_password = password;
687 } else if let Some(password) = password {
688 self.zip_password = password;
689 }
690 }
691
692 fn open_picker(&mut self, purpose: Purpose) {
693 if self.model.busy() || self.picker.is_some() {
694 return;
695 }
696 let gzip = self
697 .model
698 .list_id
699 .as_ref()
700 .is_some_and(|id| id.format == Format::Gzip);
701 let purpose = match (purpose, gzip) {
702 (Purpose::Destination, true) => Purpose::SaveGzip,
703 (Purpose::Retry, true) => Purpose::RetryGzip,
704 _ => purpose,
705 };
706 let directory = match purpose {
707 Purpose::SaveZip | Purpose::SaveSevenZip => self.zip_folder.clone(),
708 Purpose::SaveRecoveryZip | Purpose::Destination | Purpose::SaveGzip => self
709 .model
710 .archive
711 .as_ref()
712 .and_then(|path| path.parent())
713 .map(Path::to_path_buf)
714 .unwrap_or_else(present::home_directory),
715 Purpose::Retry | Purpose::RetryGzip => self.destination.clone(),
716 _ => self
717 .sources
718 .last()
719 .and_then(|path| path.parent())
720 .map(Path::to_path_buf)
721 .unwrap_or_else(present::home_directory),
722 };
723 let request = DialogRequest {
724 purpose,
725 directory,
726 file_name: if purpose == Purpose::SaveRecoveryZip {
727 let stem = self
728 .model
729 .archive
730 .as_ref()
731 .and_then(|p| p.file_stem())
732 .unwrap_or_default()
733 .to_string_lossy();
734 format!("{stem}-recovered.zip")
735 } else if matches!(purpose, Purpose::SaveGzip | Purpose::RetryGzip) {
736 self.gzip_name.clone()
737 } else {
738 self.zip_name.clone()
739 },
740 };
741 match self.dialogs.start(request) {
742 PendingDialog::Ready(answer) => self.apply_picker(purpose, answer),
743 PendingDialog::Waiting(receiver) => self.picker = Some((purpose, receiver)),
744 }
745 }
746
747 fn poll_picker(&mut self) {
748 let Some((purpose, receiver)) = &self.picker else {
749 return;
750 };
751 let purpose = *purpose;
752 let answer = match receiver.try_recv() {
753 Ok(answer) => answer,
754 Err(std::sync::mpsc::TryRecvError::Empty) => return,
755 Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(DIALOG_UNAVAILABLE.into()),
756 };
757 self.picker = None;
758 self.apply_picker(purpose, answer);
759 }
760
761 fn apply_picker(&mut self, purpose: Purpose, answer: DialogAnswer) {
762 if answer.is_ok() && self.ui_error.as_deref() == Some(DIALOG_UNAVAILABLE) {
763 self.ui_error = None;
764 }
765 match answer {
766 Ok(Some(paths)) if !paths.is_empty() => {
767 let path = paths[0].clone();
768 match purpose {
769 Purpose::SaveRecoveryZip => {
770 if let Some(archive) = self.model.archive.clone() {
771 self.start(Start::RecoverZip {
772 archive,
773 output_file: path,
774 });
775 }
776 }
777 Purpose::Open => {
778 if std::fs::symlink_metadata(&path)
779 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
780 {
781 self.open_path(path);
782 } else {
783 self.ui_error = Some("일반 압축파일을 선택하세요".into());
784 }
785 }
786 Purpose::Files => self.add_sources(paths),
787 Purpose::Folder => {
788 // 새 폴더로 처음부터 시작함. 고른 폴더가 쓸 수 없으면 기존 내용을 되돌림.
789 let previous = std::mem::take(&mut self.sources);
790 self.add_sources(paths);
791 if self.sources.is_empty() {
792 self.sources = previous;
793 } else {
794 self.aes256 = false;
795 self.clear_zip_password();
796 self.ui_error = None;
797 }
798 }
799 Purpose::Destination | Purpose::Retry => {
800 self.choose_destination(path);
801 self.selected_only = !self.model.selected.is_empty();
802 if purpose == Purpose::Retry {
803 self.retry();
804 } else {
805 self.begin_extract();
806 }
807 }
808 Purpose::SaveGzip | Purpose::RetryGzip => {
809 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
810 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
811 return;
812 };
813 if !present::valid_output_leaf(name) {
814 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
815 return;
816 }
817 let name = name.to_owned();
818 self.choose_destination(
819 path.parent().unwrap_or(Path::new("/")).to_path_buf(),
820 );
821 self.gzip_name = name.clone();
822 self.selected_only = !self.model.selected.is_empty();
823 if purpose == Purpose::RetryGzip {
824 if let Some(Start::Extract {
825 gzip_output_name, ..
826 }) = &mut self.last_request
827 {
828 *gzip_output_name = Some(name);
829 }
830 self.retry();
831 } else {
832 self.begin_extract();
833 }
834 }
835 // 저장 위치를 고르는 사이 ZIP 만들기 창을 닫았으면 아무 작업도 시작하지 않음.
836 Purpose::SaveZip | Purpose::SaveSevenZip if !self.create => {}
837 Purpose::SaveZip | Purpose::SaveSevenZip => {
838 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
839 self.zip_name = name.to_owned();
840 self.zip_folder = path.parent().unwrap_or(Path::new("/")).to_path_buf();
841 self.begin_zip();
842 }
843 }
844 }
845 }
846 Ok(_) => {}
847 Err(error) => self.ui_error = Some(error),
848 }
849 }
850
851 fn retry(&mut self) {
852 if let Some(request) = self.last_request.clone() {
853 match request {
854 Start::List { archive } => self.open_path(archive),
855 Start::Preview { .. } | Start::RecoverZip { .. } => {}
856 Start::Extract {
857 selection,
858 gzip_output_name,
859 ..
860 } => {
861 if let Some(name) = gzip_output_name {
862 self.gzip_name = name;
863 }
864 self.extract_selection(selection);
865 }
866 Start::CreateSevenZip { .. } => {
867 self.set_seven_zip(true);
868 self.create = true;
869 self.begin_zip();
870 }
871 Start::CreateZip { aes256, .. } => {
872 self.set_seven_zip(false);
873 self.create = true;
874 if aes256 {
875 // 암호는 보관하지 않으므로 ZIP 만들기 창에서 다시 받음.
876 self.aes256 = true;
877 } else {
878 self.begin_zip();
879 }
880 }
881 }
882 }
883 }
884
885 fn on_drop(&mut self, paths: Vec<PathBuf>) {
886 if self.preview_open || self.model.busy() || paths.is_empty() {
887 return;
888 }
889 if paths.len() == 1 && !self.create && !paths[0].is_dir() {
890 if std::fs::symlink_metadata(&paths[0])
891 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
892 {
893 self.open_path(paths[0].clone());
894 } else {
895 self.ui_error = Some("일반 압축파일을 선택하세요".into());
896 }
897 } else {
898 self.add_sources(paths);
899 }
900 }
901
902 fn poll(&mut self) {
903 let busy = self.model.busy();
904 let close_before = self.model.close;
905 self.model.poll();
906 if close_before == Close::Confirm && self.model.close == Close::Review {
907 // 종료 확인 창에 답하기 전에 작업이 끝났음. 사용자가 닫기를 승인하지 않았으므로
908 // 바로 닫지 않고 계속 물음(close_dialog가 작업이 끝난 문구로 바꿔 보여 줌).
909 self.model.close = Close::Confirm;
910 }
911 if busy && !self.model.busy() {
912 if let Some(path) = self.owned_destination.take() {
913 if !self.model.confirmed
914 || self
915 .model
916 .terminal
917 .as_ref()
918 .is_none_or(|t| t.outcome != Outcome::Completed)
919 {
920 present::remove_owned_empty(&path);
921 }
922 }
923 }
924 }
925
926 pub fn show(&mut self, root: &mut egui::Ui) {
927 let ctx = root.ctx().clone();
928 self.forget_password_history(&ctx);
929 if !self.initialized {
930 theme::apply(&ctx);
931 self.initialized = true;
932 }
933 self.poll();
934 let preview_was_open = self.preview_open;
935 self.poll_picker();
936 if self.model.challenge.is_some_and(|(_, _, encrypt)| encrypt)
937 && let Some(password) = self.pending_zip_password.take()
938 {
939 // ZIP 만들기 창에서 받은 암호를 작업자의 암호 요청에 바로 넘김.
940 self.model.password(password);
941 }
942 if !self.model.busy()
943 && let Some(mut pending) = self.pending_zip_password.take()
944 {
945 wipe(&mut pending);
946 }
947 let challenge = self.model.challenge.map(|(id, _, _)| id);
948 let new_challenge = challenge != self.password_challenge;
949 if new_challenge || challenge.is_none() {
950 self.clear_password();
951 }
952 self.password_challenge = challenge;
953 let dropped = ctx.input(|i| {
954 i.raw
955 .dropped_files
956 .iter()
957 .map(|file| file.path().to_path_buf())
958 .collect()
959 });
960 if self.picker.is_none() {
961 self.on_drop(dropped);
962 }
963 if ctx.input(|i| i.viewport().close_requested()) {
964 self.model.request_close();
965 // 실행 중인 작업이 없으면 결과 확인 안내 없이 바로 닫음.
966 self.model.acknowledge_close();
967 if self.model.close != Close::Allowed {
968 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
969 }
970 }
971 if self.model.close == Close::Review {
972 // 작업을 취소하고 닫기로 한 뒤 정리가 끝난 경우도 안내 없이 닫음.
973 self.model.acknowledge_close();
974 }
975 if self.model.close == Close::Allowed {
976 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
977 }
978 let title = self
979 .model
980 .archive
981 .as_ref()
982 .map(|path| {
983 let full = if path.is_absolute() {
984 path.clone()
985 } else {
986 std::env::current_dir().unwrap_or_default().join(path)
987 };
988 format!("{} — Zipelo", full.display())
989 })
990 .unwrap_or_else(|| "Zipelo".into());
991 let short_title = if let Some(path) = title.strip_suffix(" — Zipelo") {
992 format!(
993 "{} — Zipelo",
994 theme::window_title(root, path, ctx.content_rect().width() - 300.0)
995 )
996 } else {
997 title.clone()
998 };
999 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
1000 if self.custom_frame
1001 && window_frame::title_bar(
1002 root,
1003 "main",
1004 &title,
1005 window_frame::Buttons {
1006 minimize: true,
1007 maximize: true,
1008 },
1009 )
1010 {
1011 self.release_after_move = true;
1012 }
1013 egui::Panel::top("archive-actions")
1014 .frame(
1015 theme::panel(theme::PANEL)
1016 .corner_radius(0)
1017 .inner_margin(egui::Margin {
1018 left: 12,
1019 right: 12,
1020 // 버튼 안 내용은 보이는 모양 기준으로 가운데에 두므로 위아래를 같게 둠.
1021 top: 4,
1022 bottom: 4,
1023 }),
1024 )
1025 .show(root, |ui| {
1026 ui.horizontal(|ui| {
1027 ui.spacing_mut().item_spacing.x = 2.0;
1028 let idle = !self.model.busy()
1029 && self.model.close == Close::Open
1030 && self.picker.is_none();
1031 if theme::tool(ui, "열기", theme::OPEN, idle, false)
1032 .on_hover_text(&title)
1033 .clicked()
1034 {
1035 self.open_picker(Purpose::Open);
1036 }
1037 if theme::tool(
1038 ui,
1039 "미리보기",
1040 theme::PREVIEW,
1041 idle && self.can_preview() && !self.preview_open,
1042 false,
1043 )
1044 .on_disabled_hover_text(
1045 if self.model.list_id.as_ref().is_some_and(ListId::is_split) {
1046 "분할 압축파일은 미리보기를 지원하지 않습니다"
1047 } else {
1048 "일반 파일 하나를 선택하세요"
1049 },
1050 )
1051 .clicked()
1052 {
1053 self.begin_preview(ui.ctx());
1054 }
1055 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
1056 self.choose_zip_folder();
1057 }
1058 if theme::tool(
1059 ui,
1060 "압축해제",
1061 theme::EXTRACT,
1062 self.model.can_extract(),
1063 true,
1064 )
1065 .clicked()
1066 {
1067 self.open_picker(Purpose::Destination);
1068 }
1069 });
1070 });
1071 egui::Panel::bottom("archive-status")
1072 .exact_size(theme::STATUS_HEIGHT)
1073 .resizable(false)
1074 .frame(
1075 egui::Frame::new()
1076 .fill(theme::STRIPE)
1077 .inner_margin(egui::Margin::symmetric(16, 0)),
1078 )
1079 .show(root, |ui| {
1080 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1081 let selected = rows
1082 .iter()
1083 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
1084 .count();
1085 let rect = ui.max_rect();
1086 let half = (rect.width() - theme::SPACE) / 2.0;
1087 theme::status_text(
1088 ui,
1089 rect,
1090 &format!("{}개 항목", rows.len()),
1091 half,
1092 Align::Min,
1093 );
1094 theme::status_text(ui, rect, &format!("선택 {selected}개"), half, Align::Max);
1095 });
1096 if ctx.embed_viewports()
1097 && !self.work_in_parent
1098 && self.work_visible()
1099 && !self.limit_result_visible()
1100 {
1101 // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
1102 egui::Panel::bottom("archive-work")
1103 .frame(theme::panel(theme::PANEL).corner_radius(0))
1104 .show(root, |ui| self.work_area(ui));
1105 }
1106 egui::CentralPanel::default()
1107 .frame(
1108 theme::panel(theme::PANEL)
1109 .corner_radius(0)
1110 .inner_margin(egui::Margin::ZERO),
1111 )
1112 .show(root, |ui| {
1113 if let Some((_, warning)) = &self.recovery_warning {
1114 ui.colored_label(theme::WARNING, warning);
1115 }
1116 if self.model.archive.is_some() {
1117 self.archive_list(ui);
1118 } else {
1119 self.empty(ui);
1120 }
1121 });
1122 self.forget_password_history(&ctx);
1123 self.preview_dialog(&ctx);
1124 self.work_window(&ctx);
1125 self.limit_result_dialog(&ctx);
1126 self.create_window(&ctx);
1127 if self.model.challenge.is_some() {
1128 self.password_dialog(&ctx, new_challenge);
1129 }
1130 self.resource_dialog(&ctx);
1131 if self.model.conflict.is_some() && self.model.close == Close::Open {
1132 self.conflict_dialog(&ctx);
1133 }
1134 self.close_dialog(&ctx);
1135 self.picker_notice(&ctx);
1136 if !preview_was_open
1137 && !self.preview_open
1138 && !self.model.busy()
1139 && let Some(id) = self.preview_return_focus.take()
1140 {
1141 ctx.memory_mut(|m| m.request_focus(id));
1142 }
1143 if self.custom_frame {
1144 window_frame::edges(&ctx, true);
1145 }
1146 if self.model.busy() {
1147 ctx.request_repaint_after(std::time::Duration::from_millis(30));
1148 }
1149 }
1150
1151 // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
1152 fn picker_notice(&mut self, ctx: &egui::Context) {
1153 if self.picker.is_none() {
1154 return;
1155 }
1156 egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
1157 ui.set_width(360.0);
1158 ui.label("파일 선택 창에서 선택을 마쳐 주세요");
1159 });
1160 ctx.request_repaint_after(std::time::Duration::from_millis(100));
1161 }
1162
1163 fn empty(&mut self, ui: &mut egui::Ui) {
1164 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
1165 let width = (ui.available_width() * 0.60)
1166 .max(480.0)
1167 .min(ui.available_width());
1168 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
1169 ui.add_space(y);
1170 ui.vertical_centered(|ui| {
1171 let drop_frame = egui::Frame::new()
1172 .fill(if hovered { theme::DROP } else { theme::PANEL })
1173 .corner_radius(theme::DROP_RADIUS)
1174 .inner_margin(egui::Margin::same(theme::DROP_PAD))
1175 .show(ui, |ui| {
1176 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
1177 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
1178 ui.vertical_centered(|ui| {
1179 ui.add_space(theme::PAD as f32);
1180 theme::icon(ui, Icon::Archive, 48.0);
1181 ui.add_space(theme::PAD as f32);
1182 ui.label(
1183 RichText::new(if hovered {
1184 "놓으면 엽니다"
1185 } else {
1186 "압축파일을 여기에 끌어 놓으세요"
1187 })
1188 .size(theme::FONT_LARGE)
1189 .strong(),
1190 );
1191 ui.label("또는");
1192 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
1193 self.open_picker(Purpose::Open);
1194 }
1195 });
1196 });
1197 let rect = drop_frame.response.rect;
1198 if hovered {
1199 ui.painter().rect_stroke(
1200 rect,
1201 12,
1202 egui::Stroke::new(2.0, theme::BLUE),
1203 egui::StrokeKind::Inside,
1204 );
1205 } else {
1206 let stroke = egui::Stroke::new(2.0, theme::DASH);
1207 for (a, b) in [
1208 (rect.left_top(), rect.right_top()),
1209 (rect.right_top(), rect.right_bottom()),
1210 (rect.right_bottom(), rect.left_bottom()),
1211 (rect.left_bottom(), rect.left_top()),
1212 ] {
1213 let direction = (b - a).normalized();
1214 let mut distance = theme::DROP_RADIUS as f32;
1215 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
1216 ui.painter().line_segment(
1217 [
1218 a + direction * distance,
1219 a + direction
1220 * (distance + theme::SPACE)
1221 .min(a.distance(b) - theme::DROP_RADIUS as f32),
1222 ],
1223 stroke,
1224 );
1225 distance += theme::PAD as f32;
1226 }
1227 }
1228 }
1229 ui.add_space(theme::PAD as f32);
1230 ui.colored_label(
1231 theme::MUTED,
1232 "ZIP, 7z, TAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ 파일을 열 수 있습니다",
1233 );
1234 });
1235 }
1236
1237 fn archive_list(&mut self, ui: &mut egui::Ui) {
1238 // 경로 줄은 입력란 높이만 차지하고 창 너비 전체를 회색으로 채움.
1239 let path_row = egui::Frame::new()
1240 .fill(theme::STRIPE)
1241 .inner_margin(egui::Margin {
1242 left: 8,
1243 right: 12,
1244 top: 0,
1245 bottom: 0,
1246 })
1247 .show(ui, |ui| {
1248 ui.set_min_width(ui.available_width());
1249 ui.horizontal(|ui| {
1250 ui.set_height(theme::FIELD);
1251 // 간격은 아래에서 직접 넣어 위치가 흔들리지 않게 함.
1252 ui.spacing_mut().item_spacing.x = 0.0;
1253 let up = theme::flat_icon_button(
1254 ui,
1255 "위로",
1256 theme::UP,
1257 !self.folder.is_empty() && !self.model.busy(),
1258 egui::vec2(theme::FIELD, theme::FIELD),
1259 );
1260 if up.clicked() {
1261 let parent = self
1262 .folder
1263 .rsplit_once('/')
1264 .map_or("", |(parent, _)| parent)
1265 .to_owned();
1266 self.browse_folder(&parent);
1267 }
1268 ui.add_space(6.0);
1269 let path = format!("/{}", self.folder);
1270 let search_width = 240.0;
1271 let gap = 8.0;
1272 let path_width = (ui.available_width() - search_width - gap).max(0.0);
1273 // 두 입력란은 같은 높이의 칸을 받아 같은 세로 위치에 그림.
1274 let (path_rect, _) = ui.allocate_exact_size(
1275 egui::vec2(path_width, theme::FIELD),
1276 egui::Sense::hover(),
1277 );
1278 theme::field_frame(ui, path_rect, false);
1279 // 부모 배치에 영향을 주지 않는 하위 영역에 경로 글자를 그림.
1280 let mut text_ui = ui.new_child(
1281 egui::UiBuilder::new()
1282 .max_rect(path_rect.shrink2(egui::vec2(10.0, 0.0)))
1283 .layout(Layout::left_to_right(Align::Center)),
1284 );
1285 theme::bounded_text(&mut text_ui, &path, (path_width - 20.0).max(0.0));
1286 ui.add_space(gap);
1287 let (search_rect, _) = ui.allocate_exact_size(
1288 egui::vec2(search_width, theme::FIELD),
1289 egui::Sense::hover(),
1290 );
1291 let search_id = egui::Id::unique("archive-search");
1292 let focused = ui.memory(|m| m.has_focus(search_id));
1293 theme::field_frame(ui, search_rect, focused);
1294 let icon = egui::Rect::from_center_size(
1295 egui::pos2(search_rect.left() + 20.0, search_rect.center().y),
1296 egui::vec2(16.0, 16.0),
1297 );
1298 theme::svg_icon(ui.painter(), icon, theme::SEARCH, theme::MUTED);
1299 let search = ui.put(
1300 egui::Rect::from_min_max(
1301 egui::pos2(icon.right() + 8.0, search_rect.top() + 1.0),
1302 egui::pos2(search_rect.right() - 8.0, search_rect.bottom() - 1.0),
1303 ),
1304 egui::TextEdit::singleline(&mut self.search)
1305 .id(search_id)
1306 .frame(egui::Frame::NONE)
1307 .margin(egui::Margin::ZERO)
1308 .align(egui::Align2::LEFT_CENTER)
1309 .hint_text("파일 검색"),
1310 );
1311 if search.changed() {
1312 self.clear_list_selection();
1313 }
1314 });
1315 })
1316 .response
1317 .rect;
1318 // 경로 줄 아래 한 줄이 목록과의 경계이자 입력란의 아래 테두리 역할을 함.
1319 ui.painter().hline(
1320 path_row.x_range(),
1321 path_row.bottom() - 0.5,
1322 egui::Stroke::new(1.0, theme::BORDER),
1323 );
1324 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1325
1326 // 열 제목 줄 없이 바로 목록을 보여 줌. 이름과 크기는 내용으로 구분됨.
1327 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 40.0).max(120.0);
1328 let active = !self.preview_open
1329 && !self.model.busy()
1330 && !self.create
1331 && self.model.challenge.is_none()
1332 && self.model.close == Close::Open;
1333 let list_id = egui::Id::unique("archive-list");
1334 let background = ui.interact(
1335 ui.available_rect_before_wrap(),
1336 list_id,
1337 if active {
1338 egui::Sense::click_and_drag()
1339 } else {
1340 egui::Sense::hover()
1341 },
1342 );
1343 background
1344 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
1345 if background.has_focus() {
1346 ui.ctx().memory_mut(|memory| {
1347 memory.set_focus_lock_filter(
1348 list_id,
1349 egui::EventFilter {
1350 vertical_arrows: true,
1351 escape: true,
1352 ..Default::default()
1353 },
1354 )
1355 });
1356 }
1357 let mut focused = None;
1358 let mut open = None;
1359 let mut next_offset = None;
1360 let output = egui::ScrollArea::vertical()
1361 .id_salt("archive-rows")
1362 .auto_shrink([false, false])
1363 .vertical_scroll_offset(self.list_offset)
1364 .show_viewport(ui, |ui, viewport| {
1365 let origin = ui.max_rect().min;
1366 let clip = ui.clip_rect();
1367 // 행을 누르는 영역은 오른쪽 24px을 비워 둠. 목록이 길어도 그 빈 곳에서
1368 // 끌어서 선택을 시작할 수 있음. 행 배경(선택, 마우스 올림)은 너비를 꽉 채움.
1369 let full_width = ui.available_width();
1370 let width = (full_width - 24.0).max(0.0);
1371 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
1372 let point = ui.input(|i| i.pointer.interact_pos());
1373 if active && let Some(point) = point {
1374 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
1375 let relative = press - origin;
1376 let in_row = relative.x >= 0.0
1377 && relative.x <= width
1378 && relative.y >= 0.0
1379 && relative.y < rows.len() as f32 * LIST_ROW;
1380 if clip.contains(press) && !in_row && ui.input(|i| i.pointer.primary_pressed())
1381 {
1382 background.request_focus();
1383 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
1384 self.marquee = Some(Marquee {
1385 origin: relative.to_pos2(),
1386 base: if ctrl {
1387 self.model.selected.clone()
1388 } else {
1389 BTreeSet::new()
1390 },
1391 moved: false,
1392 });
1393 if !ctrl {
1394 self.model.selected.clear();
1395 self.list_anchor = None;
1396 self.list_cursor = None;
1397 }
1398 }
1399 if let Some(drag) = &mut self.marquee {
1400 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
1401 drag.moved |= drag.origin.distance(end) > 3.0;
1402 if drag.moved {
1403 let rect = egui::Rect::from_two_pos(drag.origin, end);
1404 self.model.selected = drag.base.clone();
1405 if rect.left() < width && rect.right() > 0.0 {
1406 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
1407 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
1408 .min(rows.len());
1409 for row in rows.iter().take(last).skip(first) {
1410 self.model.selected.extend(&row.ids);
1411 }
1412 if first < last {
1413 self.list_anchor = Some(first);
1414 self.list_cursor = Some(last - 1);
1415 }
1416 }
1417 let speed = if point.y > clip.bottom() - 24.0 {
1418 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
1419 } else if point.y < clip.top() + 24.0 {
1420 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
1421 } else {
1422 0.0
1423 };
1424 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
1425 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
1426 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
1427 0.0,
1428 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
1429 ));
1430 ui.ctx().request_repaint();
1431 }
1432 }
1433 }
1434 }
1435 let first = (viewport.min.y / LIST_ROW).floor() as usize;
1436 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
1437 for index in first.min(rows.len())..last {
1438 let row = &rows[index];
1439 let rect = egui::Rect::from_min_size(
1440 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
1441 egui::vec2(width, LIST_ROW),
1442 );
1443 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
1444 let response = ui
1445 .interact(
1446 rect,
1447 egui::Id::unique(("archive-row", &row.path)),
1448 if active {
1449 egui::Sense::click()
1450 } else {
1451 egui::Sense::hover()
1452 },
1453 )
1454 .on_hover_text(&row.name);
1455 theme::pointer(&response);
1456 response.widget_info(|| {
1457 egui::WidgetInfo::selected(
1458 egui::Role::ListBoxOption,
1459 active,
1460 selected,
1461 &row.name,
1462 )
1463 });
1464 if response.has_focus() {
1465 focused = Some(index);
1466 ui.ctx().memory_mut(|memory| {
1467 memory.set_focus_lock_filter(
1468 response.id,
1469 egui::EventFilter {
1470 vertical_arrows: true,
1471 escape: true,
1472 ..Default::default()
1473 },
1474 )
1475 });
1476 }
1477 theme::row_background(
1478 ui,
1479 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW)),
1480 selected,
1481 response.hovered(),
1482 );
1483 if response.clicked() {
1484 background.request_focus();
1485 let modifiers = ui.input(|i| i.modifiers);
1486 self.select_row(
1487 &rows,
1488 index,
1489 modifiers.ctrl || modifiers.command,
1490 modifiers.shift,
1491 );
1492 }
1493 if row.directory && response.double_clicked() {
1494 open = Some(row.path.clone());
1495 }
1496 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
1497 let name = if row.encrypted {
1498 format!("*{}", row.name)
1499 } else {
1500 row.name.clone()
1501 };
1502 Self::entry_cells(
1503 ui,
1504 rect,
1505 row.directory,
1506 &name,
1507 &row.name,
1508 if row.directory {
1509 "0 B".into()
1510 } else {
1511 row.bytes
1512 .map(present::bytes_text)
1513 .unwrap_or_else(|| "—".into())
1514 },
1515 name_width,
1516 );
1517 if active
1518 && self.list_cursor == Some(index)
1519 && (response.has_focus() || background.has_focus())
1520 {
1521 ui.painter().rect_stroke(
1522 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW))
1523 .shrink(1.0),
1524 0,
1525 egui::Stroke::new(1.0, theme::BLUE),
1526 egui::StrokeKind::Inside,
1527 );
1528 }
1529 }
1530 if rows.is_empty()
1531 && !(self.model.busy() && matches!(self.last_request, Some(Start::List { .. })))
1532 {
1533 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
1534 ui.centered_and_justified(|ui| {
1535 ui.label(if self.search.is_empty() {
1536 "이 폴더는 비어 있습니다"
1537 } else {
1538 "일치하는 항목이 없습니다"
1539 })
1540 });
1541 });
1542 }
1543 #[cfg(all(feature = "ui-fixture", debug_assertions))]
1544 if let Some(rect) = self.scenario_marquee {
1545 ui.painter().with_clip_rect(clip).rect(
1546 rect.translate(origin.to_vec2()),
1547 0,
1548 theme::BLUE.gamma_multiply(0.16),
1549 egui::Stroke::new(1.0, theme::BLUE),
1550 egui::StrokeKind::Inside,
1551 );
1552 }
1553 if let Some(drag) = &self.marquee
1554 && drag.moved
1555 && let Some(point) = point
1556 {
1557 let rect = egui::Rect::from_two_pos(
1558 origin + drag.origin.to_vec2(),
1559 point.clamp(clip.min, clip.max),
1560 );
1561 ui.painter().with_clip_rect(clip).rect(
1562 rect,
1563 0,
1564 theme::BLUE.gamma_multiply(0.16),
1565 egui::Stroke::new(1.0, theme::BLUE),
1566 egui::StrokeKind::Inside,
1567 );
1568 }
1569 });
1570 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
1571 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
1572 self.marquee = None;
1573 }
1574 let escape_from_list = self.list_focused
1575 && ui.ctx().memory(|memory| memory.focused()).is_none()
1576 && ui.input(|i| i.key_pressed(egui::Key::Escape));
1577 self.list_focused =
1578 active && (background.has_focus() || focused.is_some() || escape_from_list);
1579 if self.list_focused {
1580 if let Some(index) = focused {
1581 self.list_cursor = Some(index);
1582 }
1583 let modifiers = ui.input(|i| i.modifiers);
1584 let ctrl = modifiers.ctrl || modifiers.command;
1585 if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
1586 self.model.selected.clear();
1587 self.marquee = None;
1588 background.request_focus();
1589 }
1590 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
1591 self.model.selected = rows
1592 .iter()
1593 .flat_map(|row| row.ids.iter().copied())
1594 .collect();
1595 self.list_cursor = (!rows.is_empty()).then_some(0);
1596 self.list_anchor = self.list_cursor;
1597 }
1598 if !rows.is_empty() {
1599 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
1600 Some(1isize)
1601 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
1602 Some(-1)
1603 } else {
1604 None
1605 };
1606 if let Some(direction) = direction {
1607 let index = self.list_cursor.map_or(0, |index| {
1608 index.saturating_add_signed(direction).min(rows.len() - 1)
1609 });
1610 if ctrl && !modifiers.shift {
1611 self.list_cursor = Some(index);
1612 } else {
1613 self.select_row(&rows, index, ctrl, modifiers.shift);
1614 }
1615 background.request_focus();
1616 let top = index as f32 * LIST_ROW;
1617 if top < self.list_offset {
1618 self.list_offset = top;
1619 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
1620 self.list_offset = top + LIST_ROW - output.inner_rect.height();
1621 }
1622 ui.ctx().request_repaint();
1623 }
1624 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1625 let index = self
1626 .list_cursor
1627 .or(focused)
1628 .unwrap_or(0)
1629 .min(rows.len() - 1);
1630 if rows[index].directory {
1631 open = Some(rows[index].path.clone());
1632 }
1633 }
1634 }
1635 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
1636 open = Some(
1637 self.folder
1638 .rsplit_once('/')
1639 .map_or("", |(parent, _)| parent)
1640 .to_owned(),
1641 );
1642 }
1643 }
1644 if let Some(folder) = open {
1645 self.browse_folder(&folder);
1646 background.request_focus();
1647 }
1648 }
1649
1650 fn clear_list_selection(&mut self) {
1651 self.model.selected.clear();
1652 self.list_anchor = None;
1653 self.list_cursor = None;
1654 self.list_offset = 0.0;
1655 self.marquee = None;
1656 }
1657
1658 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
1659 if shift {
1660 let anchor = self
1661 .list_anchor
1662 .unwrap_or(self.list_cursor.unwrap_or(index))
1663 .min(rows.len() - 1);
1664 if !ctrl {
1665 self.model.selected.clear();
1666 }
1667 for row in &rows[anchor.min(index)..=anchor.max(index)] {
1668 self.model.selected.extend(&row.ids);
1669 }
1670 self.list_anchor = Some(anchor);
1671 } else {
1672 if !ctrl {
1673 self.model.selected.clear();
1674 }
1675 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
1676 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
1677 self.model
1678 .selected
1679 .retain(|id| !rows[index].ids.contains(id));
1680 } else {
1681 self.model.selected.extend(&rows[index].ids);
1682 }
1683 self.list_anchor = Some(index);
1684 }
1685 self.list_cursor = Some(index);
1686 }
1687
1688 fn result_visible(&self) -> bool {
1689 !self.dismissed
1690 && !self
1691 .last_request
1692 .as_ref()
1693 .is_some_and(|r| matches!(r, Start::Preview { .. }))
1694 && !self.model.busy()
1695 && self.last_request.as_ref().is_some_and(|request| {
1696 !matches!(request, Start::List { .. })
1697 || self.model.error.is_some()
1698 || self
1699 .model
1700 .terminal
1701 .as_ref()
1702 .is_some_and(|t| t.outcome != Outcome::Completed)
1703 })
1704 }
1705
1706 fn can_preview(&self) -> bool {
1707 self.model.can_preview()
1708 && browser::rows(&self.model.entries, &self.folder, &self.search)
1709 .iter()
1710 .any(|row| !row.directory && row.ids == self.model.selected)
1711 }
1712
1713 fn begin_preview(&mut self, ctx: &egui::Context) {
1714 if !self.can_preview() || self.picker.is_some() {
1715 return;
1716 }
1717 self.preview_texture = None;
1718 self.preview_text.clear();
1719 self.preview_name = self
1720 .model
1721 .entries
1722 .iter()
1723 .find(|e| self.model.selected.contains(&e.id))
1724 .unwrap()
1725 .name
1726 .clone();
1727 self.preview_return_focus = Some(
1728 ctx.memory(|m| m.focused())
1729 .unwrap_or_else(|| egui::Id::unique("archive-list")),
1730 );
1731 self.preview_initial_focus = true;
1732 let request = Start::Preview {
1733 archive: self.model.archive.clone().unwrap(),
1734 entry_id: *self.model.selected.first().unwrap(),
1735 list_id: self.model.list_id.clone().unwrap(),
1736 };
1737 self.preview_open = true;
1738 self.start(request);
1739 }
1740
1741 fn close_preview(&mut self) {
1742 self.preview_open = false;
1743 self.model.dismiss_preview();
1744 self.preview_texture = None;
1745 self.preview_text.clear();
1746 self.dismissed = true;
1747 }
1748
1749 fn preview_dialog(&mut self, ctx: &egui::Context) {
1750 if !self.preview_open
1751 || self.model.challenge.is_some()
1752 || self.model.resource.is_some()
1753 || self.model.close != Close::Open
1754 {
1755 return;
1756 }
1757 if let Some(preview) = self.model.preview.as_mut()
1758 && (!preview.data.is_empty() || preview.info.total_bytes == 0)
1759 {
1760 match preview.info.format {
1761 PreviewFormat::Utf8Text => {
1762 self.preview_text =
1763 String::from_utf8(std::mem::take(&mut preview.data)).unwrap_or_default();
1764 }
1765 PreviewFormat::Rgba8 => {
1766 let width = preview.info.width as usize;
1767 let height = preview.info.height as usize;
1768 let limit = ctx.input(|i| i.max_texture_side).max(1);
1769 let step = width.div_ceil(limit).max(height.div_ceil(limit)).max(1);
1770 let size = [width.div_ceil(step), height.div_ceil(step)];
1771 let mut colors = Vec::with_capacity(size[0] * size[1]);
1772 for y in (0..height).step_by(step) {
1773 for x in (0..width).step_by(step) {
1774 let index = (y * width + x) * 4;
1775 colors.push(egui::Color32::from_rgba_unmultiplied(
1776 preview.data[index],
1777 preview.data[index + 1],
1778 preview.data[index + 2],
1779 preview.data[index + 3],
1780 ));
1781 }
1782 }
1783 let pixels = egui::ColorImage::new(size, colors);
1784 preview.data = Vec::new();
1785 self.preview_texture = Some(ctx.load_texture(
1786 "archive-preview",
1787 pixels,
1788 egui::TextureOptions::LINEAR,
1789 ));
1790 }
1791 }
1792 }
1793 let mut close = false;
1794 let modal = egui::Modal::new(egui::Id::unique("archive-preview")).show(ctx, |ui| {
1795 ui.set_width((ctx.content_rect().width() - 64.0).clamp(240.0, 760.0));
1796 ui.horizontal(|ui| {
1797 ui.heading("미리보기");
1798 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1799 let button = theme::flat_icon_button(
1800 ui,
1801 "미리보기 닫기",
1802 theme::CLOSE,
1803 true,
1804 egui::vec2(36.0, 36.0),
1805 );
1806 if self.preview_initial_focus {
1807 button.request_focus();
1808 self.preview_initial_focus = false;
1809 }
1810 close |= button.clicked();
1811 });
1812 });
1813 ui.add(egui::Label::new(&self.preview_name).truncate())
1814 .on_hover_text(&self.preview_name);
1815 let max_height = (ctx.content_rect().height() - 220.0).clamp(100.0, 560.0);
1816 if self.model.busy() {
1817 ui.label("미리보기를 불러오는 중입니다");
1818 if ui.button("취소").clicked() {
1819 close = true;
1820 }
1821 } else if let Some(error) = self.model.error.as_ref() {
1822 Self::error_notice(ui, error);
1823 } else if let Some(texture) = self.preview_texture.as_ref() {
1824 ui.add(
1825 egui::Image::new(texture)
1826 .max_size(egui::vec2(ui.available_width(), max_height))
1827 .shrink_to_fit(),
1828 );
1829 } else if self.model.preview.is_some() {
1830 egui::ScrollArea::both()
1831 .id_salt("preview-text")
1832 .max_height(max_height)
1833 .show(ui, |ui| {
1834 let mut text = self.preview_text.as_str();
1835 ui.add(
1836 egui::TextEdit::multiline(&mut text)
1837 .desired_width(ui.available_width())
1838 .desired_rows(12)
1839 .frame(egui::Frame::NONE),
1840 );
1841 });
1842 if self.preview_text.is_empty() {
1843 ui.label("빈 텍스트 파일입니다");
1844 }
1845 } else {
1846 let code = self.model.terminal.as_ref().and_then(|t| t.error);
1847 ui.label(match code {
1848 Some(ErrorCode::Limit) => "미리보기 크기 또는 처리 한도를 초과했습니다.",
1849 Some(ErrorCode::Integrity) => "파일이 손상됐거나 UTF-8 텍스트가 아닙니다.",
1850 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature) => {
1851 "이 파일 형식은 미리보기를 지원하지 않습니다."
1852 }
1853 Some(ErrorCode::SourceChanged) => "압축파일이 변경됐습니다. 다시 열어 주세요.",
1854 Some(ErrorCode::WrongPassword) => "암호가 올바르지 않습니다.",
1855 _ => "미리보기를 불러오지 못했습니다.",
1856 });
1857 ui.label("닫은 뒤 파일을 선택하고 [압축해제]를 사용할 수 있습니다.");
1858 }
1859 });
1860 if close || modal.should_close() {
1861 self.close_preview();
1862 }
1863 }
1864
1865 fn limit_result_visible(&self) -> bool {
1866 self.result_visible()
1867 && (self.model.volume_problem.is_some()
1868 || self.model.terminal.as_ref().is_some_and(|terminal| {
1869 terminal.error == Some(ErrorCode::Limit)
1870 || (matches!(
1871 terminal.error,
1872 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature)
1873 ) && self
1874 .model
1875 .archive
1876 .as_ref()
1877 .is_some_and(|p| present::excluded_split(p)))
1878 }))
1879 }
1880
1881 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
1882 if !self.limit_result_visible() || self.main_modal_open() {
1883 return;
1884 }
1885 egui::Modal::new(egui::Id::new("archive-limit-result")).show(ctx, |ui| {
1886 ui.set_width((ctx.content_rect().width() - 64.0).min(WORK_WIDTH));
1887 ui.heading("작업 결과");
1888 self.work_area(ui);
1889 });
1890 }
1891
1892 fn error_notice(ui: &mut egui::Ui, error: &str) {
1893 let response = theme::panel(theme::ERROR_BG)
1894 .show(ui, |ui| {
1895 ui.horizontal_wrapped(|ui| {
1896 theme::icon(ui, Icon::Error, 24.0);
1897 ui.colored_label(theme::ERROR, error);
1898 });
1899 })
1900 .response;
1901 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
1902 }
1903
1904 fn work_visible(&self) -> bool {
1905 !self
1906 .last_request
1907 .as_ref()
1908 .is_some_and(|r| matches!(r, Start::Preview { .. }))
1909 && (self.model.busy()
1910 || self.result_visible()
1911 || (self.ui_error.is_some() && !self.create))
1912 }
1913
1914 /// 메인 창 가운데에 모달(암호 입력, 종료 확인, 파일 선택 안내)이나 같은 자리에 뜨는
1915 /// ZIP 만들기 창이 떠 있는지. 닫기가 정해진 뒤(Allowed)에도 결과 창을 다시 띄우지 않음.
1916 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
1917 fn main_modal_open(&self) -> bool {
1918 (self.create && !self.model.busy())
1919 || self.picker.is_some()
1920 || self.model.challenge.is_some()
1921 || self.model.resource.is_some()
1922 || self.model.conflict.is_some()
1923 || self.model.close != Close::Open
1924 }
1925
1926 fn work_window(&mut self, ctx: &egui::Context) {
1927 if !self.work_visible() {
1928 self.work = WorkWindow::default();
1929 return;
1930 }
1931 if self.limit_result_visible() {
1932 self.work.open = false;
1933 return;
1934 }
1935 if ctx.embed_viewports() && !self.work_in_parent {
1936 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1937 return;
1938 }
1939 if self.main_modal_open() {
1940 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
1941 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1942 self.work.open = false;
1943 return;
1944 }
1945 let id = egui::ViewportId::from_hash_of("archive-work");
1946 let title = if self.model.busy() {
1947 present::activity_text(
1948 &self.model,
1949 matches!(
1950 self.last_request,
1951 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
1952 ),
1953 )
1954 .to_owned()
1955 } else {
1956 "작업 결과".to_owned()
1957 };
1958 if self.work_in_parent {
1959 // Wayland는 창 올리기를 지원하지 않으므로 부모 안에서 같은 내용을 그림.
1960 let mut open = true;
1961 let mut window = egui::Window::new(RichText::new(title).size(theme::FONT_SMALL))
1962 .id(egui::Id::new("archive-work-in-parent"))
1963 .default_pos(
1964 ctx.content_rect().center() - egui::vec2(WORK_WIDTH, self.work.height) / 2.0,
1965 )
1966 .default_width(WORK_WIDTH)
1967 .min_width(WORK_WIDTH)
1968 .max_width(WORK_WIDTH)
1969 .max_height(WORK_MAX_HEIGHT)
1970 .collapsible(false)
1971 .resizable(false)
1972 .fade_in(false)
1973 .fade_out(false)
1974 .title_frame(
1975 theme::panel(theme::STRIPE)
1976 .inner_margin(egui::Margin::symmetric(16, 8))
1977 .corner_radius(0),
1978 )
1979 .frame(
1980 theme::panel(theme::PANEL)
1981 .stroke(egui::Stroke::new(1.0, theme::BORDER))
1982 .corner_radius(0),
1983 );
1984 if !self.model.busy() {
1985 window = window.open(&mut open);
1986 }
1987 window.show(ctx, |ui| self.work_area(ui));
1988 if !open {
1989 self.dismissed = true;
1990 self.ui_error = None;
1991 self.model.input_error = None;
1992 }
1993 return;
1994 }
1995 let window_title = format!("{title} — Zipelo");
1996 let custom_frame = self.custom_frame;
1997 let size = egui::vec2(WORK_WIDTH, self.work.height);
1998 let builder = self.work.builder(
1999 ctx,
2000 id,
2001 size,
2002 &window_title,
2003 !custom_frame,
2004 self.picker.is_some(),
2005 );
2006 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
2007 if ui.ctx().input(|i| i.viewport().close_requested()) {
2008 if self.model.busy() {
2009 ui.ctx()
2010 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
2011 } else {
2012 self.dismissed = true;
2013 self.ui_error = None;
2014 self.model.input_error = None;
2015 }
2016 }
2017 if class == egui::ViewportClass::EmbeddedWindow {
2018 ui.set_width(WORK_WIDTH);
2019 self.work_area(ui);
2020 return None;
2021 }
2022 let mut chrome = 0.0;
2023 if custom_frame {
2024 window_frame::title_bar(
2025 ui,
2026 "work",
2027 &window_title,
2028 window_frame::Buttons {
2029 minimize: false,
2030 maximize: false,
2031 },
2032 );
2033 window_frame::edges(ui.ctx(), false);
2034 chrome = window_frame::TITLE_HEIGHT;
2035 }
2036 let margin = theme::PAD as f32;
2037 egui::CentralPanel::default()
2038 .frame(theme::panel(theme::PANEL).corner_radius(0))
2039 .show(ui, |ui| {
2040 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
2041 Some(content.height() + 2.0 * margin + chrome)
2042 })
2043 .inner
2044 });
2045 if let Some(height) = height {
2046 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
2047 if (height - self.work.height).abs() > 1.0 {
2048 self.work.height = height;
2049 }
2050 }
2051 }
2052
2053 fn work_area(&mut self, ui: &mut egui::Ui) {
2054 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
2055 let enabled = self.picker.is_none();
2056 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
2057 }
2058
2059 fn work_contents(&mut self, ui: &mut egui::Ui) {
2060 if self.model.busy() {
2061 self.progress(ui);
2062 } else if self.result_visible() {
2063 self.result(ui);
2064 }
2065 if !self.create
2066 && let Some(error) = &self.ui_error
2067 {
2068 Self::error_notice(ui, error);
2069 if error == present::FOLDER_ERROR
2070 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
2071 {
2072 self.open_picker(Purpose::Destination);
2073 }
2074 }
2075 if let Some(error) = &self.model.input_error {
2076 ui.colored_label(
2077 theme::ERROR,
2078 if error.starts_with("암호는") {
2079 error.as_str()
2080 } else {
2081 if matches!(
2082 self.last_request,
2083 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2084 ) {
2085 "저장 위치와 추가한 항목을 확인하세요"
2086 } else {
2087 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
2088 "원본과 다른 새 복구본 저장 위치를 선택하세요"
2089 } else {
2090 "풀 위치와 선택한 항목을 확인하세요"
2091 }
2092 }
2093 },
2094 );
2095 }
2096 }
2097
2098 fn progress(&mut self, ui: &mut egui::Ui) {
2099 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
2100 ui.strong("ZIP 복구 중");
2101 ui.label(if self.model.recovery_end.is_some() {
2102 "분석 완료 / 복구본 저장과 작업자 종료 확인 중"
2103 } else {
2104 "원본을 분석하고 있습니다. 전체 항목 수는 아직 알 수 없습니다."
2105 });
2106 ui.label(format!(
2107 "확인한 항목 {}개",
2108 self.model.recovery_entries.len()
2109 ));
2110 self.cancel_action(ui, false);
2111 return;
2112 }
2113 if self.model.resource.is_some() {
2114 ui.horizontal(|ui| {
2115 ui.label("사용자 허용을 기다리고 있습니다");
2116 self.cancel_action(ui, false);
2117 });
2118 return;
2119 }
2120 let creating = matches!(
2121 self.last_request,
2122 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2123 );
2124 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
2125 let title = present::activity_text(&self.model, creating);
2126 ui.strong(title);
2127 if let Some((stage, done, total, count)) = self.model.progress {
2128 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
2129 let processed = if stage == Stage::Read {
2130 String::new()
2131 } else {
2132 format!("{count}개 처리함, ")
2133 };
2134 if let Some(total) = total.filter(|n| *n > 0) {
2135 ui.scope(|ui| {
2136 ui.visuals_mut().extreme_bg_color = theme::BORDER;
2137 ui.add(
2138 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
2139 .fill(theme::BLUE)
2140 .desired_height(theme::SPACE * 2.0),
2141 );
2142 });
2143 ui.horizontal(|ui| {
2144 ui.label(format!(
2145 "{:.0}% / {processed}{} / {}",
2146 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
2147 present::bytes_text(done),
2148 present::bytes_text(total)
2149 ));
2150 self.cancel_action(ui, cancelling);
2151 });
2152 } else {
2153 theme::indeterminate(ui);
2154 ui.horizontal(|ui| {
2155 ui.label(format!("{processed}{}", present::bytes_text(done)));
2156 self.cancel_action(ui, cancelling);
2157 });
2158 }
2159 } else {
2160 theme::indeterminate(ui);
2161 ui.horizontal(|ui| {
2162 ui.label("작업을 진행하고 있습니다");
2163 self.cancel_action(ui, cancelling);
2164 });
2165 }
2166 }
2167
2168 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
2169 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2170 if theme::action(ui, "취소", false, !cancelling).clicked() {
2171 self.clear_password();
2172 self.model.cancel();
2173 }
2174 });
2175 }
2176
2177 fn recovery_result(&mut self, ui: &mut egui::Ui) {
2178 let t = self.model.terminal.as_ref();
2179 let summary = self.model.recovery_end.as_ref();
2180 let confirmed = self.model.confirmed && self.model.error.is_none();
2181 let saved = confirmed
2182 && t.is_some_and(|t| t.publication == Publication::Complete && t.created_count == 1)
2183 && summary.is_some_and(|s| s.verified_entries > 0);
2184 let partial = summary.is_some_and(|s| !s.complete());
2185 let title = if !confirmed {
2186 "복구 결과를 확정할 수 없음"
2187 } else if saved && partial {
2188 "일부 항목만 복구함"
2189 } else if saved && t.is_some_and(|t| t.outcome == Outcome::Completed) {
2190 "복구본 저장 완료"
2191 } else if t.is_some_and(|t| t.error == Some(ErrorCode::RecoveryImpossible)) {
2192 "복구 가능한 항목 없음"
2193 } else if t.is_some_and(|t| t.outcome == Outcome::Cancelled) {
2194 "복구를 취소했습니다"
2195 } else {
2196 "복구본 저장을 완료하지 못했습니다"
2197 };
2198 ui.heading(title);
2199 ui.label(
2200 "원본은 수정하지 않습니다. 검증 통과는 손상 전 내용과 동일하다는 보증이 아닙니다.",
2201 );
2202 let output = match &self.last_request {
2203 Some(Start::RecoverZip { output_file, .. }) => output_file.clone(),
2204 _ => return,
2205 };
2206 if saved
2207 || self
2208 .model
2209 .outputs
2210 .iter()
2211 .any(|(_, d)| matches!(d, Disposition::Created | Disposition::CommitUncertain))
2212 {
2213 theme::bounded_text(ui, &output.display().to_string(), ui.available_width());
2214 }
2215 for (name, _) in self
2216 .model
2217 .outputs
2218 .iter()
2219 .filter(|(_, d)| *d == Disposition::PartialRetained)
2220 {
2221 let retained = output.parent().unwrap_or(Path::new("")).join(name);
2222 theme::bounded_text(
2223 ui,
2224 &format!("남은 임시 파일: {}", retained.display()),
2225 ui.available_width(),
2226 );
2227 }
2228 if let Some(error) = &self.model.error {
2229 ui.colored_label(theme::WARNING, error);
2230 }
2231 if let Some(t) = t {
2232 if let Some(code) = t.error {
2233 ui.label(present::error_text(code));
2234 }
2235 for warning in present::publication_warnings(
2236 Some(t),
2237 self.model.confirmed,
2238 Some(&BTreeSet::from([output
2239 .file_name()
2240 .unwrap_or_default()
2241 .to_string_lossy()
2242 .into_owned()])),
2243 &BTreeSet::new(),
2244 &self.model.outputs,
2245 ) {
2246 ui.colored_label(theme::WARNING, warning);
2247 }
2248 if let Some(warning) = present::durability_warning(t.durability) {
2249 ui.colored_label(theme::WARNING, warning);
2250 }
2251 }
2252 let notice = summary.map(|s| {
2253 format!(
2254 "검증되어 포함됨 {}개 / 유실됨 {}개 / 무결성 미확인 {}개{}",
2255 s.verified_entries,
2256 s.lost_entries,
2257 s.unverified_entries,
2258 if s.unknown_loss {
2259 " / 전체 목록을 알 수 없어 추가 유실 여부를 확인할 수 없습니다"
2260 } else {
2261 ""
2262 }
2263 )
2264 });
2265 if let Some(notice) = &notice {
2266 ui.label(notice);
2267 }
2268 egui::ScrollArea::vertical()
2269 .id_salt("recovery-findings")
2270 .max_height(220.0)
2271 .show_rows(ui, 24.0, self.model.recovery_entries.len(), |ui, rows| {
2272 for entry in &self.model.recovery_entries[rows] {
2273 let status = match entry.status {
2274 RecoveryStatus::Verified => "검증되어 포함됨",
2275 RecoveryStatus::Lost => "유실됨",
2276 RecoveryStatus::Unverified => "무결성 미확인",
2277 };
2278 let reason = match entry.reason {
2279 RecoveryReason::None => "내용 검증 통과",
2280 RecoveryReason::HeaderRebuilt => "헤더 재구성",
2281 RecoveryReason::Truncated => "파일 절단",
2282 RecoveryReason::CrcMismatch => "CRC 불일치",
2283 RecoveryReason::DecodeFailure => "압축 데이터 손상",
2284 RecoveryReason::BoundaryUnknown => "항목 경계 불명",
2285 RecoveryReason::UnsupportedFeature => "지원하지 않는 기능",
2286 RecoveryReason::MetadataMissing => "메타정보 누락",
2287 };
2288 theme::bounded_text(
2289 ui,
2290 &format!(
2291 "{status} / {reason}: {}",
2292 entry.name.as_deref().unwrap_or("이름 확인 불가")
2293 ),
2294 ui.available_width(),
2295 );
2296 }
2297 });
2298 if saved && theme::action(ui, "복구본 열기", true, true).clicked() {
2299 self.recovery_warning = partial.then(|| (output.clone(), notice.unwrap_or_default()));
2300 self.open_path(output);
2301 }
2302 if self.model.can_retry_expanded()
2303 && theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked()
2304 {
2305 self.model.retry_expanded(self.factory.as_mut());
2306 }
2307 }
2308
2309 fn result(&mut self, ui: &mut egui::Ui) {
2310 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
2311 self.recovery_result(ui);
2312 return;
2313 }
2314 if self.model.confirmed
2315 && self.model.error.is_none()
2316 && self
2317 .model
2318 .terminal
2319 .as_ref()
2320 .is_some_and(|t| t.error == Some(ErrorCode::Integrity))
2321 && matches!(
2322 self.last_request,
2323 Some(Start::List { .. } | Start::Extract { .. })
2324 )
2325 {
2326 ui.label("원본을 바꾸지 않고 새 ZIP 복구본을 만듭니다. 일부 항목은 복구되지 않을 수 있습니다.");
2327 if theme::action(ui, "복구본 저장 위치 선택", true, true).clicked() {
2328 self.open_picker(Purpose::SaveRecoveryZip);
2329 }
2330 }
2331 let t = self.model.terminal.clone();
2332 let listing = matches!(self.last_request, Some(Start::List { .. }));
2333 let creating = matches!(
2334 self.last_request,
2335 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2336 );
2337 let resolved_targets = present::resolved_targets(
2338 self.targets.as_ref(),
2339 &self.model.entries,
2340 matches!(
2341 self.last_request,
2342 Some(Start::Extract {
2343 gzip_output_name: Some(_),
2344 ..
2345 })
2346 )
2347 .then_some(self.gzip_name.as_str()),
2348 &self.model.resolutions,
2349 );
2350 let skipped = self
2351 .model
2352 .resolutions
2353 .iter()
2354 .filter(|r| r.choice == ConflictChoice::Skip)
2355 .count();
2356 let created_names = self
2357 .model
2358 .outputs
2359 .iter()
2360 .filter(|(_, disposition)| *disposition == Disposition::Created)
2361 .map(|(name, _)| name.replace('\\', "/"))
2362 .collect::<BTreeSet<_>>();
2363 let warnings = if listing {
2364 Vec::new()
2365 } else {
2366 present::publication_warnings(
2367 t.as_ref(),
2368 self.model.confirmed,
2369 resolved_targets.as_ref(),
2370 &self.directories,
2371 &self.model.outputs,
2372 )
2373 };
2374 let success = self.model.confirmed
2375 && self.model.error.is_none()
2376 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
2377 && warnings
2378 .iter()
2379 .all(|warning| !creating && *warning == present::CLEANUP_WARNING);
2380 let durability_warning = t
2381 .as_ref()
2382 .filter(|_| self.model.confirmed && !listing)
2383 .and_then(|t| present::durability_warning(t.durability));
2384 let durability_in_details = success
2385 && t.as_ref()
2386 .is_some_and(|t| t.durability == Durability::Unconfirmed);
2387 let cancelled =
2388 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
2389 let title = if success {
2390 if creating {
2391 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2392 "7z 파일을 만들었습니다"
2393 } else {
2394 "ZIP 파일을 만들었습니다"
2395 }
2396 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
2397 "모든 파일을 건너뛰었습니다"
2398 } else {
2399 "압축을 풀었습니다"
2400 }
2401 } else if cancelled {
2402 "작업을 취소했습니다"
2403 } else if listing {
2404 "압축파일을 열지 못했습니다"
2405 } else if creating {
2406 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2407 "7z 파일을 만들지 못했습니다"
2408 } else {
2409 "ZIP 파일을 만들지 못했습니다"
2410 }
2411 } else {
2412 "압축을 풀지 못했습니다"
2413 };
2414 let fill = if success {
2415 theme::SUCCESS_BG
2416 } else if cancelled {
2417 theme::STRIPE
2418 } else {
2419 theme::ERROR_BG
2420 };
2421 let mut choose = false;
2422 let mut retry = false;
2423 let mut expand = false;
2424 let mut reopen = false;
2425 let mut folder = false;
2426 theme::panel(fill).show(ui, |ui| {
2427 ui.horizontal(|ui| {
2428 theme::icon(
2429 ui,
2430 if success {
2431 Icon::Success
2432 } else if cancelled {
2433 Icon::Warning
2434 } else {
2435 Icon::Error
2436 },
2437 24.0,
2438 );
2439 ui.strong(title);
2440 });
2441 let max_height = WORK_RESULT_MAX_HEIGHT;
2442 egui::ScrollArea::vertical()
2443 .id_salt("result-message")
2444 .max_height(max_height)
2445 .show(ui, |ui| {
2446 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
2447 let path = match self.last_request.as_ref() {
2448 Some(
2449 Start::CreateZip { output_file, .. }
2450 | Start::CreateSevenZip { output_file, .. },
2451 ) => output_file.display().to_string(),
2452 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
2453 };
2454 theme::bounded_text(ui, &path, ui.available_width());
2455 } else if let Some(problem) = &self.model.volume_problem {
2456 ui.add(egui::Label::new(present::volume_problem_text(problem)).wrap());
2457 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
2458 ui.label(
2459 if matches!(
2460 code,
2461 ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature
2462 ) && self
2463 .model
2464 .archive
2465 .as_ref()
2466 .is_some_and(|p| present::excluded_split(p))
2467 {
2468 present::SPLIT_SUPPORT.to_owned()
2469 } else if creating && code == ErrorCode::SourceChanged {
2470 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
2471 .to_owned()
2472 } else {
2473 present::operation_text(present::error_text(code), creating)
2474 },
2475 );
2476 } else if let Some(error) = &self.model.error {
2477 ui.label(present::operation_text(
2478 present::client_error_text(error),
2479 creating,
2480 ));
2481 }
2482 if skipped > 0 {
2483 ui.label(format!("건너뛴 파일 {skipped}개"));
2484 }
2485 for resolution in self.model.resolutions.iter().filter(|r| {
2486 r.choice == ConflictChoice::Rename
2487 && created_names.contains(&r.relative_name.replace('\\', "/"))
2488 }) {
2489 theme::bounded_text(
2490 ui,
2491 &format!("이름 바꿔 저장: {}", resolution.relative_name),
2492 ui.available_width(),
2493 );
2494 }
2495 for warning in warnings
2496 .iter()
2497 .copied()
2498 .chain(durability_warning.filter(|_| !durability_in_details))
2499 {
2500 ui.horizontal_wrapped(|ui| {
2501 theme::icon(ui, Icon::Warning, 20.0);
2502 ui.colored_label(
2503 theme::WARNING,
2504 present::operation_text(warning, creating),
2505 );
2506 });
2507 }
2508 if !success
2509 && !listing
2510 && present::definitely_unsaved(
2511 t.as_ref(),
2512 self.model.confirmed,
2513 &self.model.outputs,
2514 )
2515 {
2516 ui.label(if creating {
2517 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2518 "7z 파일을 만들지 않았습니다"
2519 } else {
2520 "ZIP 파일을 만들지 않았습니다"
2521 }
2522 } else {
2523 "아무 파일도 풀지 않았습니다"
2524 });
2525 }
2526 if t.as_ref().is_some_and(|t| {
2527 t.error == Some(ErrorCode::Limit)
2528 && (t.created_count > 0
2529 || t.retained_partial_count > 0
2530 || t.publication != Publication::None)
2531 }) {
2532 ui.label(format!(
2533 "{}개 파일이 저장되었거나 일부 남아 있습니다. 저장 위치를 확인하세요.",
2534 t.as_ref().unwrap().created_count
2535 ));
2536 theme::bounded_text(
2537 ui,
2538 &self.destination.display().to_string(),
2539 ui.available_width(),
2540 );
2541 }
2542 if self.details {
2543 theme::panel(theme::STRIPE).show(ui, |ui| {
2544 if durability_in_details {
2545 if let Some(warning) = durability_warning {
2546 ui.label(present::operation_text(warning, creating));
2547 }
2548 }
2549 if let Some(t) = &t {
2550 for line in terminal_lines(t) {
2551 ui.label(line);
2552 }
2553 }
2554 if let Some(error) = &self.model.error {
2555 ui.label(error);
2556 }
2557 for (name, state) in &self.model.outputs {
2558 theme::bounded_text(
2559 ui,
2560 &format!("{name}: {}", disposition_label(*state)),
2561 ui.available_width(),
2562 );
2563 }
2564 });
2565 }
2566 });
2567 let conflict = t
2568 .as_ref()
2569 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
2570 && !creating;
2571 let uncertain = warnings.contains(&present::UNCERTAIN);
2572 if conflict && uncertain {
2573 let response = ui.checkbox(
2574 &mut self.checked_destination,
2575 "기존 풀 위치 폴더를 확인했습니다",
2576 );
2577 theme::pointer(&response);
2578 theme::focus(&response);
2579 }
2580 ui.horizontal(|ui| {
2581 if theme::action(
2582 ui,
2583 if self.details {
2584 "자세히 닫기"
2585 } else {
2586 "자세히 보기"
2587 },
2588 false,
2589 true,
2590 )
2591 .clicked()
2592 {
2593 self.details = !self.details;
2594 }
2595 let action = if success {
2596 Some(("폴더 열기", true))
2597 } else if conflict {
2598 Some((
2599 if self
2600 .model
2601 .list_id
2602 .as_ref()
2603 .is_some_and(|id| id.format == Format::Gzip)
2604 {
2605 "다른 이름으로 저장"
2606 } else {
2607 "다른 폴더에 풀기"
2608 },
2609 !uncertain || self.checked_destination,
2610 ))
2611 } else if t
2612 .as_ref()
2613 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
2614 {
2615 Some((
2616 if creating {
2617 "다시 만들기"
2618 } else {
2619 "압축파일 다시 열기"
2620 },
2621 true,
2622 ))
2623 } else if self.model.can_retry_expanded() {
2624 None
2625 } else if t
2626 .as_ref()
2627 .is_some_and(|t| t.error == Some(ErrorCode::Limit))
2628 {
2629 None
2630 } else if !cancelled && (!uncertain || listing) {
2631 Some(("다시 시도", true))
2632 } else {
2633 None
2634 };
2635 let (confirm, primary) = theme::action_pair(ui, "확인", action);
2636 if confirm {
2637 self.dismissed = true;
2638 self.ui_error = None;
2639 self.model.input_error = None;
2640 }
2641 if primary {
2642 match action.map(|(label, _)| label) {
2643 Some("폴더 열기") => folder = true,
2644 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
2645 choose = true
2646 }
2647 Some("압축파일 다시 열기") => reopen = true,
2648 Some("다시 시도" | "다시 만들기") => retry = true,
2649 _ => {}
2650 }
2651 }
2652 });
2653 if self.model.can_retry_expanded() {
2654 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2655 expand = theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked();
2656 });
2657 }
2658 });
2659 if choose {
2660 self.open_picker(Purpose::Retry);
2661 }
2662 if retry {
2663 self.retry();
2664 }
2665 if expand {
2666 let ready = if matches!(self.last_request, Some(Start::Extract { .. })) {
2667 match present::prepare_destination(&self.destination, self.automatic_destination) {
2668 Ok(created) => {
2669 self.owned_destination = created.then(|| self.destination.clone());
2670 true
2671 }
2672 Err(_) => {
2673 self.ui_error = Some(present::FOLDER_ERROR.into());
2674 false
2675 }
2676 }
2677 } else {
2678 true
2679 };
2680 if ready && self.model.retry_expanded(self.factory.as_mut()) {
2681 self.dismissed = false;
2682 self.details = false;
2683 self.ui_error = None;
2684 }
2685 }
2686 if reopen {
2687 if let Some(path) = self.model.archive.clone() {
2688 self.open_path(path);
2689 }
2690 }
2691 if folder {
2692 let path = match self.last_request.as_ref() {
2693 Some(
2694 Start::CreateZip { output_file, .. }
2695 | Start::CreateSevenZip { output_file, .. },
2696 ) => output_file.parent().unwrap_or(Path::new("/")),
2697 _ => self.destination.as_path(),
2698 };
2699 match present::folder_command(path).spawn() {
2700 Ok(mut child) => {
2701 std::thread::spawn(move || {
2702 let _ = child.wait();
2703 });
2704 }
2705 Err(_) => {
2706 self.ui_error = Some(
2707 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
2708 )
2709 }
2710 }
2711 }
2712 }
2713
2714 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
2715 fn entry_cells(
2716 ui: &mut egui::Ui,
2717 rect: egui::Rect,
2718 directory: bool,
2719 name: &str,
2720 hover: &str,
2721 size: String,
2722 name_width: f32,
2723 ) {
2724 ui.scope_builder(
2725 egui::UiBuilder::new()
2726 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
2727 .layout(Layout::left_to_right(Align::Center)),
2728 |ui| {
2729 ui.style_mut().interaction.selectable_labels = false;
2730 ui.add_space(16.0);
2731 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
2732 theme::bounded_text_hover(ui, name, hover, name_width);
2733 theme::column_label(ui, size, 96.0, Align::Max);
2734 },
2735 );
2736 }
2737
2738 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
2739 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
2740 fn create_window(&mut self, ctx: &egui::Context) {
2741 if !self.create || self.model.busy() {
2742 self.create_win = WorkWindow::default();
2743 return;
2744 }
2745 if ctx.embed_viewports() {
2746 let mut close = false;
2747 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
2748 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
2749 ui.horizontal(|ui| {
2750 ui.heading(if self.seven_zip {
2751 "7z 만들기"
2752 } else {
2753 "ZIP 만들기"
2754 });
2755 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2756 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
2757 close = button.clicked();
2758 });
2759 });
2760 close |= self.create_area(ui);
2761 ui.add_space(theme::SPACE);
2762 close |= self.create_actions(ui);
2763 });
2764 if close || modal.should_close() {
2765 self.close_create();
2766 }
2767 return;
2768 }
2769 let id = egui::ViewportId::from_hash_of("archive-create");
2770 let title = if self.seven_zip {
2771 "7z 만들기 — Zipelo"
2772 } else {
2773 "ZIP 만들기 — Zipelo"
2774 };
2775 let custom_frame = self.custom_frame;
2776 if !self.create_win.open {
2777 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
2778 }
2779 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
2780 let builder =
2781 self.create_win
2782 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
2783 let mut close = false;
2784 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
2785 if ui.ctx().input(|i| i.viewport().close_requested()) {
2786 close = true;
2787 }
2788 if class == egui::ViewportClass::EmbeddedWindow {
2789 ui.set_width(CREATE_WIDTH);
2790 close |= self.create_area(ui);
2791 close |= self.create_actions(ui);
2792 return None;
2793 }
2794 let mut chrome = 0.0;
2795 if custom_frame {
2796 window_frame::title_bar(
2797 ui,
2798 "create",
2799 title,
2800 window_frame::Buttons {
2801 minimize: false,
2802 maximize: false,
2803 },
2804 );
2805 window_frame::edges(ui.ctx(), false);
2806 chrome = window_frame::TITLE_HEIGHT;
2807 }
2808 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
2809 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
2810 .resizable(false)
2811 .show_separator_line(false)
2812 .frame(
2813 egui::Frame::new()
2814 .fill(theme::PANEL)
2815 .inner_margin(egui::Margin {
2816 left: theme::PAD,
2817 right: theme::PAD,
2818 top: 0,
2819 bottom: theme::PAD,
2820 }),
2821 )
2822 .show(ui, |ui| close |= self.create_actions(ui))
2823 .response
2824 .rect
2825 .height();
2826 let margin = theme::PAD as f32;
2827 egui::CentralPanel::default()
2828 .frame(theme::panel(theme::PANEL).corner_radius(0))
2829 .show(ui, |ui| {
2830 let content = ui
2831 .vertical(|ui| close |= self.create_area(ui))
2832 .response
2833 .rect;
2834 Some(content.height() + 2.0 * margin + chrome + actions)
2835 })
2836 .inner
2837 });
2838 if let Some(height) = height {
2839 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
2840 if (height - self.create_win.height).abs() > 1.0 {
2841 self.create_win.height = height;
2842 }
2843 }
2844 if close {
2845 self.close_create();
2846 }
2847 }
2848
2849 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
2850 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
2851 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
2852 let enabled = self.picker.is_none();
2853 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
2854 .inner
2855 }
2856
2857 fn set_seven_zip(&mut self, selected: bool) {
2858 if self.seven_zip == selected {
2859 return;
2860 }
2861 self.seven_zip = selected;
2862 self.aes256 = false;
2863 self.clear_zip_password();
2864 self.ui_error = None;
2865 let name = self.zip_name.clone();
2866 let lower = name.to_ascii_lowercase();
2867 let stem = if lower.ends_with(".zip") {
2868 &name[..name.len() - 4]
2869 } else if lower.ends_with(".7z") {
2870 &name[..name.len() - 3]
2871 } else {
2872 &name
2873 };
2874 self.zip_name = format!("{stem}{}", if selected { ".7z" } else { ".zip" });
2875 }
2876
2877 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
2878 let mut selected = self.seven_zip;
2879 ui.horizontal(|ui| {
2880 ui.label("형식");
2881 ui.selectable_value(&mut selected, false, "ZIP");
2882 ui.selectable_value(&mut selected, true, "7z");
2883 if selected {
2884 ui.label("LZMA2");
2885 }
2886 });
2887 self.set_seven_zip(selected);
2888
2889 let rows = self.create_rows();
2890 let root = self.create_root();
2891
2892 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
2893 ui.horizontal(|ui| {
2894 ui.set_height(theme::FIELD);
2895 ui.spacing_mut().item_spacing.x = 0.0;
2896 let up = theme::flat_icon_button(
2897 ui,
2898 "위로",
2899 theme::UP,
2900 !self.create_folder.is_empty(),
2901 egui::vec2(theme::FIELD, theme::FIELD),
2902 );
2903 if up.clicked() {
2904 self.create_folder = self
2905 .create_folder
2906 .rsplit_once('/')
2907 .map_or("", |(parent, _)| parent)
2908 .to_owned();
2909 self.create_selected = None;
2910 }
2911 ui.add_space(6.0);
2912 let path = match &root {
2913 Some(root) => {
2914 let name = root.file_name().unwrap_or_default().to_string_lossy();
2915 if self.create_folder.is_empty() {
2916 format!("/{name}")
2917 } else {
2918 format!("/{name}/{}", self.create_folder)
2919 }
2920 }
2921 None => "/".to_owned(),
2922 };
2923 let (rect, _) = ui.allocate_exact_size(
2924 egui::vec2(ui.available_width(), theme::FIELD),
2925 egui::Sense::hover(),
2926 );
2927 theme::boxed_field(ui, rect);
2928 theme::field_text(ui, rect, &path);
2929 });
2930 ui.add_space(theme::SPACE);
2931
2932 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
2933 let mut enter = None;
2934 egui::Frame::new()
2935 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2936 .show(ui, |ui| {
2937 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
2938 ui.set_max_height(CREATE_LIST_HEIGHT);
2939 let message = match &rows {
2940 None => Some("폴더를 읽지 못했습니다"),
2941 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
2942 Some(_) => None,
2943 };
2944 if let Some(message) = message {
2945 ui.centered_and_justified(|ui| ui.label(message));
2946 return;
2947 }
2948 let rows = rows.unwrap();
2949 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
2950 egui::ScrollArea::vertical()
2951 .id_salt("create-rows")
2952 .auto_shrink([false, false])
2953 .max_height(CREATE_LIST_HEIGHT)
2954 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
2955 for row in &rows[range] {
2956 let (rect, response) = ui.allocate_exact_size(
2957 egui::vec2(ui.available_width(), LIST_ROW),
2958 egui::Sense::click(),
2959 );
2960 let response = response.on_hover_text(&row.name);
2961 theme::pointer(&response);
2962 response.widget_info(|| {
2963 egui::WidgetInfo::labeled(
2964 egui::Role::ListBoxOption,
2965 true,
2966 &row.name,
2967 )
2968 });
2969 if response.clicked() {
2970 self.create_selected = Some(row.name.clone());
2971 }
2972 theme::row_background(
2973 ui,
2974 rect,
2975 self.create_selected.as_deref() == Some(row.name.as_str()),
2976 response.hovered(),
2977 );
2978 if row.directory && root.is_some() && response.clicked() {
2979 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
2980 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
2981 let frame = ui.ctx().cumulative_frame_nr();
2982 let time = ui.input(|i| i.time);
2983 match &self.create_last_click {
2984 Some((name, last_frame, last_time))
2985 if name == &row.name
2986 && *last_frame != frame
2987 && time - last_time < 0.4 =>
2988 {
2989 enter = Some(row.name.clone());
2990 self.create_last_click = None;
2991 }
2992 Some((name, last_frame, _))
2993 if name == &row.name && *last_frame == frame => {}
2994 _ => {
2995 self.create_last_click =
2996 Some((row.name.clone(), frame, time));
2997 }
2998 }
2999 }
3000 Self::entry_cells(
3001 ui,
3002 rect,
3003 row.directory,
3004 &row.name,
3005 &row.name,
3006 row.bytes.map(present::bytes_text).unwrap_or_default(),
3007 name_width,
3008 );
3009 }
3010 });
3011 });
3012 if let Some(name) = enter {
3013 self.create_folder = if self.create_folder.is_empty() {
3014 name
3015 } else {
3016 format!("{}/{name}", self.create_folder)
3017 };
3018 self.create_selected = None;
3019 }
3020 ui.add_space(theme::SPACE);
3021
3022 if let Some(error) = &self.ui_error {
3023 Self::error_notice(ui, error);
3024 }
3025
3026 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
3027 if self.seven_zip {
3028 ui.label("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요");
3029 return false;
3030 }
3031 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
3032 theme::pointer(&check);
3033 theme::focus(&check);
3034 if self.aes256 {
3035 let label_width = 72.0;
3036 ui.horizontal(|ui| {
3037 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
3038 let toggle = if self.zip_password_visible {
3039 "숨기기"
3040 } else {
3041 "보기"
3042 };
3043 let toggle_width = 72.0;
3044 let edit = ui.add_sized(
3045 [
3046 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
3047 theme::FIELD,
3048 ],
3049 egui::TextEdit::singleline(&mut self.zip_password)
3050 .password(!self.zip_password_visible)
3051 .id(egui::Id::unique("zip-password-input"))
3052 .char_limit(1024)
3053 .align(egui::Align2::LEFT_CENTER),
3054 );
3055 theme::focus(&edit);
3056 if theme::action(ui, toggle, false, true).clicked() {
3057 self.zip_password_visible = !self.zip_password_visible;
3058 }
3059 });
3060 ui.horizontal(|ui| {
3061 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
3062 let edit = ui.add_sized(
3063 [
3064 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
3065 theme::FIELD,
3066 ],
3067 egui::TextEdit::singleline(&mut self.zip_password_confirm)
3068 .password(!self.zip_password_visible)
3069 .id(egui::Id::unique("zip-password-confirm"))
3070 .char_limit(1024)
3071 .align(egui::Align2::LEFT_CENTER),
3072 );
3073 theme::focus(&edit);
3074 });
3075 if self.zip_password.len() > 1024 {
3076 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
3077 } else if !self.zip_password_confirm.is_empty()
3078 && self.zip_password != self.zip_password_confirm
3079 {
3080 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
3081 }
3082 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
3083 } else if check.changed()
3084 || !self.zip_password.is_empty()
3085 || !self.zip_password_confirm.is_empty()
3086 {
3087 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
3088 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
3089 self.clear_zip_password();
3090 }
3091 false
3092 }
3093
3094 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
3095 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
3096 let ready = !self.sources.is_empty() && self.zip_password_ready();
3097 let enabled = self.picker.is_none();
3098 let (cancel, compress) = ui
3099 .add_enabled_ui(enabled, |ui| {
3100 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
3101 })
3102 .inner;
3103 if compress {
3104 self.open_picker(if self.seven_zip {
3105 Purpose::SaveSevenZip
3106 } else {
3107 Purpose::SaveZip
3108 });
3109 }
3110 cancel
3111 }
3112
3113 fn resource_dialog(&mut self, ctx: &egui::Context) {
3114 let Some(question) = self.model.resource.clone() else {
3115 return;
3116 };
3117 let Some(job) = self.model.job_id() else {
3118 return;
3119 };
3120 let mut allow = false;
3121 let mut cancel = false;
3122 let modal = egui::Modal::new(egui::Id::unique(("archive-resource", job, question.id)))
3123 .show(ctx, |ui| {
3124 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
3125 ui.heading(if question.scope.ratio {
3126 "압축률이 매우 높습니다"
3127 } else {
3128 "큰 작업을 허용할까요?"
3129 });
3130 ui.label(match question.action {
3131 ActionKind::List => "압축파일 목록 열기",
3132 ActionKind::Extract => "압축 해제",
3133 ActionKind::CreateZip => "ZIP 만들기",
3134 ActionKind::CreateSevenZip => "7z 만들기",
3135 ActionKind::RecoverZip => "ZIP 복구",
3136 ActionKind::Preview => "파일 미리보기",
3137 });
3138 if question.scope.ratio {
3139 ui.label("작은 압축파일도 많은 저장 공간을 사용할 수 있습니다.");
3140 }
3141 if question.scope.output {
3142 ui.label(format!(
3143 "총량 한도: {}에서 {}로",
3144 present::bytes_text(question.soft_limits.output),
3145 present::bytes_text(question.ceiling.output)
3146 ));
3147 }
3148 if question.scope.entries {
3149 ui.label(format!(
3150 "항목 한도: {}개에서 {}개로",
3151 question.soft_limits.entries, question.ceiling.entries
3152 ));
3153 }
3154 let mut u = question.usage;
3155 let estimated = self.model.estimated_usage();
3156 u.estimated_bytes = u.estimated_bytes.or(estimated.estimated_bytes);
3157 u.estimated_entries = u.estimated_entries.or(estimated.estimated_entries);
3158 let bytes = |value: Option<u64>| {
3159 value
3160 .map(present::bytes_text)
3161 .unwrap_or_else(|| "미확인".into())
3162 };
3163 let entries = |value: Option<u32>| {
3164 value
3165 .map(|n| format!("{n}개"))
3166 .unwrap_or_else(|| "미확인".into())
3167 };
3168 ui.label(format!(
3169 "예상 총량: {} / 실제 총량: {}",
3170 bytes(u.estimated_bytes),
3171 bytes(u.actual_bytes)
3172 ));
3173 ui.label(format!(
3174 "예상 항목: {} / 실제 항목: {}",
3175 entries(u.estimated_entries),
3176 entries(u.actual_entries)
3177 ));
3178 if question.scope.ratio {
3179 ui.label(format!(
3180 "압축 크기: {} / 풀린 크기: {}",
3181 bytes(u.compressed_bytes),
3182 bytes(u.ratio_output_bytes)
3183 ));
3184 }
3185 ui.label(format!(
3186 "확인한 저장 볼륨의 여유 공간: {}",
3187 bytes(u.available_bytes)
3188 ));
3189 ui.label(format!(
3190 "이 작업의 상한: {} / {}개",
3191 present::bytes_text(question.ceiling.output),
3192 question.ceiling.entries
3193 ));
3194 ui.label("이 작업에만 적용합니다. 공간 부족이나 자원 상한에 도달하면 중단합니다.");
3195 ui.horizontal(|ui| {
3196 cancel = theme::action(ui, "취소", false, true).clicked();
3197 allow = theme::action(ui, "이 작업 허용", true, true).clicked();
3198 });
3199 });
3200 if cancel || modal.should_close() {
3201 self.clear_password();
3202 self.model.cancel();
3203 } else if allow {
3204 self.model.resource_reply(job, question.id, true);
3205 }
3206 }
3207
3208 fn conflict_dialog(&mut self, ctx: &egui::Context) {
3209 let conflict = self.model.conflict.clone().unwrap();
3210 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
3211 if self.conflict_challenge != Some(question) {
3212 self.conflict_challenge = Some(question);
3213 self.conflict_apply = false;
3214 }
3215 let mut choice = None;
3216 let mut cancel = false;
3217 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
3218 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
3219 ui.heading("같은 이름의 파일이 있습니다");
3220 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
3221 ui.add_space(theme::SPACE);
3222 egui::Grid::new("conflict-sizes")
3223 .spacing([24.0, 8.0])
3224 .show(ui, |ui| {
3225 ui.label("기존 파일");
3226 ui.label(present::bytes_text(conflict.existing_size));
3227 ui.end_row();
3228 ui.label("압축파일 안의 파일");
3229 ui.label(present::bytes_text(conflict.incoming_size));
3230 ui.end_row();
3231 });
3232 ui.add_space(theme::SPACE);
3233 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
3234 ui.add_space(theme::SPACE);
3235 ui.horizontal_wrapped(|ui| {
3236 for (label, value) in [
3237 ("덮어쓰기", ConflictChoice::Overwrite),
3238 ("건너뛰기", ConflictChoice::Skip),
3239 ("이름 바꿔 저장", ConflictChoice::Rename),
3240 ] {
3241 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
3242 choice = Some(value);
3243 }
3244 }
3245 });
3246 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
3247 if let Some(error) = &self.model.error {
3248 Self::error_notice(ui, present::client_error_text(error));
3249 }
3250 cancel = theme::action(ui, "작업 취소", false, true).clicked();
3251 });
3252 if modal.should_close() || cancel {
3253 self.model.cancel();
3254 } else if let Some(choice) = choice {
3255 self.model.resolve_conflict(choice, self.conflict_apply);
3256 }
3257 }
3258
3259 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
3260 let (_, attempt, encrypt) = self.model.challenge.unwrap();
3261 let mut submit = false;
3262 let mut cancel = false;
3263 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
3264 id == egui::Id::unique("archive-password-input")
3265 || id == egui::Id::unique("archive-password-confirm")
3266 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
3267 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
3268 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
3269 ui.heading(if encrypt {
3270 "ZIP 암호 설정"
3271 } else {
3272 "암호가 필요합니다"
3273 });
3274 if encrypt {
3275 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
3276 } else if let Some(path) = &self.model.archive {
3277 ui.label(format!(
3278 "{}은 암호로 보호되어 있습니다.",
3279 present::middle_text(
3280 &path.file_name().unwrap_or_default().to_string_lossy(),
3281 24
3282 )
3283 ));
3284 }
3285 ui.horizontal(|ui| {
3286 ui.label("암호");
3287 let edit = ui.add(
3288 egui::TextEdit::singleline(&mut self.password)
3289 .password(!self.password_visible)
3290 .id(egui::Id::unique("archive-password-input"))
3291 .char_limit(1024)
3292 .desired_width(232.0),
3293 );
3294 theme::focus(&edit);
3295 if new_challenge {
3296 edit.request_focus();
3297 }
3298 if theme::action(
3299 ui,
3300 if self.password_visible {
3301 "숨기기"
3302 } else {
3303 "보기"
3304 },
3305 false,
3306 true,
3307 )
3308 .clicked()
3309 {
3310 self.password_visible = !self.password_visible;
3311 }
3312 });
3313 if encrypt {
3314 ui.horizontal(|ui| {
3315 ui.label("암호 확인");
3316 let edit = ui.add(
3317 egui::TextEdit::singleline(&mut self.password_confirm)
3318 .password(!self.password_visible)
3319 .id(egui::Id::unique("archive-password-confirm"))
3320 .char_limit(1024)
3321 .desired_width(232.0),
3322 );
3323 theme::focus(&edit);
3324 });
3325 if self.password != self.password_confirm {
3326 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
3327 }
3328 } else if attempt > 1 {
3329 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
3330 }
3331 if self.password.len() > 1024 {
3332 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
3333 }
3334 let valid = !self.password.is_empty()
3335 && self.password.len() <= 1024
3336 && (!encrypt || self.password == self.password_confirm);
3337 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
3338 cancel = actions.0;
3339 submit = actions.1 || (valid && password_enter);
3340 });
3341 if modal.should_close() || cancel {
3342 self.clear_password();
3343 self.model.cancel();
3344 } else if submit {
3345 let password = std::mem::take(&mut self.password);
3346 self.clear_password();
3347 self.model.password(password);
3348 }
3349 }
3350
3351 fn close_dialog(&mut self, ctx: &egui::Context) {
3352 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
3353 if matches!(
3354 self.model.close,
3355 Close::Open | Close::Allowed | Close::Review
3356 ) {
3357 return;
3358 }
3359 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
3360 ui.set_width(420.0);
3361 match self.model.close {
3362 Close::Confirm => {
3363 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
3364 let busy = self.model.busy();
3365 let (heading, text, keep, close) = if busy {
3366 (
3367 "작업 중 닫기",
3368 "작업을 취소하고 닫을까요?",
3369 "계속 작업",
3370 "취소하고 닫기",
3371 )
3372 } else {
3373 (
3374 "닫기",
3375 "작업이 끝났습니다. 창을 닫을까요?",
3376 "열어 두기",
3377 "닫기",
3378 )
3379 };
3380 ui.heading(heading);
3381 ui.label(text);
3382 ui.horizontal(|ui| {
3383 if theme::action(ui, keep, false, true).clicked() {
3384 self.model.keep_open();
3385 }
3386 if theme::action(ui, close, true, true).clicked() {
3387 self.clear_password();
3388 self.model.confirm_close();
3389 }
3390 });
3391 }
3392 Close::Waiting => {
3393 ui.heading("종료 확인 중");
3394 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
3395 if theme::action(ui, "닫기 취소", false, true).clicked() {
3396 self.model.keep_open();
3397 }
3398 }
3399 _ => {}
3400 }
3401 });
3402 }
3403}
3404
3405impl eframe::App for ArchiveApp {
3406 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
3407 self.show(root);
3408 }
3409
3410 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
3411 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
3412 if std::mem::take(&mut self.release_after_move) {
3413 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
3414 raw_input.events.insert(
3415 0,
3416 egui::Event::PointerButton {
3417 pos,
3418 button: egui::PointerButton::Primary,
3419 pressed: false,
3420 modifiers: ctx.input(|i| i.modifiers),
3421 },
3422 );
3423 }
3424 }
3425}
3426impl Drop for ArchiveApp {
3427 fn drop(&mut self) {
3428 self.clear_password();
3429 }
3430}