team-ljyzipelo

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