team-ljyzipelo

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