team-ljyzipelo

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