team-ljyzipelo

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