team-ljyzipelo

공개
2,475줄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 theme::pointer(&response);
1256 response.widget_info(|| {
1257 egui::WidgetInfo::selected(
1258 egui::Role::ListBoxOption,
1259 active,
1260 selected,
1261 &row.name,
1262 )
1263 });
1264 if response.has_focus() {
1265 focused = Some(index);
1266 ui.ctx().memory_mut(|memory| {
1267 memory.set_focus_lock_filter(
1268 response.id,
1269 egui::EventFilter {
1270 vertical_arrows: true,
1271 escape: true,
1272 ..Default::default()
1273 },
1274 )
1275 });
1276 }
1277 theme::row_background(ui, rect, selected, response.hovered());
1278 if response.clicked() {
1279 background.request_focus();
1280 let modifiers = ui.input(|i| i.modifiers);
1281 self.select_row(
1282 &rows,
1283 index,
1284 modifiers.ctrl || modifiers.command,
1285 modifiers.shift,
1286 );
1287 }
1288 if row.directory && response.double_clicked() {
1289 open = Some(row.path.clone());
1290 }
1291 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
1292 let name = if row.encrypted {
1293 format!("*{}", row.name)
1294 } else {
1295 row.name.clone()
1296 };
1297 Self::entry_cells(
1298 ui,
1299 rect,
1300 row.directory,
1301 &name,
1302 &row.name,
1303 if row.directory {
1304 "0 B".into()
1305 } else {
1306 row.bytes
1307 .map(present::bytes_text)
1308 .unwrap_or_else(|| "—".into())
1309 },
1310 name_width,
1311 );
1312 if active
1313 && self.list_cursor == Some(index)
1314 && (response.has_focus() || background.has_focus())
1315 {
1316 ui.painter().rect_stroke(
1317 rect.shrink(1.0),
1318 0,
1319 egui::Stroke::new(1.0, theme::BLUE),
1320 egui::StrokeKind::Inside,
1321 );
1322 }
1323 }
1324 if rows.is_empty() {
1325 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
1326 ui.centered_and_justified(|ui| {
1327 ui.label(if self.search.is_empty() {
1328 "이 폴더는 비어 있습니다"
1329 } else {
1330 "일치하는 항목이 없습니다"
1331 })
1332 });
1333 });
1334 }
1335 if let Some(drag) = &self.marquee
1336 && drag.moved
1337 && let Some(point) = point
1338 {
1339 let rect = egui::Rect::from_two_pos(
1340 origin + drag.origin.to_vec2(),
1341 point.clamp(clip.min, clip.max),
1342 );
1343 ui.painter().with_clip_rect(clip).rect(
1344 rect,
1345 0,
1346 theme::BLUE.gamma_multiply(0.16),
1347 egui::Stroke::new(1.0, theme::BLUE),
1348 egui::StrokeKind::Inside,
1349 );
1350 }
1351 });
1352 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
1353 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
1354 self.marquee = None;
1355 }
1356 let escape_from_list = self.list_focused
1357 && ui.ctx().memory(|memory| memory.focused()).is_none()
1358 && ui.input(|i| i.key_pressed(egui::Key::Escape));
1359 self.list_focused =
1360 active && (background.has_focus() || focused.is_some() || escape_from_list);
1361 if self.list_focused {
1362 if let Some(index) = focused {
1363 self.list_cursor = Some(index);
1364 }
1365 let modifiers = ui.input(|i| i.modifiers);
1366 let ctrl = modifiers.ctrl || modifiers.command;
1367 if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
1368 self.model.selected.clear();
1369 self.marquee = None;
1370 background.request_focus();
1371 }
1372 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
1373 self.model.selected = rows
1374 .iter()
1375 .flat_map(|row| row.ids.iter().copied())
1376 .collect();
1377 self.list_cursor = (!rows.is_empty()).then_some(0);
1378 self.list_anchor = self.list_cursor;
1379 }
1380 if !rows.is_empty() {
1381 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
1382 Some(1isize)
1383 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
1384 Some(-1)
1385 } else {
1386 None
1387 };
1388 if let Some(direction) = direction {
1389 let index = self.list_cursor.map_or(0, |index| {
1390 index.saturating_add_signed(direction).min(rows.len() - 1)
1391 });
1392 if ctrl && !modifiers.shift {
1393 self.list_cursor = Some(index);
1394 } else {
1395 self.select_row(&rows, index, ctrl, modifiers.shift);
1396 }
1397 background.request_focus();
1398 let top = index as f32 * LIST_ROW;
1399 if top < self.list_offset {
1400 self.list_offset = top;
1401 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
1402 self.list_offset = top + LIST_ROW - output.inner_rect.height();
1403 }
1404 ui.ctx().request_repaint();
1405 }
1406 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1407 let index = self
1408 .list_cursor
1409 .or(focused)
1410 .unwrap_or(0)
1411 .min(rows.len() - 1);
1412 if rows[index].directory {
1413 open = Some(rows[index].path.clone());
1414 }
1415 }
1416 }
1417 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
1418 open = Some(
1419 self.folder
1420 .rsplit_once('/')
1421 .map_or("", |(parent, _)| parent)
1422 .to_owned(),
1423 );
1424 }
1425 }
1426 if let Some(folder) = open {
1427 self.browse_folder(&folder);
1428 background.request_focus();
1429 }
1430 }
1431
1432 fn clear_list_selection(&mut self) {
1433 self.model.selected.clear();
1434 self.list_anchor = None;
1435 self.list_cursor = None;
1436 self.list_offset = 0.0;
1437 self.marquee = None;
1438 }
1439
1440 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
1441 if shift {
1442 let anchor = self
1443 .list_anchor
1444 .unwrap_or(self.list_cursor.unwrap_or(index))
1445 .min(rows.len() - 1);
1446 if !ctrl {
1447 self.model.selected.clear();
1448 }
1449 for row in &rows[anchor.min(index)..=anchor.max(index)] {
1450 self.model.selected.extend(&row.ids);
1451 }
1452 self.list_anchor = Some(anchor);
1453 } else {
1454 if !ctrl {
1455 self.model.selected.clear();
1456 }
1457 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
1458 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
1459 self.model
1460 .selected
1461 .retain(|id| !rows[index].ids.contains(id));
1462 } else {
1463 self.model.selected.extend(&rows[index].ids);
1464 }
1465 self.list_anchor = Some(index);
1466 }
1467 self.list_cursor = Some(index);
1468 }
1469
1470 fn result_visible(&self) -> bool {
1471 !self.dismissed
1472 && !self.model.busy()
1473 && self.last_request.as_ref().is_some_and(|request| {
1474 !matches!(request, Start::List { .. })
1475 || self.model.error.is_some()
1476 || self
1477 .model
1478 .terminal
1479 .as_ref()
1480 .is_some_and(|t| t.outcome != Outcome::Completed)
1481 })
1482 }
1483
1484 fn error_notice(ui: &mut egui::Ui, error: &str) {
1485 let response = theme::panel(theme::ERROR_BG)
1486 .show(ui, |ui| {
1487 ui.horizontal_wrapped(|ui| {
1488 theme::icon(ui, Icon::Error, 24.0);
1489 ui.colored_label(theme::ERROR, error);
1490 });
1491 })
1492 .response;
1493 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
1494 }
1495
1496 fn work_visible(&self) -> bool {
1497 self.model.busy() || self.result_visible() || (self.ui_error.is_some() && !self.create)
1498 }
1499
1500 fn work_window(&mut self, ctx: &egui::Context) {
1501 if !self.work_visible() {
1502 self.work = WorkWindow::default();
1503 return;
1504 }
1505 if ctx.embed_viewports() {
1506 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1507 return;
1508 }
1509 if self.model.challenge.is_some() {
1510 // 암호 입력 창은 메인 창 가운데에 뜨므로, 위에 떠 있는 진행 창이 입력란을
1511 // 가리지 않게 그동안 진행 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1512 self.work.open = false;
1513 return;
1514 }
1515 let id = egui::ViewportId::from_hash_of("archive-work");
1516 let title = if self.model.busy() {
1517 present::activity_text(
1518 &self.model,
1519 matches!(self.last_request, Some(Start::CreateZip { .. })),
1520 )
1521 .to_owned()
1522 } else {
1523 "작업 결과".to_owned()
1524 };
1525 let window_title = format!("{title} — Zipelo");
1526 let custom_frame = self.custom_frame;
1527 let size = egui::vec2(WORK_WIDTH, self.work.height);
1528 let builder = self
1529 .work
1530 .builder(ctx, id, size, &window_title, !custom_frame);
1531 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1532 if ui.ctx().input(|i| i.viewport().close_requested()) {
1533 if self.model.busy() {
1534 ui.ctx()
1535 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1536 } else {
1537 self.dismissed = true;
1538 self.ui_error = None;
1539 self.model.input_error = None;
1540 }
1541 }
1542 if class == egui::ViewportClass::EmbeddedWindow {
1543 ui.set_width(WORK_WIDTH);
1544 self.work_area(ui);
1545 return None;
1546 }
1547 let mut chrome = 0.0;
1548 if custom_frame {
1549 window_frame::title_bar(
1550 ui,
1551 "work",
1552 &window_title,
1553 window_frame::Buttons {
1554 minimize: false,
1555 maximize: false,
1556 },
1557 );
1558 window_frame::edges(ui.ctx(), false);
1559 chrome = window_frame::TITLE_HEIGHT;
1560 }
1561 let margin = theme::PAD as f32;
1562 egui::CentralPanel::default()
1563 .frame(theme::panel(theme::PANEL).corner_radius(0))
1564 .show(ui, |ui| {
1565 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1566 Some(content.height() + 2.0 * margin + chrome)
1567 })
1568 .inner
1569 });
1570 if let Some(height) = height {
1571 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1572 if (height - self.work.height).abs() > 1.0 {
1573 self.work.height = height;
1574 }
1575 }
1576 }
1577
1578 fn work_area(&mut self, ui: &mut egui::Ui) {
1579 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
1580 let enabled = self.picker.is_none();
1581 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
1582 }
1583
1584 fn work_contents(&mut self, ui: &mut egui::Ui) {
1585 if self.model.busy() {
1586 self.progress(ui);
1587 } else if self.result_visible() {
1588 self.result(ui);
1589 }
1590 if !self.create
1591 && let Some(error) = &self.ui_error
1592 {
1593 Self::error_notice(ui, error);
1594 if error == present::FOLDER_ERROR
1595 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
1596 {
1597 self.open_picker(Purpose::Destination);
1598 }
1599 }
1600 if let Some(error) = &self.model.input_error {
1601 ui.colored_label(
1602 theme::ERROR,
1603 if error.starts_with("암호는") {
1604 error.as_str()
1605 } else {
1606 if matches!(self.last_request, Some(Start::CreateZip { .. })) {
1607 "저장 위치와 추가한 항목을 확인하세요"
1608 } else {
1609 "풀 위치와 선택한 항목을 확인하세요"
1610 }
1611 },
1612 );
1613 }
1614 }
1615
1616 fn progress(&mut self, ui: &mut egui::Ui) {
1617 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1618 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
1619 let title = present::activity_text(&self.model, creating);
1620 ui.strong(title);
1621 if let Some((stage, done, total, count)) = self.model.progress {
1622 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
1623 let processed = if stage == Stage::Read {
1624 String::new()
1625 } else {
1626 format!("{count}개 처리함, ")
1627 };
1628 if let Some(total) = total.filter(|n| *n > 0) {
1629 ui.scope(|ui| {
1630 ui.visuals_mut().extreme_bg_color = theme::BORDER;
1631 ui.add(
1632 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
1633 .fill(theme::BLUE)
1634 .desired_height(theme::SPACE * 2.0),
1635 );
1636 });
1637 ui.horizontal(|ui| {
1638 ui.label(format!(
1639 "{:.0}% / {processed}{} / {}",
1640 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
1641 present::bytes_text(done),
1642 present::bytes_text(total)
1643 ));
1644 self.cancel_action(ui, cancelling);
1645 });
1646 } else {
1647 theme::indeterminate(ui);
1648 ui.horizontal(|ui| {
1649 ui.label(format!("{processed}{}", present::bytes_text(done)));
1650 self.cancel_action(ui, cancelling);
1651 });
1652 }
1653 } else {
1654 theme::indeterminate(ui);
1655 ui.horizontal(|ui| {
1656 ui.label("작업을 진행하고 있습니다");
1657 self.cancel_action(ui, cancelling);
1658 });
1659 }
1660 }
1661
1662 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
1663 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1664 if theme::action(ui, "취소", false, !cancelling).clicked() {
1665 self.clear_password();
1666 self.model.cancel();
1667 }
1668 });
1669 }
1670
1671 fn result(&mut self, ui: &mut egui::Ui) {
1672 let t = self.model.terminal.clone();
1673 let listing = matches!(self.last_request, Some(Start::List { .. }));
1674 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
1675 let warnings = if listing {
1676 Vec::new()
1677 } else {
1678 present::publication_warnings(
1679 t.as_ref(),
1680 self.model.confirmed,
1681 self.targets.as_ref(),
1682 &self.directories,
1683 &self.model.outputs,
1684 )
1685 };
1686 let success = self.model.confirmed
1687 && self.model.error.is_none()
1688 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
1689 && warnings.is_empty();
1690 let durability_warning = t
1691 .as_ref()
1692 .filter(|_| self.model.confirmed && !listing)
1693 .and_then(|t| present::durability_warning(t.durability));
1694 let durability_in_details = success
1695 && t.as_ref()
1696 .is_some_and(|t| t.durability == Durability::Unconfirmed);
1697 let cancelled =
1698 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
1699 let title = if success {
1700 if creating {
1701 "ZIP 파일을 만들었습니다"
1702 } else {
1703 "압축을 풀었습니다"
1704 }
1705 } else if cancelled {
1706 "작업을 취소했습니다"
1707 } else if listing {
1708 "압축파일을 열지 못했습니다"
1709 } else if creating {
1710 "ZIP 파일을 만들지 못했습니다"
1711 } else {
1712 "압축을 풀지 못했습니다"
1713 };
1714 let fill = if success {
1715 theme::SUCCESS_BG
1716 } else if cancelled {
1717 theme::STRIPE
1718 } else {
1719 theme::ERROR_BG
1720 };
1721 let mut choose = false;
1722 let mut retry = false;
1723 let mut reopen = false;
1724 let mut folder = false;
1725 theme::panel(fill).show(ui, |ui| {
1726 ui.horizontal(|ui| {
1727 theme::icon(
1728 ui,
1729 if success {
1730 Icon::Success
1731 } else if cancelled {
1732 Icon::Warning
1733 } else {
1734 Icon::Error
1735 },
1736 24.0,
1737 );
1738 ui.strong(title);
1739 });
1740 let max_height = WORK_RESULT_MAX_HEIGHT;
1741 egui::ScrollArea::vertical()
1742 .id_salt("result-message")
1743 .max_height(max_height)
1744 .show(ui, |ui| {
1745 if success {
1746 let path = match self.last_request.as_ref() {
1747 Some(Start::CreateZip { output_file, .. }) => {
1748 output_file.display().to_string()
1749 }
1750 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
1751 };
1752 theme::bounded_text(ui, &path, ui.available_width());
1753 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
1754 ui.label(if creating && code == ErrorCode::SourceChanged {
1755 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요".to_owned()
1756 } else {
1757 present::operation_text(present::error_text(code), creating)
1758 });
1759 } else if let Some(error) = &self.model.error {
1760 ui.label(present::operation_text(
1761 present::client_error_text(error),
1762 creating,
1763 ));
1764 }
1765 for warning in warnings
1766 .iter()
1767 .copied()
1768 .chain(durability_warning.filter(|_| !durability_in_details))
1769 {
1770 ui.horizontal_wrapped(|ui| {
1771 theme::icon(ui, Icon::Warning, 20.0);
1772 ui.colored_label(
1773 theme::WARNING,
1774 present::operation_text(warning, creating),
1775 );
1776 });
1777 }
1778 if !success
1779 && !listing
1780 && present::definitely_unsaved(
1781 t.as_ref(),
1782 self.model.confirmed,
1783 &self.model.outputs,
1784 )
1785 {
1786 ui.label(if creating {
1787 "ZIP 파일을 만들지 않았습니다"
1788 } else {
1789 "아무 파일도 풀지 않았습니다"
1790 });
1791 }
1792 if self.details {
1793 theme::panel(theme::STRIPE).show(ui, |ui| {
1794 if durability_in_details {
1795 if let Some(warning) = durability_warning {
1796 ui.label(present::operation_text(warning, creating));
1797 }
1798 }
1799 if let Some(t) = &t {
1800 for line in terminal_lines(t) {
1801 ui.label(line);
1802 }
1803 }
1804 if let Some(error) = &self.model.error {
1805 ui.label(error);
1806 }
1807 for (name, state) in &self.model.outputs {
1808 theme::bounded_text(
1809 ui,
1810 &format!("{name}: {}", disposition_label(*state)),
1811 ui.available_width(),
1812 );
1813 }
1814 });
1815 }
1816 });
1817 let conflict = t
1818 .as_ref()
1819 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
1820 && !creating;
1821 let uncertain = warnings.contains(&present::UNCERTAIN);
1822 if conflict && uncertain {
1823 let response = ui.checkbox(
1824 &mut self.checked_destination,
1825 "기존 풀 위치 폴더를 확인했습니다",
1826 );
1827 theme::pointer(&response);
1828 theme::focus(&response);
1829 }
1830 ui.horizontal(|ui| {
1831 if theme::action(
1832 ui,
1833 if self.details {
1834 "자세히 닫기"
1835 } else {
1836 "자세히 보기"
1837 },
1838 false,
1839 true,
1840 )
1841 .clicked()
1842 {
1843 self.details = !self.details;
1844 }
1845 let action = if success {
1846 Some(("폴더 열기", true))
1847 } else if conflict {
1848 Some((
1849 if self
1850 .model
1851 .list_id
1852 .as_ref()
1853 .is_some_and(|id| id.format == Format::Gzip)
1854 {
1855 "다른 이름으로 저장"
1856 } else {
1857 "다른 폴더에 풀기"
1858 },
1859 !uncertain || self.checked_destination,
1860 ))
1861 } else if t
1862 .as_ref()
1863 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
1864 {
1865 Some((
1866 if creating {
1867 "다시 만들기"
1868 } else {
1869 "압축파일 다시 열기"
1870 },
1871 true,
1872 ))
1873 } else if !cancelled && (!uncertain || listing) {
1874 Some(("다시 시도", true))
1875 } else {
1876 None
1877 };
1878 let (confirm, primary) = theme::action_pair(ui, "확인", action);
1879 if confirm {
1880 self.dismissed = true;
1881 self.ui_error = None;
1882 self.model.input_error = None;
1883 }
1884 if primary {
1885 match action.map(|(label, _)| label) {
1886 Some("폴더 열기") => folder = true,
1887 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
1888 choose = true
1889 }
1890 Some("압축파일 다시 열기") => reopen = true,
1891 Some("다시 시도" | "다시 만들기") => retry = true,
1892 _ => {}
1893 }
1894 }
1895 });
1896 });
1897 if choose {
1898 self.open_picker(Purpose::Retry);
1899 }
1900 if retry {
1901 self.retry();
1902 }
1903 if reopen {
1904 if let Some(path) = self.model.archive.clone() {
1905 self.open_path(path);
1906 }
1907 }
1908 if folder {
1909 let path = match self.last_request.as_ref() {
1910 Some(Start::CreateZip { output_file, .. }) => {
1911 output_file.parent().unwrap_or(Path::new("/"))
1912 }
1913 _ => self.destination.as_path(),
1914 };
1915 match present::folder_command(path).spawn() {
1916 Ok(mut child) => {
1917 std::thread::spawn(move || {
1918 let _ = child.wait();
1919 });
1920 }
1921 Err(_) => {
1922 self.ui_error = Some(
1923 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
1924 )
1925 }
1926 }
1927 }
1928 }
1929
1930 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
1931 fn entry_cells(
1932 ui: &mut egui::Ui,
1933 rect: egui::Rect,
1934 directory: bool,
1935 name: &str,
1936 hover: &str,
1937 size: String,
1938 name_width: f32,
1939 ) {
1940 ui.scope_builder(
1941 egui::UiBuilder::new()
1942 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
1943 .layout(Layout::left_to_right(Align::Center)),
1944 |ui| {
1945 ui.style_mut().interaction.selectable_labels = false;
1946 ui.add_space(16.0);
1947 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
1948 theme::bounded_text_hover(ui, name, hover, name_width);
1949 theme::column_label(ui, size, 96.0, Align::Max);
1950 },
1951 );
1952 }
1953
1954 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
1955 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
1956 fn create_window(&mut self, ctx: &egui::Context) {
1957 if !self.create || self.model.busy() {
1958 self.create_win = WorkWindow::default();
1959 return;
1960 }
1961 if ctx.embed_viewports() {
1962 let mut close = false;
1963 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
1964 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
1965 ui.horizontal(|ui| {
1966 ui.heading("ZIP 만들기");
1967 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1968 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
1969 close = button.clicked();
1970 });
1971 });
1972 close |= self.create_area(ui);
1973 ui.add_space(theme::SPACE);
1974 close |= self.create_actions(ui);
1975 });
1976 if close || modal.should_close() {
1977 self.close_create();
1978 }
1979 return;
1980 }
1981 let id = egui::ViewportId::from_hash_of("archive-create");
1982 let title = "ZIP 만들기 — Zipelo";
1983 let custom_frame = self.custom_frame;
1984 if !self.create_win.open {
1985 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
1986 }
1987 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
1988 let builder = self.create_win.builder(ctx, id, size, title, !custom_frame);
1989 let mut close = false;
1990 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1991 if ui.ctx().input(|i| i.viewport().close_requested()) {
1992 close = true;
1993 }
1994 if class == egui::ViewportClass::EmbeddedWindow {
1995 ui.set_width(CREATE_WIDTH);
1996 close |= self.create_area(ui);
1997 close |= self.create_actions(ui);
1998 return None;
1999 }
2000 let mut chrome = 0.0;
2001 if custom_frame {
2002 window_frame::title_bar(
2003 ui,
2004 "create",
2005 title,
2006 window_frame::Buttons {
2007 minimize: false,
2008 maximize: false,
2009 },
2010 );
2011 window_frame::edges(ui.ctx(), false);
2012 chrome = window_frame::TITLE_HEIGHT;
2013 }
2014 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
2015 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
2016 .resizable(false)
2017 .show_separator_line(false)
2018 .frame(
2019 egui::Frame::new()
2020 .fill(theme::PANEL)
2021 .inner_margin(egui::Margin {
2022 left: theme::PAD,
2023 right: theme::PAD,
2024 top: 0,
2025 bottom: theme::PAD,
2026 }),
2027 )
2028 .show(ui, |ui| close |= self.create_actions(ui))
2029 .response
2030 .rect
2031 .height();
2032 let margin = theme::PAD as f32;
2033 egui::CentralPanel::default()
2034 .frame(theme::panel(theme::PANEL).corner_radius(0))
2035 .show(ui, |ui| {
2036 let content = ui
2037 .vertical(|ui| close |= self.create_area(ui))
2038 .response
2039 .rect;
2040 Some(content.height() + 2.0 * margin + chrome + actions)
2041 })
2042 .inner
2043 });
2044 if let Some(height) = height {
2045 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
2046 if (height - self.create_win.height).abs() > 1.0 {
2047 self.create_win.height = height;
2048 }
2049 }
2050 if close {
2051 self.close_create();
2052 }
2053 }
2054
2055 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
2056 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
2057 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
2058 let enabled = self.picker.is_none();
2059 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
2060 .inner
2061 }
2062
2063 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
2064 let rows = self.create_rows();
2065 let root = self.create_root();
2066
2067 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
2068 ui.horizontal(|ui| {
2069 ui.set_height(theme::FIELD);
2070 ui.spacing_mut().item_spacing.x = 0.0;
2071 let up = theme::flat_icon_button(
2072 ui,
2073 "위로",
2074 theme::UP,
2075 !self.create_folder.is_empty(),
2076 egui::vec2(theme::FIELD, theme::FIELD),
2077 );
2078 if up.clicked() {
2079 self.create_folder = self
2080 .create_folder
2081 .rsplit_once('/')
2082 .map_or("", |(parent, _)| parent)
2083 .to_owned();
2084 self.create_selected = None;
2085 }
2086 ui.add_space(6.0);
2087 let path = match &root {
2088 Some(root) => {
2089 let name = root.file_name().unwrap_or_default().to_string_lossy();
2090 if self.create_folder.is_empty() {
2091 format!("/{name}")
2092 } else {
2093 format!("/{name}/{}", self.create_folder)
2094 }
2095 }
2096 None => "/".to_owned(),
2097 };
2098 let (rect, _) = ui.allocate_exact_size(
2099 egui::vec2(ui.available_width(), theme::FIELD),
2100 egui::Sense::hover(),
2101 );
2102 theme::boxed_field(ui, rect);
2103 theme::field_text(ui, rect, &path);
2104 });
2105 ui.add_space(theme::SPACE);
2106
2107 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
2108 let mut enter = None;
2109 egui::Frame::new()
2110 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2111 .show(ui, |ui| {
2112 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
2113 ui.set_max_height(CREATE_LIST_HEIGHT);
2114 let message = match &rows {
2115 None => Some("폴더를 읽지 못했습니다"),
2116 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
2117 Some(_) => None,
2118 };
2119 if let Some(message) = message {
2120 ui.centered_and_justified(|ui| ui.label(message));
2121 return;
2122 }
2123 let rows = rows.unwrap();
2124 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
2125 egui::ScrollArea::vertical()
2126 .id_salt("create-rows")
2127 .auto_shrink([false, false])
2128 .max_height(CREATE_LIST_HEIGHT)
2129 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
2130 for row in &rows[range] {
2131 let (rect, response) = ui.allocate_exact_size(
2132 egui::vec2(ui.available_width(), LIST_ROW),
2133 egui::Sense::click(),
2134 );
2135 let response = response.on_hover_text(&row.name);
2136 theme::pointer(&response);
2137 response.widget_info(|| {
2138 egui::WidgetInfo::labeled(
2139 egui::Role::ListBoxOption,
2140 true,
2141 &row.name,
2142 )
2143 });
2144 if response.clicked() {
2145 self.create_selected = Some(row.name.clone());
2146 }
2147 theme::row_background(
2148 ui,
2149 rect,
2150 self.create_selected.as_deref() == Some(row.name.as_str()),
2151 response.hovered(),
2152 );
2153 if row.directory && root.is_some() && response.clicked() {
2154 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
2155 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
2156 let frame = ui.ctx().cumulative_frame_nr();
2157 let time = ui.input(|i| i.time);
2158 match &self.create_last_click {
2159 Some((name, last_frame, last_time))
2160 if name == &row.name
2161 && *last_frame != frame
2162 && time - last_time < 0.4 =>
2163 {
2164 enter = Some(row.name.clone());
2165 self.create_last_click = None;
2166 }
2167 Some((name, last_frame, _))
2168 if name == &row.name && *last_frame == frame => {}
2169 _ => {
2170 self.create_last_click =
2171 Some((row.name.clone(), frame, time));
2172 }
2173 }
2174 }
2175 Self::entry_cells(
2176 ui,
2177 rect,
2178 row.directory,
2179 &row.name,
2180 &row.name,
2181 row.bytes.map(present::bytes_text).unwrap_or_default(),
2182 name_width,
2183 );
2184 }
2185 });
2186 });
2187 if let Some(name) = enter {
2188 self.create_folder = if self.create_folder.is_empty() {
2189 name
2190 } else {
2191 format!("{}/{name}", self.create_folder)
2192 };
2193 self.create_selected = None;
2194 }
2195 ui.add_space(theme::SPACE);
2196
2197 if let Some(error) = &self.ui_error {
2198 Self::error_notice(ui, error);
2199 }
2200
2201 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
2202 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
2203 theme::pointer(&check);
2204 theme::focus(&check);
2205 if self.aes256 {
2206 let label_width = 72.0;
2207 ui.horizontal(|ui| {
2208 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
2209 let toggle = if self.zip_password_visible {
2210 "숨기기"
2211 } else {
2212 "보기"
2213 };
2214 let toggle_width = 72.0;
2215 let edit = ui.add_sized(
2216 [
2217 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
2218 theme::FIELD,
2219 ],
2220 egui::TextEdit::singleline(&mut self.zip_password)
2221 .password(!self.zip_password_visible)
2222 .id(egui::Id::unique("zip-password-input"))
2223 .char_limit(1024)
2224 .align(egui::Align2::LEFT_CENTER),
2225 );
2226 theme::focus(&edit);
2227 if theme::action(ui, toggle, false, true).clicked() {
2228 self.zip_password_visible = !self.zip_password_visible;
2229 }
2230 });
2231 ui.horizontal(|ui| {
2232 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
2233 let edit = ui.add_sized(
2234 [
2235 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
2236 theme::FIELD,
2237 ],
2238 egui::TextEdit::singleline(&mut self.zip_password_confirm)
2239 .password(!self.zip_password_visible)
2240 .id(egui::Id::unique("zip-password-confirm"))
2241 .char_limit(1024)
2242 .align(egui::Align2::LEFT_CENTER),
2243 );
2244 theme::focus(&edit);
2245 });
2246 if self.zip_password.len() > 1024 {
2247 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2248 } else if !self.zip_password_confirm.is_empty()
2249 && self.zip_password != self.zip_password_confirm
2250 {
2251 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2252 }
2253 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
2254 } else if !self.zip_password.is_empty() || !self.zip_password_confirm.is_empty() {
2255 // 체크를 해제하면 입력한 암호를 남겨 두지 않음.
2256 wipe(&mut self.zip_password);
2257 wipe(&mut self.zip_password_confirm);
2258 self.zip_password_visible = false;
2259 }
2260 false
2261 }
2262
2263 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
2264 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
2265 let ready = !self.sources.is_empty() && self.zip_password_ready();
2266 let enabled = self.picker.is_none();
2267 let (cancel, compress) = ui
2268 .add_enabled_ui(enabled, |ui| {
2269 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
2270 })
2271 .inner;
2272 if compress {
2273 self.open_picker(Purpose::SaveZip);
2274 }
2275 cancel
2276 }
2277
2278 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
2279 let (_, attempt, encrypt) = self.model.challenge.unwrap();
2280 let mut submit = false;
2281 let mut cancel = false;
2282 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
2283 id == egui::Id::unique("archive-password-input")
2284 || id == egui::Id::unique("archive-password-confirm")
2285 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
2286 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
2287 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
2288 ui.heading(if encrypt {
2289 "ZIP 암호 설정"
2290 } else {
2291 "암호가 필요합니다"
2292 });
2293 if encrypt {
2294 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
2295 } else if let Some(path) = &self.model.archive {
2296 ui.label(format!(
2297 "{}은 암호로 보호되어 있습니다.",
2298 present::middle_text(
2299 &path.file_name().unwrap_or_default().to_string_lossy(),
2300 24
2301 )
2302 ));
2303 }
2304 ui.horizontal(|ui| {
2305 ui.label("암호");
2306 let edit = ui.add(
2307 egui::TextEdit::singleline(&mut self.password)
2308 .password(!self.password_visible)
2309 .id(egui::Id::unique("archive-password-input"))
2310 .char_limit(1024)
2311 .desired_width(232.0),
2312 );
2313 theme::focus(&edit);
2314 if new_challenge {
2315 edit.request_focus();
2316 }
2317 if theme::action(
2318 ui,
2319 if self.password_visible {
2320 "숨기기"
2321 } else {
2322 "보기"
2323 },
2324 false,
2325 true,
2326 )
2327 .clicked()
2328 {
2329 self.password_visible = !self.password_visible;
2330 }
2331 });
2332 if encrypt {
2333 ui.horizontal(|ui| {
2334 ui.label("암호 확인");
2335 let edit = ui.add(
2336 egui::TextEdit::singleline(&mut self.password_confirm)
2337 .password(!self.password_visible)
2338 .id(egui::Id::unique("archive-password-confirm"))
2339 .char_limit(1024)
2340 .desired_width(232.0),
2341 );
2342 theme::focus(&edit);
2343 });
2344 if self.password != self.password_confirm {
2345 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2346 }
2347 } else if attempt > 1 {
2348 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
2349 }
2350 if self.password.len() > 1024 {
2351 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2352 }
2353 let valid = !self.password.is_empty()
2354 && self.password.len() <= 1024
2355 && (!encrypt || self.password == self.password_confirm);
2356 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
2357 cancel = actions.0;
2358 submit = actions.1 || (valid && password_enter);
2359 });
2360 if modal.should_close() || cancel {
2361 self.clear_password();
2362 self.model.cancel();
2363 } else if submit {
2364 let password = std::mem::take(&mut self.password);
2365 self.clear_password();
2366 self.model.password(password);
2367 }
2368 }
2369
2370 fn close_dialog(&mut self, ctx: &egui::Context) {
2371 if self.model.close == Close::Open || self.model.close == Close::Allowed {
2372 return;
2373 }
2374 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
2375 ui.set_width(420.0);
2376 match self.model.close {
2377 Close::Confirm => {
2378 ui.heading("작업 중 닫기");
2379 ui.label("작업을 취소하고 닫을까요?");
2380 ui.horizontal(|ui| {
2381 if theme::action(ui, "계속 작업", false, true).clicked() {
2382 self.model.keep_open();
2383 }
2384 if theme::action(ui, "취소하고 닫기", true, true).clicked() {
2385 self.clear_password();
2386 self.model.confirm_close();
2387 }
2388 });
2389 }
2390 Close::Waiting => {
2391 ui.heading("종료 확인 중");
2392 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
2393 if theme::action(ui, "닫기 취소", false, true).clicked() {
2394 self.model.keep_open();
2395 }
2396 }
2397 Close::Review => {
2398 let creating = matches!(self.last_request, Some(Start::CreateZip { .. }));
2399 ui.heading("결과 확인 후 닫기");
2400 let wrote = self
2401 .last_request
2402 .as_ref()
2403 .is_some_and(|request| !matches!(request, Start::List { .. }));
2404 ui.label(if !wrote {
2405 "프로그램을 닫을까요?".to_owned()
2406 } else if self.model.confirmed {
2407 "작업 결과를 확인한 뒤 닫으세요".to_owned()
2408 } else {
2409 present::operation_text(present::UNCERTAIN, creating)
2410 });
2411 egui::ScrollArea::vertical()
2412 .max_height(160.0)
2413 .show(ui, |ui| {
2414 if let Some(code) = self.model.terminal.as_ref().and_then(|t| t.error) {
2415 ui.colored_label(
2416 theme::ERROR,
2417 present::operation_text(present::error_text(code), creating),
2418 );
2419 }
2420 if wrote {
2421 for warning in present::warnings(
2422 self.model.terminal.as_ref(),
2423 self.model.confirmed,
2424 self.targets.as_ref(),
2425 &self.directories,
2426 &self.model.outputs,
2427 ) {
2428 ui.colored_label(
2429 theme::WARNING,
2430 present::operation_text(warning, creating),
2431 );
2432 }
2433 }
2434 });
2435 ui.horizontal(|ui| {
2436 if theme::action(ui, "계속 작업", false, true).clicked() {
2437 self.model.keep_open();
2438 }
2439 if theme::action(ui, "닫기", true, true).clicked() {
2440 self.model.acknowledge_close();
2441 }
2442 });
2443 }
2444 _ => {}
2445 }
2446 });
2447 }
2448}
2449
2450impl eframe::App for ArchiveApp {
2451 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
2452 self.show(root);
2453 }
2454
2455 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
2456 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
2457 if std::mem::take(&mut self.release_after_move) {
2458 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
2459 raw_input.events.insert(
2460 0,
2461 egui::Event::PointerButton {
2462 pos,
2463 button: egui::PointerButton::Primary,
2464 pressed: false,
2465 modifiers: ctx.input(|i| i.modifiers),
2466 },
2467 );
2468 }
2469 }
2470}
2471impl Drop for ArchiveApp {
2472 fn drop(&mut self) {
2473 self.clear_password();
2474 }
2475}