team-ljyzipelo

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