team-ljyzipelo

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