team-ljyzipelo

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