team-ljyzipelo

공개
3,170줄128 KB
1#[cfg(all(feature = "ui-fixture", debug_assertions))]
2#[path = "../../../tests/rust-app-ui/scenarios.rs"]
3pub mod scenarios;
4
5use crate::{
6 archive_browser as browser,
7 archive_dialog::{
8 DIALOG_UNAVAILABLE, DialogAnswer, DialogRequest, Dialogs, NativeDialogs, PendingDialog,
9 Purpose,
10 },
11 archive_present as present,
12 archive_theme::{self as theme, Icon},
13 archive_ui::*,
14 window_frame,
15};
16use eframe::egui::{self, Align, Layout, RichText};
17use std::{
18 collections::BTreeSet,
19 path::{Path, PathBuf},
20};
21
22const WORK_WIDTH: f32 = 480.0;
23const CREATE_WIDTH: f32 = 560.0;
24/// 처음 열 때의 높이. 그다음부터는 내용 높이에 맞춤.
25const CREATE_MIN_HEIGHT: f32 = 560.0;
26const CREATE_LIST_HEIGHT: f32 = 288.0;
27
28/// ZIP 만들기 창 목록의 한 행. 디스크에서 읽은 파일이나 폴더임.
29#[derive(Clone)]
30struct SourceRow {
31 name: String,
32 directory: bool,
33 bytes: Option<u64>,
34}
35
36fn source_row(path: &Path) -> SourceRow {
37 let metadata = std::fs::symlink_metadata(path).ok();
38 SourceRow {
39 name: path
40 .file_name()
41 .map(|name| name.to_string_lossy().into_owned())
42 .unwrap_or_default(),
43 // 심볼릭 링크는 따라가지 않으므로 폴더로 보이지 않음.
44 directory: metadata.as_ref().is_some_and(|m| m.is_dir()),
45 bytes: metadata.filter(|m| m.is_file()).map(|m| m.len()),
46 }
47}
48
49/// 폴더 안 항목을 메인 목록과 같은 순서(폴더 먼저, 이름순)로 읽음. 읽지 못하면 None.
50fn read_source_dir(dir: &Path) -> Option<std::rc::Rc<Vec<SourceRow>>> {
51 let mut rows = std::fs::read_dir(dir)
52 .ok()?
53 .filter_map(Result::ok)
54 .map(|entry| source_row(&entry.path()))
55 .collect::<Vec<_>>();
56 rows.sort_by(|a, b| {
57 b.directory
58 .cmp(&a.directory)
59 .then_with(|| a.name.cmp(&b.name))
60 });
61 Some(std::rc::Rc::new(rows))
62}
63
64/// 덮어쓴 뒤 버려 메모리에 암호가 남지 않게 함.
65fn wipe(value: &mut String) {
66 let mut bytes = std::mem::take(value).into_bytes();
67 bytes.fill(0);
68}
69const WORK_MIN_HEIGHT: f32 = 96.0;
70const WORK_MAX_HEIGHT: f32 = 520.0;
71const WORK_RESULT_MAX_HEIGHT: f32 = 220.0;
72
73/// 작업 진행·결과를 보여주는 자식 창의 위치 상태.
74/// 부모 창 기준 상대 위치를 기억해 두고, 부모 창이 움직이면 같은 상대 위치로 따라감.
75struct WorkWindow {
76 open: bool,
77 initial: Option<egui::Pos2>,
78 offset: Option<egui::Vec2>,
79 parent: Option<egui::Pos2>,
80 expected: Option<egui::Pos2>,
81 settle_until: f64,
82 height: f32,
83}
84
85impl Default for WorkWindow {
86 fn default() -> Self {
87 Self {
88 open: false,
89 initial: None,
90 offset: None,
91 parent: None,
92 expected: None,
93 settle_until: 0.0,
94 height: 168.0,
95 }
96 }
97}
98
99impl WorkWindow {
100 /// 부모 창 가운데에 열고, 사용자가 옮긴 상대 위치를 유지한 채 부모 창을 따라가게 함.
101 /// 앱을 쓰는 동안에만 부모 위에 두고, 처음 위치를 담은 ViewportBuilder를 돌려줌.
102 /// Wayland처럼 창 위치를 알 수 없으면 위치는 창 관리자에 맡김.
103 fn builder(
104 &mut self,
105 ctx: &egui::Context,
106 id: egui::ViewportId,
107 size: egui::Vec2,
108 title: &str,
109 decorations: bool,
110 native_dialog_open: bool,
111 ) -> egui::ViewportBuilder {
112 let (parent, parent_focused, now) = ctx.input(|i| {
113 (
114 i.viewport().outer_rect,
115 i.viewport().focused.unwrap_or(false),
116 i.time,
117 )
118 });
119 let (child, child_focused) = ctx.input(|i| {
120 i.raw.viewports.get(&id).map_or((None, false), |v| {
121 (v.outer_rect, v.focused.unwrap_or(false))
122 })
123 });
124 if !self.open {
125 // 처음 열 때 부모 창 가운데에 둠. 닫혔다 다시 열 때는 기억한 위치에 둠.
126 self.open = true;
127 self.initial = parent.map(|p| match self.offset {
128 Some(offset) => (p.min + offset).round(),
129 None => (p.center() - size / 2.0).round(),
130 });
131 self.offset = self.initial.zip(parent).map(|(c, p)| c - p.min);
132 self.parent = parent.map(|p| p.min);
133 self.expected = self.initial;
134 self.settle_until = now + 0.5;
135 }
136 if let (Some(parent), Some(child)) = (parent, child) {
137 let parent_moved = self.parent.is_some_and(|p| (p - parent.min).length() > 0.5);
138 let settled = self
139 .expected
140 .is_some_and(|e| (child.min - e).length() <= 2.0);
141 if settled || now >= self.settle_until {
142 self.settle_until = 0.0;
143 }
144 if parent_moved {
145 if let Some(offset) = self.offset {
146 let target = (parent.min + offset).round();
147 ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
148 self.expected = Some(target);
149 self.settle_until = now + 0.5;
150 }
151 } else if self.settle_until == 0.0 && !settled {
152 // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
153 self.offset = Some(child.min - parent.min);
154 self.expected = Some(child.min);
155 }
156 self.parent = Some(parent.min);
157 }
158 let mut builder = egui::ViewportBuilder::default()
159 .with_title(title)
160 .with_icon(crate::app_icon::load())
161 .with_decorations(decorations)
162 .with_inner_size(size)
163 .with_resizable(false)
164 .with_minimize_button(false)
165 .with_maximize_button(false)
166 .with_taskbar(false)
167 .with_window_level(
168 if !native_dialog_open && (parent_focused || child_focused) {
169 egui::WindowLevel::AlwaysOnTop
170 } else {
171 egui::WindowLevel::Normal
172 },
173 );
174 if let Some(position) = self.initial {
175 builder = builder.with_position(position);
176 }
177 builder
178 }
179}
180
181struct Marquee {
182 // 스크롤 중에도 시작점을 목록 좌표로 유지함.
183 origin: egui::Pos2,
184 base: BTreeSet<u32>,
185 moved: bool,
186}
187
188/// 파일 목록 한 행의 높이. 행 안의 크기 칸(theme::ROW)이 위아래 2px 여백으로 들어감.
189const LIST_ROW: f32 = 36.0;
190
191pub struct ArchiveApp {
192 pub model: Model,
193 factory: Box<dyn Factory>,
194 destination: PathBuf,
195 automatic_destination: bool,
196 owned_destination: Option<PathBuf>,
197 gzip_name: String,
198 sources: Vec<PathBuf>,
199 zip_folder: PathBuf,
200 zip_name: String,
201 password: String,
202 password_confirm: String,
203 password_visible: bool,
204 password_challenge: Option<u64>,
205 conflict_challenge: Option<(u64, u64)>,
206 conflict_apply: bool,
207 aes256: bool,
208 create: bool,
209 selected_only: bool,
210 method: Method,
211 seven_zip: bool,
212 dialogs: Box<dyn Dialogs>,
213 picker: Option<(Purpose, std::sync::mpsc::Receiver<DialogAnswer>)>,
214 preview_open: bool,
215 preview_name: String,
216 preview_text: String,
217 preview_texture: Option<egui::TextureHandle>,
218 preview_return_focus: Option<egui::Id>,
219 preview_initial_focus: bool,
220 work: WorkWindow,
221 create_win: WorkWindow,
222 /// ZIP 만들기 창에서 보고 있는 폴더 (고른 폴더 기준 상대 경로, 비어 있으면 최상위).
223 create_folder: String,
224 create_listing: Option<(PathBuf, Option<std::rc::Rc<Vec<SourceRow>>>)>,
225 /// 마지막으로 누른 폴더 행 (이름, 프레임 번호, 시각). 두 번 누름을 직접 판단할 때 씀.
226 create_last_click: Option<(String, u64, f64)>,
227 /// ZIP 만들기 목록에서 한 번 눌러 선택한 항목 이름. 보고 있는 폴더가 바뀌면 지움.
228 create_selected: Option<String>,
229 zip_password: String,
230 zip_password_confirm: String,
231 zip_password_visible: bool,
232 /// 암호를 지웠으면 입력창의 실행 취소 기록도 다음 그리기 전에 지움.
233 forget_password_history: Vec<&'static str>,
234 /// 작업을 시작한 뒤 작업자가 암호를 요청하면 넘길 암호. 넘기거나 작업이 끝나면 지움.
235 pending_zip_password: Option<String>,
236 custom_frame: bool,
237 release_after_move: bool,
238 folder: String,
239 search: String,
240 list_anchor: Option<usize>,
241 list_cursor: Option<usize>,
242 list_offset: f32,
243 list_focused: bool,
244 marquee: Option<Marquee>,
245 last_request: Option<Start>,
246 targets: Option<BTreeSet<String>>,
247 directories: BTreeSet<String>,
248 dismissed: bool,
249 details: bool,
250 checked_destination: bool,
251 ui_error: Option<String>,
252 initialized: bool,
253 #[cfg(all(feature = "ui-fixture", debug_assertions))]
254 scenario_marquee: Option<egui::Rect>,
255 #[cfg(all(feature = "ui-fixture", debug_assertions))]
256 scenario_sources: Option<std::rc::Rc<Vec<SourceRow>>>,
257}
258
259impl ArchiveApp {
260 pub fn new(factory: Box<dyn Factory>, startup: Option<PathBuf>, _fixture: bool) -> Self {
261 let mut app = Self {
262 model: Model::default(),
263 factory,
264 destination: PathBuf::new(),
265 automatic_destination: true,
266 owned_destination: None,
267 gzip_name: String::new(),
268 sources: Vec::new(),
269 zip_folder: present::home_directory(),
270 zip_name: String::new(),
271 password: String::new(),
272 password_confirm: String::new(),
273 password_visible: false,
274 password_challenge: None,
275 conflict_challenge: None,
276 conflict_apply: false,
277 aes256: false,
278 create: false,
279 selected_only: false,
280 method: Method::Deflate,
281 seven_zip: false,
282 dialogs: Box::new(NativeDialogs),
283 picker: None,
284 preview_open: false,
285 preview_name: String::new(),
286 preview_text: String::new(),
287 preview_texture: None,
288 preview_return_focus: None,
289 preview_initial_focus: false,
290 work: WorkWindow::default(),
291 create_win: WorkWindow::default(),
292 create_folder: String::new(),
293 create_listing: None,
294 create_last_click: None,
295 create_selected: None,
296 zip_password: String::new(),
297 zip_password_confirm: String::new(),
298 zip_password_visible: false,
299 forget_password_history: Vec::new(),
300 pending_zip_password: None,
301 custom_frame: false,
302 release_after_move: false,
303 folder: String::new(),
304 search: String::new(),
305 list_anchor: None,
306 list_cursor: None,
307 list_offset: 0.0,
308 list_focused: false,
309 marquee: None,
310 last_request: None,
311 targets: None,
312 directories: BTreeSet::new(),
313 dismissed: false,
314 details: false,
315 checked_destination: false,
316 ui_error: None,
317 initialized: false,
318 #[cfg(all(feature = "ui-fixture", debug_assertions))]
319 scenario_marquee: None,
320 #[cfg(all(feature = "ui-fixture", debug_assertions))]
321 scenario_sources: None,
322 };
323 if let Some(path) = startup {
324 app.open_path(path);
325 }
326 app
327 }
328
329 pub fn set_dialogs(&mut self, dialogs: Box<dyn Dialogs>) {
330 self.dialogs = dialogs;
331 }
332
333 /// 운영체제가 창 테두리를 그려 주지 않을 때(GNOME Wayland) 제목 표시줄을 직접 그림.
334 pub fn set_custom_frame(&mut self, custom: bool) {
335 self.custom_frame = custom;
336 }
337
338 pub fn browse_folder(&mut self, folder: &str) {
339 self.folder = folder.trim_matches('/').to_owned();
340 self.search.clear();
341 self.clear_list_selection();
342 }
343
344 pub fn show_create(&mut self, encrypted: bool) {
345 if !self.model.busy() {
346 self.create = true;
347 self.aes256 = encrypted && !self.seven_zip;
348 self.ui_error = None;
349 }
350 }
351
352 fn clear_password(&mut self) {
353 for value in [&mut self.password, &mut self.password_confirm] {
354 let mut bytes = std::mem::take(value).into_bytes();
355 bytes.fill(0);
356 }
357 self.password_visible = false;
358 // 이 함수는 암호 요청이 없는 동안 매 프레임 불리므로, 암호 창을 쓴 뒤에만 기록을 지움.
359 if self.password_challenge.is_some() {
360 self.forget_password_history
361 .extend(["archive-password-input", "archive-password-confirm"]);
362 }
363 }
364
365 /// 지운 암호가 입력창의 실행 취소(Ctrl+Z)로 되살아나지 않게 egui가 보관하는
366 /// 입력창 상태(실행 취소 기록 포함)를 지움.
367 fn forget_password_history(&mut self, ctx: &egui::Context) {
368 if self.forget_password_history.is_empty() {
369 return;
370 }
371 let names = std::mem::take(&mut self.forget_password_history);
372 ctx.data_mut(|data| {
373 for name in names {
374 data.remove::<egui::text_edit::TextEditState>(egui::Id::unique(name));
375 }
376 });
377 }
378
379 fn clear_zip_password(&mut self) {
380 wipe(&mut self.zip_password);
381 wipe(&mut self.zip_password_confirm);
382 if let Some(mut pending) = self.pending_zip_password.take() {
383 wipe(&mut pending);
384 }
385 self.zip_password_visible = false;
386 self.forget_password_history
387 .extend(["zip-password-input", "zip-password-confirm"]);
388 }
389
390 /// 암호로 보호하지 않거나, 두 암호가 같고 1~1024바이트이면 만들 수 있음.
391 fn zip_password_ready(&self) -> bool {
392 !self.aes256
393 || (!self.zip_password.is_empty()
394 && self.zip_password.len() <= 1024
395 && self.zip_password == self.zip_password_confirm)
396 }
397
398 fn close_create(&mut self) {
399 self.create = false;
400 self.ui_error = None;
401 self.clear_zip_password();
402 self.create_win = WorkWindow::default();
403 }
404
405 /// 압축하기: 묶을 폴더를 운영체제 폴더 선택 창에서 고른 뒤 ZIP 만들기 창을 엶.
406 fn choose_zip_folder(&mut self) {
407 if self.model.busy() || self.picker.is_some() {
408 return;
409 }
410 // 이미 열린 ZIP 만들기 창의 목록과 암호 설정은 새 폴더를 실제로 고른 뒤에만 바꿈.
411 // 선택을 취소하면 그대로 남음(apply_picker의 Purpose::Folder).
412 self.open_picker(Purpose::Folder);
413 }
414
415 /// 폴더 하나를 골랐으면 그 폴더 안을 목록으로 보여 줌. 여러 항목이면 그 항목들을 보여 줌.
416 fn create_root(&self) -> Option<PathBuf> {
417 (self.sources.len() == 1 && self.sources[0].is_dir()).then(|| self.sources[0].clone())
418 }
419
420 fn create_rows(&mut self) -> Option<std::rc::Rc<Vec<SourceRow>>> {
421 #[cfg(all(feature = "ui-fixture", debug_assertions))]
422 if let Some(rows) = &self.scenario_sources {
423 return Some(rows.clone());
424 }
425 let Some(root) = self.create_root() else {
426 return Some(std::rc::Rc::new(
427 self.sources.iter().map(|path| source_row(path)).collect(),
428 ));
429 };
430 let dir = if self.create_folder.is_empty() {
431 root
432 } else {
433 root.join(&self.create_folder)
434 };
435 // 프레임마다 디스크를 읽지 않도록 보고 있는 폴더가 바뀔 때만 다시 읽음.
436 if self
437 .create_listing
438 .as_ref()
439 .is_none_or(|(path, _)| path != &dir)
440 {
441 let rows = read_source_dir(&dir);
442 self.create_listing = Some((dir, rows));
443 }
444 self.create_listing
445 .as_ref()
446 .and_then(|(_, rows)| rows.clone())
447 }
448
449 pub fn open_path(&mut self, archive: PathBuf) {
450 if self.model.busy() {
451 return;
452 }
453 self.clear_password();
454 self.destination = present::default_destination(&archive);
455 self.automatic_destination = true;
456 self.gzip_name = present::gzip_output_name(&archive);
457 self.selected_only = false;
458 self.folder.clear();
459 self.search.clear();
460 self.clear_list_selection();
461 self.targets = None;
462 self.directories.clear();
463 self.start(Start::List { archive });
464 }
465
466 fn start(&mut self, request: Start) -> bool {
467 // 파일 선택 창이 응답을 기다리는 동안에는 어느 창에서도 새 작업을 시작하지 않음.
468 if self.picker.is_some() {
469 return false;
470 }
471 self.last_request = Some(request.clone());
472 self.dismissed = false;
473 self.details = false;
474 self.checked_destination = false;
475 self.ui_error = None;
476 self.model.begin(request, self.factory.as_mut())
477 }
478
479 pub fn choose_destination(&mut self, path: PathBuf) {
480 self.destination = path;
481 self.automatic_destination = false;
482 self.ui_error = None;
483 }
484
485 pub fn add_sources(&mut self, paths: Vec<PathBuf>) {
486 if self.model.busy() {
487 return;
488 }
489 let mut validated = Vec::new();
490 for path in paths {
491 let Ok(metadata) = std::fs::symlink_metadata(&path) else {
492 self.ui_error = Some("파일이나 폴더를 찾지 못했습니다. 다시 선택하세요".into());
493 return;
494 };
495 if metadata.file_type().is_symlink() || !(metadata.is_file() || metadata.is_dir()) {
496 self.ui_error = Some("일반 파일과 폴더만 추가할 수 있습니다".into());
497 return;
498 }
499 let Ok(path) = path.canonicalize() else {
500 return;
501 };
502 if path.to_str().is_none()
503 || !path
504 .file_name()
505 .and_then(|name| name.to_str())
506 .is_some_and(valid_leaf)
507 {
508 self.ui_error = Some("파일이나 폴더의 이름을 확인하세요".into());
509 return;
510 }
511 validated.push(crate::archive_path::worker_path(&path));
512 }
513 let paths = validated;
514 if self.sources.is_empty() {
515 if let Some(first) = paths.first() {
516 self.zip_folder = first.parent().unwrap_or(Path::new("/")).to_path_buf();
517 let name = if first.is_dir() {
518 first.file_name()
519 } else {
520 first.file_stem()
521 };
522 self.zip_name = format!(
523 "{}.{}",
524 name.unwrap_or_default().to_string_lossy(),
525 if self.seven_zip { "7z" } else { "zip" }
526 );
527 }
528 }
529 for path in paths {
530 if !self.sources.contains(&path) {
531 self.sources.push(path);
532 }
533 }
534 self.create_folder.clear();
535 self.create_listing = None;
536 self.create_selected = None;
537 self.create = true;
538 }
539
540 pub fn begin_extract(&mut self) -> bool {
541 self.selected_only = !self.model.selected.is_empty();
542 let selection = if self.selected_only {
543 Selection::EntryIds(
544 browser::expand_selection(&self.model.entries, &self.model.selected)
545 .into_iter()
546 .collect(),
547 )
548 } else {
549 Selection::All
550 };
551 self.extract_selection(selection)
552 }
553
554 fn extract_selection(&mut self, selection: Selection) -> bool {
555 if !self.model.can_extract()
556 || matches!(&selection, Selection::EntryIds(ids) if ids.is_empty())
557 {
558 return false;
559 }
560 self.selected_only = matches!(&selection, Selection::EntryIds(_));
561 match present::prepare_destination(&self.destination, self.automatic_destination) {
562 Ok(true) => self.owned_destination = Some(self.destination.clone()),
563 Ok(false) => self.owned_destination = None,
564 Err(_) => {
565 self.ui_error = Some(present::FOLDER_ERROR.into());
566 return false;
567 }
568 }
569 let gzip = self
570 .model
571 .list_id
572 .as_ref()
573 .is_some_and(|id| id.format == Format::Gzip);
574 self.targets = present::target_files(
575 &self.model.entries,
576 &selection,
577 gzip.then_some(self.gzip_name.as_str()),
578 );
579 self.directories = if gzip {
580 BTreeSet::new()
581 } else {
582 present::target_directories(&self.model.entries, &selection)
583 };
584 let request = Start::Extract {
585 archive: self.model.archive.clone().unwrap(),
586 destination: self.destination.clone(),
587 selection,
588 list_id: self.model.list_id.clone().unwrap(),
589 gzip_output_name: gzip.then(|| self.gzip_name.clone()),
590 };
591 if self.start(request) {
592 true
593 } else {
594 if let Some(path) = self.owned_destination.take() {
595 present::remove_owned_empty(&path);
596 }
597 false
598 }
599 }
600
601 fn begin_zip(&mut self) {
602 if self.sources.is_empty() {
603 return;
604 }
605 let extension = if self.seven_zip { ".7z" } else { ".zip" };
606 if !self.zip_name.to_ascii_lowercase().ends_with(extension) {
607 self.zip_name.push_str(extension);
608 }
609 if !valid_leaf(&self.zip_name) {
610 self.ui_error = Some("압축파일 이름을 확인하세요".into());
611 return;
612 }
613 let output_file = self.zip_folder.join(&self.zip_name);
614 if std::fs::symlink_metadata(&output_file).is_ok() {
615 self.ui_error = Some("같은 이름의 파일이 이미 있습니다. 다른 이름을 입력하세요".into());
616 return;
617 }
618 let mut sources = Vec::new();
619 for path in &self.sources {
620 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
621 self.ui_error = Some(
622 "이름을 읽을 수 없는 파일이 있습니다. 파일 이름을 바꾼 뒤 다시 추가하세요"
623 .into(),
624 );
625 return;
626 };
627 sources.push((path.clone(), name.to_owned()));
628 }
629 if self.seven_zip
630 && (self.aes256
631 || !self.zip_password.is_empty()
632 || !self.zip_password_confirm.is_empty())
633 {
634 self.ui_error =
635 Some("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요".into());
636 return;
637 }
638 if !self.zip_password_ready() {
639 self.ui_error = Some("두 암호가 같은지 확인하세요".into());
640 return;
641 }
642 self.targets = Some([self.zip_name.clone()].into_iter().collect());
643 self.directories.clear();
644 // 암호는 ZIP 만들기 창에서 받아 두었다가 작업자가 요청하면 넘김.
645 let password = self.aes256.then(|| std::mem::take(&mut self.zip_password));
646 let request = if self.seven_zip {
647 Start::CreateSevenZip {
648 sources,
649 output_file,
650 }
651 } else {
652 Start::CreateZip {
653 sources,
654 output_file,
655 method: self.method,
656 aes256: self.aes256,
657 }
658 };
659 if self.start(request) {
660 self.create = false;
661 self.create_win = WorkWindow::default();
662 self.clear_zip_password();
663 self.pending_zip_password = password;
664 } else if let Some(password) = password {
665 self.zip_password = password;
666 }
667 }
668
669 fn open_picker(&mut self, purpose: Purpose) {
670 if self.model.busy() || self.picker.is_some() {
671 return;
672 }
673 let gzip = self
674 .model
675 .list_id
676 .as_ref()
677 .is_some_and(|id| id.format == Format::Gzip);
678 let purpose = match (purpose, gzip) {
679 (Purpose::Destination, true) => Purpose::SaveGzip,
680 (Purpose::Retry, true) => Purpose::RetryGzip,
681 _ => purpose,
682 };
683 let directory = match purpose {
684 Purpose::SaveZip | Purpose::SaveSevenZip => self.zip_folder.clone(),
685 Purpose::Destination | Purpose::SaveGzip => self
686 .model
687 .archive
688 .as_ref()
689 .and_then(|path| path.parent())
690 .map(Path::to_path_buf)
691 .unwrap_or_else(present::home_directory),
692 Purpose::Retry | Purpose::RetryGzip => self.destination.clone(),
693 _ => self
694 .sources
695 .last()
696 .and_then(|path| path.parent())
697 .map(Path::to_path_buf)
698 .unwrap_or_else(present::home_directory),
699 };
700 let request = DialogRequest {
701 purpose,
702 directory,
703 file_name: if matches!(purpose, Purpose::SaveGzip | Purpose::RetryGzip) {
704 self.gzip_name.clone()
705 } else {
706 self.zip_name.clone()
707 },
708 };
709 match self.dialogs.start(request) {
710 PendingDialog::Ready(answer) => self.apply_picker(purpose, answer),
711 PendingDialog::Waiting(receiver) => self.picker = Some((purpose, receiver)),
712 }
713 }
714
715 fn poll_picker(&mut self) {
716 let Some((purpose, receiver)) = &self.picker else {
717 return;
718 };
719 let purpose = *purpose;
720 let answer = match receiver.try_recv() {
721 Ok(answer) => answer,
722 Err(std::sync::mpsc::TryRecvError::Empty) => return,
723 Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(DIALOG_UNAVAILABLE.into()),
724 };
725 self.picker = None;
726 self.apply_picker(purpose, answer);
727 }
728
729 fn apply_picker(&mut self, purpose: Purpose, answer: DialogAnswer) {
730 if answer.is_ok() && self.ui_error.as_deref() == Some(DIALOG_UNAVAILABLE) {
731 self.ui_error = None;
732 }
733 match answer {
734 Ok(Some(paths)) if !paths.is_empty() => {
735 let path = paths[0].clone();
736 match purpose {
737 Purpose::Open => {
738 if std::fs::symlink_metadata(&path)
739 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
740 {
741 self.open_path(path);
742 } else {
743 self.ui_error = Some("일반 압축파일을 선택하세요".into());
744 }
745 }
746 Purpose::Files => self.add_sources(paths),
747 Purpose::Folder => {
748 // 새 폴더로 처음부터 시작함. 고른 폴더가 쓸 수 없으면 기존 내용을 되돌림.
749 let previous = std::mem::take(&mut self.sources);
750 self.add_sources(paths);
751 if self.sources.is_empty() {
752 self.sources = previous;
753 } else {
754 self.aes256 = false;
755 self.clear_zip_password();
756 self.ui_error = None;
757 }
758 }
759 Purpose::Destination | Purpose::Retry => {
760 self.choose_destination(path);
761 self.selected_only = !self.model.selected.is_empty();
762 if purpose == Purpose::Retry {
763 self.retry();
764 } else {
765 self.begin_extract();
766 }
767 }
768 Purpose::SaveGzip | Purpose::RetryGzip => {
769 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
770 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
771 return;
772 };
773 if !present::valid_output_leaf(name) {
774 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
775 return;
776 }
777 let name = name.to_owned();
778 self.choose_destination(
779 path.parent().unwrap_or(Path::new("/")).to_path_buf(),
780 );
781 self.gzip_name = name.clone();
782 self.selected_only = !self.model.selected.is_empty();
783 if purpose == Purpose::RetryGzip {
784 if let Some(Start::Extract {
785 gzip_output_name, ..
786 }) = &mut self.last_request
787 {
788 *gzip_output_name = Some(name);
789 }
790 self.retry();
791 } else {
792 self.begin_extract();
793 }
794 }
795 // 저장 위치를 고르는 사이 ZIP 만들기 창을 닫았으면 아무 작업도 시작하지 않음.
796 Purpose::SaveZip | Purpose::SaveSevenZip if !self.create => {}
797 Purpose::SaveZip | Purpose::SaveSevenZip => {
798 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
799 self.zip_name = name.to_owned();
800 self.zip_folder = path.parent().unwrap_or(Path::new("/")).to_path_buf();
801 self.begin_zip();
802 }
803 }
804 }
805 }
806 Ok(_) => {}
807 Err(error) => self.ui_error = Some(error),
808 }
809 }
810
811 fn retry(&mut self) {
812 if let Some(request) = self.last_request.clone() {
813 match request {
814 Start::List { archive } => self.open_path(archive),
815 Start::Preview { .. } => {}
816 Start::Extract {
817 selection,
818 gzip_output_name,
819 ..
820 } => {
821 if let Some(name) = gzip_output_name {
822 self.gzip_name = name;
823 }
824 self.extract_selection(selection);
825 }
826 Start::CreateSevenZip { .. } => {
827 self.set_seven_zip(true);
828 self.create = true;
829 self.begin_zip();
830 }
831 Start::CreateZip { aes256, .. } => {
832 self.set_seven_zip(false);
833 self.create = true;
834 if aes256 {
835 // 암호는 보관하지 않으므로 ZIP 만들기 창에서 다시 받음.
836 self.aes256 = true;
837 } else {
838 self.begin_zip();
839 }
840 }
841 }
842 }
843 }
844
845 fn on_drop(&mut self, paths: Vec<PathBuf>) {
846 if self.preview_open || self.model.busy() || paths.is_empty() {
847 return;
848 }
849 if paths.len() == 1 && !self.create && !paths[0].is_dir() {
850 if std::fs::symlink_metadata(&paths[0])
851 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
852 {
853 self.open_path(paths[0].clone());
854 } else {
855 self.ui_error = Some("일반 압축파일을 선택하세요".into());
856 }
857 } else {
858 self.add_sources(paths);
859 }
860 }
861
862 fn poll(&mut self) {
863 let busy = self.model.busy();
864 let close_before = self.model.close;
865 self.model.poll();
866 if close_before == Close::Confirm && self.model.close == Close::Review {
867 // 종료 확인 창에 답하기 전에 작업이 끝났음. 사용자가 닫기를 승인하지 않았으므로
868 // 바로 닫지 않고 계속 물음(close_dialog가 작업이 끝난 문구로 바꿔 보여 줌).
869 self.model.close = Close::Confirm;
870 }
871 if busy && !self.model.busy() {
872 if let Some(path) = self.owned_destination.take() {
873 if !self.model.confirmed
874 || self
875 .model
876 .terminal
877 .as_ref()
878 .is_none_or(|t| t.outcome != Outcome::Completed)
879 {
880 present::remove_owned_empty(&path);
881 }
882 }
883 }
884 }
885
886 pub fn show(&mut self, root: &mut egui::Ui) {
887 let ctx = root.ctx().clone();
888 self.forget_password_history(&ctx);
889 if !self.initialized {
890 theme::apply(&ctx);
891 self.initialized = true;
892 }
893 self.poll();
894 let preview_was_open = self.preview_open;
895 self.poll_picker();
896 if self.model.challenge.is_some_and(|(_, _, encrypt)| encrypt)
897 && let Some(password) = self.pending_zip_password.take()
898 {
899 // ZIP 만들기 창에서 받은 암호를 작업자의 암호 요청에 바로 넘김.
900 self.model.password(password);
901 }
902 if !self.model.busy()
903 && let Some(mut pending) = self.pending_zip_password.take()
904 {
905 wipe(&mut pending);
906 }
907 let challenge = self.model.challenge.map(|(id, _, _)| id);
908 let new_challenge = challenge != self.password_challenge;
909 if new_challenge || challenge.is_none() {
910 self.clear_password();
911 }
912 self.password_challenge = challenge;
913 let dropped = ctx.input(|i| {
914 i.raw
915 .dropped_files
916 .iter()
917 .map(|file| file.path().to_path_buf())
918 .collect()
919 });
920 if self.picker.is_none() {
921 self.on_drop(dropped);
922 }
923 if ctx.input(|i| i.viewport().close_requested()) {
924 self.model.request_close();
925 // 실행 중인 작업이 없으면 결과 확인 안내 없이 바로 닫음.
926 self.model.acknowledge_close();
927 if self.model.close != Close::Allowed {
928 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
929 }
930 }
931 if self.model.close == Close::Review {
932 // 작업을 취소하고 닫기로 한 뒤 정리가 끝난 경우도 안내 없이 닫음.
933 self.model.acknowledge_close();
934 }
935 if self.model.close == Close::Allowed {
936 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
937 }
938 let title = self
939 .model
940 .archive
941 .as_ref()
942 .map(|path| {
943 let full = if path.is_absolute() {
944 path.clone()
945 } else {
946 std::env::current_dir().unwrap_or_default().join(path)
947 };
948 format!("{} — Zipelo", full.display())
949 })
950 .unwrap_or_else(|| "Zipelo".into());
951 let short_title = if let Some(path) = title.strip_suffix(" — Zipelo") {
952 format!(
953 "{} — Zipelo",
954 theme::window_title(root, path, ctx.content_rect().width() - 300.0)
955 )
956 } else {
957 title.clone()
958 };
959 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
960 if self.custom_frame
961 && window_frame::title_bar(
962 root,
963 "main",
964 &title,
965 window_frame::Buttons {
966 minimize: true,
967 maximize: true,
968 },
969 )
970 {
971 self.release_after_move = true;
972 }
973 egui::Panel::top("archive-actions")
974 .frame(
975 theme::panel(theme::PANEL)
976 .corner_radius(0)
977 .inner_margin(egui::Margin {
978 left: 12,
979 right: 12,
980 // 버튼 안 내용은 보이는 모양 기준으로 가운데에 두므로 위아래를 같게 둠.
981 top: 4,
982 bottom: 4,
983 }),
984 )
985 .show(root, |ui| {
986 ui.horizontal(|ui| {
987 ui.spacing_mut().item_spacing.x = 2.0;
988 let idle = !self.model.busy()
989 && self.model.close == Close::Open
990 && self.picker.is_none();
991 if theme::tool(ui, "열기", theme::OPEN, idle, false)
992 .on_hover_text(&title)
993 .clicked()
994 {
995 self.open_picker(Purpose::Open);
996 }
997 if theme::tool(
998 ui,
999 "미리보기",
1000 theme::PREVIEW,
1001 idle && self.can_preview() && !self.preview_open,
1002 false,
1003 )
1004 .on_disabled_hover_text(
1005 if self.model.list_id.as_ref().is_some_and(ListId::is_split) {
1006 "분할 압축파일은 미리보기를 지원하지 않습니다"
1007 } else {
1008 "일반 파일 하나를 선택하세요"
1009 },
1010 )
1011 .clicked()
1012 {
1013 self.begin_preview(ui.ctx());
1014 }
1015 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
1016 self.choose_zip_folder();
1017 }
1018 if theme::tool(
1019 ui,
1020 "압축해제",
1021 theme::EXTRACT,
1022 self.model.can_extract(),
1023 true,
1024 )
1025 .clicked()
1026 {
1027 self.open_picker(Purpose::Destination);
1028 }
1029 });
1030 });
1031 egui::Panel::bottom("archive-status")
1032 .exact_size(theme::STATUS_HEIGHT)
1033 .resizable(false)
1034 .frame(
1035 egui::Frame::new()
1036 .fill(theme::STRIPE)
1037 .inner_margin(egui::Margin::symmetric(16, 0)),
1038 )
1039 .show(root, |ui| {
1040 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1041 let selected = rows
1042 .iter()
1043 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
1044 .count();
1045 let rect = ui.max_rect();
1046 let half = (rect.width() - theme::SPACE) / 2.0;
1047 theme::status_text(
1048 ui,
1049 rect,
1050 &format!("{}개 항목", rows.len()),
1051 half,
1052 Align::Min,
1053 );
1054 theme::status_text(ui, rect, &format!("선택 {selected}개"), half, Align::Max);
1055 });
1056 if ctx.embed_viewports() && self.work_visible() && !self.limit_result_visible() {
1057 // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
1058 egui::Panel::bottom("archive-work")
1059 .frame(theme::panel(theme::PANEL).corner_radius(0))
1060 .show(root, |ui| self.work_area(ui));
1061 }
1062 egui::CentralPanel::default()
1063 .frame(
1064 theme::panel(theme::PANEL)
1065 .corner_radius(0)
1066 .inner_margin(egui::Margin::ZERO),
1067 )
1068 .show(root, |ui| {
1069 if self.model.archive.is_some() {
1070 self.archive_list(ui);
1071 } else {
1072 self.empty(ui);
1073 }
1074 });
1075 self.forget_password_history(&ctx);
1076 self.preview_dialog(&ctx);
1077 self.work_window(&ctx);
1078 self.limit_result_dialog(&ctx);
1079 self.create_window(&ctx);
1080 if self.model.challenge.is_some() {
1081 self.password_dialog(&ctx, new_challenge);
1082 }
1083 self.resource_dialog(&ctx);
1084 if self.model.conflict.is_some() && self.model.close == Close::Open {
1085 self.conflict_dialog(&ctx);
1086 }
1087 self.close_dialog(&ctx);
1088 self.picker_notice(&ctx);
1089 if !preview_was_open
1090 && !self.preview_open
1091 && !self.model.busy()
1092 && let Some(id) = self.preview_return_focus.take()
1093 {
1094 ctx.memory_mut(|m| m.request_focus(id));
1095 }
1096 if self.custom_frame {
1097 window_frame::edges(&ctx, true);
1098 }
1099 if self.model.busy() {
1100 ctx.request_repaint_after(std::time::Duration::from_millis(30));
1101 }
1102 }
1103
1104 // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
1105 fn picker_notice(&mut self, ctx: &egui::Context) {
1106 if self.picker.is_none() {
1107 return;
1108 }
1109 egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
1110 ui.set_width(360.0);
1111 ui.label("파일 선택 창에서 선택을 마쳐 주세요");
1112 });
1113 ctx.request_repaint_after(std::time::Duration::from_millis(100));
1114 }
1115
1116 fn empty(&mut self, ui: &mut egui::Ui) {
1117 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
1118 let width = (ui.available_width() * 0.60)
1119 .max(480.0)
1120 .min(ui.available_width());
1121 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
1122 ui.add_space(y);
1123 ui.vertical_centered(|ui| {
1124 let drop_frame = egui::Frame::new()
1125 .fill(if hovered { theme::DROP } else { theme::PANEL })
1126 .corner_radius(theme::DROP_RADIUS)
1127 .inner_margin(egui::Margin::same(theme::DROP_PAD))
1128 .show(ui, |ui| {
1129 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
1130 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
1131 ui.vertical_centered(|ui| {
1132 ui.add_space(theme::PAD as f32);
1133 theme::icon(ui, Icon::Archive, 48.0);
1134 ui.add_space(theme::PAD as f32);
1135 ui.label(
1136 RichText::new(if hovered {
1137 "놓으면 엽니다"
1138 } else {
1139 "압축파일을 여기에 끌어 놓으세요"
1140 })
1141 .size(theme::FONT_LARGE)
1142 .strong(),
1143 );
1144 ui.label("또는");
1145 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
1146 self.open_picker(Purpose::Open);
1147 }
1148 });
1149 });
1150 let rect = drop_frame.response.rect;
1151 if hovered {
1152 ui.painter().rect_stroke(
1153 rect,
1154 12,
1155 egui::Stroke::new(2.0, theme::BLUE),
1156 egui::StrokeKind::Inside,
1157 );
1158 } else {
1159 let stroke = egui::Stroke::new(2.0, theme::DASH);
1160 for (a, b) in [
1161 (rect.left_top(), rect.right_top()),
1162 (rect.right_top(), rect.right_bottom()),
1163 (rect.right_bottom(), rect.left_bottom()),
1164 (rect.left_bottom(), rect.left_top()),
1165 ] {
1166 let direction = (b - a).normalized();
1167 let mut distance = theme::DROP_RADIUS as f32;
1168 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
1169 ui.painter().line_segment(
1170 [
1171 a + direction * distance,
1172 a + direction
1173 * (distance + theme::SPACE)
1174 .min(a.distance(b) - theme::DROP_RADIUS as f32),
1175 ],
1176 stroke,
1177 );
1178 distance += theme::PAD as f32;
1179 }
1180 }
1181 }
1182 ui.add_space(theme::PAD as f32);
1183 ui.colored_label(
1184 theme::MUTED,
1185 "ZIP, 7z, TAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ 파일을 열 수 있습니다",
1186 );
1187 });
1188 }
1189
1190 fn archive_list(&mut self, ui: &mut egui::Ui) {
1191 // 경로 줄은 입력란 높이만 차지하고 창 너비 전체를 회색으로 채움.
1192 let path_row = egui::Frame::new()
1193 .fill(theme::STRIPE)
1194 .inner_margin(egui::Margin {
1195 left: 8,
1196 right: 12,
1197 top: 0,
1198 bottom: 0,
1199 })
1200 .show(ui, |ui| {
1201 ui.set_min_width(ui.available_width());
1202 ui.horizontal(|ui| {
1203 ui.set_height(theme::FIELD);
1204 // 간격은 아래에서 직접 넣어 위치가 흔들리지 않게 함.
1205 ui.spacing_mut().item_spacing.x = 0.0;
1206 let up = theme::flat_icon_button(
1207 ui,
1208 "위로",
1209 theme::UP,
1210 !self.folder.is_empty() && !self.model.busy(),
1211 egui::vec2(theme::FIELD, theme::FIELD),
1212 );
1213 if up.clicked() {
1214 let parent = self
1215 .folder
1216 .rsplit_once('/')
1217 .map_or("", |(parent, _)| parent)
1218 .to_owned();
1219 self.browse_folder(&parent);
1220 }
1221 ui.add_space(6.0);
1222 let path = format!("/{}", self.folder);
1223 let search_width = 240.0;
1224 let gap = 8.0;
1225 let path_width = (ui.available_width() - search_width - gap).max(0.0);
1226 // 두 입력란은 같은 높이의 칸을 받아 같은 세로 위치에 그림.
1227 let (path_rect, _) = ui.allocate_exact_size(
1228 egui::vec2(path_width, theme::FIELD),
1229 egui::Sense::hover(),
1230 );
1231 theme::field_frame(ui, path_rect, false);
1232 // 부모 배치에 영향을 주지 않는 하위 영역에 경로 글자를 그림.
1233 let mut text_ui = ui.new_child(
1234 egui::UiBuilder::new()
1235 .max_rect(path_rect.shrink2(egui::vec2(10.0, 0.0)))
1236 .layout(Layout::left_to_right(Align::Center)),
1237 );
1238 theme::bounded_text(&mut text_ui, &path, (path_width - 20.0).max(0.0));
1239 ui.add_space(gap);
1240 let (search_rect, _) = ui.allocate_exact_size(
1241 egui::vec2(search_width, theme::FIELD),
1242 egui::Sense::hover(),
1243 );
1244 let search_id = egui::Id::unique("archive-search");
1245 let focused = ui.memory(|m| m.has_focus(search_id));
1246 theme::field_frame(ui, search_rect, focused);
1247 let icon = egui::Rect::from_center_size(
1248 egui::pos2(search_rect.left() + 20.0, search_rect.center().y),
1249 egui::vec2(16.0, 16.0),
1250 );
1251 theme::svg_icon(ui.painter(), icon, theme::SEARCH, theme::MUTED);
1252 let search = ui.put(
1253 egui::Rect::from_min_max(
1254 egui::pos2(icon.right() + 8.0, search_rect.top() + 1.0),
1255 egui::pos2(search_rect.right() - 8.0, search_rect.bottom() - 1.0),
1256 ),
1257 egui::TextEdit::singleline(&mut self.search)
1258 .id(search_id)
1259 .frame(egui::Frame::NONE)
1260 .margin(egui::Margin::ZERO)
1261 .align(egui::Align2::LEFT_CENTER)
1262 .hint_text("파일 검색"),
1263 );
1264 if search.changed() {
1265 self.clear_list_selection();
1266 }
1267 });
1268 })
1269 .response
1270 .rect;
1271 // 경로 줄 아래 한 줄이 목록과의 경계이자 입력란의 아래 테두리 역할을 함.
1272 ui.painter().hline(
1273 path_row.x_range(),
1274 path_row.bottom() - 0.5,
1275 egui::Stroke::new(1.0, theme::BORDER),
1276 );
1277 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1278
1279 // 열 제목 줄 없이 바로 목록을 보여 줌. 이름과 크기는 내용으로 구분됨.
1280 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 40.0).max(120.0);
1281 let active = !self.preview_open
1282 && !self.model.busy()
1283 && !self.create
1284 && self.model.challenge.is_none()
1285 && self.model.close == Close::Open;
1286 let list_id = egui::Id::unique("archive-list");
1287 let background = ui.interact(
1288 ui.available_rect_before_wrap(),
1289 list_id,
1290 if active {
1291 egui::Sense::click_and_drag()
1292 } else {
1293 egui::Sense::hover()
1294 },
1295 );
1296 background
1297 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
1298 if background.has_focus() {
1299 ui.ctx().memory_mut(|memory| {
1300 memory.set_focus_lock_filter(
1301 list_id,
1302 egui::EventFilter {
1303 vertical_arrows: true,
1304 escape: true,
1305 ..Default::default()
1306 },
1307 )
1308 });
1309 }
1310 let mut focused = None;
1311 let mut open = None;
1312 let mut next_offset = None;
1313 let output = egui::ScrollArea::vertical()
1314 .id_salt("archive-rows")
1315 .auto_shrink([false, false])
1316 .vertical_scroll_offset(self.list_offset)
1317 .show_viewport(ui, |ui, viewport| {
1318 let origin = ui.max_rect().min;
1319 let clip = ui.clip_rect();
1320 // 행을 누르는 영역은 오른쪽 24px을 비워 둠. 목록이 길어도 그 빈 곳에서
1321 // 끌어서 선택을 시작할 수 있음. 행 배경(선택, 마우스 올림)은 너비를 꽉 채움.
1322 let full_width = ui.available_width();
1323 let width = (full_width - 24.0).max(0.0);
1324 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
1325 let point = ui.input(|i| i.pointer.interact_pos());
1326 if active && let Some(point) = point {
1327 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
1328 let relative = press - origin;
1329 let in_row = relative.x >= 0.0
1330 && relative.x <= width
1331 && relative.y >= 0.0
1332 && relative.y < rows.len() as f32 * LIST_ROW;
1333 if clip.contains(press) && !in_row && ui.input(|i| i.pointer.primary_pressed())
1334 {
1335 background.request_focus();
1336 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
1337 self.marquee = Some(Marquee {
1338 origin: relative.to_pos2(),
1339 base: if ctrl {
1340 self.model.selected.clone()
1341 } else {
1342 BTreeSet::new()
1343 },
1344 moved: false,
1345 });
1346 if !ctrl {
1347 self.model.selected.clear();
1348 self.list_anchor = None;
1349 self.list_cursor = None;
1350 }
1351 }
1352 if let Some(drag) = &mut self.marquee {
1353 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
1354 drag.moved |= drag.origin.distance(end) > 3.0;
1355 if drag.moved {
1356 let rect = egui::Rect::from_two_pos(drag.origin, end);
1357 self.model.selected = drag.base.clone();
1358 if rect.left() < width && rect.right() > 0.0 {
1359 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
1360 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
1361 .min(rows.len());
1362 for row in rows.iter().take(last).skip(first) {
1363 self.model.selected.extend(&row.ids);
1364 }
1365 if first < last {
1366 self.list_anchor = Some(first);
1367 self.list_cursor = Some(last - 1);
1368 }
1369 }
1370 let speed = if point.y > clip.bottom() - 24.0 {
1371 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
1372 } else if point.y < clip.top() + 24.0 {
1373 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
1374 } else {
1375 0.0
1376 };
1377 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
1378 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
1379 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
1380 0.0,
1381 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
1382 ));
1383 ui.ctx().request_repaint();
1384 }
1385 }
1386 }
1387 }
1388 let first = (viewport.min.y / LIST_ROW).floor() as usize;
1389 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
1390 for index in first.min(rows.len())..last {
1391 let row = &rows[index];
1392 let rect = egui::Rect::from_min_size(
1393 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
1394 egui::vec2(width, LIST_ROW),
1395 );
1396 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
1397 let response = ui
1398 .interact(
1399 rect,
1400 egui::Id::unique(("archive-row", &row.path)),
1401 if active {
1402 egui::Sense::click()
1403 } else {
1404 egui::Sense::hover()
1405 },
1406 )
1407 .on_hover_text(&row.name);
1408 theme::pointer(&response);
1409 response.widget_info(|| {
1410 egui::WidgetInfo::selected(
1411 egui::Role::ListBoxOption,
1412 active,
1413 selected,
1414 &row.name,
1415 )
1416 });
1417 if response.has_focus() {
1418 focused = Some(index);
1419 ui.ctx().memory_mut(|memory| {
1420 memory.set_focus_lock_filter(
1421 response.id,
1422 egui::EventFilter {
1423 vertical_arrows: true,
1424 escape: true,
1425 ..Default::default()
1426 },
1427 )
1428 });
1429 }
1430 theme::row_background(
1431 ui,
1432 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW)),
1433 selected,
1434 response.hovered(),
1435 );
1436 if response.clicked() {
1437 background.request_focus();
1438 let modifiers = ui.input(|i| i.modifiers);
1439 self.select_row(
1440 &rows,
1441 index,
1442 modifiers.ctrl || modifiers.command,
1443 modifiers.shift,
1444 );
1445 }
1446 if row.directory && response.double_clicked() {
1447 open = Some(row.path.clone());
1448 }
1449 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
1450 let name = if row.encrypted {
1451 format!("*{}", row.name)
1452 } else {
1453 row.name.clone()
1454 };
1455 Self::entry_cells(
1456 ui,
1457 rect,
1458 row.directory,
1459 &name,
1460 &row.name,
1461 if row.directory {
1462 "0 B".into()
1463 } else {
1464 row.bytes
1465 .map(present::bytes_text)
1466 .unwrap_or_else(|| "—".into())
1467 },
1468 name_width,
1469 );
1470 if active
1471 && self.list_cursor == Some(index)
1472 && (response.has_focus() || background.has_focus())
1473 {
1474 ui.painter().rect_stroke(
1475 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW))
1476 .shrink(1.0),
1477 0,
1478 egui::Stroke::new(1.0, theme::BLUE),
1479 egui::StrokeKind::Inside,
1480 );
1481 }
1482 }
1483 if rows.is_empty() {
1484 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
1485 ui.centered_and_justified(|ui| {
1486 ui.label(if self.search.is_empty() {
1487 "이 폴더는 비어 있습니다"
1488 } else {
1489 "일치하는 항목이 없습니다"
1490 })
1491 });
1492 });
1493 }
1494 #[cfg(all(feature = "ui-fixture", debug_assertions))]
1495 if let Some(rect) = self.scenario_marquee {
1496 ui.painter().with_clip_rect(clip).rect(
1497 rect.translate(origin.to_vec2()),
1498 0,
1499 theme::BLUE.gamma_multiply(0.16),
1500 egui::Stroke::new(1.0, theme::BLUE),
1501 egui::StrokeKind::Inside,
1502 );
1503 }
1504 if let Some(drag) = &self.marquee
1505 && drag.moved
1506 && let Some(point) = point
1507 {
1508 let rect = egui::Rect::from_two_pos(
1509 origin + drag.origin.to_vec2(),
1510 point.clamp(clip.min, clip.max),
1511 );
1512 ui.painter().with_clip_rect(clip).rect(
1513 rect,
1514 0,
1515 theme::BLUE.gamma_multiply(0.16),
1516 egui::Stroke::new(1.0, theme::BLUE),
1517 egui::StrokeKind::Inside,
1518 );
1519 }
1520 });
1521 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
1522 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
1523 self.marquee = None;
1524 }
1525 let escape_from_list = self.list_focused
1526 && ui.ctx().memory(|memory| memory.focused()).is_none()
1527 && ui.input(|i| i.key_pressed(egui::Key::Escape));
1528 self.list_focused =
1529 active && (background.has_focus() || focused.is_some() || escape_from_list);
1530 if self.list_focused {
1531 if let Some(index) = focused {
1532 self.list_cursor = Some(index);
1533 }
1534 let modifiers = ui.input(|i| i.modifiers);
1535 let ctrl = modifiers.ctrl || modifiers.command;
1536 if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
1537 self.model.selected.clear();
1538 self.marquee = None;
1539 background.request_focus();
1540 }
1541 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
1542 self.model.selected = rows
1543 .iter()
1544 .flat_map(|row| row.ids.iter().copied())
1545 .collect();
1546 self.list_cursor = (!rows.is_empty()).then_some(0);
1547 self.list_anchor = self.list_cursor;
1548 }
1549 if !rows.is_empty() {
1550 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
1551 Some(1isize)
1552 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
1553 Some(-1)
1554 } else {
1555 None
1556 };
1557 if let Some(direction) = direction {
1558 let index = self.list_cursor.map_or(0, |index| {
1559 index.saturating_add_signed(direction).min(rows.len() - 1)
1560 });
1561 if ctrl && !modifiers.shift {
1562 self.list_cursor = Some(index);
1563 } else {
1564 self.select_row(&rows, index, ctrl, modifiers.shift);
1565 }
1566 background.request_focus();
1567 let top = index as f32 * LIST_ROW;
1568 if top < self.list_offset {
1569 self.list_offset = top;
1570 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
1571 self.list_offset = top + LIST_ROW - output.inner_rect.height();
1572 }
1573 ui.ctx().request_repaint();
1574 }
1575 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1576 let index = self
1577 .list_cursor
1578 .or(focused)
1579 .unwrap_or(0)
1580 .min(rows.len() - 1);
1581 if rows[index].directory {
1582 open = Some(rows[index].path.clone());
1583 }
1584 }
1585 }
1586 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
1587 open = Some(
1588 self.folder
1589 .rsplit_once('/')
1590 .map_or("", |(parent, _)| parent)
1591 .to_owned(),
1592 );
1593 }
1594 }
1595 if let Some(folder) = open {
1596 self.browse_folder(&folder);
1597 background.request_focus();
1598 }
1599 }
1600
1601 fn clear_list_selection(&mut self) {
1602 self.model.selected.clear();
1603 self.list_anchor = None;
1604 self.list_cursor = None;
1605 self.list_offset = 0.0;
1606 self.marquee = None;
1607 }
1608
1609 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
1610 if shift {
1611 let anchor = self
1612 .list_anchor
1613 .unwrap_or(self.list_cursor.unwrap_or(index))
1614 .min(rows.len() - 1);
1615 if !ctrl {
1616 self.model.selected.clear();
1617 }
1618 for row in &rows[anchor.min(index)..=anchor.max(index)] {
1619 self.model.selected.extend(&row.ids);
1620 }
1621 self.list_anchor = Some(anchor);
1622 } else {
1623 if !ctrl {
1624 self.model.selected.clear();
1625 }
1626 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
1627 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
1628 self.model
1629 .selected
1630 .retain(|id| !rows[index].ids.contains(id));
1631 } else {
1632 self.model.selected.extend(&rows[index].ids);
1633 }
1634 self.list_anchor = Some(index);
1635 }
1636 self.list_cursor = Some(index);
1637 }
1638
1639 fn result_visible(&self) -> bool {
1640 !self.dismissed
1641 && !self
1642 .last_request
1643 .as_ref()
1644 .is_some_and(|r| matches!(r, Start::Preview { .. }))
1645 && !self.model.busy()
1646 && self.last_request.as_ref().is_some_and(|request| {
1647 !matches!(request, Start::List { .. })
1648 || self.model.error.is_some()
1649 || self
1650 .model
1651 .terminal
1652 .as_ref()
1653 .is_some_and(|t| t.outcome != Outcome::Completed)
1654 })
1655 }
1656
1657 fn can_preview(&self) -> bool {
1658 self.model.can_preview()
1659 && browser::rows(&self.model.entries, &self.folder, &self.search)
1660 .iter()
1661 .any(|row| !row.directory && row.ids == self.model.selected)
1662 }
1663
1664 fn begin_preview(&mut self, ctx: &egui::Context) {
1665 if !self.can_preview() || self.picker.is_some() {
1666 return;
1667 }
1668 self.preview_texture = None;
1669 self.preview_text.clear();
1670 self.preview_name = self
1671 .model
1672 .entries
1673 .iter()
1674 .find(|e| self.model.selected.contains(&e.id))
1675 .unwrap()
1676 .name
1677 .clone();
1678 self.preview_return_focus = Some(
1679 ctx.memory(|m| m.focused())
1680 .unwrap_or_else(|| egui::Id::unique("archive-list")),
1681 );
1682 self.preview_initial_focus = true;
1683 let request = Start::Preview {
1684 archive: self.model.archive.clone().unwrap(),
1685 entry_id: *self.model.selected.first().unwrap(),
1686 list_id: self.model.list_id.clone().unwrap(),
1687 };
1688 self.preview_open = true;
1689 self.start(request);
1690 }
1691
1692 fn close_preview(&mut self) {
1693 self.preview_open = false;
1694 self.model.dismiss_preview();
1695 self.preview_texture = None;
1696 self.preview_text.clear();
1697 self.dismissed = true;
1698 }
1699
1700 fn preview_dialog(&mut self, ctx: &egui::Context) {
1701 if !self.preview_open
1702 || self.model.challenge.is_some()
1703 || self.model.resource.is_some()
1704 || self.model.close != Close::Open
1705 {
1706 return;
1707 }
1708 if let Some(preview) = self.model.preview.as_mut()
1709 && (!preview.data.is_empty() || preview.info.total_bytes == 0)
1710 {
1711 match preview.info.format {
1712 PreviewFormat::Utf8Text => {
1713 self.preview_text =
1714 String::from_utf8(std::mem::take(&mut preview.data)).unwrap_or_default();
1715 }
1716 PreviewFormat::Rgba8 => {
1717 let width = preview.info.width as usize;
1718 let height = preview.info.height as usize;
1719 let limit = ctx.input(|i| i.max_texture_side).max(1);
1720 let step = width.div_ceil(limit).max(height.div_ceil(limit)).max(1);
1721 let size = [width.div_ceil(step), height.div_ceil(step)];
1722 let mut colors = Vec::with_capacity(size[0] * size[1]);
1723 for y in (0..height).step_by(step) {
1724 for x in (0..width).step_by(step) {
1725 let index = (y * width + x) * 4;
1726 colors.push(egui::Color32::from_rgba_unmultiplied(
1727 preview.data[index],
1728 preview.data[index + 1],
1729 preview.data[index + 2],
1730 preview.data[index + 3],
1731 ));
1732 }
1733 }
1734 let pixels = egui::ColorImage::new(size, colors);
1735 preview.data = Vec::new();
1736 self.preview_texture = Some(ctx.load_texture(
1737 "archive-preview",
1738 pixels,
1739 egui::TextureOptions::LINEAR,
1740 ));
1741 }
1742 }
1743 }
1744 let mut close = false;
1745 let modal = egui::Modal::new(egui::Id::unique("archive-preview")).show(ctx, |ui| {
1746 ui.set_width((ctx.content_rect().width() - 64.0).clamp(240.0, 760.0));
1747 ui.horizontal(|ui| {
1748 ui.heading("미리보기");
1749 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
1750 let button = theme::flat_icon_button(
1751 ui,
1752 "미리보기 닫기",
1753 theme::CLOSE,
1754 true,
1755 egui::vec2(36.0, 36.0),
1756 );
1757 if self.preview_initial_focus {
1758 button.request_focus();
1759 self.preview_initial_focus = false;
1760 }
1761 close |= button.clicked();
1762 });
1763 });
1764 ui.add(egui::Label::new(&self.preview_name).truncate())
1765 .on_hover_text(&self.preview_name);
1766 let max_height = (ctx.content_rect().height() - 220.0).clamp(100.0, 560.0);
1767 if self.model.busy() {
1768 ui.label("미리보기를 불러오는 중입니다");
1769 if ui.button("취소").clicked() {
1770 close = true;
1771 }
1772 } else if let Some(error) = self.model.error.as_ref() {
1773 Self::error_notice(ui, error);
1774 } else if let Some(texture) = self.preview_texture.as_ref() {
1775 ui.add(
1776 egui::Image::new(texture)
1777 .max_size(egui::vec2(ui.available_width(), max_height))
1778 .shrink_to_fit(),
1779 );
1780 } else if self.model.preview.is_some() {
1781 egui::ScrollArea::both()
1782 .id_salt("preview-text")
1783 .max_height(max_height)
1784 .show(ui, |ui| {
1785 let mut text = self.preview_text.as_str();
1786 ui.add(
1787 egui::TextEdit::multiline(&mut text)
1788 .desired_width(ui.available_width())
1789 .desired_rows(12)
1790 .frame(egui::Frame::NONE),
1791 );
1792 });
1793 if self.preview_text.is_empty() {
1794 ui.label("빈 텍스트 파일입니다");
1795 }
1796 } else {
1797 let code = self.model.terminal.as_ref().and_then(|t| t.error);
1798 ui.label(match code {
1799 Some(ErrorCode::Limit) => "미리보기 크기 또는 처리 한도를 초과했습니다.",
1800 Some(ErrorCode::Integrity) => "파일이 손상됐거나 UTF-8 텍스트가 아닙니다.",
1801 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature) => {
1802 "이 파일 형식은 미리보기를 지원하지 않습니다."
1803 }
1804 Some(ErrorCode::SourceChanged) => "압축파일이 변경됐습니다. 다시 열어 주세요.",
1805 Some(ErrorCode::WrongPassword) => "암호가 올바르지 않습니다.",
1806 _ => "미리보기를 불러오지 못했습니다.",
1807 });
1808 ui.label("닫은 뒤 파일을 선택하고 [압축해제]를 사용할 수 있습니다.");
1809 }
1810 });
1811 if close || modal.should_close() {
1812 self.close_preview();
1813 }
1814 }
1815
1816 fn limit_result_visible(&self) -> bool {
1817 self.result_visible()
1818 && (self.model.volume_problem.is_some()
1819 || self.model.terminal.as_ref().is_some_and(|terminal| {
1820 terminal.error == Some(ErrorCode::Limit)
1821 || (matches!(
1822 terminal.error,
1823 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature)
1824 ) && self
1825 .model
1826 .archive
1827 .as_ref()
1828 .is_some_and(|p| present::excluded_split(p)))
1829 }))
1830 }
1831
1832 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
1833 if !self.limit_result_visible() || self.main_modal_open() {
1834 return;
1835 }
1836 egui::Modal::new(egui::Id::new("archive-limit-result")).show(ctx, |ui| {
1837 ui.set_width((ctx.content_rect().width() - 64.0).min(WORK_WIDTH));
1838 ui.heading("작업 결과");
1839 self.work_area(ui);
1840 });
1841 }
1842
1843 fn error_notice(ui: &mut egui::Ui, error: &str) {
1844 let response = theme::panel(theme::ERROR_BG)
1845 .show(ui, |ui| {
1846 ui.horizontal_wrapped(|ui| {
1847 theme::icon(ui, Icon::Error, 24.0);
1848 ui.colored_label(theme::ERROR, error);
1849 });
1850 })
1851 .response;
1852 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
1853 }
1854
1855 fn work_visible(&self) -> bool {
1856 !self
1857 .last_request
1858 .as_ref()
1859 .is_some_and(|r| matches!(r, Start::Preview { .. }))
1860 && (self.model.busy()
1861 || self.result_visible()
1862 || (self.ui_error.is_some() && !self.create))
1863 }
1864
1865 /// 메인 창 가운데에 모달(암호 입력, 종료 확인, 파일 선택 안내)이나 같은 자리에 뜨는
1866 /// ZIP 만들기 창이 떠 있는지. 닫기가 정해진 뒤(Allowed)에도 결과 창을 다시 띄우지 않음.
1867 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
1868 fn main_modal_open(&self) -> bool {
1869 (self.create && !self.model.busy())
1870 || self.picker.is_some()
1871 || self.model.challenge.is_some()
1872 || self.model.resource.is_some()
1873 || self.model.conflict.is_some()
1874 || self.model.close != Close::Open
1875 }
1876
1877 fn work_window(&mut self, ctx: &egui::Context) {
1878 if !self.work_visible() {
1879 self.work = WorkWindow::default();
1880 return;
1881 }
1882 if self.limit_result_visible() {
1883 self.work.open = false;
1884 return;
1885 }
1886 if ctx.embed_viewports() {
1887 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
1888 return;
1889 }
1890 if self.main_modal_open() {
1891 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
1892 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
1893 self.work.open = false;
1894 return;
1895 }
1896 let id = egui::ViewportId::from_hash_of("archive-work");
1897 let title = if self.model.busy() {
1898 present::activity_text(
1899 &self.model,
1900 matches!(
1901 self.last_request,
1902 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
1903 ),
1904 )
1905 .to_owned()
1906 } else {
1907 "작업 결과".to_owned()
1908 };
1909 let window_title = format!("{title} — Zipelo");
1910 let custom_frame = self.custom_frame;
1911 let size = egui::vec2(WORK_WIDTH, self.work.height);
1912 let builder = self.work.builder(
1913 ctx,
1914 id,
1915 size,
1916 &window_title,
1917 !custom_frame,
1918 self.picker.is_some(),
1919 );
1920 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
1921 if ui.ctx().input(|i| i.viewport().close_requested()) {
1922 if self.model.busy() {
1923 ui.ctx()
1924 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
1925 } else {
1926 self.dismissed = true;
1927 self.ui_error = None;
1928 self.model.input_error = None;
1929 }
1930 }
1931 if class == egui::ViewportClass::EmbeddedWindow {
1932 ui.set_width(WORK_WIDTH);
1933 self.work_area(ui);
1934 return None;
1935 }
1936 let mut chrome = 0.0;
1937 if custom_frame {
1938 window_frame::title_bar(
1939 ui,
1940 "work",
1941 &window_title,
1942 window_frame::Buttons {
1943 minimize: false,
1944 maximize: false,
1945 },
1946 );
1947 window_frame::edges(ui.ctx(), false);
1948 chrome = window_frame::TITLE_HEIGHT;
1949 }
1950 let margin = theme::PAD as f32;
1951 egui::CentralPanel::default()
1952 .frame(theme::panel(theme::PANEL).corner_radius(0))
1953 .show(ui, |ui| {
1954 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
1955 Some(content.height() + 2.0 * margin + chrome)
1956 })
1957 .inner
1958 });
1959 if let Some(height) = height {
1960 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
1961 if (height - self.work.height).abs() > 1.0 {
1962 self.work.height = height;
1963 }
1964 }
1965 }
1966
1967 fn work_area(&mut self, ui: &mut egui::Ui) {
1968 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
1969 let enabled = self.picker.is_none();
1970 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
1971 }
1972
1973 fn work_contents(&mut self, ui: &mut egui::Ui) {
1974 if self.model.busy() {
1975 self.progress(ui);
1976 } else if self.result_visible() {
1977 self.result(ui);
1978 }
1979 if !self.create
1980 && let Some(error) = &self.ui_error
1981 {
1982 Self::error_notice(ui, error);
1983 if error == present::FOLDER_ERROR
1984 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
1985 {
1986 self.open_picker(Purpose::Destination);
1987 }
1988 }
1989 if let Some(error) = &self.model.input_error {
1990 ui.colored_label(
1991 theme::ERROR,
1992 if error.starts_with("암호는") {
1993 error.as_str()
1994 } else {
1995 if matches!(
1996 self.last_request,
1997 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
1998 ) {
1999 "저장 위치와 추가한 항목을 확인하세요"
2000 } else {
2001 "풀 위치와 선택한 항목을 확인하세요"
2002 }
2003 },
2004 );
2005 }
2006 }
2007
2008 fn progress(&mut self, ui: &mut egui::Ui) {
2009 if self.model.resource.is_some() {
2010 ui.horizontal(|ui| {
2011 ui.label("사용자 허용을 기다리고 있습니다");
2012 self.cancel_action(ui, false);
2013 });
2014 return;
2015 }
2016 let creating = matches!(
2017 self.last_request,
2018 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2019 );
2020 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
2021 let title = present::activity_text(&self.model, creating);
2022 ui.strong(title);
2023 if let Some((stage, done, total, count)) = self.model.progress {
2024 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
2025 let processed = if stage == Stage::Read {
2026 String::new()
2027 } else {
2028 format!("{count}개 처리함, ")
2029 };
2030 if let Some(total) = total.filter(|n| *n > 0) {
2031 ui.scope(|ui| {
2032 ui.visuals_mut().extreme_bg_color = theme::BORDER;
2033 ui.add(
2034 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
2035 .fill(theme::BLUE)
2036 .desired_height(theme::SPACE * 2.0),
2037 );
2038 });
2039 ui.horizontal(|ui| {
2040 ui.label(format!(
2041 "{:.0}% / {processed}{} / {}",
2042 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
2043 present::bytes_text(done),
2044 present::bytes_text(total)
2045 ));
2046 self.cancel_action(ui, cancelling);
2047 });
2048 } else {
2049 theme::indeterminate(ui);
2050 ui.horizontal(|ui| {
2051 ui.label(format!("{processed}{}", present::bytes_text(done)));
2052 self.cancel_action(ui, cancelling);
2053 });
2054 }
2055 } else {
2056 theme::indeterminate(ui);
2057 ui.horizontal(|ui| {
2058 ui.label("작업을 진행하고 있습니다");
2059 self.cancel_action(ui, cancelling);
2060 });
2061 }
2062 }
2063
2064 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
2065 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2066 if theme::action(ui, "취소", false, !cancelling).clicked() {
2067 self.clear_password();
2068 self.model.cancel();
2069 }
2070 });
2071 }
2072
2073 fn result(&mut self, ui: &mut egui::Ui) {
2074 let t = self.model.terminal.clone();
2075 let listing = matches!(self.last_request, Some(Start::List { .. }));
2076 let creating = matches!(
2077 self.last_request,
2078 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
2079 );
2080 let resolved_targets = present::resolved_targets(
2081 self.targets.as_ref(),
2082 &self.model.entries,
2083 matches!(
2084 self.last_request,
2085 Some(Start::Extract {
2086 gzip_output_name: Some(_),
2087 ..
2088 })
2089 )
2090 .then_some(self.gzip_name.as_str()),
2091 &self.model.resolutions,
2092 );
2093 let skipped = self
2094 .model
2095 .resolutions
2096 .iter()
2097 .filter(|r| r.choice == ConflictChoice::Skip)
2098 .count();
2099 let created_names = self
2100 .model
2101 .outputs
2102 .iter()
2103 .filter(|(_, disposition)| *disposition == Disposition::Created)
2104 .map(|(name, _)| name.replace('\\', "/"))
2105 .collect::<BTreeSet<_>>();
2106 let warnings = if listing {
2107 Vec::new()
2108 } else {
2109 present::publication_warnings(
2110 t.as_ref(),
2111 self.model.confirmed,
2112 resolved_targets.as_ref(),
2113 &self.directories,
2114 &self.model.outputs,
2115 )
2116 };
2117 let success = self.model.confirmed
2118 && self.model.error.is_none()
2119 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
2120 && warnings.is_empty();
2121 let durability_warning = t
2122 .as_ref()
2123 .filter(|_| self.model.confirmed && !listing)
2124 .and_then(|t| present::durability_warning(t.durability));
2125 let durability_in_details = success
2126 && t.as_ref()
2127 .is_some_and(|t| t.durability == Durability::Unconfirmed);
2128 let cancelled =
2129 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
2130 let title = if success {
2131 if creating {
2132 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2133 "7z 파일을 만들었습니다"
2134 } else {
2135 "ZIP 파일을 만들었습니다"
2136 }
2137 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
2138 "모든 파일을 건너뛰었습니다"
2139 } else {
2140 "압축을 풀었습니다"
2141 }
2142 } else if cancelled {
2143 "작업을 취소했습니다"
2144 } else if listing {
2145 "압축파일을 열지 못했습니다"
2146 } else if creating {
2147 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2148 "7z 파일을 만들지 못했습니다"
2149 } else {
2150 "ZIP 파일을 만들지 못했습니다"
2151 }
2152 } else {
2153 "압축을 풀지 못했습니다"
2154 };
2155 let fill = if success {
2156 theme::SUCCESS_BG
2157 } else if cancelled {
2158 theme::STRIPE
2159 } else {
2160 theme::ERROR_BG
2161 };
2162 let mut choose = false;
2163 let mut retry = false;
2164 let mut expand = false;
2165 let mut reopen = false;
2166 let mut folder = false;
2167 theme::panel(fill).show(ui, |ui| {
2168 ui.horizontal(|ui| {
2169 theme::icon(
2170 ui,
2171 if success {
2172 Icon::Success
2173 } else if cancelled {
2174 Icon::Warning
2175 } else {
2176 Icon::Error
2177 },
2178 24.0,
2179 );
2180 ui.strong(title);
2181 });
2182 let max_height = WORK_RESULT_MAX_HEIGHT;
2183 egui::ScrollArea::vertical()
2184 .id_salt("result-message")
2185 .max_height(max_height)
2186 .show(ui, |ui| {
2187 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
2188 let path = match self.last_request.as_ref() {
2189 Some(
2190 Start::CreateZip { output_file, .. }
2191 | Start::CreateSevenZip { output_file, .. },
2192 ) => output_file.display().to_string(),
2193 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
2194 };
2195 theme::bounded_text(ui, &path, ui.available_width());
2196 } else if let Some(problem) = &self.model.volume_problem {
2197 ui.add(egui::Label::new(present::volume_problem_text(problem)).wrap());
2198 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
2199 ui.label(
2200 if matches!(
2201 code,
2202 ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature
2203 ) && self
2204 .model
2205 .archive
2206 .as_ref()
2207 .is_some_and(|p| present::excluded_split(p))
2208 {
2209 present::SPLIT_SUPPORT.to_owned()
2210 } else if creating && code == ErrorCode::SourceChanged {
2211 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
2212 .to_owned()
2213 } else {
2214 present::operation_text(present::error_text(code), creating)
2215 },
2216 );
2217 } else if let Some(error) = &self.model.error {
2218 ui.label(present::operation_text(
2219 present::client_error_text(error),
2220 creating,
2221 ));
2222 }
2223 if skipped > 0 {
2224 ui.label(format!("건너뛴 파일 {skipped}개"));
2225 }
2226 for resolution in self.model.resolutions.iter().filter(|r| {
2227 r.choice == ConflictChoice::Rename
2228 && created_names.contains(&r.relative_name.replace('\\', "/"))
2229 }) {
2230 theme::bounded_text(
2231 ui,
2232 &format!("이름 바꿔 저장: {}", resolution.relative_name),
2233 ui.available_width(),
2234 );
2235 }
2236 for warning in warnings
2237 .iter()
2238 .copied()
2239 .chain(durability_warning.filter(|_| !durability_in_details))
2240 {
2241 ui.horizontal_wrapped(|ui| {
2242 theme::icon(ui, Icon::Warning, 20.0);
2243 ui.colored_label(
2244 theme::WARNING,
2245 present::operation_text(warning, creating),
2246 );
2247 });
2248 }
2249 if !success
2250 && !listing
2251 && present::definitely_unsaved(
2252 t.as_ref(),
2253 self.model.confirmed,
2254 &self.model.outputs,
2255 )
2256 {
2257 ui.label(if creating {
2258 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
2259 "7z 파일을 만들지 않았습니다"
2260 } else {
2261 "ZIP 파일을 만들지 않았습니다"
2262 }
2263 } else {
2264 "아무 파일도 풀지 않았습니다"
2265 });
2266 }
2267 if t.as_ref().is_some_and(|t| {
2268 t.error == Some(ErrorCode::Limit)
2269 && (t.created_count > 0
2270 || t.retained_partial_count > 0
2271 || t.publication != Publication::None)
2272 }) {
2273 ui.label(format!(
2274 "{}개 파일이 저장되었거나 일부 남아 있습니다. 저장 위치를 확인하세요.",
2275 t.as_ref().unwrap().created_count
2276 ));
2277 theme::bounded_text(
2278 ui,
2279 &self.destination.display().to_string(),
2280 ui.available_width(),
2281 );
2282 }
2283 if self.details {
2284 theme::panel(theme::STRIPE).show(ui, |ui| {
2285 if durability_in_details {
2286 if let Some(warning) = durability_warning {
2287 ui.label(present::operation_text(warning, creating));
2288 }
2289 }
2290 if let Some(t) = &t {
2291 for line in terminal_lines(t) {
2292 ui.label(line);
2293 }
2294 }
2295 if let Some(error) = &self.model.error {
2296 ui.label(error);
2297 }
2298 for (name, state) in &self.model.outputs {
2299 theme::bounded_text(
2300 ui,
2301 &format!("{name}: {}", disposition_label(*state)),
2302 ui.available_width(),
2303 );
2304 }
2305 });
2306 }
2307 });
2308 let conflict = t
2309 .as_ref()
2310 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
2311 && !creating;
2312 let uncertain = warnings.contains(&present::UNCERTAIN);
2313 if conflict && uncertain {
2314 let response = ui.checkbox(
2315 &mut self.checked_destination,
2316 "기존 풀 위치 폴더를 확인했습니다",
2317 );
2318 theme::pointer(&response);
2319 theme::focus(&response);
2320 }
2321 ui.horizontal(|ui| {
2322 if theme::action(
2323 ui,
2324 if self.details {
2325 "자세히 닫기"
2326 } else {
2327 "자세히 보기"
2328 },
2329 false,
2330 true,
2331 )
2332 .clicked()
2333 {
2334 self.details = !self.details;
2335 }
2336 let action = if success {
2337 Some(("폴더 열기", true))
2338 } else if conflict {
2339 Some((
2340 if self
2341 .model
2342 .list_id
2343 .as_ref()
2344 .is_some_and(|id| id.format == Format::Gzip)
2345 {
2346 "다른 이름으로 저장"
2347 } else {
2348 "다른 폴더에 풀기"
2349 },
2350 !uncertain || self.checked_destination,
2351 ))
2352 } else if t
2353 .as_ref()
2354 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
2355 {
2356 Some((
2357 if creating {
2358 "다시 만들기"
2359 } else {
2360 "압축파일 다시 열기"
2361 },
2362 true,
2363 ))
2364 } else if self.model.can_retry_expanded() {
2365 None
2366 } else if t
2367 .as_ref()
2368 .is_some_and(|t| t.error == Some(ErrorCode::Limit))
2369 {
2370 None
2371 } else if !cancelled && (!uncertain || listing) {
2372 Some(("다시 시도", true))
2373 } else {
2374 None
2375 };
2376 let (confirm, primary) = theme::action_pair(ui, "확인", action);
2377 if confirm {
2378 self.dismissed = true;
2379 self.ui_error = None;
2380 self.model.input_error = None;
2381 }
2382 if primary {
2383 match action.map(|(label, _)| label) {
2384 Some("폴더 열기") => folder = true,
2385 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
2386 choose = true
2387 }
2388 Some("압축파일 다시 열기") => reopen = true,
2389 Some("다시 시도" | "다시 만들기") => retry = true,
2390 _ => {}
2391 }
2392 }
2393 });
2394 if self.model.can_retry_expanded() {
2395 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2396 expand = theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked();
2397 });
2398 }
2399 });
2400 if choose {
2401 self.open_picker(Purpose::Retry);
2402 }
2403 if retry {
2404 self.retry();
2405 }
2406 if expand {
2407 let ready = if matches!(self.last_request, Some(Start::Extract { .. })) {
2408 match present::prepare_destination(&self.destination, self.automatic_destination) {
2409 Ok(created) => {
2410 self.owned_destination = created.then(|| self.destination.clone());
2411 true
2412 }
2413 Err(_) => {
2414 self.ui_error = Some(present::FOLDER_ERROR.into());
2415 false
2416 }
2417 }
2418 } else {
2419 true
2420 };
2421 if ready && self.model.retry_expanded(self.factory.as_mut()) {
2422 self.dismissed = false;
2423 self.details = false;
2424 self.ui_error = None;
2425 }
2426 }
2427 if reopen {
2428 if let Some(path) = self.model.archive.clone() {
2429 self.open_path(path);
2430 }
2431 }
2432 if folder {
2433 let path = match self.last_request.as_ref() {
2434 Some(
2435 Start::CreateZip { output_file, .. }
2436 | Start::CreateSevenZip { output_file, .. },
2437 ) => output_file.parent().unwrap_or(Path::new("/")),
2438 _ => self.destination.as_path(),
2439 };
2440 match present::folder_command(path).spawn() {
2441 Ok(mut child) => {
2442 std::thread::spawn(move || {
2443 let _ = child.wait();
2444 });
2445 }
2446 Err(_) => {
2447 self.ui_error = Some(
2448 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
2449 )
2450 }
2451 }
2452 }
2453 }
2454
2455 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
2456 fn entry_cells(
2457 ui: &mut egui::Ui,
2458 rect: egui::Rect,
2459 directory: bool,
2460 name: &str,
2461 hover: &str,
2462 size: String,
2463 name_width: f32,
2464 ) {
2465 ui.scope_builder(
2466 egui::UiBuilder::new()
2467 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
2468 .layout(Layout::left_to_right(Align::Center)),
2469 |ui| {
2470 ui.style_mut().interaction.selectable_labels = false;
2471 ui.add_space(16.0);
2472 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
2473 theme::bounded_text_hover(ui, name, hover, name_width);
2474 theme::column_label(ui, size, 96.0, Align::Max);
2475 },
2476 );
2477 }
2478
2479 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
2480 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
2481 fn create_window(&mut self, ctx: &egui::Context) {
2482 if !self.create || self.model.busy() {
2483 self.create_win = WorkWindow::default();
2484 return;
2485 }
2486 if ctx.embed_viewports() {
2487 let mut close = false;
2488 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
2489 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
2490 ui.horizontal(|ui| {
2491 ui.heading(if self.seven_zip {
2492 "7z 만들기"
2493 } else {
2494 "ZIP 만들기"
2495 });
2496 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2497 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
2498 close = button.clicked();
2499 });
2500 });
2501 close |= self.create_area(ui);
2502 ui.add_space(theme::SPACE);
2503 close |= self.create_actions(ui);
2504 });
2505 if close || modal.should_close() {
2506 self.close_create();
2507 }
2508 return;
2509 }
2510 let id = egui::ViewportId::from_hash_of("archive-create");
2511 let title = if self.seven_zip {
2512 "7z 만들기 — Zipelo"
2513 } else {
2514 "ZIP 만들기 — Zipelo"
2515 };
2516 let custom_frame = self.custom_frame;
2517 if !self.create_win.open {
2518 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
2519 }
2520 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
2521 let builder =
2522 self.create_win
2523 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
2524 let mut close = false;
2525 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
2526 if ui.ctx().input(|i| i.viewport().close_requested()) {
2527 close = true;
2528 }
2529 if class == egui::ViewportClass::EmbeddedWindow {
2530 ui.set_width(CREATE_WIDTH);
2531 close |= self.create_area(ui);
2532 close |= self.create_actions(ui);
2533 return None;
2534 }
2535 let mut chrome = 0.0;
2536 if custom_frame {
2537 window_frame::title_bar(
2538 ui,
2539 "create",
2540 title,
2541 window_frame::Buttons {
2542 minimize: false,
2543 maximize: false,
2544 },
2545 );
2546 window_frame::edges(ui.ctx(), false);
2547 chrome = window_frame::TITLE_HEIGHT;
2548 }
2549 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
2550 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
2551 .resizable(false)
2552 .show_separator_line(false)
2553 .frame(
2554 egui::Frame::new()
2555 .fill(theme::PANEL)
2556 .inner_margin(egui::Margin {
2557 left: theme::PAD,
2558 right: theme::PAD,
2559 top: 0,
2560 bottom: theme::PAD,
2561 }),
2562 )
2563 .show(ui, |ui| close |= self.create_actions(ui))
2564 .response
2565 .rect
2566 .height();
2567 let margin = theme::PAD as f32;
2568 egui::CentralPanel::default()
2569 .frame(theme::panel(theme::PANEL).corner_radius(0))
2570 .show(ui, |ui| {
2571 let content = ui
2572 .vertical(|ui| close |= self.create_area(ui))
2573 .response
2574 .rect;
2575 Some(content.height() + 2.0 * margin + chrome + actions)
2576 })
2577 .inner
2578 });
2579 if let Some(height) = height {
2580 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
2581 if (height - self.create_win.height).abs() > 1.0 {
2582 self.create_win.height = height;
2583 }
2584 }
2585 if close {
2586 self.close_create();
2587 }
2588 }
2589
2590 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
2591 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
2592 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
2593 let enabled = self.picker.is_none();
2594 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
2595 .inner
2596 }
2597
2598 fn set_seven_zip(&mut self, selected: bool) {
2599 if self.seven_zip == selected {
2600 return;
2601 }
2602 self.seven_zip = selected;
2603 self.aes256 = false;
2604 self.clear_zip_password();
2605 self.ui_error = None;
2606 let name = self.zip_name.clone();
2607 let lower = name.to_ascii_lowercase();
2608 let stem = if lower.ends_with(".zip") {
2609 &name[..name.len() - 4]
2610 } else if lower.ends_with(".7z") {
2611 &name[..name.len() - 3]
2612 } else {
2613 &name
2614 };
2615 self.zip_name = format!("{stem}{}", if selected { ".7z" } else { ".zip" });
2616 }
2617
2618 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
2619 let mut selected = self.seven_zip;
2620 ui.horizontal(|ui| {
2621 ui.label("형식");
2622 ui.selectable_value(&mut selected, false, "ZIP");
2623 ui.selectable_value(&mut selected, true, "7z");
2624 if selected {
2625 ui.label("LZMA2");
2626 }
2627 });
2628 self.set_seven_zip(selected);
2629
2630 let rows = self.create_rows();
2631 let root = self.create_root();
2632
2633 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
2634 ui.horizontal(|ui| {
2635 ui.set_height(theme::FIELD);
2636 ui.spacing_mut().item_spacing.x = 0.0;
2637 let up = theme::flat_icon_button(
2638 ui,
2639 "위로",
2640 theme::UP,
2641 !self.create_folder.is_empty(),
2642 egui::vec2(theme::FIELD, theme::FIELD),
2643 );
2644 if up.clicked() {
2645 self.create_folder = self
2646 .create_folder
2647 .rsplit_once('/')
2648 .map_or("", |(parent, _)| parent)
2649 .to_owned();
2650 self.create_selected = None;
2651 }
2652 ui.add_space(6.0);
2653 let path = match &root {
2654 Some(root) => {
2655 let name = root.file_name().unwrap_or_default().to_string_lossy();
2656 if self.create_folder.is_empty() {
2657 format!("/{name}")
2658 } else {
2659 format!("/{name}/{}", self.create_folder)
2660 }
2661 }
2662 None => "/".to_owned(),
2663 };
2664 let (rect, _) = ui.allocate_exact_size(
2665 egui::vec2(ui.available_width(), theme::FIELD),
2666 egui::Sense::hover(),
2667 );
2668 theme::boxed_field(ui, rect);
2669 theme::field_text(ui, rect, &path);
2670 });
2671 ui.add_space(theme::SPACE);
2672
2673 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
2674 let mut enter = None;
2675 egui::Frame::new()
2676 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2677 .show(ui, |ui| {
2678 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
2679 ui.set_max_height(CREATE_LIST_HEIGHT);
2680 let message = match &rows {
2681 None => Some("폴더를 읽지 못했습니다"),
2682 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
2683 Some(_) => None,
2684 };
2685 if let Some(message) = message {
2686 ui.centered_and_justified(|ui| ui.label(message));
2687 return;
2688 }
2689 let rows = rows.unwrap();
2690 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
2691 egui::ScrollArea::vertical()
2692 .id_salt("create-rows")
2693 .auto_shrink([false, false])
2694 .max_height(CREATE_LIST_HEIGHT)
2695 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
2696 for row in &rows[range] {
2697 let (rect, response) = ui.allocate_exact_size(
2698 egui::vec2(ui.available_width(), LIST_ROW),
2699 egui::Sense::click(),
2700 );
2701 let response = response.on_hover_text(&row.name);
2702 theme::pointer(&response);
2703 response.widget_info(|| {
2704 egui::WidgetInfo::labeled(
2705 egui::Role::ListBoxOption,
2706 true,
2707 &row.name,
2708 )
2709 });
2710 if response.clicked() {
2711 self.create_selected = Some(row.name.clone());
2712 }
2713 theme::row_background(
2714 ui,
2715 rect,
2716 self.create_selected.as_deref() == Some(row.name.as_str()),
2717 response.hovered(),
2718 );
2719 if row.directory && root.is_some() && response.clicked() {
2720 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
2721 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
2722 let frame = ui.ctx().cumulative_frame_nr();
2723 let time = ui.input(|i| i.time);
2724 match &self.create_last_click {
2725 Some((name, last_frame, last_time))
2726 if name == &row.name
2727 && *last_frame != frame
2728 && time - last_time < 0.4 =>
2729 {
2730 enter = Some(row.name.clone());
2731 self.create_last_click = None;
2732 }
2733 Some((name, last_frame, _))
2734 if name == &row.name && *last_frame == frame => {}
2735 _ => {
2736 self.create_last_click =
2737 Some((row.name.clone(), frame, time));
2738 }
2739 }
2740 }
2741 Self::entry_cells(
2742 ui,
2743 rect,
2744 row.directory,
2745 &row.name,
2746 &row.name,
2747 row.bytes.map(present::bytes_text).unwrap_or_default(),
2748 name_width,
2749 );
2750 }
2751 });
2752 });
2753 if let Some(name) = enter {
2754 self.create_folder = if self.create_folder.is_empty() {
2755 name
2756 } else {
2757 format!("{}/{name}", self.create_folder)
2758 };
2759 self.create_selected = None;
2760 }
2761 ui.add_space(theme::SPACE);
2762
2763 if let Some(error) = &self.ui_error {
2764 Self::error_notice(ui, error);
2765 }
2766
2767 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
2768 if self.seven_zip {
2769 ui.label("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요");
2770 return false;
2771 }
2772 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
2773 theme::pointer(&check);
2774 theme::focus(&check);
2775 if self.aes256 {
2776 let label_width = 72.0;
2777 ui.horizontal(|ui| {
2778 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
2779 let toggle = if self.zip_password_visible {
2780 "숨기기"
2781 } else {
2782 "보기"
2783 };
2784 let toggle_width = 72.0;
2785 let edit = ui.add_sized(
2786 [
2787 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
2788 theme::FIELD,
2789 ],
2790 egui::TextEdit::singleline(&mut self.zip_password)
2791 .password(!self.zip_password_visible)
2792 .id(egui::Id::unique("zip-password-input"))
2793 .char_limit(1024)
2794 .align(egui::Align2::LEFT_CENTER),
2795 );
2796 theme::focus(&edit);
2797 if theme::action(ui, toggle, false, true).clicked() {
2798 self.zip_password_visible = !self.zip_password_visible;
2799 }
2800 });
2801 ui.horizontal(|ui| {
2802 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
2803 let edit = ui.add_sized(
2804 [
2805 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
2806 theme::FIELD,
2807 ],
2808 egui::TextEdit::singleline(&mut self.zip_password_confirm)
2809 .password(!self.zip_password_visible)
2810 .id(egui::Id::unique("zip-password-confirm"))
2811 .char_limit(1024)
2812 .align(egui::Align2::LEFT_CENTER),
2813 );
2814 theme::focus(&edit);
2815 });
2816 if self.zip_password.len() > 1024 {
2817 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
2818 } else if !self.zip_password_confirm.is_empty()
2819 && self.zip_password != self.zip_password_confirm
2820 {
2821 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
2822 }
2823 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
2824 } else if check.changed()
2825 || !self.zip_password.is_empty()
2826 || !self.zip_password_confirm.is_empty()
2827 {
2828 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
2829 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
2830 self.clear_zip_password();
2831 }
2832 false
2833 }
2834
2835 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
2836 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
2837 let ready = !self.sources.is_empty() && self.zip_password_ready();
2838 let enabled = self.picker.is_none();
2839 let (cancel, compress) = ui
2840 .add_enabled_ui(enabled, |ui| {
2841 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
2842 })
2843 .inner;
2844 if compress {
2845 self.open_picker(if self.seven_zip {
2846 Purpose::SaveSevenZip
2847 } else {
2848 Purpose::SaveZip
2849 });
2850 }
2851 cancel
2852 }
2853
2854 fn resource_dialog(&mut self, ctx: &egui::Context) {
2855 let Some(question) = self.model.resource.clone() else {
2856 return;
2857 };
2858 let Some(job) = self.model.job_id() else {
2859 return;
2860 };
2861 let mut allow = false;
2862 let mut cancel = false;
2863 let modal = egui::Modal::new(egui::Id::unique(("archive-resource", job, question.id)))
2864 .show(ctx, |ui| {
2865 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
2866 ui.heading(if question.scope.ratio {
2867 "압축률이 매우 높습니다"
2868 } else {
2869 "큰 작업을 허용할까요?"
2870 });
2871 ui.label(match question.action {
2872 ActionKind::List => "압축파일 목록 열기",
2873 ActionKind::Extract => "압축 해제",
2874 ActionKind::CreateZip => "ZIP 만들기",
2875 ActionKind::CreateSevenZip => "7z 만들기",
2876 ActionKind::Preview => "파일 미리보기",
2877 });
2878 if question.scope.ratio {
2879 ui.label("작은 압축파일도 많은 저장 공간을 사용할 수 있습니다.");
2880 }
2881 if question.scope.output {
2882 ui.label(format!(
2883 "총량 한도: {}에서 {}로",
2884 present::bytes_text(question.soft_limits.output),
2885 present::bytes_text(question.ceiling.output)
2886 ));
2887 }
2888 if question.scope.entries {
2889 ui.label(format!(
2890 "항목 한도: {}개에서 {}개로",
2891 question.soft_limits.entries, question.ceiling.entries
2892 ));
2893 }
2894 let mut u = question.usage;
2895 let estimated = self.model.estimated_usage();
2896 u.estimated_bytes = u.estimated_bytes.or(estimated.estimated_bytes);
2897 u.estimated_entries = u.estimated_entries.or(estimated.estimated_entries);
2898 let bytes = |value: Option<u64>| {
2899 value
2900 .map(present::bytes_text)
2901 .unwrap_or_else(|| "미확인".into())
2902 };
2903 let entries = |value: Option<u32>| {
2904 value
2905 .map(|n| format!("{n}개"))
2906 .unwrap_or_else(|| "미확인".into())
2907 };
2908 ui.label(format!(
2909 "예상 총량: {} / 실제 총량: {}",
2910 bytes(u.estimated_bytes),
2911 bytes(u.actual_bytes)
2912 ));
2913 ui.label(format!(
2914 "예상 항목: {} / 실제 항목: {}",
2915 entries(u.estimated_entries),
2916 entries(u.actual_entries)
2917 ));
2918 if question.scope.ratio {
2919 ui.label(format!(
2920 "압축 크기: {} / 풀린 크기: {}",
2921 bytes(u.compressed_bytes),
2922 bytes(u.ratio_output_bytes)
2923 ));
2924 }
2925 ui.label(format!(
2926 "확인한 저장 볼륨의 여유 공간: {}",
2927 bytes(u.available_bytes)
2928 ));
2929 ui.label(format!(
2930 "이 작업의 상한: {} / {}개",
2931 present::bytes_text(question.ceiling.output),
2932 question.ceiling.entries
2933 ));
2934 ui.label("이 작업에만 적용합니다. 공간 부족이나 자원 상한에 도달하면 중단합니다.");
2935 ui.horizontal(|ui| {
2936 cancel = theme::action(ui, "취소", false, true).clicked();
2937 allow = theme::action(ui, "이 작업 허용", true, true).clicked();
2938 });
2939 });
2940 if cancel || modal.should_close() {
2941 self.clear_password();
2942 self.model.cancel();
2943 } else if allow {
2944 self.model.resource_reply(job, question.id, true);
2945 }
2946 }
2947
2948 fn conflict_dialog(&mut self, ctx: &egui::Context) {
2949 let conflict = self.model.conflict.clone().unwrap();
2950 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
2951 if self.conflict_challenge != Some(question) {
2952 self.conflict_challenge = Some(question);
2953 self.conflict_apply = false;
2954 }
2955 let mut choice = None;
2956 let mut cancel = false;
2957 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
2958 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
2959 ui.heading("같은 이름의 파일이 있습니다");
2960 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
2961 ui.add_space(theme::SPACE);
2962 egui::Grid::new("conflict-sizes")
2963 .spacing([24.0, 8.0])
2964 .show(ui, |ui| {
2965 ui.label("기존 파일");
2966 ui.label(present::bytes_text(conflict.existing_size));
2967 ui.end_row();
2968 ui.label("압축파일 안의 파일");
2969 ui.label(present::bytes_text(conflict.incoming_size));
2970 ui.end_row();
2971 });
2972 ui.add_space(theme::SPACE);
2973 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
2974 ui.add_space(theme::SPACE);
2975 ui.horizontal_wrapped(|ui| {
2976 for (label, value) in [
2977 ("덮어쓰기", ConflictChoice::Overwrite),
2978 ("건너뛰기", ConflictChoice::Skip),
2979 ("이름 바꿔 저장", ConflictChoice::Rename),
2980 ] {
2981 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
2982 choice = Some(value);
2983 }
2984 }
2985 });
2986 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
2987 if let Some(error) = &self.model.error {
2988 Self::error_notice(ui, present::client_error_text(error));
2989 }
2990 cancel = theme::action(ui, "작업 취소", false, true).clicked();
2991 });
2992 if modal.should_close() || cancel {
2993 self.model.cancel();
2994 } else if let Some(choice) = choice {
2995 self.model.resolve_conflict(choice, self.conflict_apply);
2996 }
2997 }
2998
2999 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
3000 let (_, attempt, encrypt) = self.model.challenge.unwrap();
3001 let mut submit = false;
3002 let mut cancel = false;
3003 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
3004 id == egui::Id::unique("archive-password-input")
3005 || id == egui::Id::unique("archive-password-confirm")
3006 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
3007 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
3008 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
3009 ui.heading(if encrypt {
3010 "ZIP 암호 설정"
3011 } else {
3012 "암호가 필요합니다"
3013 });
3014 if encrypt {
3015 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
3016 } else if let Some(path) = &self.model.archive {
3017 ui.label(format!(
3018 "{}은 암호로 보호되어 있습니다.",
3019 present::middle_text(
3020 &path.file_name().unwrap_or_default().to_string_lossy(),
3021 24
3022 )
3023 ));
3024 }
3025 ui.horizontal(|ui| {
3026 ui.label("암호");
3027 let edit = ui.add(
3028 egui::TextEdit::singleline(&mut self.password)
3029 .password(!self.password_visible)
3030 .id(egui::Id::unique("archive-password-input"))
3031 .char_limit(1024)
3032 .desired_width(232.0),
3033 );
3034 theme::focus(&edit);
3035 if new_challenge {
3036 edit.request_focus();
3037 }
3038 if theme::action(
3039 ui,
3040 if self.password_visible {
3041 "숨기기"
3042 } else {
3043 "보기"
3044 },
3045 false,
3046 true,
3047 )
3048 .clicked()
3049 {
3050 self.password_visible = !self.password_visible;
3051 }
3052 });
3053 if encrypt {
3054 ui.horizontal(|ui| {
3055 ui.label("암호 확인");
3056 let edit = ui.add(
3057 egui::TextEdit::singleline(&mut self.password_confirm)
3058 .password(!self.password_visible)
3059 .id(egui::Id::unique("archive-password-confirm"))
3060 .char_limit(1024)
3061 .desired_width(232.0),
3062 );
3063 theme::focus(&edit);
3064 });
3065 if self.password != self.password_confirm {
3066 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
3067 }
3068 } else if attempt > 1 {
3069 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
3070 }
3071 if self.password.len() > 1024 {
3072 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
3073 }
3074 let valid = !self.password.is_empty()
3075 && self.password.len() <= 1024
3076 && (!encrypt || self.password == self.password_confirm);
3077 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
3078 cancel = actions.0;
3079 submit = actions.1 || (valid && password_enter);
3080 });
3081 if modal.should_close() || cancel {
3082 self.clear_password();
3083 self.model.cancel();
3084 } else if submit {
3085 let password = std::mem::take(&mut self.password);
3086 self.clear_password();
3087 self.model.password(password);
3088 }
3089 }
3090
3091 fn close_dialog(&mut self, ctx: &egui::Context) {
3092 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
3093 if matches!(
3094 self.model.close,
3095 Close::Open | Close::Allowed | Close::Review
3096 ) {
3097 return;
3098 }
3099 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
3100 ui.set_width(420.0);
3101 match self.model.close {
3102 Close::Confirm => {
3103 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
3104 let busy = self.model.busy();
3105 let (heading, text, keep, close) = if busy {
3106 (
3107 "작업 중 닫기",
3108 "작업을 취소하고 닫을까요?",
3109 "계속 작업",
3110 "취소하고 닫기",
3111 )
3112 } else {
3113 (
3114 "닫기",
3115 "작업이 끝났습니다. 창을 닫을까요?",
3116 "열어 두기",
3117 "닫기",
3118 )
3119 };
3120 ui.heading(heading);
3121 ui.label(text);
3122 ui.horizontal(|ui| {
3123 if theme::action(ui, keep, false, true).clicked() {
3124 self.model.keep_open();
3125 }
3126 if theme::action(ui, close, true, true).clicked() {
3127 self.clear_password();
3128 self.model.confirm_close();
3129 }
3130 });
3131 }
3132 Close::Waiting => {
3133 ui.heading("종료 확인 중");
3134 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
3135 if theme::action(ui, "닫기 취소", false, true).clicked() {
3136 self.model.keep_open();
3137 }
3138 }
3139 _ => {}
3140 }
3141 });
3142 }
3143}
3144
3145impl eframe::App for ArchiveApp {
3146 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
3147 self.show(root);
3148 }
3149
3150 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
3151 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
3152 if std::mem::take(&mut self.release_after_move) {
3153 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
3154 raw_input.events.insert(
3155 0,
3156 egui::Event::PointerButton {
3157 pos,
3158 button: egui::PointerButton::Primary,
3159 pressed: false,
3160 modifiers: ctx.input(|i| i.modifiers),
3161 },
3162 );
3163 }
3164 }
3165}
3166impl Drop for ArchiveApp {
3167 fn drop(&mut self) {
3168 self.clear_password();
3169 }
3170}