team-ljyzipelo

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