team-ljyzipelo

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