team-ljyzipelo

공개
3,066줄125 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 || (matches!(
1792 terminal.error,
1793 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature)
1794 ) && self
1795 .model
1796 .archive
1797 .as_ref()
1798 .is_some_and(|p| present::excluded_split(p)))
1799 }))
1800 }
1801
1802 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
1803 if !self.limit_result_visible() || self.main_modal_open() {
1804 return;
1805 }
1806 egui::Modal::new(egui::Id::new("archive-limit-result")).show(ctx, |ui| {
1807 ui.set_width((ctx.content_rect().width() - 64.0).min(WORK_WIDTH));
1808 ui.heading("작업 결과");
1809 self.work_area(ui);
1810 });
1811 }
1812
1813 fn error_notice(ui: &mut egui::Ui, error: &str) {
1814 let response = theme::panel(theme::ERROR_BG)
1815 .show(ui, |ui| {
1816 ui.horizontal_wrapped(|ui| {
1817 theme::icon(ui, Icon::Error, 24.0);
1818 ui.colored_label(theme::ERROR, error);
1819 });
1820 })
1821 .response;
1822 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
1823 }
1824
1825 fn work_visible(&self) -> bool {
1826 !self
1827 .last_request
1828 .as_ref()
1829 .is_some_and(|r| matches!(r, Start::Preview { .. }))
1830 && (self.model.busy()
1831 || self.result_visible()
1832 || (self.ui_error.is_some() && !self.create))
1833 }
1834
1835 /// 메인 창 가운데에 모달(암호 입력, 종료 확인, 파일 선택 안내)이나 같은 자리에 뜨는
1836 /// ZIP 만들기 창이 떠 있는지. 닫기가 정해진 뒤(Allowed)에도 결과 창을 다시 띄우지 않음.
1837 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
1838 fn main_modal_open(&self) -> bool {
1839 (self.create && !self.model.busy())
1840 || self.picker.is_some()
1841 || self.model.challenge.is_some()
1842 || self.model.resource.is_some()
1843 || self.model.conflict.is_some()
1844 || self.model.close != Close::Open
1845 }
1846
1847 fn work_window(&mut self, ctx: &egui::Context) {
1848 if !self.work_visible() {
1849 self.work = WorkWindow::default();
1850 return;
1851 }
1852 if self.limit_result_visible() {
1853 self.work.open = false;
1854 return;
1855 }
1856 if ctx.embed_viewports() {
1857 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1858 return;
1859 }
1860 if self.main_modal_open() {
1861 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
1862 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1863 self.work.open = false;
1864 return;
1865 }
1866 let id = egui::ViewportId::from_hash_of("archive-work");
1867 let title = if self.model.busy() {
1868 present::activity_text(
1869 &self.model,
1870 matches!(self.last_request, Some(Start::CreateZip { .. })),
1871 )
1872 .to_owned()
1873 } else {
1874 "작업 결과".to_owned()
1875 };
1876 let window_title = format!("{title} — Zipelo");
1877 let custom_frame = self.custom_frame;
1878 let size = egui::vec2(WORK_WIDTH, self.work.height);
1879 let builder = self.work.builder(
1880 ctx,
1881 id,
1882 size,
1883 &window_title,
1884 !custom_frame,
1885 self.picker.is_some(),
1886 );
1887 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1888 if ui.ctx().input(|i| i.viewport().close_requested()) {
1889 if self.model.busy() {
1890 ui.ctx()
1891 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1892 } else {
1893 self.dismissed = true;
1894 self.ui_error = None;
1895 self.model.input_error = None;
1896 }
1897 }
1898 if class == egui::ViewportClass::EmbeddedWindow {
1899 ui.set_width(WORK_WIDTH);
1900 self.work_area(ui);
1901 return None;
1902 }
1903 let mut chrome = 0.0;
1904 if custom_frame {
1905 window_frame::title_bar(
1906 ui,
1907 "work",
1908 &window_title,
1909 window_frame::Buttons {
1910 minimize: false,
1911 maximize: false,
1912 },
1913 );
1914 window_frame::edges(ui.ctx(), false);
1915 chrome = window_frame::TITLE_HEIGHT;
1916 }
1917 let margin = theme::PAD as f32;
1918 egui::CentralPanel::default()
1919 .frame(theme::panel(theme::PANEL).corner_radius(0))
1920 .show(ui, |ui| {
1921 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1922 Some(content.height() + 2.0 * margin + chrome)
1923 })
1924 .inner
1925 });
1926 if let Some(height) = height {
1927 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1928 if (height - self.work.height).abs() > 1.0 {
1929 self.work.height = height;
1930 }
1931 }
1932 }
1933
1934 fn work_area(&mut self, ui: &mut egui::Ui) {
1935 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
1936 let enabled = self.picker.is_none();
1937 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
1938 }
1939
1940 fn work_contents(&mut self, ui: &mut egui::Ui) {
1941 if self.model.busy() {
1942 self.progress(ui);
1943 } else if self.result_visible() {
1944 self.result(ui);
1945 }
1946 if !self.create
1947 && let Some(error) = &self.ui_error
1948 {
1949 Self::error_notice(ui, error);
1950 if error == present::FOLDER_ERROR
1951 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
1952 {
1953 self.open_picker(Purpose::Destination);
1954 }
1955 }
1956 if let Some(error) = &self.model.input_error {
1957 ui.colored_label(
1958 theme::ERROR,
1959 if error.starts_with("암호는") {
1960 error.as_str()
1961 } else {
1962 if matches!(self.last_request, Some(Start::CreateZip { .. })) {
1963 "저장 위치와 추가한 항목을 확인하세요"
1964 } else {
1965 "풀 위치와 선택한 항목을 확인하세요"
1966 }
1967 },
1968 );
1969 }
1970 }
1971
1972 fn progress(&mut self, ui: &mut egui::Ui) {
1973 if self.model.resource.is_some() {
1974 ui.horizontal(|ui| {
1975 ui.label("사용자 허용을 기다리고 있습니다");
1976 self.cancel_action(ui, false);
1977 });
1978 return;
1979 }
1980 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1981 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
1982 let title = present::activity_text(&self.model, creating);
1983 ui.strong(title);
1984 if let Some((stage, done, total, count)) = self.model.progress {
1985 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
1986 let processed = if stage == Stage::Read {
1987 String::new()
1988 } else {
1989 format!("{count}개 처리함, ")
1990 };
1991 if let Some(total) = total.filter(|n| *n > 0) {
1992 ui.scope(|ui| {
1993 ui.visuals_mut().extreme_bg_color = theme::BORDER;
1994 ui.add(
1995 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
1996 .fill(theme::BLUE)
1997 .desired_height(theme::SPACE * 2.0),
1998 );
1999 });
2000 ui.horizontal(|ui| {
2001 ui.label(format!(
2002 "{:.0}% / {processed}{} / {}",
2003 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
2004 present::bytes_text(done),
2005 present::bytes_text(total)
2006 ));
2007 self.cancel_action(ui, cancelling);
2008 });
2009 } else {
2010 theme::indeterminate(ui);
2011 ui.horizontal(|ui| {
2012 ui.label(format!("{processed}{}", present::bytes_text(done)));
2013 self.cancel_action(ui, cancelling);
2014 });
2015 }
2016 } else {
2017 theme::indeterminate(ui);
2018 ui.horizontal(|ui| {
2019 ui.label("작업을 진행하고 있습니다");
2020 self.cancel_action(ui, cancelling);
2021 });
2022 }
2023 }
2024
2025 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
2026 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2027 if theme::action(ui, "취소", false, !cancelling).clicked() {
2028 self.clear_password();
2029 self.model.cancel();
2030 }
2031 });
2032 }
2033
2034 fn result(&mut self, ui: &mut egui::Ui) {
2035 let t = self.model.terminal.clone();
2036 let listing = matches!(self.last_request, Some(Start::List { .. }));
2037 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
2038 let resolved_targets = present::resolved_targets(
2039 self.targets.as_ref(),
2040 &self.model.entries,
2041 matches!(
2042 self.last_request,
2043 Some(Start::Extract {
2044 gzip_output_name: Some(_),
2045 ..
2046 })
2047 )
2048 .then_some(self.gzip_name.as_str()),
2049 &self.model.resolutions,
2050 );
2051 let skipped = self
2052 .model
2053 .resolutions
2054 .iter()
2055 .filter(|r| r.choice == ConflictChoice::Skip)
2056 .count();
2057 let created_names = self
2058 .model
2059 .outputs
2060 .iter()
2061 .filter(|(_, disposition)| *disposition == Disposition::Created)
2062 .map(|(name, _)| name.replace('\\', "/"))
2063 .collect::<BTreeSet<_>>();
2064 let warnings = if listing {
2065 Vec::new()
2066 } else {
2067 present::publication_warnings(
2068 t.as_ref(),
2069 self.model.confirmed,
2070 resolved_targets.as_ref(),
2071 &self.directories,
2072 &self.model.outputs,
2073 )
2074 };
2075 let success = self.model.confirmed
2076 && self.model.error.is_none()
2077 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
2078 && warnings.is_empty();
2079 let durability_warning = t
2080 .as_ref()
2081 .filter(|_| self.model.confirmed && !listing)
2082 .and_then(|t| present::durability_warning(t.durability));
2083 let durability_in_details = success
2084 && t.as_ref()
2085 .is_some_and(|t| t.durability == Durability::Unconfirmed);
2086 let cancelled =
2087 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
2088 let title = if success {
2089 if creating {
2090 "ZIP 파일을 만들었습니다"
2091 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
2092 "모든 파일을 건너뛰었습니다"
2093 } else {
2094 "압축을 풀었습니다"
2095 }
2096 } else if cancelled {
2097 "작업을 취소했습니다"
2098 } else if listing {
2099 "압축파일을 열지 못했습니다"
2100 } else if creating {
2101 "ZIP 파일을 만들지 못했습니다"
2102 } else {
2103 "압축을 풀지 못했습니다"
2104 };
2105 let fill = if success {
2106 theme::SUCCESS_BG
2107 } else if cancelled {
2108 theme::STRIPE
2109 } else {
2110 theme::ERROR_BG
2111 };
2112 let mut choose = false;
2113 let mut retry = false;
2114 let mut expand = false;
2115 let mut reopen = false;
2116 let mut folder = false;
2117 theme::panel(fill).show(ui, |ui| {
2118 ui.horizontal(|ui| {
2119 theme::icon(
2120 ui,
2121 if success {
2122 Icon::Success
2123 } else if cancelled {
2124 Icon::Warning
2125 } else {
2126 Icon::Error
2127 },
2128 24.0,
2129 );
2130 ui.strong(title);
2131 });
2132 let max_height = WORK_RESULT_MAX_HEIGHT;
2133 egui::ScrollArea::vertical()
2134 .id_salt("result-message")
2135 .max_height(max_height)
2136 .show(ui, |ui| {
2137 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
2138 let path = match self.last_request.as_ref() {
2139 Some(Start::CreateZip { output_file, .. }) => {
2140 output_file.display().to_string()
2141 }
2142 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
2143 };
2144 theme::bounded_text(ui, &path, ui.available_width());
2145 } else if let Some(problem) = &self.model.volume_problem {
2146 ui.add(egui::Label::new(present::volume_problem_text(problem)).wrap());
2147 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
2148 ui.label(
2149 if matches!(
2150 code,
2151 ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature
2152 ) && self
2153 .model
2154 .archive
2155 .as_ref()
2156 .is_some_and(|p| present::excluded_split(p))
2157 {
2158 present::SPLIT_SUPPORT.to_owned()
2159 } else if creating && code == ErrorCode::SourceChanged {
2160 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
2161 .to_owned()
2162 } else {
2163 present::operation_text(present::error_text(code), creating)
2164 },
2165 );
2166 } else if let Some(error) = &self.model.error {
2167 ui.label(present::operation_text(
2168 present::client_error_text(error),
2169 creating,
2170 ));
2171 }
2172 if skipped > 0 {
2173 ui.label(format!("건너뛴 파일 {skipped}개"));
2174 }
2175 for resolution in self.model.resolutions.iter().filter(|r| {
2176 r.choice == ConflictChoice::Rename
2177 && created_names.contains(&r.relative_name.replace('\\', "/"))
2178 }) {
2179 theme::bounded_text(
2180 ui,
2181 &format!("이름 바꿔 저장: {}", resolution.relative_name),
2182 ui.available_width(),
2183 );
2184 }
2185 for warning in warnings
2186 .iter()
2187 .copied()
2188 .chain(durability_warning.filter(|_| !durability_in_details))
2189 {
2190 ui.horizontal_wrapped(|ui| {
2191 theme::icon(ui, Icon::Warning, 20.0);
2192 ui.colored_label(
2193 theme::WARNING,
2194 present::operation_text(warning, creating),
2195 );
2196 });
2197 }
2198 if !success
2199 && !listing
2200 && present::definitely_unsaved(
2201 t.as_ref(),
2202 self.model.confirmed,
2203 &self.model.outputs,
2204 )
2205 {
2206 ui.label(if creating {
2207 "ZIP 파일을 만들지 않았습니다"
2208 } else {
2209 "아무 파일도 풀지 않았습니다"
2210 });
2211 }
2212 if t.as_ref().is_some_and(|t| {
2213 t.error == Some(ErrorCode::Limit)
2214 && (t.created_count > 0
2215 || t.retained_partial_count > 0
2216 || t.publication != Publication::None)
2217 }) {
2218 ui.label(format!(
2219 "{}개 파일이 저장되었거나 일부 남아 있습니다. 저장 위치를 확인하세요.",
2220 t.as_ref().unwrap().created_count
2221 ));
2222 theme::bounded_text(
2223 ui,
2224 &self.destination.display().to_string(),
2225 ui.available_width(),
2226 );
2227 }
2228 if self.details {
2229 theme::panel(theme::STRIPE).show(ui, |ui| {
2230 if durability_in_details {
2231 if let Some(warning) = durability_warning {
2232 ui.label(present::operation_text(warning, creating));
2233 }
2234 }
2235 if let Some(t) = &t {
2236 for line in terminal_lines(t) {
2237 ui.label(line);
2238 }
2239 }
2240 if let Some(error) = &self.model.error {
2241 ui.label(error);
2242 }
2243 for (name, state) in &self.model.outputs {
2244 theme::bounded_text(
2245 ui,
2246 &format!("{name}: {}", disposition_label(*state)),
2247 ui.available_width(),
2248 );
2249 }
2250 });
2251 }
2252 });
2253 let conflict = t
2254 .as_ref()
2255 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
2256 && !creating;
2257 let uncertain = warnings.contains(&present::UNCERTAIN);
2258 if conflict && uncertain {
2259 let response = ui.checkbox(
2260 &mut self.checked_destination,
2261 "기존 풀 위치 폴더를 확인했습니다",
2262 );
2263 theme::pointer(&response);
2264 theme::focus(&response);
2265 }
2266 ui.horizontal(|ui| {
2267 if theme::action(
2268 ui,
2269 if self.details {
2270 "자세히 닫기"
2271 } else {
2272 "자세히 보기"
2273 },
2274 false,
2275 true,
2276 )
2277 .clicked()
2278 {
2279 self.details = !self.details;
2280 }
2281 let action = if success {
2282 Some(("폴더 열기", true))
2283 } else if conflict {
2284 Some((
2285 if self
2286 .model
2287 .list_id
2288 .as_ref()
2289 .is_some_and(|id| id.format == Format::Gzip)
2290 {
2291 "다른 이름으로 저장"
2292 } else {
2293 "다른 폴더에 풀기"
2294 },
2295 !uncertain || self.checked_destination,
2296 ))
2297 } else if t
2298 .as_ref()
2299 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
2300 {
2301 Some((
2302 if creating {
2303 "다시 만들기"
2304 } else {
2305 "압축파일 다시 열기"
2306 },
2307 true,
2308 ))
2309 } else if self.model.can_retry_expanded() {
2310 None
2311 } else if t
2312 .as_ref()
2313 .is_some_and(|t| t.error == Some(ErrorCode::Limit))
2314 {
2315 None
2316 } else if !cancelled && (!uncertain || listing) {
2317 Some(("다시 시도", true))
2318 } else {
2319 None
2320 };
2321 let (confirm, primary) = theme::action_pair(ui, "확인", action);
2322 if confirm {
2323 self.dismissed = true;
2324 self.ui_error = None;
2325 self.model.input_error = None;
2326 }
2327 if primary {
2328 match action.map(|(label, _)| label) {
2329 Some("폴더 열기") => folder = true,
2330 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
2331 choose = true
2332 }
2333 Some("압축파일 다시 열기") => reopen = true,
2334 Some("다시 시도" | "다시 만들기") => retry = true,
2335 _ => {}
2336 }
2337 }
2338 });
2339 if self.model.can_retry_expanded() {
2340 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2341 expand = theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked();
2342 });
2343 }
2344 });
2345 if choose {
2346 self.open_picker(Purpose::Retry);
2347 }
2348 if retry {
2349 self.retry();
2350 }
2351 if expand {
2352 let ready = if matches!(self.last_request, Some(Start::Extract { .. })) {
2353 match present::prepare_destination(&self.destination, self.automatic_destination) {
2354 Ok(created) => {
2355 self.owned_destination = created.then(|| self.destination.clone());
2356 true
2357 }
2358 Err(_) => {
2359 self.ui_error = Some(present::FOLDER_ERROR.into());
2360 false
2361 }
2362 }
2363 } else {
2364 true
2365 };
2366 if ready && self.model.retry_expanded(self.factory.as_mut()) {
2367 self.dismissed = false;
2368 self.details = false;
2369 self.ui_error = None;
2370 }
2371 }
2372 if reopen {
2373 if let Some(path) = self.model.archive.clone() {
2374 self.open_path(path);
2375 }
2376 }
2377 if folder {
2378 let path = match self.last_request.as_ref() {
2379 Some(Start::CreateZip { output_file, .. }) => {
2380 output_file.parent().unwrap_or(Path::new("/"))
2381 }
2382 _ => self.destination.as_path(),
2383 };
2384 match present::folder_command(path).spawn() {
2385 Ok(mut child) => {
2386 std::thread::spawn(move || {
2387 let _ = child.wait();
2388 });
2389 }
2390 Err(_) => {
2391 self.ui_error = Some(
2392 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
2393 )
2394 }
2395 }
2396 }
2397 }
2398
2399 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
2400 fn entry_cells(
2401 ui: &mut egui::Ui,
2402 rect: egui::Rect,
2403 directory: bool,
2404 name: &str,
2405 hover: &str,
2406 size: String,
2407 name_width: f32,
2408 ) {
2409 ui.scope_builder(
2410 egui::UiBuilder::new()
2411 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
2412 .layout(Layout::left_to_right(Align::Center)),
2413 |ui| {
2414 ui.style_mut().interaction.selectable_labels = false;
2415 ui.add_space(16.0);
2416 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
2417 theme::bounded_text_hover(ui, name, hover, name_width);
2418 theme::column_label(ui, size, 96.0, Align::Max);
2419 },
2420 );
2421 }
2422
2423 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
2424 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
2425 fn create_window(&mut self, ctx: &egui::Context) {
2426 if !self.create || self.model.busy() {
2427 self.create_win = WorkWindow::default();
2428 return;
2429 }
2430 if ctx.embed_viewports() {
2431 let mut close = false;
2432 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
2433 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
2434 ui.horizontal(|ui| {
2435 ui.heading("ZIP 만들기");
2436 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2437 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
2438 close = button.clicked();
2439 });
2440 });
2441 close |= self.create_area(ui);
2442 ui.add_space(theme::SPACE);
2443 close |= self.create_actions(ui);
2444 });
2445 if close || modal.should_close() {
2446 self.close_create();
2447 }
2448 return;
2449 }
2450 let id = egui::ViewportId::from_hash_of("archive-create");
2451 let title = "ZIP 만들기 — Zipelo";
2452 let custom_frame = self.custom_frame;
2453 if !self.create_win.open {
2454 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
2455 }
2456 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
2457 let builder =
2458 self.create_win
2459 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
2460 let mut close = false;
2461 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
2462 if ui.ctx().input(|i| i.viewport().close_requested()) {
2463 close = true;
2464 }
2465 if class == egui::ViewportClass::EmbeddedWindow {
2466 ui.set_width(CREATE_WIDTH);
2467 close |= self.create_area(ui);
2468 close |= self.create_actions(ui);
2469 return None;
2470 }
2471 let mut chrome = 0.0;
2472 if custom_frame {
2473 window_frame::title_bar(
2474 ui,
2475 "create",
2476 title,
2477 window_frame::Buttons {
2478 minimize: false,
2479 maximize: false,
2480 },
2481 );
2482 window_frame::edges(ui.ctx(), false);
2483 chrome = window_frame::TITLE_HEIGHT;
2484 }
2485 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
2486 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
2487 .resizable(false)
2488 .show_separator_line(false)
2489 .frame(
2490 egui::Frame::new()
2491 .fill(theme::PANEL)
2492 .inner_margin(egui::Margin {
2493 left: theme::PAD,
2494 right: theme::PAD,
2495 top: 0,
2496 bottom: theme::PAD,
2497 }),
2498 )
2499 .show(ui, |ui| close |= self.create_actions(ui))
2500 .response
2501 .rect
2502 .height();
2503 let margin = theme::PAD as f32;
2504 egui::CentralPanel::default()
2505 .frame(theme::panel(theme::PANEL).corner_radius(0))
2506 .show(ui, |ui| {
2507 let content = ui
2508 .vertical(|ui| close |= self.create_area(ui))
2509 .response
2510 .rect;
2511 Some(content.height() + 2.0 * margin + chrome + actions)
2512 })
2513 .inner
2514 });
2515 if let Some(height) = height {
2516 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
2517 if (height - self.create_win.height).abs() > 1.0 {
2518 self.create_win.height = height;
2519 }
2520 }
2521 if close {
2522 self.close_create();
2523 }
2524 }
2525
2526 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
2527 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
2528 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
2529 let enabled = self.picker.is_none();
2530 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
2531 .inner
2532 }
2533
2534 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
2535 let rows = self.create_rows();
2536 let root = self.create_root();
2537
2538 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
2539 ui.horizontal(|ui| {
2540 ui.set_height(theme::FIELD);
2541 ui.spacing_mut().item_spacing.x = 0.0;
2542 let up = theme::flat_icon_button(
2543 ui,
2544 "위로",
2545 theme::UP,
2546 !self.create_folder.is_empty(),
2547 egui::vec2(theme::FIELD, theme::FIELD),
2548 );
2549 if up.clicked() {
2550 self.create_folder = self
2551 .create_folder
2552 .rsplit_once('/')
2553 .map_or("", |(parent, _)| parent)
2554 .to_owned();
2555 self.create_selected = None;
2556 }
2557 ui.add_space(6.0);
2558 let path = match &root {
2559 Some(root) => {
2560 let name = root.file_name().unwrap_or_default().to_string_lossy();
2561 if self.create_folder.is_empty() {
2562 format!("/{name}")
2563 } else {
2564 format!("/{name}/{}", self.create_folder)
2565 }
2566 }
2567 None => "/".to_owned(),
2568 };
2569 let (rect, _) = ui.allocate_exact_size(
2570 egui::vec2(ui.available_width(), theme::FIELD),
2571 egui::Sense::hover(),
2572 );
2573 theme::boxed_field(ui, rect);
2574 theme::field_text(ui, rect, &path);
2575 });
2576 ui.add_space(theme::SPACE);
2577
2578 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
2579 let mut enter = None;
2580 egui::Frame::new()
2581 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2582 .show(ui, |ui| {
2583 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
2584 ui.set_max_height(CREATE_LIST_HEIGHT);
2585 let message = match &rows {
2586 None => Some("폴더를 읽지 못했습니다"),
2587 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
2588 Some(_) => None,
2589 };
2590 if let Some(message) = message {
2591 ui.centered_and_justified(|ui| ui.label(message));
2592 return;
2593 }
2594 let rows = rows.unwrap();
2595 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
2596 egui::ScrollArea::vertical()
2597 .id_salt("create-rows")
2598 .auto_shrink([false, false])
2599 .max_height(CREATE_LIST_HEIGHT)
2600 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
2601 for row in &rows[range] {
2602 let (rect, response) = ui.allocate_exact_size(
2603 egui::vec2(ui.available_width(), LIST_ROW),
2604 egui::Sense::click(),
2605 );
2606 let response = response.on_hover_text(&row.name);
2607 theme::pointer(&response);
2608 response.widget_info(|| {
2609 egui::WidgetInfo::labeled(
2610 egui::Role::ListBoxOption,
2611 true,
2612 &row.name,
2613 )
2614 });
2615 if response.clicked() {
2616 self.create_selected = Some(row.name.clone());
2617 }
2618 theme::row_background(
2619 ui,
2620 rect,
2621 self.create_selected.as_deref() == Some(row.name.as_str()),
2622 response.hovered(),
2623 );
2624 if row.directory && root.is_some() && response.clicked() {
2625 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
2626 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
2627 let frame = ui.ctx().cumulative_frame_nr();
2628 let time = ui.input(|i| i.time);
2629 match &self.create_last_click {
2630 Some((name, last_frame, last_time))
2631 if name == &row.name
2632 && *last_frame != frame
2633 && time - last_time < 0.4 =>
2634 {
2635 enter = Some(row.name.clone());
2636 self.create_last_click = None;
2637 }
2638 Some((name, last_frame, _))
2639 if name == &row.name && *last_frame == frame => {}
2640 _ => {
2641 self.create_last_click =
2642 Some((row.name.clone(), frame, time));
2643 }
2644 }
2645 }
2646 Self::entry_cells(
2647 ui,
2648 rect,
2649 row.directory,
2650 &row.name,
2651 &row.name,
2652 row.bytes.map(present::bytes_text).unwrap_or_default(),
2653 name_width,
2654 );
2655 }
2656 });
2657 });
2658 if let Some(name) = enter {
2659 self.create_folder = if self.create_folder.is_empty() {
2660 name
2661 } else {
2662 format!("{}/{name}", self.create_folder)
2663 };
2664 self.create_selected = None;
2665 }
2666 ui.add_space(theme::SPACE);
2667
2668 if let Some(error) = &self.ui_error {
2669 Self::error_notice(ui, error);
2670 }
2671
2672 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
2673 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
2674 theme::pointer(&check);
2675 theme::focus(&check);
2676 if self.aes256 {
2677 let label_width = 72.0;
2678 ui.horizontal(|ui| {
2679 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
2680 let toggle = if self.zip_password_visible {
2681 "숨기기"
2682 } else {
2683 "보기"
2684 };
2685 let toggle_width = 72.0;
2686 let edit = ui.add_sized(
2687 [
2688 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
2689 theme::FIELD,
2690 ],
2691 egui::TextEdit::singleline(&mut self.zip_password)
2692 .password(!self.zip_password_visible)
2693 .id(egui::Id::unique("zip-password-input"))
2694 .char_limit(1024)
2695 .align(egui::Align2::LEFT_CENTER),
2696 );
2697 theme::focus(&edit);
2698 if theme::action(ui, toggle, false, true).clicked() {
2699 self.zip_password_visible = !self.zip_password_visible;
2700 }
2701 });
2702 ui.horizontal(|ui| {
2703 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
2704 let edit = ui.add_sized(
2705 [
2706 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
2707 theme::FIELD,
2708 ],
2709 egui::TextEdit::singleline(&mut self.zip_password_confirm)
2710 .password(!self.zip_password_visible)
2711 .id(egui::Id::unique("zip-password-confirm"))
2712 .char_limit(1024)
2713 .align(egui::Align2::LEFT_CENTER),
2714 );
2715 theme::focus(&edit);
2716 });
2717 if self.zip_password.len() > 1024 {
2718 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2719 } else if !self.zip_password_confirm.is_empty()
2720 && self.zip_password != self.zip_password_confirm
2721 {
2722 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2723 }
2724 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
2725 } else if check.changed()
2726 || !self.zip_password.is_empty()
2727 || !self.zip_password_confirm.is_empty()
2728 {
2729 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
2730 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
2731 self.clear_zip_password();
2732 }
2733 false
2734 }
2735
2736 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
2737 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
2738 let ready = !self.sources.is_empty() && self.zip_password_ready();
2739 let enabled = self.picker.is_none();
2740 let (cancel, compress) = ui
2741 .add_enabled_ui(enabled, |ui| {
2742 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
2743 })
2744 .inner;
2745 if compress {
2746 self.open_picker(Purpose::SaveZip);
2747 }
2748 cancel
2749 }
2750
2751 fn resource_dialog(&mut self, ctx: &egui::Context) {
2752 let Some(question) = self.model.resource.clone() else {
2753 return;
2754 };
2755 let Some(job) = self.model.job_id() else {
2756 return;
2757 };
2758 let mut allow = false;
2759 let mut cancel = false;
2760 let modal = egui::Modal::new(egui::Id::unique(("archive-resource", job, question.id)))
2761 .show(ctx, |ui| {
2762 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
2763 ui.heading(if question.scope.ratio {
2764 "압축률이 매우 높습니다"
2765 } else {
2766 "큰 작업을 허용할까요?"
2767 });
2768 ui.label(match question.action {
2769 ActionKind::List => "압축파일 목록 열기",
2770 ActionKind::Extract => "압축 해제",
2771 ActionKind::CreateZip => "ZIP 만들기",
2772 ActionKind::Preview => "파일 미리보기",
2773 });
2774 if question.scope.ratio {
2775 ui.label("작은 압축파일도 많은 저장 공간을 사용할 수 있습니다.");
2776 }
2777 if question.scope.output {
2778 ui.label(format!(
2779 "총량 한도: {}에서 {}로",
2780 present::bytes_text(question.soft_limits.output),
2781 present::bytes_text(question.ceiling.output)
2782 ));
2783 }
2784 if question.scope.entries {
2785 ui.label(format!(
2786 "항목 한도: {}개에서 {}개로",
2787 question.soft_limits.entries, question.ceiling.entries
2788 ));
2789 }
2790 let mut u = question.usage;
2791 let estimated = self.model.estimated_usage();
2792 u.estimated_bytes = u.estimated_bytes.or(estimated.estimated_bytes);
2793 u.estimated_entries = u.estimated_entries.or(estimated.estimated_entries);
2794 let bytes = |value: Option<u64>| {
2795 value
2796 .map(present::bytes_text)
2797 .unwrap_or_else(|| "미확인".into())
2798 };
2799 let entries = |value: Option<u32>| {
2800 value
2801 .map(|n| format!("{n}개"))
2802 .unwrap_or_else(|| "미확인".into())
2803 };
2804 ui.label(format!(
2805 "예상 총량: {} / 실제 총량: {}",
2806 bytes(u.estimated_bytes),
2807 bytes(u.actual_bytes)
2808 ));
2809 ui.label(format!(
2810 "예상 항목: {} / 실제 항목: {}",
2811 entries(u.estimated_entries),
2812 entries(u.actual_entries)
2813 ));
2814 if question.scope.ratio {
2815 ui.label(format!(
2816 "압축 크기: {} / 풀린 크기: {}",
2817 bytes(u.compressed_bytes),
2818 bytes(u.ratio_output_bytes)
2819 ));
2820 }
2821 ui.label(format!(
2822 "확인한 저장 볼륨의 여유 공간: {}",
2823 bytes(u.available_bytes)
2824 ));
2825 ui.label(format!(
2826 "이 작업의 상한: {} / {}개",
2827 present::bytes_text(question.ceiling.output),
2828 question.ceiling.entries
2829 ));
2830 ui.label("이 작업에만 적용합니다. 공간 부족이나 자원 상한에 도달하면 중단합니다.");
2831 ui.horizontal(|ui| {
2832 cancel = theme::action(ui, "취소", false, true).clicked();
2833 allow = theme::action(ui, "이 작업 허용", true, true).clicked();
2834 });
2835 });
2836 if cancel || modal.should_close() {
2837 self.clear_password();
2838 self.model.cancel();
2839 } else if allow {
2840 self.model.resource_reply(job, question.id, true);
2841 }
2842 }
2843
2844 fn conflict_dialog(&mut self, ctx: &egui::Context) {
2845 let conflict = self.model.conflict.clone().unwrap();
2846 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
2847 if self.conflict_challenge != Some(question) {
2848 self.conflict_challenge = Some(question);
2849 self.conflict_apply = false;
2850 }
2851 let mut choice = None;
2852 let mut cancel = false;
2853 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
2854 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
2855 ui.heading("같은 이름의 파일이 있습니다");
2856 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
2857 ui.add_space(theme::SPACE);
2858 egui::Grid::new("conflict-sizes")
2859 .spacing([24.0, 8.0])
2860 .show(ui, |ui| {
2861 ui.label("기존 파일");
2862 ui.label(present::bytes_text(conflict.existing_size));
2863 ui.end_row();
2864 ui.label("압축파일 안의 파일");
2865 ui.label(present::bytes_text(conflict.incoming_size));
2866 ui.end_row();
2867 });
2868 ui.add_space(theme::SPACE);
2869 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
2870 ui.add_space(theme::SPACE);
2871 ui.horizontal_wrapped(|ui| {
2872 for (label, value) in [
2873 ("덮어쓰기", ConflictChoice::Overwrite),
2874 ("건너뛰기", ConflictChoice::Skip),
2875 ("이름 바꿔 저장", ConflictChoice::Rename),
2876 ] {
2877 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
2878 choice = Some(value);
2879 }
2880 }
2881 });
2882 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
2883 if let Some(error) = &self.model.error {
2884 Self::error_notice(ui, present::client_error_text(error));
2885 }
2886 cancel = theme::action(ui, "작업 취소", false, true).clicked();
2887 });
2888 if modal.should_close() || cancel {
2889 self.model.cancel();
2890 } else if let Some(choice) = choice {
2891 self.model.resolve_conflict(choice, self.conflict_apply);
2892 }
2893 }
2894
2895 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
2896 let (_, attempt, encrypt) = self.model.challenge.unwrap();
2897 let mut submit = false;
2898 let mut cancel = false;
2899 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
2900 id == egui::Id::unique("archive-password-input")
2901 || id == egui::Id::unique("archive-password-confirm")
2902 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
2903 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
2904 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
2905 ui.heading(if encrypt {
2906 "ZIP 암호 설정"
2907 } else {
2908 "암호가 필요합니다"
2909 });
2910 if encrypt {
2911 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
2912 } else if let Some(path) = &self.model.archive {
2913 ui.label(format!(
2914 "{}은 암호로 보호되어 있습니다.",
2915 present::middle_text(
2916 &path.file_name().unwrap_or_default().to_string_lossy(),
2917 24
2918 )
2919 ));
2920 }
2921 ui.horizontal(|ui| {
2922 ui.label("암호");
2923 let edit = ui.add(
2924 egui::TextEdit::singleline(&mut self.password)
2925 .password(!self.password_visible)
2926 .id(egui::Id::unique("archive-password-input"))
2927 .char_limit(1024)
2928 .desired_width(232.0),
2929 );
2930 theme::focus(&edit);
2931 if new_challenge {
2932 edit.request_focus();
2933 }
2934 if theme::action(
2935 ui,
2936 if self.password_visible {
2937 "숨기기"
2938 } else {
2939 "보기"
2940 },
2941 false,
2942 true,
2943 )
2944 .clicked()
2945 {
2946 self.password_visible = !self.password_visible;
2947 }
2948 });
2949 if encrypt {
2950 ui.horizontal(|ui| {
2951 ui.label("암호 확인");
2952 let edit = ui.add(
2953 egui::TextEdit::singleline(&mut self.password_confirm)
2954 .password(!self.password_visible)
2955 .id(egui::Id::unique("archive-password-confirm"))
2956 .char_limit(1024)
2957 .desired_width(232.0),
2958 );
2959 theme::focus(&edit);
2960 });
2961 if self.password != self.password_confirm {
2962 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2963 }
2964 } else if attempt > 1 {
2965 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
2966 }
2967 if self.password.len() > 1024 {
2968 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2969 }
2970 let valid = !self.password.is_empty()
2971 && self.password.len() <= 1024
2972 && (!encrypt || self.password == self.password_confirm);
2973 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
2974 cancel = actions.0;
2975 submit = actions.1 || (valid && password_enter);
2976 });
2977 if modal.should_close() || cancel {
2978 self.clear_password();
2979 self.model.cancel();
2980 } else if submit {
2981 let password = std::mem::take(&mut self.password);
2982 self.clear_password();
2983 self.model.password(password);
2984 }
2985 }
2986
2987 fn close_dialog(&mut self, ctx: &egui::Context) {
2988 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
2989 if matches!(
2990 self.model.close,
2991 Close::Open | Close::Allowed | Close::Review
2992 ) {
2993 return;
2994 }
2995 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
2996 ui.set_width(420.0);
2997 match self.model.close {
2998 Close::Confirm => {
2999 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
3000 let busy = self.model.busy();
3001 let (heading, text, keep, close) = if busy {
3002 (
3003 "작업 중 닫기",
3004 "작업을 취소하고 닫을까요?",
3005 "계속 작업",
3006 "취소하고 닫기",
3007 )
3008 } else {
3009 (
3010 "닫기",
3011 "작업이 끝났습니다. 창을 닫을까요?",
3012 "열어 두기",
3013 "닫기",
3014 )
3015 };
3016 ui.heading(heading);
3017 ui.label(text);
3018 ui.horizontal(|ui| {
3019 if theme::action(ui, keep, false, true).clicked() {
3020 self.model.keep_open();
3021 }
3022 if theme::action(ui, close, true, true).clicked() {
3023 self.clear_password();
3024 self.model.confirm_close();
3025 }
3026 });
3027 }
3028 Close::Waiting => {
3029 ui.heading("종료 확인 중");
3030 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
3031 if theme::action(ui, "닫기 취소", false, true).clicked() {
3032 self.model.keep_open();
3033 }
3034 }
3035 _ => {}
3036 }
3037 });
3038 }
3039}
3040
3041impl eframe::App for ArchiveApp {
3042 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
3043 self.show(root);
3044 }
3045
3046 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
3047 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
3048 if std::mem::take(&mut self.release_after_move) {
3049 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
3050 raw_input.events.insert(
3051 0,
3052 egui::Event::PointerButton {
3053 pos,
3054 button: egui::PointerButton::Primary,
3055 pressed: false,
3056 modifiers: ctx.input(|i| i.modifiers),
3057 },
3058 );
3059 }
3060 }
3061}
3062impl Drop for ArchiveApp {
3063 fn drop(&mut self) {
3064 self.clear_password();
3065 }
3066}