team-ljyzipelo

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