team-ljyzipelo

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