team-ljyzipelo

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