team-ljyzipelo

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