team-ljyzipelo

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