team-ljyzipelo

공개
3,030줄123 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.model.can_preview() && !self.preview_open,
972 false,
973 )
974 .clicked()
975 {
976 self.begin_preview(ui.ctx());
977 }
978 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
979 self.choose_zip_folder();
980 }
981 if theme::tool(
982 ui,
983 "압축해제",
984 theme::EXTRACT,
985 self.model.can_extract(),
986 true,
987 )
988 .clicked()
989 {
990 self.open_picker(Purpose::Destination);
991 }
992 });
993 });
994 egui::Panel::bottom("archive-status")
995 .exact_size(theme::STATUS_HEIGHT)
996 .resizable(false)
997 .frame(
998 egui::Frame::new()
999 .fill(theme::STRIPE)
1000 .inner_margin(egui::Margin::symmetric(16, 0)),
1001 )
1002 .show(root, |ui| {
1003 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1004 let selected = rows
1005 .iter()
1006 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
1007 .count();
1008 let rect = ui.max_rect();
1009 let half = (rect.width() - theme::SPACE) / 2.0;
1010 theme::status_text(
1011 ui,
1012 rect,
1013 &format!("{}개 항목", rows.len()),
1014 half,
1015 Align::Min,
1016 );
1017 theme::status_text(ui, rect, &format!("선택 {selected}개"), half, Align::Max);
1018 });
1019 if ctx.embed_viewports() && self.work_visible() && !self.limit_result_visible() {
1020 // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
1021 egui::Panel::bottom("archive-work")
1022 .frame(theme::panel(theme::PANEL).corner_radius(0))
1023 .show(root, |ui| self.work_area(ui));
1024 }
1025 egui::CentralPanel::default()
1026 .frame(
1027 theme::panel(theme::PANEL)
1028 .corner_radius(0)
1029 .inner_margin(egui::Margin::ZERO),
1030 )
1031 .show(root, |ui| {
1032 if self.model.archive.is_some() {
1033 self.archive_list(ui);
1034 } else {
1035 self.empty(ui);
1036 }
1037 });
1038 self.forget_password_history(&ctx);
1039 self.preview_dialog(&ctx);
1040 self.work_window(&ctx);
1041 self.limit_result_dialog(&ctx);
1042 self.create_window(&ctx);
1043 if self.model.challenge.is_some() {
1044 self.password_dialog(&ctx, new_challenge);
1045 }
1046 self.resource_dialog(&ctx);
1047 if self.model.conflict.is_some() && self.model.close == Close::Open {
1048 self.conflict_dialog(&ctx);
1049 }
1050 self.close_dialog(&ctx);
1051 self.picker_notice(&ctx);
1052 if !preview_was_open
1053 && !self.preview_open
1054 && !self.model.busy()
1055 && let Some(id) = self.preview_return_focus.take()
1056 {
1057 ctx.memory_mut(|m| m.request_focus(id));
1058 }
1059 if self.custom_frame {
1060 window_frame::edges(&ctx, true);
1061 }
1062 if self.model.busy() {
1063 ctx.request_repaint_after(std::time::Duration::from_millis(30));
1064 }
1065 }
1066
1067 // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
1068 fn picker_notice(&mut self, ctx: &egui::Context) {
1069 if self.picker.is_none() {
1070 return;
1071 }
1072 egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
1073 ui.set_width(360.0);
1074 ui.label("파일 선택 창에서 선택을 마쳐 주세요");
1075 });
1076 ctx.request_repaint_after(std::time::Duration::from_millis(100));
1077 }
1078
1079 fn empty(&mut self, ui: &mut egui::Ui) {
1080 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
1081 let width = (ui.available_width() * 0.60)
1082 .max(480.0)
1083 .min(ui.available_width());
1084 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
1085 ui.add_space(y);
1086 ui.vertical_centered(|ui| {
1087 let drop_frame = egui::Frame::new()
1088 .fill(if hovered { theme::DROP } else { theme::PANEL })
1089 .corner_radius(theme::DROP_RADIUS)
1090 .inner_margin(egui::Margin::same(theme::DROP_PAD))
1091 .show(ui, |ui| {
1092 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
1093 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
1094 ui.vertical_centered(|ui| {
1095 ui.add_space(theme::PAD as f32);
1096 theme::icon(ui, Icon::Archive, 48.0);
1097 ui.add_space(theme::PAD as f32);
1098 ui.label(
1099 RichText::new(if hovered {
1100 "놓으면 엽니다"
1101 } else {
1102 "압축파일을 여기에 끌어 놓으세요"
1103 })
1104 .size(theme::FONT_LARGE)
1105 .strong(),
1106 );
1107 ui.label("또는");
1108 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
1109 self.open_picker(Purpose::Open);
1110 }
1111 });
1112 });
1113 let rect = drop_frame.response.rect;
1114 if hovered {
1115 ui.painter().rect_stroke(
1116 rect,
1117 12,
1118 egui::Stroke::new(2.0, theme::BLUE),
1119 egui::StrokeKind::Inside,
1120 );
1121 } else {
1122 let stroke = egui::Stroke::new(2.0, theme::DASH);
1123 for (a, b) in [
1124 (rect.left_top(), rect.right_top()),
1125 (rect.right_top(), rect.right_bottom()),
1126 (rect.right_bottom(), rect.left_bottom()),
1127 (rect.left_bottom(), rect.left_top()),
1128 ] {
1129 let direction = (b - a).normalized();
1130 let mut distance = theme::DROP_RADIUS as f32;
1131 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
1132 ui.painter().line_segment(
1133 [
1134 a + direction * distance,
1135 a + direction
1136 * (distance + theme::SPACE)
1137 .min(a.distance(b) - theme::DROP_RADIUS as f32),
1138 ],
1139 stroke,
1140 );
1141 distance += theme::PAD as f32;
1142 }
1143 }
1144 }
1145 ui.add_space(theme::PAD as f32);
1146 ui.colored_label(
1147 theme::MUTED,
1148 "ZIP, 7z, TAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ 파일을 열 수 있습니다",
1149 );
1150 });
1151 }
1152
1153 fn archive_list(&mut self, ui: &mut egui::Ui) {
1154 // 경로 줄은 입력란 높이만 차지하고 창 너비 전체를 회색으로 채움.
1155 let path_row = egui::Frame::new()
1156 .fill(theme::STRIPE)
1157 .inner_margin(egui::Margin {
1158 left: 8,
1159 right: 12,
1160 top: 0,
1161 bottom: 0,
1162 })
1163 .show(ui, |ui| {
1164 ui.set_min_width(ui.available_width());
1165 ui.horizontal(|ui| {
1166 ui.set_height(theme::FIELD);
1167 // 간격은 아래에서 직접 넣어 위치가 흔들리지 않게 함.
1168 ui.spacing_mut().item_spacing.x = 0.0;
1169 let up = theme::flat_icon_button(
1170 ui,
1171 "위로",
1172 theme::UP,
1173 !self.folder.is_empty() && !self.model.busy(),
1174 egui::vec2(theme::FIELD, theme::FIELD),
1175 );
1176 if up.clicked() {
1177 let parent = self
1178 .folder
1179 .rsplit_once('/')
1180 .map_or("", |(parent, _)| parent)
1181 .to_owned();
1182 self.browse_folder(&parent);
1183 }
1184 ui.add_space(6.0);
1185 let path = format!("/{}", self.folder);
1186 let search_width = 240.0;
1187 let gap = 8.0;
1188 let path_width = (ui.available_width() - search_width - gap).max(0.0);
1189 // 두 입력란은 같은 높이의 칸을 받아 같은 세로 위치에 그림.
1190 let (path_rect, _) = ui.allocate_exact_size(
1191 egui::vec2(path_width, theme::FIELD),
1192 egui::Sense::hover(),
1193 );
1194 theme::field_frame(ui, path_rect, false);
1195 // 부모 배치에 영향을 주지 않는 하위 영역에 경로 글자를 그림.
1196 let mut text_ui = ui.new_child(
1197 egui::UiBuilder::new()
1198 .max_rect(path_rect.shrink2(egui::vec2(10.0, 0.0)))
1199 .layout(Layout::left_to_right(Align::Center)),
1200 );
1201 theme::bounded_text(&mut text_ui, &path, (path_width - 20.0).max(0.0));
1202 ui.add_space(gap);
1203 let (search_rect, _) = ui.allocate_exact_size(
1204 egui::vec2(search_width, theme::FIELD),
1205 egui::Sense::hover(),
1206 );
1207 let search_id = egui::Id::unique("archive-search");
1208 let focused = ui.memory(|m| m.has_focus(search_id));
1209 theme::field_frame(ui, search_rect, focused);
1210 let icon = egui::Rect::from_center_size(
1211 egui::pos2(search_rect.left() + 20.0, search_rect.center().y),
1212 egui::vec2(16.0, 16.0),
1213 );
1214 theme::svg_icon(ui.painter(), icon, theme::SEARCH, theme::MUTED);
1215 let search = ui.put(
1216 egui::Rect::from_min_max(
1217 egui::pos2(icon.right() + 8.0, search_rect.top() + 1.0),
1218 egui::pos2(search_rect.right() - 8.0, search_rect.bottom() - 1.0),
1219 ),
1220 egui::TextEdit::singleline(&mut self.search)
1221 .id(search_id)
1222 .frame(egui::Frame::NONE)
1223 .margin(egui::Margin::ZERO)
1224 .align(egui::Align2::LEFT_CENTER)
1225 .hint_text("파일 검색"),
1226 );
1227 if search.changed() {
1228 self.clear_list_selection();
1229 }
1230 });
1231 })
1232 .response
1233 .rect;
1234 // 경로 줄 아래 한 줄이 목록과의 경계이자 입력란의 아래 테두리 역할을 함.
1235 ui.painter().hline(
1236 path_row.x_range(),
1237 path_row.bottom() - 0.5,
1238 egui::Stroke::new(1.0, theme::BORDER),
1239 );
1240 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1241
1242 // 열 제목 줄 없이 바로 목록을 보여 줌. 이름과 크기는 내용으로 구분됨.
1243 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 40.0).max(120.0);
1244 let active = !self.preview_open
1245 && !self.model.busy()
1246 && !self.create
1247 && self.model.challenge.is_none()
1248 && self.model.close == Close::Open;
1249 let list_id = egui::Id::unique("archive-list");
1250 let background = ui.interact(
1251 ui.available_rect_before_wrap(),
1252 list_id,
1253 if active {
1254 egui::Sense::click_and_drag()
1255 } else {
1256 egui::Sense::hover()
1257 },
1258 );
1259 background
1260 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
1261 if background.has_focus() {
1262 ui.ctx().memory_mut(|memory| {
1263 memory.set_focus_lock_filter(
1264 list_id,
1265 egui::EventFilter {
1266 vertical_arrows: true,
1267 escape: true,
1268 ..Default::default()
1269 },
1270 )
1271 });
1272 }
1273 let mut focused = None;
1274 let mut open = None;
1275 let mut next_offset = None;
1276 let output = egui::ScrollArea::vertical()
1277 .id_salt("archive-rows")
1278 .auto_shrink([false, false])
1279 .vertical_scroll_offset(self.list_offset)
1280 .show_viewport(ui, |ui, viewport| {
1281 let origin = ui.max_rect().min;
1282 let clip = ui.clip_rect();
1283 // 행을 누르는 영역은 오른쪽 24px을 비워 둠. 목록이 길어도 그 빈 곳에서
1284 // 끌어서 선택을 시작할 수 있음. 행 배경(선택, 마우스 올림)은 너비를 꽉 채움.
1285 let full_width = ui.available_width();
1286 let width = (full_width - 24.0).max(0.0);
1287 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
1288 let point = ui.input(|i| i.pointer.interact_pos());
1289 if active && let Some(point) = point {
1290 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
1291 let relative = press - origin;
1292 let in_row = relative.x >= 0.0
1293 && relative.x <= width
1294 && relative.y >= 0.0
1295 && relative.y < rows.len() as f32 * LIST_ROW;
1296 if clip.contains(press) && !in_row && ui.input(|i| i.pointer.primary_pressed())
1297 {
1298 background.request_focus();
1299 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
1300 self.marquee = Some(Marquee {
1301 origin: relative.to_pos2(),
1302 base: if ctrl {
1303 self.model.selected.clone()
1304 } else {
1305 BTreeSet::new()
1306 },
1307 moved: false,
1308 });
1309 if !ctrl {
1310 self.model.selected.clear();
1311 self.list_anchor = None;
1312 self.list_cursor = None;
1313 }
1314 }
1315 if let Some(drag) = &mut self.marquee {
1316 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
1317 drag.moved |= drag.origin.distance(end) > 3.0;
1318 if drag.moved {
1319 let rect = egui::Rect::from_two_pos(drag.origin, end);
1320 self.model.selected = drag.base.clone();
1321 if rect.left() < width && rect.right() > 0.0 {
1322 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
1323 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
1324 .min(rows.len());
1325 for row in rows.iter().take(last).skip(first) {
1326 self.model.selected.extend(&row.ids);
1327 }
1328 if first < last {
1329 self.list_anchor = Some(first);
1330 self.list_cursor = Some(last - 1);
1331 }
1332 }
1333 let speed = if point.y > clip.bottom() - 24.0 {
1334 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
1335 } else if point.y < clip.top() + 24.0 {
1336 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
1337 } else {
1338 0.0
1339 };
1340 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
1341 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
1342 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
1343 0.0,
1344 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
1345 ));
1346 ui.ctx().request_repaint();
1347 }
1348 }
1349 }
1350 }
1351 let first = (viewport.min.y / LIST_ROW).floor() as usize;
1352 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
1353 for index in first.min(rows.len())..last {
1354 let row = &rows[index];
1355 let rect = egui::Rect::from_min_size(
1356 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
1357 egui::vec2(width, LIST_ROW),
1358 );
1359 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
1360 let response = ui
1361 .interact(
1362 rect,
1363 egui::Id::unique(("archive-row", &row.path)),
1364 if active {
1365 egui::Sense::click()
1366 } else {
1367 egui::Sense::hover()
1368 },
1369 )
1370 .on_hover_text(&row.name);
1371 theme::pointer(&response);
1372 response.widget_info(|| {
1373 egui::WidgetInfo::selected(
1374 egui::Role::ListBoxOption,
1375 active,
1376 selected,
1377 &row.name,
1378 )
1379 });
1380 if response.has_focus() {
1381 focused = Some(index);
1382 ui.ctx().memory_mut(|memory| {
1383 memory.set_focus_lock_filter(
1384 response.id,
1385 egui::EventFilter {
1386 vertical_arrows: true,
1387 escape: true,
1388 ..Default::default()
1389 },
1390 )
1391 });
1392 }
1393 theme::row_background(
1394 ui,
1395 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW)),
1396 selected,
1397 response.hovered(),
1398 );
1399 if response.clicked() {
1400 background.request_focus();
1401 let modifiers = ui.input(|i| i.modifiers);
1402 self.select_row(
1403 &rows,
1404 index,
1405 modifiers.ctrl || modifiers.command,
1406 modifiers.shift,
1407 );
1408 }
1409 if row.directory && response.double_clicked() {
1410 open = Some(row.path.clone());
1411 }
1412 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
1413 let name = if row.encrypted {
1414 format!("*{}", row.name)
1415 } else {
1416 row.name.clone()
1417 };
1418 Self::entry_cells(
1419 ui,
1420 rect,
1421 row.directory,
1422 &name,
1423 &row.name,
1424 if row.directory {
1425 "0 B".into()
1426 } else {
1427 row.bytes
1428 .map(present::bytes_text)
1429 .unwrap_or_else(|| "—".into())
1430 },
1431 name_width,
1432 );
1433 if active
1434 && self.list_cursor == Some(index)
1435 && (response.has_focus() || background.has_focus())
1436 {
1437 ui.painter().rect_stroke(
1438 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW))
1439 .shrink(1.0),
1440 0,
1441 egui::Stroke::new(1.0, theme::BLUE),
1442 egui::StrokeKind::Inside,
1443 );
1444 }
1445 }
1446 if rows.is_empty() {
1447 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
1448 ui.centered_and_justified(|ui| {
1449 ui.label(if self.search.is_empty() {
1450 "이 폴더는 비어 있습니다"
1451 } else {
1452 "일치하는 항목이 없습니다"
1453 })
1454 });
1455 });
1456 }
1457 #[cfg(all(feature = "ui-fixture", debug_assertions))]
1458 if let Some(rect) = self.scenario_marquee {
1459 ui.painter().with_clip_rect(clip).rect(
1460 rect.translate(origin.to_vec2()),
1461 0,
1462 theme::BLUE.gamma_multiply(0.16),
1463 egui::Stroke::new(1.0, theme::BLUE),
1464 egui::StrokeKind::Inside,
1465 );
1466 }
1467 if let Some(drag) = &self.marquee
1468 && drag.moved
1469 && let Some(point) = point
1470 {
1471 let rect = egui::Rect::from_two_pos(
1472 origin + drag.origin.to_vec2(),
1473 point.clamp(clip.min, clip.max),
1474 );
1475 ui.painter().with_clip_rect(clip).rect(
1476 rect,
1477 0,
1478 theme::BLUE.gamma_multiply(0.16),
1479 egui::Stroke::new(1.0, theme::BLUE),
1480 egui::StrokeKind::Inside,
1481 );
1482 }
1483 });
1484 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
1485 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
1486 self.marquee = None;
1487 }
1488 let escape_from_list = self.list_focused
1489 && ui.ctx().memory(|memory| memory.focused()).is_none()
1490 && ui.input(|i| i.key_pressed(egui::Key::Escape));
1491 self.list_focused =
1492 active && (background.has_focus() || focused.is_some() || escape_from_list);
1493 if self.list_focused {
1494 if let Some(index) = focused {
1495 self.list_cursor = Some(index);
1496 }
1497 let modifiers = ui.input(|i| i.modifiers);
1498 let ctrl = modifiers.ctrl || modifiers.command;
1499 if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
1500 self.model.selected.clear();
1501 self.marquee = None;
1502 background.request_focus();
1503 }
1504 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
1505 self.model.selected = rows
1506 .iter()
1507 .flat_map(|row| row.ids.iter().copied())
1508 .collect();
1509 self.list_cursor = (!rows.is_empty()).then_some(0);
1510 self.list_anchor = self.list_cursor;
1511 }
1512 if !rows.is_empty() {
1513 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
1514 Some(1isize)
1515 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
1516 Some(-1)
1517 } else {
1518 None
1519 };
1520 if let Some(direction) = direction {
1521 let index = self.list_cursor.map_or(0, |index| {
1522 index.saturating_add_signed(direction).min(rows.len() - 1)
1523 });
1524 if ctrl && !modifiers.shift {
1525 self.list_cursor = Some(index);
1526 } else {
1527 self.select_row(&rows, index, ctrl, modifiers.shift);
1528 }
1529 background.request_focus();
1530 let top = index as f32 * LIST_ROW;
1531 if top < self.list_offset {
1532 self.list_offset = top;
1533 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
1534 self.list_offset = top + LIST_ROW - output.inner_rect.height();
1535 }
1536 ui.ctx().request_repaint();
1537 }
1538 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1539 let index = self
1540 .list_cursor
1541 .or(focused)
1542 .unwrap_or(0)
1543 .min(rows.len() - 1);
1544 if rows[index].directory {
1545 open = Some(rows[index].path.clone());
1546 }
1547 }
1548 }
1549 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
1550 open = Some(
1551 self.folder
1552 .rsplit_once('/')
1553 .map_or("", |(parent, _)| parent)
1554 .to_owned(),
1555 );
1556 }
1557 }
1558 if let Some(folder) = open {
1559 self.browse_folder(&folder);
1560 background.request_focus();
1561 }
1562 }
1563
1564 fn clear_list_selection(&mut self) {
1565 self.model.selected.clear();
1566 self.list_anchor = None;
1567 self.list_cursor = None;
1568 self.list_offset = 0.0;
1569 self.marquee = None;
1570 }
1571
1572 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
1573 if shift {
1574 let anchor = self
1575 .list_anchor
1576 .unwrap_or(self.list_cursor.unwrap_or(index))
1577 .min(rows.len() - 1);
1578 if !ctrl {
1579 self.model.selected.clear();
1580 }
1581 for row in &rows[anchor.min(index)..=anchor.max(index)] {
1582 self.model.selected.extend(&row.ids);
1583 }
1584 self.list_anchor = Some(anchor);
1585 } else {
1586 if !ctrl {
1587 self.model.selected.clear();
1588 }
1589 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
1590 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
1591 self.model
1592 .selected
1593 .retain(|id| !rows[index].ids.contains(id));
1594 } else {
1595 self.model.selected.extend(&rows[index].ids);
1596 }
1597 self.list_anchor = Some(index);
1598 }
1599 self.list_cursor = Some(index);
1600 }
1601
1602 fn result_visible(&self) -> bool {
1603 !self.dismissed
1604 && !self
1605 .last_request
1606 .as_ref()
1607 .is_some_and(|r| matches!(r, Start::Preview { .. }))
1608 && !self.model.busy()
1609 && self.last_request.as_ref().is_some_and(|request| {
1610 !matches!(request, Start::List { .. })
1611 || self.model.error.is_some()
1612 || self
1613 .model
1614 .terminal
1615 .as_ref()
1616 .is_some_and(|t| t.outcome != Outcome::Completed)
1617 })
1618 }
1619
1620 fn begin_preview(&mut self, ctx: &egui::Context) {
1621 if !self.model.can_preview() || self.picker.is_some() {
1622 return;
1623 }
1624 self.preview_texture = None;
1625 self.preview_text.clear();
1626 self.preview_name = self
1627 .model
1628 .entries
1629 .iter()
1630 .find(|e| self.model.selected.contains(&e.id))
1631 .unwrap()
1632 .name
1633 .clone();
1634 self.preview_return_focus = Some(
1635 ctx.memory(|m| m.focused())
1636 .unwrap_or_else(|| egui::Id::unique("archive-list")),
1637 );
1638 self.preview_initial_focus = true;
1639 let request = Start::Preview {
1640 archive: self.model.archive.clone().unwrap(),
1641 entry_id: *self.model.selected.first().unwrap(),
1642 list_id: self.model.list_id.clone().unwrap(),
1643 };
1644 self.preview_open = true;
1645 self.start(request);
1646 }
1647
1648 fn close_preview(&mut self) {
1649 self.preview_open = false;
1650 self.model.dismiss_preview();
1651 self.preview_texture = None;
1652 self.preview_text.clear();
1653 self.dismissed = true;
1654 }
1655
1656 fn preview_dialog(&mut self, ctx: &egui::Context) {
1657 if !self.preview_open
1658 || self.model.challenge.is_some()
1659 || self.model.resource.is_some()
1660 || self.model.close != Close::Open
1661 {
1662 return;
1663 }
1664 if let Some(preview) = self.model.preview.as_mut()
1665 && (!preview.data.is_empty() || preview.info.total_bytes == 0)
1666 {
1667 match preview.info.format {
1668 PreviewFormat::Utf8Text => {
1669 self.preview_text =
1670 String::from_utf8(std::mem::take(&mut preview.data)).unwrap_or_default();
1671 }
1672 PreviewFormat::Rgba8 => {
1673 let width = preview.info.width as usize;
1674 let height = preview.info.height as usize;
1675 let limit = ctx.input(|i| i.max_texture_side).max(1);
1676 let step = width.div_ceil(limit).max(height.div_ceil(limit)).max(1);
1677 let size = [width.div_ceil(step), height.div_ceil(step)];
1678 let mut colors = Vec::with_capacity(size[0] * size[1]);
1679 for y in (0..height).step_by(step) {
1680 for x in (0..width).step_by(step) {
1681 let index = (y * width + x) * 4;
1682 colors.push(egui::Color32::from_rgba_unmultiplied(
1683 preview.data[index],
1684 preview.data[index + 1],
1685 preview.data[index + 2],
1686 preview.data[index + 3],
1687 ));
1688 }
1689 }
1690 let pixels = egui::ColorImage::new(size, colors);
1691 preview.data = Vec::new();
1692 self.preview_texture = Some(ctx.load_texture(
1693 "archive-preview",
1694 pixels,
1695 egui::TextureOptions::LINEAR,
1696 ));
1697 }
1698 }
1699 }
1700 let mut close = false;
1701 let modal = egui::Modal::new(egui::Id::unique("archive-preview")).show(ctx, |ui| {
1702 ui.set_width((ctx.content_rect().width() - 64.0).clamp(240.0, 760.0));
1703 ui.horizontal(|ui| {
1704 ui.heading("미리보기");
1705 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1706 let button = theme::flat_icon_button(
1707 ui,
1708 "미리보기 닫기",
1709 theme::CLOSE,
1710 true,
1711 egui::vec2(36.0, 36.0),
1712 );
1713 if self.preview_initial_focus {
1714 button.request_focus();
1715 self.preview_initial_focus = false;
1716 }
1717 close |= button.clicked();
1718 });
1719 });
1720 ui.add(egui::Label::new(&self.preview_name).truncate())
1721 .on_hover_text(&self.preview_name);
1722 let max_height = (ctx.content_rect().height() - 220.0).clamp(100.0, 560.0);
1723 if self.model.busy() {
1724 ui.label("미리보기를 불러오는 중입니다");
1725 if ui.button("취소").clicked() {
1726 close = true;
1727 }
1728 } else if let Some(error) = self.model.error.as_ref() {
1729 Self::error_notice(ui, error);
1730 } else if let Some(texture) = self.preview_texture.as_ref() {
1731 ui.add(
1732 egui::Image::new(texture)
1733 .max_size(egui::vec2(ui.available_width(), max_height))
1734 .shrink_to_fit(),
1735 );
1736 } else if self.model.preview.is_some() {
1737 egui::ScrollArea::both()
1738 .id_salt("preview-text")
1739 .max_height(max_height)
1740 .show(ui, |ui| {
1741 let mut text = self.preview_text.as_str();
1742 ui.add(
1743 egui::TextEdit::multiline(&mut text)
1744 .desired_width(ui.available_width())
1745 .desired_rows(12)
1746 .frame(egui::Frame::NONE),
1747 );
1748 });
1749 if self.preview_text.is_empty() {
1750 ui.label("빈 텍스트 파일입니다");
1751 }
1752 } else {
1753 let code = self.model.terminal.as_ref().and_then(|t| t.error);
1754 ui.label(match code {
1755 Some(ErrorCode::Limit) => "미리보기 크기 또는 처리 한도를 초과했습니다.",
1756 Some(ErrorCode::Integrity) => "파일이 손상됐거나 UTF-8 텍스트가 아닙니다.",
1757 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature) => {
1758 "이 파일 형식은 미리보기를 지원하지 않습니다."
1759 }
1760 Some(ErrorCode::SourceChanged) => "압축파일이 변경됐습니다. 다시 열어 주세요.",
1761 Some(ErrorCode::WrongPassword) => "암호가 올바르지 않습니다.",
1762 _ => "미리보기를 불러오지 못했습니다.",
1763 });
1764 ui.label("닫은 뒤 파일을 선택하고 [압축해제]를 사용할 수 있습니다.");
1765 }
1766 });
1767 if close || modal.should_close() {
1768 self.close_preview();
1769 }
1770 }
1771
1772 fn limit_result_visible(&self) -> bool {
1773 self.result_visible()
1774 && self
1775 .model
1776 .terminal
1777 .as_ref()
1778 .is_some_and(|terminal| terminal.error == Some(ErrorCode::Limit))
1779 }
1780
1781 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
1782 if !self.limit_result_visible() || self.main_modal_open() {
1783 return;
1784 }
1785 egui::Modal::new(egui::Id::new("archive-limit-result")).show(ctx, |ui| {
1786 ui.set_width((ctx.content_rect().width() - 64.0).min(WORK_WIDTH));
1787 ui.heading("작업 결과");
1788 self.work_area(ui);
1789 });
1790 }
1791
1792 fn error_notice(ui: &mut egui::Ui, error: &str) {
1793 let response = theme::panel(theme::ERROR_BG)
1794 .show(ui, |ui| {
1795 ui.horizontal_wrapped(|ui| {
1796 theme::icon(ui, Icon::Error, 24.0);
1797 ui.colored_label(theme::ERROR, error);
1798 });
1799 })
1800 .response;
1801 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
1802 }
1803
1804 fn work_visible(&self) -> bool {
1805 !self
1806 .last_request
1807 .as_ref()
1808 .is_some_and(|r| matches!(r, Start::Preview { .. }))
1809 && (self.model.busy()
1810 || self.result_visible()
1811 || (self.ui_error.is_some() && !self.create))
1812 }
1813
1814 /// 메인 창 가운데에 모달(암호 입력, 종료 확인, 파일 선택 안내)이나 같은 자리에 뜨는
1815 /// ZIP 만들기 창이 떠 있는지. 닫기가 정해진 뒤(Allowed)에도 결과 창을 다시 띄우지 않음.
1816 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
1817 fn main_modal_open(&self) -> bool {
1818 (self.create && !self.model.busy())
1819 || self.picker.is_some()
1820 || self.model.challenge.is_some()
1821 || self.model.resource.is_some()
1822 || self.model.conflict.is_some()
1823 || self.model.close != Close::Open
1824 }
1825
1826 fn work_window(&mut self, ctx: &egui::Context) {
1827 if !self.work_visible() {
1828 self.work = WorkWindow::default();
1829 return;
1830 }
1831 if self.limit_result_visible() {
1832 self.work.open = false;
1833 return;
1834 }
1835 if ctx.embed_viewports() {
1836 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1837 return;
1838 }
1839 if self.main_modal_open() {
1840 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
1841 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1842 self.work.open = false;
1843 return;
1844 }
1845 let id = egui::ViewportId::from_hash_of("archive-work");
1846 let title = if self.model.busy() {
1847 present::activity_text(
1848 &self.model,
1849 matches!(self.last_request, Some(Start::CreateZip { .. })),
1850 )
1851 .to_owned()
1852 } else {
1853 "작업 결과".to_owned()
1854 };
1855 let window_title = format!("{title} — Zipelo");
1856 let custom_frame = self.custom_frame;
1857 let size = egui::vec2(WORK_WIDTH, self.work.height);
1858 let builder = self.work.builder(
1859 ctx,
1860 id,
1861 size,
1862 &window_title,
1863 !custom_frame,
1864 self.picker.is_some(),
1865 );
1866 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1867 if ui.ctx().input(|i| i.viewport().close_requested()) {
1868 if self.model.busy() {
1869 ui.ctx()
1870 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1871 } else {
1872 self.dismissed = true;
1873 self.ui_error = None;
1874 self.model.input_error = None;
1875 }
1876 }
1877 if class == egui::ViewportClass::EmbeddedWindow {
1878 ui.set_width(WORK_WIDTH);
1879 self.work_area(ui);
1880 return None;
1881 }
1882 let mut chrome = 0.0;
1883 if custom_frame {
1884 window_frame::title_bar(
1885 ui,
1886 "work",
1887 &window_title,
1888 window_frame::Buttons {
1889 minimize: false,
1890 maximize: false,
1891 },
1892 );
1893 window_frame::edges(ui.ctx(), false);
1894 chrome = window_frame::TITLE_HEIGHT;
1895 }
1896 let margin = theme::PAD as f32;
1897 egui::CentralPanel::default()
1898 .frame(theme::panel(theme::PANEL).corner_radius(0))
1899 .show(ui, |ui| {
1900 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1901 Some(content.height() + 2.0 * margin + chrome)
1902 })
1903 .inner
1904 });
1905 if let Some(height) = height {
1906 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1907 if (height - self.work.height).abs() > 1.0 {
1908 self.work.height = height;
1909 }
1910 }
1911 }
1912
1913 fn work_area(&mut self, ui: &mut egui::Ui) {
1914 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
1915 let enabled = self.picker.is_none();
1916 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
1917 }
1918
1919 fn work_contents(&mut self, ui: &mut egui::Ui) {
1920 if self.model.busy() {
1921 self.progress(ui);
1922 } else if self.result_visible() {
1923 self.result(ui);
1924 }
1925 if !self.create
1926 && let Some(error) = &self.ui_error
1927 {
1928 Self::error_notice(ui, error);
1929 if error == present::FOLDER_ERROR
1930 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
1931 {
1932 self.open_picker(Purpose::Destination);
1933 }
1934 }
1935 if let Some(error) = &self.model.input_error {
1936 ui.colored_label(
1937 theme::ERROR,
1938 if error.starts_with("암호는") {
1939 error.as_str()
1940 } else {
1941 if matches!(self.last_request, Some(Start::CreateZip { .. })) {
1942 "저장 위치와 추가한 항목을 확인하세요"
1943 } else {
1944 "풀 위치와 선택한 항목을 확인하세요"
1945 }
1946 },
1947 );
1948 }
1949 }
1950
1951 fn progress(&mut self, ui: &mut egui::Ui) {
1952 if self.model.resource.is_some() {
1953 ui.horizontal(|ui| {
1954 ui.label("사용자 허용을 기다리고 있습니다");
1955 self.cancel_action(ui, false);
1956 });
1957 return;
1958 }
1959 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1960 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
1961 let title = present::activity_text(&self.model, creating);
1962 ui.strong(title);
1963 if let Some((stage, done, total, count)) = self.model.progress {
1964 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
1965 let processed = if stage == Stage::Read {
1966 String::new()
1967 } else {
1968 format!("{count}개 처리함, ")
1969 };
1970 if let Some(total) = total.filter(|n| *n > 0) {
1971 ui.scope(|ui| {
1972 ui.visuals_mut().extreme_bg_color = theme::BORDER;
1973 ui.add(
1974 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
1975 .fill(theme::BLUE)
1976 .desired_height(theme::SPACE * 2.0),
1977 );
1978 });
1979 ui.horizontal(|ui| {
1980 ui.label(format!(
1981 "{:.0}% / {processed}{} / {}",
1982 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
1983 present::bytes_text(done),
1984 present::bytes_text(total)
1985 ));
1986 self.cancel_action(ui, cancelling);
1987 });
1988 } else {
1989 theme::indeterminate(ui);
1990 ui.horizontal(|ui| {
1991 ui.label(format!("{processed}{}", present::bytes_text(done)));
1992 self.cancel_action(ui, cancelling);
1993 });
1994 }
1995 } else {
1996 theme::indeterminate(ui);
1997 ui.horizontal(|ui| {
1998 ui.label("작업을 진행하고 있습니다");
1999 self.cancel_action(ui, cancelling);
2000 });
2001 }
2002 }
2003
2004 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
2005 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2006 if theme::action(ui, "취소", false, !cancelling).clicked() {
2007 self.clear_password();
2008 self.model.cancel();
2009 }
2010 });
2011 }
2012
2013 fn result(&mut self, ui: &mut egui::Ui) {
2014 let t = self.model.terminal.clone();
2015 let listing = matches!(self.last_request, Some(Start::List { .. }));
2016 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
2017 let resolved_targets = present::resolved_targets(
2018 self.targets.as_ref(),
2019 &self.model.entries,
2020 matches!(
2021 self.last_request,
2022 Some(Start::Extract {
2023 gzip_output_name: Some(_),
2024 ..
2025 })
2026 )
2027 .then_some(self.gzip_name.as_str()),
2028 &self.model.resolutions,
2029 );
2030 let skipped = self
2031 .model
2032 .resolutions
2033 .iter()
2034 .filter(|r| r.choice == ConflictChoice::Skip)
2035 .count();
2036 let created_names = self
2037 .model
2038 .outputs
2039 .iter()
2040 .filter(|(_, disposition)| *disposition == Disposition::Created)
2041 .map(|(name, _)| name.replace('\\', "/"))
2042 .collect::<BTreeSet<_>>();
2043 let warnings = if listing {
2044 Vec::new()
2045 } else {
2046 present::publication_warnings(
2047 t.as_ref(),
2048 self.model.confirmed,
2049 resolved_targets.as_ref(),
2050 &self.directories,
2051 &self.model.outputs,
2052 )
2053 };
2054 let success = self.model.confirmed
2055 && self.model.error.is_none()
2056 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
2057 && warnings.is_empty();
2058 let durability_warning = t
2059 .as_ref()
2060 .filter(|_| self.model.confirmed && !listing)
2061 .and_then(|t| present::durability_warning(t.durability));
2062 let durability_in_details = success
2063 && t.as_ref()
2064 .is_some_and(|t| t.durability == Durability::Unconfirmed);
2065 let cancelled =
2066 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
2067 let title = if success {
2068 if creating {
2069 "ZIP 파일을 만들었습니다"
2070 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
2071 "모든 파일을 건너뛰었습니다"
2072 } else {
2073 "압축을 풀었습니다"
2074 }
2075 } else if cancelled {
2076 "작업을 취소했습니다"
2077 } else if listing {
2078 "압축파일을 열지 못했습니다"
2079 } else if creating {
2080 "ZIP 파일을 만들지 못했습니다"
2081 } else {
2082 "압축을 풀지 못했습니다"
2083 };
2084 let fill = if success {
2085 theme::SUCCESS_BG
2086 } else if cancelled {
2087 theme::STRIPE
2088 } else {
2089 theme::ERROR_BG
2090 };
2091 let mut choose = false;
2092 let mut retry = false;
2093 let mut expand = false;
2094 let mut reopen = false;
2095 let mut folder = false;
2096 theme::panel(fill).show(ui, |ui| {
2097 ui.horizontal(|ui| {
2098 theme::icon(
2099 ui,
2100 if success {
2101 Icon::Success
2102 } else if cancelled {
2103 Icon::Warning
2104 } else {
2105 Icon::Error
2106 },
2107 24.0,
2108 );
2109 ui.strong(title);
2110 });
2111 let max_height = WORK_RESULT_MAX_HEIGHT;
2112 egui::ScrollArea::vertical()
2113 .id_salt("result-message")
2114 .max_height(max_height)
2115 .show(ui, |ui| {
2116 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
2117 let path = match self.last_request.as_ref() {
2118 Some(Start::CreateZip { output_file, .. }) => {
2119 output_file.display().to_string()
2120 }
2121 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
2122 };
2123 theme::bounded_text(ui, &path, ui.available_width());
2124 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
2125 ui.label(if creating && code == ErrorCode::SourceChanged {
2126 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요".to_owned()
2127 } else {
2128 present::operation_text(present::error_text(code), creating)
2129 });
2130 } else if let Some(error) = &self.model.error {
2131 ui.label(present::operation_text(
2132 present::client_error_text(error),
2133 creating,
2134 ));
2135 }
2136 if skipped > 0 {
2137 ui.label(format!("건너뛴 파일 {skipped}개"));
2138 }
2139 for resolution in self.model.resolutions.iter().filter(|r| {
2140 r.choice == ConflictChoice::Rename
2141 && created_names.contains(&r.relative_name.replace('\\', "/"))
2142 }) {
2143 theme::bounded_text(
2144 ui,
2145 &format!("이름 바꿔 저장: {}", resolution.relative_name),
2146 ui.available_width(),
2147 );
2148 }
2149 for warning in warnings
2150 .iter()
2151 .copied()
2152 .chain(durability_warning.filter(|_| !durability_in_details))
2153 {
2154 ui.horizontal_wrapped(|ui| {
2155 theme::icon(ui, Icon::Warning, 20.0);
2156 ui.colored_label(
2157 theme::WARNING,
2158 present::operation_text(warning, creating),
2159 );
2160 });
2161 }
2162 if !success
2163 && !listing
2164 && present::definitely_unsaved(
2165 t.as_ref(),
2166 self.model.confirmed,
2167 &self.model.outputs,
2168 )
2169 {
2170 ui.label(if creating {
2171 "ZIP 파일을 만들지 않았습니다"
2172 } else {
2173 "아무 파일도 풀지 않았습니다"
2174 });
2175 }
2176 if t.as_ref().is_some_and(|t| {
2177 t.error == Some(ErrorCode::Limit)
2178 && (t.created_count > 0
2179 || t.retained_partial_count > 0
2180 || t.publication != Publication::None)
2181 }) {
2182 ui.label(format!(
2183 "{}개 파일이 저장되었거나 일부 남아 있습니다. 저장 위치를 확인하세요.",
2184 t.as_ref().unwrap().created_count
2185 ));
2186 theme::bounded_text(
2187 ui,
2188 &self.destination.display().to_string(),
2189 ui.available_width(),
2190 );
2191 }
2192 if self.details {
2193 theme::panel(theme::STRIPE).show(ui, |ui| {
2194 if durability_in_details {
2195 if let Some(warning) = durability_warning {
2196 ui.label(present::operation_text(warning, creating));
2197 }
2198 }
2199 if let Some(t) = &t {
2200 for line in terminal_lines(t) {
2201 ui.label(line);
2202 }
2203 }
2204 if let Some(error) = &self.model.error {
2205 ui.label(error);
2206 }
2207 for (name, state) in &self.model.outputs {
2208 theme::bounded_text(
2209 ui,
2210 &format!("{name}: {}", disposition_label(*state)),
2211 ui.available_width(),
2212 );
2213 }
2214 });
2215 }
2216 });
2217 let conflict = t
2218 .as_ref()
2219 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
2220 && !creating;
2221 let uncertain = warnings.contains(&present::UNCERTAIN);
2222 if conflict && uncertain {
2223 let response = ui.checkbox(
2224 &mut self.checked_destination,
2225 "기존 풀 위치 폴더를 확인했습니다",
2226 );
2227 theme::pointer(&response);
2228 theme::focus(&response);
2229 }
2230 ui.horizontal(|ui| {
2231 if theme::action(
2232 ui,
2233 if self.details {
2234 "자세히 닫기"
2235 } else {
2236 "자세히 보기"
2237 },
2238 false,
2239 true,
2240 )
2241 .clicked()
2242 {
2243 self.details = !self.details;
2244 }
2245 let action = if success {
2246 Some(("폴더 열기", true))
2247 } else if conflict {
2248 Some((
2249 if self
2250 .model
2251 .list_id
2252 .as_ref()
2253 .is_some_and(|id| id.format == Format::Gzip)
2254 {
2255 "다른 이름으로 저장"
2256 } else {
2257 "다른 폴더에 풀기"
2258 },
2259 !uncertain || self.checked_destination,
2260 ))
2261 } else if t
2262 .as_ref()
2263 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
2264 {
2265 Some((
2266 if creating {
2267 "다시 만들기"
2268 } else {
2269 "압축파일 다시 열기"
2270 },
2271 true,
2272 ))
2273 } else if self.model.can_retry_expanded() {
2274 None
2275 } else if t
2276 .as_ref()
2277 .is_some_and(|t| t.error == Some(ErrorCode::Limit))
2278 {
2279 None
2280 } else if !cancelled && (!uncertain || listing) {
2281 Some(("다시 시도", true))
2282 } else {
2283 None
2284 };
2285 let (confirm, primary) = theme::action_pair(ui, "확인", action);
2286 if confirm {
2287 self.dismissed = true;
2288 self.ui_error = None;
2289 self.model.input_error = None;
2290 }
2291 if primary {
2292 match action.map(|(label, _)| label) {
2293 Some("폴더 열기") => folder = true,
2294 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
2295 choose = true
2296 }
2297 Some("압축파일 다시 열기") => reopen = true,
2298 Some("다시 시도" | "다시 만들기") => retry = true,
2299 _ => {}
2300 }
2301 }
2302 });
2303 if self.model.can_retry_expanded() {
2304 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2305 expand = theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked();
2306 });
2307 }
2308 });
2309 if choose {
2310 self.open_picker(Purpose::Retry);
2311 }
2312 if retry {
2313 self.retry();
2314 }
2315 if expand {
2316 let ready = if matches!(self.last_request, Some(Start::Extract { .. })) {
2317 match present::prepare_destination(&self.destination, self.automatic_destination) {
2318 Ok(created) => {
2319 self.owned_destination = created.then(|| self.destination.clone());
2320 true
2321 }
2322 Err(_) => {
2323 self.ui_error = Some(present::FOLDER_ERROR.into());
2324 false
2325 }
2326 }
2327 } else {
2328 true
2329 };
2330 if ready && self.model.retry_expanded(self.factory.as_mut()) {
2331 self.dismissed = false;
2332 self.details = false;
2333 self.ui_error = None;
2334 }
2335 }
2336 if reopen {
2337 if let Some(path) = self.model.archive.clone() {
2338 self.open_path(path);
2339 }
2340 }
2341 if folder {
2342 let path = match self.last_request.as_ref() {
2343 Some(Start::CreateZip { output_file, .. }) => {
2344 output_file.parent().unwrap_or(Path::new("/"))
2345 }
2346 _ => self.destination.as_path(),
2347 };
2348 match present::folder_command(path).spawn() {
2349 Ok(mut child) => {
2350 std::thread::spawn(move || {
2351 let _ = child.wait();
2352 });
2353 }
2354 Err(_) => {
2355 self.ui_error = Some(
2356 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
2357 )
2358 }
2359 }
2360 }
2361 }
2362
2363 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
2364 fn entry_cells(
2365 ui: &mut egui::Ui,
2366 rect: egui::Rect,
2367 directory: bool,
2368 name: &str,
2369 hover: &str,
2370 size: String,
2371 name_width: f32,
2372 ) {
2373 ui.scope_builder(
2374 egui::UiBuilder::new()
2375 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
2376 .layout(Layout::left_to_right(Align::Center)),
2377 |ui| {
2378 ui.style_mut().interaction.selectable_labels = false;
2379 ui.add_space(16.0);
2380 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
2381 theme::bounded_text_hover(ui, name, hover, name_width);
2382 theme::column_label(ui, size, 96.0, Align::Max);
2383 },
2384 );
2385 }
2386
2387 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
2388 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
2389 fn create_window(&mut self, ctx: &egui::Context) {
2390 if !self.create || self.model.busy() {
2391 self.create_win = WorkWindow::default();
2392 return;
2393 }
2394 if ctx.embed_viewports() {
2395 let mut close = false;
2396 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
2397 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
2398 ui.horizontal(|ui| {
2399 ui.heading("ZIP 만들기");
2400 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2401 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
2402 close = button.clicked();
2403 });
2404 });
2405 close |= self.create_area(ui);
2406 ui.add_space(theme::SPACE);
2407 close |= self.create_actions(ui);
2408 });
2409 if close || modal.should_close() {
2410 self.close_create();
2411 }
2412 return;
2413 }
2414 let id = egui::ViewportId::from_hash_of("archive-create");
2415 let title = "ZIP 만들기 — Zipelo";
2416 let custom_frame = self.custom_frame;
2417 if !self.create_win.open {
2418 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
2419 }
2420 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
2421 let builder =
2422 self.create_win
2423 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
2424 let mut close = false;
2425 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
2426 if ui.ctx().input(|i| i.viewport().close_requested()) {
2427 close = true;
2428 }
2429 if class == egui::ViewportClass::EmbeddedWindow {
2430 ui.set_width(CREATE_WIDTH);
2431 close |= self.create_area(ui);
2432 close |= self.create_actions(ui);
2433 return None;
2434 }
2435 let mut chrome = 0.0;
2436 if custom_frame {
2437 window_frame::title_bar(
2438 ui,
2439 "create",
2440 title,
2441 window_frame::Buttons {
2442 minimize: false,
2443 maximize: false,
2444 },
2445 );
2446 window_frame::edges(ui.ctx(), false);
2447 chrome = window_frame::TITLE_HEIGHT;
2448 }
2449 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
2450 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
2451 .resizable(false)
2452 .show_separator_line(false)
2453 .frame(
2454 egui::Frame::new()
2455 .fill(theme::PANEL)
2456 .inner_margin(egui::Margin {
2457 left: theme::PAD,
2458 right: theme::PAD,
2459 top: 0,
2460 bottom: theme::PAD,
2461 }),
2462 )
2463 .show(ui, |ui| close |= self.create_actions(ui))
2464 .response
2465 .rect
2466 .height();
2467 let margin = theme::PAD as f32;
2468 egui::CentralPanel::default()
2469 .frame(theme::panel(theme::PANEL).corner_radius(0))
2470 .show(ui, |ui| {
2471 let content = ui
2472 .vertical(|ui| close |= self.create_area(ui))
2473 .response
2474 .rect;
2475 Some(content.height() + 2.0 * margin + chrome + actions)
2476 })
2477 .inner
2478 });
2479 if let Some(height) = height {
2480 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
2481 if (height - self.create_win.height).abs() > 1.0 {
2482 self.create_win.height = height;
2483 }
2484 }
2485 if close {
2486 self.close_create();
2487 }
2488 }
2489
2490 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
2491 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
2492 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
2493 let enabled = self.picker.is_none();
2494 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
2495 .inner
2496 }
2497
2498 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
2499 let rows = self.create_rows();
2500 let root = self.create_root();
2501
2502 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
2503 ui.horizontal(|ui| {
2504 ui.set_height(theme::FIELD);
2505 ui.spacing_mut().item_spacing.x = 0.0;
2506 let up = theme::flat_icon_button(
2507 ui,
2508 "위로",
2509 theme::UP,
2510 !self.create_folder.is_empty(),
2511 egui::vec2(theme::FIELD, theme::FIELD),
2512 );
2513 if up.clicked() {
2514 self.create_folder = self
2515 .create_folder
2516 .rsplit_once('/')
2517 .map_or("", |(parent, _)| parent)
2518 .to_owned();
2519 self.create_selected = None;
2520 }
2521 ui.add_space(6.0);
2522 let path = match &root {
2523 Some(root) => {
2524 let name = root.file_name().unwrap_or_default().to_string_lossy();
2525 if self.create_folder.is_empty() {
2526 format!("/{name}")
2527 } else {
2528 format!("/{name}/{}", self.create_folder)
2529 }
2530 }
2531 None => "/".to_owned(),
2532 };
2533 let (rect, _) = ui.allocate_exact_size(
2534 egui::vec2(ui.available_width(), theme::FIELD),
2535 egui::Sense::hover(),
2536 );
2537 theme::boxed_field(ui, rect);
2538 theme::field_text(ui, rect, &path);
2539 });
2540 ui.add_space(theme::SPACE);
2541
2542 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
2543 let mut enter = None;
2544 egui::Frame::new()
2545 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2546 .show(ui, |ui| {
2547 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
2548 ui.set_max_height(CREATE_LIST_HEIGHT);
2549 let message = match &rows {
2550 None => Some("폴더를 읽지 못했습니다"),
2551 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
2552 Some(_) => None,
2553 };
2554 if let Some(message) = message {
2555 ui.centered_and_justified(|ui| ui.label(message));
2556 return;
2557 }
2558 let rows = rows.unwrap();
2559 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
2560 egui::ScrollArea::vertical()
2561 .id_salt("create-rows")
2562 .auto_shrink([false, false])
2563 .max_height(CREATE_LIST_HEIGHT)
2564 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
2565 for row in &rows[range] {
2566 let (rect, response) = ui.allocate_exact_size(
2567 egui::vec2(ui.available_width(), LIST_ROW),
2568 egui::Sense::click(),
2569 );
2570 let response = response.on_hover_text(&row.name);
2571 theme::pointer(&response);
2572 response.widget_info(|| {
2573 egui::WidgetInfo::labeled(
2574 egui::Role::ListBoxOption,
2575 true,
2576 &row.name,
2577 )
2578 });
2579 if response.clicked() {
2580 self.create_selected = Some(row.name.clone());
2581 }
2582 theme::row_background(
2583 ui,
2584 rect,
2585 self.create_selected.as_deref() == Some(row.name.as_str()),
2586 response.hovered(),
2587 );
2588 if row.directory && root.is_some() && response.clicked() {
2589 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
2590 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
2591 let frame = ui.ctx().cumulative_frame_nr();
2592 let time = ui.input(|i| i.time);
2593 match &self.create_last_click {
2594 Some((name, last_frame, last_time))
2595 if name == &row.name
2596 && *last_frame != frame
2597 && time - last_time < 0.4 =>
2598 {
2599 enter = Some(row.name.clone());
2600 self.create_last_click = None;
2601 }
2602 Some((name, last_frame, _))
2603 if name == &row.name && *last_frame == frame => {}
2604 _ => {
2605 self.create_last_click =
2606 Some((row.name.clone(), frame, time));
2607 }
2608 }
2609 }
2610 Self::entry_cells(
2611 ui,
2612 rect,
2613 row.directory,
2614 &row.name,
2615 &row.name,
2616 row.bytes.map(present::bytes_text).unwrap_or_default(),
2617 name_width,
2618 );
2619 }
2620 });
2621 });
2622 if let Some(name) = enter {
2623 self.create_folder = if self.create_folder.is_empty() {
2624 name
2625 } else {
2626 format!("{}/{name}", self.create_folder)
2627 };
2628 self.create_selected = None;
2629 }
2630 ui.add_space(theme::SPACE);
2631
2632 if let Some(error) = &self.ui_error {
2633 Self::error_notice(ui, error);
2634 }
2635
2636 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
2637 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
2638 theme::pointer(&check);
2639 theme::focus(&check);
2640 if self.aes256 {
2641 let label_width = 72.0;
2642 ui.horizontal(|ui| {
2643 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
2644 let toggle = if self.zip_password_visible {
2645 "숨기기"
2646 } else {
2647 "보기"
2648 };
2649 let toggle_width = 72.0;
2650 let edit = ui.add_sized(
2651 [
2652 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
2653 theme::FIELD,
2654 ],
2655 egui::TextEdit::singleline(&mut self.zip_password)
2656 .password(!self.zip_password_visible)
2657 .id(egui::Id::unique("zip-password-input"))
2658 .char_limit(1024)
2659 .align(egui::Align2::LEFT_CENTER),
2660 );
2661 theme::focus(&edit);
2662 if theme::action(ui, toggle, false, true).clicked() {
2663 self.zip_password_visible = !self.zip_password_visible;
2664 }
2665 });
2666 ui.horizontal(|ui| {
2667 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
2668 let edit = ui.add_sized(
2669 [
2670 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
2671 theme::FIELD,
2672 ],
2673 egui::TextEdit::singleline(&mut self.zip_password_confirm)
2674 .password(!self.zip_password_visible)
2675 .id(egui::Id::unique("zip-password-confirm"))
2676 .char_limit(1024)
2677 .align(egui::Align2::LEFT_CENTER),
2678 );
2679 theme::focus(&edit);
2680 });
2681 if self.zip_password.len() > 1024 {
2682 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2683 } else if !self.zip_password_confirm.is_empty()
2684 && self.zip_password != self.zip_password_confirm
2685 {
2686 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2687 }
2688 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
2689 } else if check.changed()
2690 || !self.zip_password.is_empty()
2691 || !self.zip_password_confirm.is_empty()
2692 {
2693 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
2694 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
2695 self.clear_zip_password();
2696 }
2697 false
2698 }
2699
2700 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
2701 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
2702 let ready = !self.sources.is_empty() && self.zip_password_ready();
2703 let enabled = self.picker.is_none();
2704 let (cancel, compress) = ui
2705 .add_enabled_ui(enabled, |ui| {
2706 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
2707 })
2708 .inner;
2709 if compress {
2710 self.open_picker(Purpose::SaveZip);
2711 }
2712 cancel
2713 }
2714
2715 fn resource_dialog(&mut self, ctx: &egui::Context) {
2716 let Some(question) = self.model.resource.clone() else {
2717 return;
2718 };
2719 let Some(job) = self.model.job_id() else {
2720 return;
2721 };
2722 let mut allow = false;
2723 let mut cancel = false;
2724 let modal = egui::Modal::new(egui::Id::unique(("archive-resource", job, question.id)))
2725 .show(ctx, |ui| {
2726 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
2727 ui.heading(if question.scope.ratio {
2728 "압축률이 매우 높습니다"
2729 } else {
2730 "큰 작업을 허용할까요?"
2731 });
2732 ui.label(match question.action {
2733 ActionKind::List => "압축파일 목록 열기",
2734 ActionKind::Extract => "압축 해제",
2735 ActionKind::CreateZip => "ZIP 만들기",
2736 ActionKind::Preview => "파일 미리보기",
2737 });
2738 if question.scope.ratio {
2739 ui.label("작은 압축파일도 많은 저장 공간을 사용할 수 있습니다.");
2740 }
2741 if question.scope.output {
2742 ui.label(format!(
2743 "총량 한도: {}에서 {}로",
2744 present::bytes_text(question.soft_limits.output),
2745 present::bytes_text(question.ceiling.output)
2746 ));
2747 }
2748 if question.scope.entries {
2749 ui.label(format!(
2750 "항목 한도: {}개에서 {}개로",
2751 question.soft_limits.entries, question.ceiling.entries
2752 ));
2753 }
2754 let mut u = question.usage;
2755 let estimated = self.model.estimated_usage();
2756 u.estimated_bytes = u.estimated_bytes.or(estimated.estimated_bytes);
2757 u.estimated_entries = u.estimated_entries.or(estimated.estimated_entries);
2758 let bytes = |value: Option<u64>| {
2759 value
2760 .map(present::bytes_text)
2761 .unwrap_or_else(|| "미확인".into())
2762 };
2763 let entries = |value: Option<u32>| {
2764 value
2765 .map(|n| format!("{n}개"))
2766 .unwrap_or_else(|| "미확인".into())
2767 };
2768 ui.label(format!(
2769 "예상 총량: {} / 실제 총량: {}",
2770 bytes(u.estimated_bytes),
2771 bytes(u.actual_bytes)
2772 ));
2773 ui.label(format!(
2774 "예상 항목: {} / 실제 항목: {}",
2775 entries(u.estimated_entries),
2776 entries(u.actual_entries)
2777 ));
2778 if question.scope.ratio {
2779 ui.label(format!(
2780 "압축 크기: {} / 풀린 크기: {}",
2781 bytes(u.compressed_bytes),
2782 bytes(u.ratio_output_bytes)
2783 ));
2784 }
2785 ui.label(format!(
2786 "확인한 저장 볼륨의 여유 공간: {}",
2787 bytes(u.available_bytes)
2788 ));
2789 ui.label(format!(
2790 "이 작업의 상한: {} / {}개",
2791 present::bytes_text(question.ceiling.output),
2792 question.ceiling.entries
2793 ));
2794 ui.label("이 작업에만 적용합니다. 공간 부족이나 자원 상한에 도달하면 중단합니다.");
2795 ui.horizontal(|ui| {
2796 cancel = theme::action(ui, "취소", false, true).clicked();
2797 allow = theme::action(ui, "이 작업 허용", true, true).clicked();
2798 });
2799 });
2800 if cancel || modal.should_close() {
2801 self.clear_password();
2802 self.model.cancel();
2803 } else if allow {
2804 self.model.resource_reply(job, question.id, true);
2805 }
2806 }
2807
2808 fn conflict_dialog(&mut self, ctx: &egui::Context) {
2809 let conflict = self.model.conflict.clone().unwrap();
2810 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
2811 if self.conflict_challenge != Some(question) {
2812 self.conflict_challenge = Some(question);
2813 self.conflict_apply = false;
2814 }
2815 let mut choice = None;
2816 let mut cancel = false;
2817 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
2818 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
2819 ui.heading("같은 이름의 파일이 있습니다");
2820 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
2821 ui.add_space(theme::SPACE);
2822 egui::Grid::new("conflict-sizes")
2823 .spacing([24.0, 8.0])
2824 .show(ui, |ui| {
2825 ui.label("기존 파일");
2826 ui.label(present::bytes_text(conflict.existing_size));
2827 ui.end_row();
2828 ui.label("압축파일 안의 파일");
2829 ui.label(present::bytes_text(conflict.incoming_size));
2830 ui.end_row();
2831 });
2832 ui.add_space(theme::SPACE);
2833 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
2834 ui.add_space(theme::SPACE);
2835 ui.horizontal_wrapped(|ui| {
2836 for (label, value) in [
2837 ("덮어쓰기", ConflictChoice::Overwrite),
2838 ("건너뛰기", ConflictChoice::Skip),
2839 ("이름 바꿔 저장", ConflictChoice::Rename),
2840 ] {
2841 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
2842 choice = Some(value);
2843 }
2844 }
2845 });
2846 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
2847 if let Some(error) = &self.model.error {
2848 Self::error_notice(ui, present::client_error_text(error));
2849 }
2850 cancel = theme::action(ui, "작업 취소", false, true).clicked();
2851 });
2852 if modal.should_close() || cancel {
2853 self.model.cancel();
2854 } else if let Some(choice) = choice {
2855 self.model.resolve_conflict(choice, self.conflict_apply);
2856 }
2857 }
2858
2859 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
2860 let (_, attempt, encrypt) = self.model.challenge.unwrap();
2861 let mut submit = false;
2862 let mut cancel = false;
2863 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
2864 id == egui::Id::unique("archive-password-input")
2865 || id == egui::Id::unique("archive-password-confirm")
2866 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
2867 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
2868 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
2869 ui.heading(if encrypt {
2870 "ZIP 암호 설정"
2871 } else {
2872 "암호가 필요합니다"
2873 });
2874 if encrypt {
2875 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
2876 } else if let Some(path) = &self.model.archive {
2877 ui.label(format!(
2878 "{}은 암호로 보호되어 있습니다.",
2879 present::middle_text(
2880 &path.file_name().unwrap_or_default().to_string_lossy(),
2881 24
2882 )
2883 ));
2884 }
2885 ui.horizontal(|ui| {
2886 ui.label("암호");
2887 let edit = ui.add(
2888 egui::TextEdit::singleline(&mut self.password)
2889 .password(!self.password_visible)
2890 .id(egui::Id::unique("archive-password-input"))
2891 .char_limit(1024)
2892 .desired_width(232.0),
2893 );
2894 theme::focus(&edit);
2895 if new_challenge {
2896 edit.request_focus();
2897 }
2898 if theme::action(
2899 ui,
2900 if self.password_visible {
2901 "숨기기"
2902 } else {
2903 "보기"
2904 },
2905 false,
2906 true,
2907 )
2908 .clicked()
2909 {
2910 self.password_visible = !self.password_visible;
2911 }
2912 });
2913 if encrypt {
2914 ui.horizontal(|ui| {
2915 ui.label("암호 확인");
2916 let edit = ui.add(
2917 egui::TextEdit::singleline(&mut self.password_confirm)
2918 .password(!self.password_visible)
2919 .id(egui::Id::unique("archive-password-confirm"))
2920 .char_limit(1024)
2921 .desired_width(232.0),
2922 );
2923 theme::focus(&edit);
2924 });
2925 if self.password != self.password_confirm {
2926 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2927 }
2928 } else if attempt > 1 {
2929 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
2930 }
2931 if self.password.len() > 1024 {
2932 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2933 }
2934 let valid = !self.password.is_empty()
2935 && self.password.len() <= 1024
2936 && (!encrypt || self.password == self.password_confirm);
2937 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
2938 cancel = actions.0;
2939 submit = actions.1 || (valid && password_enter);
2940 });
2941 if modal.should_close() || cancel {
2942 self.clear_password();
2943 self.model.cancel();
2944 } else if submit {
2945 let password = std::mem::take(&mut self.password);
2946 self.clear_password();
2947 self.model.password(password);
2948 }
2949 }
2950
2951 fn close_dialog(&mut self, ctx: &egui::Context) {
2952 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
2953 if matches!(
2954 self.model.close,
2955 Close::Open | Close::Allowed | Close::Review
2956 ) {
2957 return;
2958 }
2959 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
2960 ui.set_width(420.0);
2961 match self.model.close {
2962 Close::Confirm => {
2963 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
2964 let busy = self.model.busy();
2965 let (heading, text, keep, close) = if busy {
2966 (
2967 "작업 중 닫기",
2968 "작업을 취소하고 닫을까요?",
2969 "계속 작업",
2970 "취소하고 닫기",
2971 )
2972 } else {
2973 (
2974 "닫기",
2975 "작업이 끝났습니다. 창을 닫을까요?",
2976 "열어 두기",
2977 "닫기",
2978 )
2979 };
2980 ui.heading(heading);
2981 ui.label(text);
2982 ui.horizontal(|ui| {
2983 if theme::action(ui, keep, false, true).clicked() {
2984 self.model.keep_open();
2985 }
2986 if theme::action(ui, close, true, true).clicked() {
2987 self.clear_password();
2988 self.model.confirm_close();
2989 }
2990 });
2991 }
2992 Close::Waiting => {
2993 ui.heading("종료 확인 중");
2994 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
2995 if theme::action(ui, "닫기 취소", false, true).clicked() {
2996 self.model.keep_open();
2997 }
2998 }
2999 _ => {}
3000 }
3001 });
3002 }
3003}
3004
3005impl eframe::App for ArchiveApp {
3006 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
3007 self.show(root);
3008 }
3009
3010 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
3011 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
3012 if std::mem::take(&mut self.release_after_move) {
3013 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
3014 raw_input.events.insert(
3015 0,
3016 egui::Event::PointerButton {
3017 pos,
3018 button: egui::PointerButton::Primary,
3019 pressed: false,
3020 modifiers: ctx.input(|i| i.modifiers),
3021 },
3022 );
3023 }
3024 }
3025}
3026impl Drop for ArchiveApp {
3027 fn drop(&mut self) {
3028 self.clear_password();
3029 }
3030}