team-ljyzipelo

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