team-ljyzipelo

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