team-ljyzipelo

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