team-ljyzipelo

공개
2,652줄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 파일을 열 수 있습니다",
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 warnings = if listing {
1807 Vec::new()
1808 } else {
1809 present::publication_warnings(
1810 t.as_ref(),
1811 self.model.confirmed,
1812 resolved_targets.as_ref(),
1813 &self.directories,
1814 &self.model.outputs,
1815 )
1816 };
1817 let success = self.model.confirmed
1818 && self.model.error.is_none()
1819 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
1820 && warnings.is_empty();
1821 let durability_warning = t
1822 .as_ref()
1823 .filter(|_| self.model.confirmed && !listing)
1824 .and_then(|t| present::durability_warning(t.durability));
1825 let durability_in_details = success
1826 && t.as_ref()
1827 .is_some_and(|t| t.durability == Durability::Unconfirmed);
1828 let cancelled =
1829 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
1830 let title = if success {
1831 if creating {
1832 "ZIP 파일을 만들었습니다"
1833 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
1834 "모든 파일을 건너뛰었습니다"
1835 } else {
1836 "압축을 풀었습니다"
1837 }
1838 } else if cancelled {
1839 "작업을 취소했습니다"
1840 } else if listing {
1841 "압축파일을 열지 못했습니다"
1842 } else if creating {
1843 "ZIP 파일을 만들지 못했습니다"
1844 } else {
1845 "압축을 풀지 못했습니다"
1846 };
1847 let fill = if success {
1848 theme::SUCCESS_BG
1849 } else if cancelled {
1850 theme::STRIPE
1851 } else {
1852 theme::ERROR_BG
1853 };
1854 let mut choose = false;
1855 let mut retry = false;
1856 let mut reopen = false;
1857 let mut folder = false;
1858 theme::panel(fill).show(ui, |ui| {
1859 ui.horizontal(|ui| {
1860 theme::icon(
1861 ui,
1862 if success {
1863 Icon::Success
1864 } else if cancelled {
1865 Icon::Warning
1866 } else {
1867 Icon::Error
1868 },
1869 24.0,
1870 );
1871 ui.strong(title);
1872 });
1873 let max_height = WORK_RESULT_MAX_HEIGHT;
1874 egui::ScrollArea::vertical()
1875 .id_salt("result-message")
1876 .max_height(max_height)
1877 .show(ui, |ui| {
1878 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
1879 let path = match self.last_request.as_ref() {
1880 Some(Start::CreateZip { output_file, .. }) => {
1881 output_file.display().to_string()
1882 }
1883 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
1884 };
1885 theme::bounded_text(ui, &path, ui.available_width());
1886 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
1887 ui.label(if creating && code == ErrorCode::SourceChanged {
1888 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요".to_owned()
1889 } else {
1890 present::operation_text(present::error_text(code), creating)
1891 });
1892 } else if let Some(error) = &self.model.error {
1893 ui.label(present::operation_text(
1894 present::client_error_text(error),
1895 creating,
1896 ));
1897 }
1898 if skipped > 0 {
1899 ui.label(format!("건너뛴 파일 {skipped}개"));
1900 }
1901 for resolution in self
1902 .model
1903 .resolutions
1904 .iter()
1905 .filter(|r| r.choice == ConflictChoice::Rename)
1906 {
1907 theme::bounded_text(
1908 ui,
1909 &format!("이름 바꿔 저장: {}", resolution.relative_name),
1910 ui.available_width(),
1911 );
1912 }
1913 for warning in warnings
1914 .iter()
1915 .copied()
1916 .chain(durability_warning.filter(|_| !durability_in_details))
1917 {
1918 ui.horizontal_wrapped(|ui| {
1919 theme::icon(ui, Icon::Warning, 20.0);
1920 ui.colored_label(
1921 theme::WARNING,
1922 present::operation_text(warning, creating),
1923 );
1924 });
1925 }
1926 if !success
1927 && !listing
1928 && present::definitely_unsaved(
1929 t.as_ref(),
1930 self.model.confirmed,
1931 &self.model.outputs,
1932 )
1933 {
1934 ui.label(if creating {
1935 "ZIP 파일을 만들지 않았습니다"
1936 } else {
1937 "아무 파일도 풀지 않았습니다"
1938 });
1939 }
1940 if self.details {
1941 theme::panel(theme::STRIPE).show(ui, |ui| {
1942 if durability_in_details {
1943 if let Some(warning) = durability_warning {
1944 ui.label(present::operation_text(warning, creating));
1945 }
1946 }
1947 if let Some(t) = &t {
1948 for line in terminal_lines(t) {
1949 ui.label(line);
1950 }
1951 }
1952 if let Some(error) = &self.model.error {
1953 ui.label(error);
1954 }
1955 for (name, state) in &self.model.outputs {
1956 theme::bounded_text(
1957 ui,
1958 &format!("{name}: {}", disposition_label(*state)),
1959 ui.available_width(),
1960 );
1961 }
1962 });
1963 }
1964 });
1965 let conflict = t
1966 .as_ref()
1967 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
1968 && !creating;
1969 let uncertain = warnings.contains(&present::UNCERTAIN);
1970 if conflict && uncertain {
1971 let response = ui.checkbox(
1972 &mut self.checked_destination,
1973 "기존 풀 위치 폴더를 확인했습니다",
1974 );
1975 theme::pointer(&response);
1976 theme::focus(&response);
1977 }
1978 ui.horizontal(|ui| {
1979 if theme::action(
1980 ui,
1981 if self.details {
1982 "자세히 닫기"
1983 } else {
1984 "자세히 보기"
1985 },
1986 false,
1987 true,
1988 )
1989 .clicked()
1990 {
1991 self.details = !self.details;
1992 }
1993 let action = if success {
1994 Some(("폴더 열기", true))
1995 } else if conflict {
1996 Some((
1997 if self
1998 .model
1999 .list_id
2000 .as_ref()
2001 .is_some_and(|id| id.format == Format::Gzip)
2002 {
2003 "다른 이름으로 저장"
2004 } else {
2005 "다른 폴더에 풀기"
2006 },
2007 !uncertain || self.checked_destination,
2008 ))
2009 } else if t
2010 .as_ref()
2011 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
2012 {
2013 Some((
2014 if creating {
2015 "다시 만들기"
2016 } else {
2017 "압축파일 다시 열기"
2018 },
2019 true,
2020 ))
2021 } else if !cancelled && (!uncertain || listing) {
2022 Some(("다시 시도", true))
2023 } else {
2024 None
2025 };
2026 let (confirm, primary) = theme::action_pair(ui, "확인", action);
2027 if confirm {
2028 self.dismissed = true;
2029 self.ui_error = None;
2030 self.model.input_error = None;
2031 }
2032 if primary {
2033 match action.map(|(label, _)| label) {
2034 Some("폴더 열기") => folder = true,
2035 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
2036 choose = true
2037 }
2038 Some("압축파일 다시 열기") => reopen = true,
2039 Some("다시 시도" | "다시 만들기") => retry = true,
2040 _ => {}
2041 }
2042 }
2043 });
2044 });
2045 if choose {
2046 self.open_picker(Purpose::Retry);
2047 }
2048 if retry {
2049 self.retry();
2050 }
2051 if reopen {
2052 if let Some(path) = self.model.archive.clone() {
2053 self.open_path(path);
2054 }
2055 }
2056 if folder {
2057 let path = match self.last_request.as_ref() {
2058 Some(Start::CreateZip { output_file, .. }) => {
2059 output_file.parent().unwrap_or(Path::new("/"))
2060 }
2061 _ => self.destination.as_path(),
2062 };
2063 match present::folder_command(path).spawn() {
2064 Ok(mut child) => {
2065 std::thread::spawn(move || {
2066 let _ = child.wait();
2067 });
2068 }
2069 Err(_) => {
2070 self.ui_error = Some(
2071 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
2072 )
2073 }
2074 }
2075 }
2076 }
2077
2078 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
2079 fn entry_cells(
2080 ui: &mut egui::Ui,
2081 rect: egui::Rect,
2082 directory: bool,
2083 name: &str,
2084 hover: &str,
2085 size: String,
2086 name_width: f32,
2087 ) {
2088 ui.scope_builder(
2089 egui::UiBuilder::new()
2090 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
2091 .layout(Layout::left_to_right(Align::Center)),
2092 |ui| {
2093 ui.style_mut().interaction.selectable_labels = false;
2094 ui.add_space(16.0);
2095 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
2096 theme::bounded_text_hover(ui, name, hover, name_width);
2097 theme::column_label(ui, size, 96.0, Align::Max);
2098 },
2099 );
2100 }
2101
2102 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
2103 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
2104 fn create_window(&mut self, ctx: &egui::Context) {
2105 if !self.create || self.model.busy() {
2106 self.create_win = WorkWindow::default();
2107 return;
2108 }
2109 if ctx.embed_viewports() {
2110 let mut close = false;
2111 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
2112 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
2113 ui.horizontal(|ui| {
2114 ui.heading("ZIP 만들기");
2115 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2116 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
2117 close = button.clicked();
2118 });
2119 });
2120 close |= self.create_area(ui);
2121 ui.add_space(theme::SPACE);
2122 close |= self.create_actions(ui);
2123 });
2124 if close || modal.should_close() {
2125 self.close_create();
2126 }
2127 return;
2128 }
2129 let id = egui::ViewportId::from_hash_of("archive-create");
2130 let title = "ZIP 만들기 — Zipelo";
2131 let custom_frame = self.custom_frame;
2132 if !self.create_win.open {
2133 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
2134 }
2135 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
2136 let builder =
2137 self.create_win
2138 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
2139 let mut close = false;
2140 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
2141 if ui.ctx().input(|i| i.viewport().close_requested()) {
2142 close = true;
2143 }
2144 if class == egui::ViewportClass::EmbeddedWindow {
2145 ui.set_width(CREATE_WIDTH);
2146 close |= self.create_area(ui);
2147 close |= self.create_actions(ui);
2148 return None;
2149 }
2150 let mut chrome = 0.0;
2151 if custom_frame {
2152 window_frame::title_bar(
2153 ui,
2154 "create",
2155 title,
2156 window_frame::Buttons {
2157 minimize: false,
2158 maximize: false,
2159 },
2160 );
2161 window_frame::edges(ui.ctx(), false);
2162 chrome = window_frame::TITLE_HEIGHT;
2163 }
2164 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
2165 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
2166 .resizable(false)
2167 .show_separator_line(false)
2168 .frame(
2169 egui::Frame::new()
2170 .fill(theme::PANEL)
2171 .inner_margin(egui::Margin {
2172 left: theme::PAD,
2173 right: theme::PAD,
2174 top: 0,
2175 bottom: theme::PAD,
2176 }),
2177 )
2178 .show(ui, |ui| close |= self.create_actions(ui))
2179 .response
2180 .rect
2181 .height();
2182 let margin = theme::PAD as f32;
2183 egui::CentralPanel::default()
2184 .frame(theme::panel(theme::PANEL).corner_radius(0))
2185 .show(ui, |ui| {
2186 let content = ui
2187 .vertical(|ui| close |= self.create_area(ui))
2188 .response
2189 .rect;
2190 Some(content.height() + 2.0 * margin + chrome + actions)
2191 })
2192 .inner
2193 });
2194 if let Some(height) = height {
2195 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
2196 if (height - self.create_win.height).abs() > 1.0 {
2197 self.create_win.height = height;
2198 }
2199 }
2200 if close {
2201 self.close_create();
2202 }
2203 }
2204
2205 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
2206 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
2207 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
2208 let enabled = self.picker.is_none();
2209 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
2210 .inner
2211 }
2212
2213 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
2214 let rows = self.create_rows();
2215 let root = self.create_root();
2216
2217 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
2218 ui.horizontal(|ui| {
2219 ui.set_height(theme::FIELD);
2220 ui.spacing_mut().item_spacing.x = 0.0;
2221 let up = theme::flat_icon_button(
2222 ui,
2223 "위로",
2224 theme::UP,
2225 !self.create_folder.is_empty(),
2226 egui::vec2(theme::FIELD, theme::FIELD),
2227 );
2228 if up.clicked() {
2229 self.create_folder = self
2230 .create_folder
2231 .rsplit_once('/')
2232 .map_or("", |(parent, _)| parent)
2233 .to_owned();
2234 self.create_selected = None;
2235 }
2236 ui.add_space(6.0);
2237 let path = match &root {
2238 Some(root) => {
2239 let name = root.file_name().unwrap_or_default().to_string_lossy();
2240 if self.create_folder.is_empty() {
2241 format!("/{name}")
2242 } else {
2243 format!("/{name}/{}", self.create_folder)
2244 }
2245 }
2246 None => "/".to_owned(),
2247 };
2248 let (rect, _) = ui.allocate_exact_size(
2249 egui::vec2(ui.available_width(), theme::FIELD),
2250 egui::Sense::hover(),
2251 );
2252 theme::boxed_field(ui, rect);
2253 theme::field_text(ui, rect, &path);
2254 });
2255 ui.add_space(theme::SPACE);
2256
2257 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
2258 let mut enter = None;
2259 egui::Frame::new()
2260 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2261 .show(ui, |ui| {
2262 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
2263 ui.set_max_height(CREATE_LIST_HEIGHT);
2264 let message = match &rows {
2265 None => Some("폴더를 읽지 못했습니다"),
2266 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
2267 Some(_) => None,
2268 };
2269 if let Some(message) = message {
2270 ui.centered_and_justified(|ui| ui.label(message));
2271 return;
2272 }
2273 let rows = rows.unwrap();
2274 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
2275 egui::ScrollArea::vertical()
2276 .id_salt("create-rows")
2277 .auto_shrink([false, false])
2278 .max_height(CREATE_LIST_HEIGHT)
2279 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
2280 for row in &rows[range] {
2281 let (rect, response) = ui.allocate_exact_size(
2282 egui::vec2(ui.available_width(), LIST_ROW),
2283 egui::Sense::click(),
2284 );
2285 let response = response.on_hover_text(&row.name);
2286 theme::pointer(&response);
2287 response.widget_info(|| {
2288 egui::WidgetInfo::labeled(
2289 egui::Role::ListBoxOption,
2290 true,
2291 &row.name,
2292 )
2293 });
2294 if response.clicked() {
2295 self.create_selected = Some(row.name.clone());
2296 }
2297 theme::row_background(
2298 ui,
2299 rect,
2300 self.create_selected.as_deref() == Some(row.name.as_str()),
2301 response.hovered(),
2302 );
2303 if row.directory && root.is_some() && response.clicked() {
2304 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
2305 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
2306 let frame = ui.ctx().cumulative_frame_nr();
2307 let time = ui.input(|i| i.time);
2308 match &self.create_last_click {
2309 Some((name, last_frame, last_time))
2310 if name == &row.name
2311 && *last_frame != frame
2312 && time - last_time < 0.4 =>
2313 {
2314 enter = Some(row.name.clone());
2315 self.create_last_click = None;
2316 }
2317 Some((name, last_frame, _))
2318 if name == &row.name && *last_frame == frame => {}
2319 _ => {
2320 self.create_last_click =
2321 Some((row.name.clone(), frame, time));
2322 }
2323 }
2324 }
2325 Self::entry_cells(
2326 ui,
2327 rect,
2328 row.directory,
2329 &row.name,
2330 &row.name,
2331 row.bytes.map(present::bytes_text).unwrap_or_default(),
2332 name_width,
2333 );
2334 }
2335 });
2336 });
2337 if let Some(name) = enter {
2338 self.create_folder = if self.create_folder.is_empty() {
2339 name
2340 } else {
2341 format!("{}/{name}", self.create_folder)
2342 };
2343 self.create_selected = None;
2344 }
2345 ui.add_space(theme::SPACE);
2346
2347 if let Some(error) = &self.ui_error {
2348 Self::error_notice(ui, error);
2349 }
2350
2351 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
2352 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
2353 theme::pointer(&check);
2354 theme::focus(&check);
2355 if self.aes256 {
2356 let label_width = 72.0;
2357 ui.horizontal(|ui| {
2358 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
2359 let toggle = if self.zip_password_visible {
2360 "숨기기"
2361 } else {
2362 "보기"
2363 };
2364 let toggle_width = 72.0;
2365 let edit = ui.add_sized(
2366 [
2367 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
2368 theme::FIELD,
2369 ],
2370 egui::TextEdit::singleline(&mut self.zip_password)
2371 .password(!self.zip_password_visible)
2372 .id(egui::Id::unique("zip-password-input"))
2373 .char_limit(1024)
2374 .align(egui::Align2::LEFT_CENTER),
2375 );
2376 theme::focus(&edit);
2377 if theme::action(ui, toggle, false, true).clicked() {
2378 self.zip_password_visible = !self.zip_password_visible;
2379 }
2380 });
2381 ui.horizontal(|ui| {
2382 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
2383 let edit = ui.add_sized(
2384 [
2385 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
2386 theme::FIELD,
2387 ],
2388 egui::TextEdit::singleline(&mut self.zip_password_confirm)
2389 .password(!self.zip_password_visible)
2390 .id(egui::Id::unique("zip-password-confirm"))
2391 .char_limit(1024)
2392 .align(egui::Align2::LEFT_CENTER),
2393 );
2394 theme::focus(&edit);
2395 });
2396 if self.zip_password.len() > 1024 {
2397 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2398 } else if !self.zip_password_confirm.is_empty()
2399 && self.zip_password != self.zip_password_confirm
2400 {
2401 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2402 }
2403 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
2404 } else if check.changed()
2405 || !self.zip_password.is_empty()
2406 || !self.zip_password_confirm.is_empty()
2407 {
2408 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
2409 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
2410 self.clear_zip_password();
2411 }
2412 false
2413 }
2414
2415 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
2416 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
2417 let ready = !self.sources.is_empty() && self.zip_password_ready();
2418 let enabled = self.picker.is_none();
2419 let (cancel, compress) = ui
2420 .add_enabled_ui(enabled, |ui| {
2421 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
2422 })
2423 .inner;
2424 if compress {
2425 self.open_picker(Purpose::SaveZip);
2426 }
2427 cancel
2428 }
2429
2430 fn conflict_dialog(&mut self, ctx: &egui::Context) {
2431 let conflict = self.model.conflict.clone().unwrap();
2432 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
2433 if self.conflict_challenge != Some(question) {
2434 self.conflict_challenge = Some(question);
2435 self.conflict_apply = false;
2436 }
2437 let mut choice = None;
2438 let mut cancel = false;
2439 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
2440 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
2441 ui.heading("같은 이름의 파일이 있습니다");
2442 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
2443 ui.add_space(theme::SPACE);
2444 egui::Grid::new("conflict-sizes")
2445 .spacing([24.0, 8.0])
2446 .show(ui, |ui| {
2447 ui.label("기존 파일");
2448 ui.label(present::bytes_text(conflict.existing_size));
2449 ui.end_row();
2450 ui.label("압축파일 안의 파일");
2451 ui.label(present::bytes_text(conflict.incoming_size));
2452 ui.end_row();
2453 });
2454 ui.add_space(theme::SPACE);
2455 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
2456 ui.add_space(theme::SPACE);
2457 ui.horizontal_wrapped(|ui| {
2458 for (label, value) in [
2459 ("덮어쓰기", ConflictChoice::Overwrite),
2460 ("건너뛰기", ConflictChoice::Skip),
2461 ("이름 바꿔 저장", ConflictChoice::Rename),
2462 ] {
2463 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
2464 choice = Some(value);
2465 }
2466 }
2467 });
2468 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
2469 if let Some(error) = &self.model.error {
2470 Self::error_notice(ui, present::client_error_text(error));
2471 }
2472 cancel = theme::action(ui, "작업 취소", false, true).clicked();
2473 });
2474 if modal.should_close() || cancel {
2475 self.model.cancel();
2476 } else if let Some(choice) = choice {
2477 self.model.resolve_conflict(choice, self.conflict_apply);
2478 }
2479 }
2480
2481 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
2482 let (_, attempt, encrypt) = self.model.challenge.unwrap();
2483 let mut submit = false;
2484 let mut cancel = false;
2485 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
2486 id == egui::Id::unique("archive-password-input")
2487 || id == egui::Id::unique("archive-password-confirm")
2488 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
2489 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
2490 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
2491 ui.heading(if encrypt {
2492 "ZIP 암호 설정"
2493 } else {
2494 "암호가 필요합니다"
2495 });
2496 if encrypt {
2497 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
2498 } else if let Some(path) = &self.model.archive {
2499 ui.label(format!(
2500 "{}은 암호로 보호되어 있습니다.",
2501 present::middle_text(
2502 &path.file_name().unwrap_or_default().to_string_lossy(),
2503 24
2504 )
2505 ));
2506 }
2507 ui.horizontal(|ui| {
2508 ui.label("암호");
2509 let edit = ui.add(
2510 egui::TextEdit::singleline(&mut self.password)
2511 .password(!self.password_visible)
2512 .id(egui::Id::unique("archive-password-input"))
2513 .char_limit(1024)
2514 .desired_width(232.0),
2515 );
2516 theme::focus(&edit);
2517 if new_challenge {
2518 edit.request_focus();
2519 }
2520 if theme::action(
2521 ui,
2522 if self.password_visible {
2523 "숨기기"
2524 } else {
2525 "보기"
2526 },
2527 false,
2528 true,
2529 )
2530 .clicked()
2531 {
2532 self.password_visible = !self.password_visible;
2533 }
2534 });
2535 if encrypt {
2536 ui.horizontal(|ui| {
2537 ui.label("암호 확인");
2538 let edit = ui.add(
2539 egui::TextEdit::singleline(&mut self.password_confirm)
2540 .password(!self.password_visible)
2541 .id(egui::Id::unique("archive-password-confirm"))
2542 .char_limit(1024)
2543 .desired_width(232.0),
2544 );
2545 theme::focus(&edit);
2546 });
2547 if self.password != self.password_confirm {
2548 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2549 }
2550 } else if attempt > 1 {
2551 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
2552 }
2553 if self.password.len() > 1024 {
2554 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2555 }
2556 let valid = !self.password.is_empty()
2557 && self.password.len() <= 1024
2558 && (!encrypt || self.password == self.password_confirm);
2559 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
2560 cancel = actions.0;
2561 submit = actions.1 || (valid && password_enter);
2562 });
2563 if modal.should_close() || cancel {
2564 self.clear_password();
2565 self.model.cancel();
2566 } else if submit {
2567 let password = std::mem::take(&mut self.password);
2568 self.clear_password();
2569 self.model.password(password);
2570 }
2571 }
2572
2573 fn close_dialog(&mut self, ctx: &egui::Context) {
2574 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
2575 if matches!(
2576 self.model.close,
2577 Close::Open | Close::Allowed | Close::Review
2578 ) {
2579 return;
2580 }
2581 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
2582 ui.set_width(420.0);
2583 match self.model.close {
2584 Close::Confirm => {
2585 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
2586 let busy = self.model.busy();
2587 let (heading, text, keep, close) = if busy {
2588 (
2589 "작업 중 닫기",
2590 "작업을 취소하고 닫을까요?",
2591 "계속 작업",
2592 "취소하고 닫기",
2593 )
2594 } else {
2595 (
2596 "닫기",
2597 "작업이 끝났습니다. 창을 닫을까요?",
2598 "열어 두기",
2599 "닫기",
2600 )
2601 };
2602 ui.heading(heading);
2603 ui.label(text);
2604 ui.horizontal(|ui| {
2605 if theme::action(ui, keep, false, true).clicked() {
2606 self.model.keep_open();
2607 }
2608 if theme::action(ui, close, true, true).clicked() {
2609 self.clear_password();
2610 self.model.confirm_close();
2611 }
2612 });
2613 }
2614 Close::Waiting => {
2615 ui.heading("종료 확인 중");
2616 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
2617 if theme::action(ui, "닫기 취소", false, true).clicked() {
2618 self.model.keep_open();
2619 }
2620 }
2621 _ => {}
2622 }
2623 });
2624 }
2625}
2626
2627impl eframe::App for ArchiveApp {
2628 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
2629 self.show(root);
2630 }
2631
2632 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
2633 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
2634 if std::mem::take(&mut self.release_after_move) {
2635 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
2636 raw_input.events.insert(
2637 0,
2638 egui::Event::PointerButton {
2639 pos,
2640 button: egui::PointerButton::Primary,
2641 pressed: false,
2642 modifiers: ctx.input(|i| i.modifiers),
2643 },
2644 );
2645 }
2646 }
2647}
2648impl Drop for ArchiveApp {
2649 fn drop(&mut self) {
2650 self.clear_password();
2651 }
2652}