team-ljyzipelo

공개
4,726줄193 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 created: bool,
78 initial: Option<egui::Pos2>,
79 offset: Option<egui::Vec2>,
80 parent: Option<egui::Pos2>,
81 expected: Option<egui::Pos2>,
82 settle_until: f64,
83 height: f32,
84}
85
86impl Default for WorkWindow {
87 fn default() -> Self {
88 Self {
89 open: false,
90 created: false,
91 initial: None,
92 offset: None,
93 parent: None,
94 expected: None,
95 settle_until: 0.0,
96 height: 168.0,
97 }
98 }
99}
100
101impl WorkWindow {
102 /// 부모 창 가운데에 열고, 사용자가 옮긴 상대 위치를 유지한 채 부모 창을 따라가게 함.
103 /// 앱을 쓰는 동안에만 부모 위에 두고, 처음 위치를 담은 ViewportBuilder를 돌려줌.
104 /// Wayland처럼 창 위치를 알 수 없으면 위치는 창 관리자에 맡김.
105 fn builder(
106 &mut self,
107 ctx: &egui::Context,
108 id: egui::ViewportId,
109 size: egui::Vec2,
110 title: &str,
111 decorations: bool,
112 native_dialog_open: bool,
113 ) -> egui::ViewportBuilder {
114 let (parent, parent_focused, now) =
115 ctx.input(|i| (i.viewport().outer_rect, i.viewport().focused, i.time));
116 let (child, child_focused) = ctx.input(|i| {
117 i.raw
118 .viewports
119 .get(&id)
120 .map_or((None, None), |v| (v.outer_rect, v.focused))
121 });
122 let initial_focus_unknown =
123 !self.created && parent_focused.is_none() && child_focused.is_none();
124 self.created = true;
125 let opening = !self.open;
126 if opening {
127 // 처음 열 때 부모 창 가운데에 둠. 닫혔다 다시 열 때는 기억한 위치에 둠.
128 self.open = true;
129 self.initial = parent.map(|p| match self.offset {
130 Some(offset) => (p.min + offset).round(),
131 None => (p.center() - size / 2.0).round(),
132 });
133 self.offset = self.initial.zip(parent).map(|(c, p)| c - p.min);
134 self.parent = parent.map(|p| p.min);
135 self.expected = self.initial;
136 self.settle_until = now + 0.5;
137 }
138 if let (Some(parent), Some(child)) = (parent, child) {
139 let parent_moved = self.parent.is_some_and(|p| (p - parent.min).length() > 0.5);
140 let settled = self
141 .expected
142 .is_some_and(|e| (child.min - e).length() <= 2.0);
143 if settled || now >= self.settle_until {
144 self.settle_until = 0.0;
145 }
146 if parent_moved {
147 if let Some(offset) = self.offset {
148 let target = (parent.min + offset).round();
149 ctx.send_viewport_cmd_to(id, egui::ViewportCommand::OuterPosition(target));
150 self.expected = Some(target);
151 self.settle_until = now + 0.5;
152 }
153 } else if self.settle_until == 0.0 && !settled {
154 // 사용자가 자식 창을 옮긴 위치를 부모 기준으로 기억함.
155 self.offset = Some(child.min - parent.min);
156 self.expected = Some(child.min);
157 }
158 self.parent = Some(parent.min);
159 }
160 let mut builder = egui::ViewportBuilder::default()
161 .with_title(title)
162 .with_icon(crate::app_icon::load())
163 .with_decorations(decorations)
164 .with_inner_size(size)
165 .with_resizable(false)
166 .with_minimize_button(false)
167 .with_maximize_button(false)
168 .with_taskbar(false)
169 .with_window_level(
170 if !native_dialog_open
171 && (initial_focus_unknown
172 || parent_focused == Some(true)
173 || child_focused == Some(true))
174 {
175 egui::WindowLevel::AlwaysOnTop
176 } else {
177 egui::WindowLevel::Normal
178 },
179 );
180 if let Some(position) = self.initial {
181 builder = builder.with_position(position);
182 }
183 builder
184 }
185}
186
187struct Marquee {
188 // 스크롤 중에도 시작점을 목록 좌표로 유지함.
189 origin: egui::Pos2,
190 base: BTreeSet<u32>,
191 moved: bool,
192}
193
194/// 끌어 놓으려고 풀 폴더에서 넘길 항목의 경로(아직 없어도 됨).
195fn planned_paths(folder: &Path, names: &[String]) -> Vec<PathBuf> {
196 names
197 .iter()
198 .map(|name| name.split('/').fold(folder.to_path_buf(), |path, part| path.join(part)))
199 .collect()
200}
201
202/// 끌어 놓으려고 푼 폴더에서 넘길 항목의 경로. 실제로 있는 것만 돌려줌.
203fn drag_paths(folder: &Path, names: &[String]) -> Vec<PathBuf> {
204 planned_paths(folder, names)
205 .into_iter()
206 .filter(|path| path.exists())
207 .collect()
208}
209
210/// 창 밖 끌기를 시작하려면 누른 곳에서 이만큼(px) 움직여야 함.
211const DRAG_OUT_DISTANCE: f32 = 8.0;
212
213/// 파일 목록 한 행의 높이. 행 안의 크기 칸(theme::ROW)이 위아래 2px 여백으로 들어감.
214const LIST_ROW: f32 = 36.0;
215
216/// 기본 프로그램으로 열려고 임시 폴더에 푸는 작업. 끝나면 원래 풀 위치로 되돌림.
217struct OpenRequest {
218 folder: PathBuf,
219 /// 풀린 뒤 열 파일의 압축파일 안 경로. 작업자는 새로 만든 상위 폴더도 출력으로 알리므로
220 /// 출력 목록에서 이 경로와 같은 항목을 찾아 엶.
221 name: String,
222 destination: PathBuf,
223 automatic: bool,
224 /// 창 밖으로 끌어 놓으려고 푸는 경우, 받는 쪽에 넘길 항목(압축파일 안 경로).
225 drag: Option<Vec<String>>,
226 /// 끌어 놓을 항목을 구분하는 값. 같은 항목을 다시 끌 때 풀어 둔 파일을 다시 씀.
227 key: Option<DragKey>,
228}
229
230/// 끌어 놓을 항목 묶음: 압축파일, 목록 식별값, 선택한 항목 ID, 넘길 경로.
231type DragKey = (PathBuf, Option<ListId>, BTreeSet<u32>, Vec<String>);
232
233/// 찾기 창(Ctrl+F, Ctrl+Shift+F) 크기. 검색어 입력란 아래로 결과 목록이 길게 이어지는
234/// 작은 세로 창임.
235const FIND_WIDTH: f32 = 360.0;
236const FIND_HEIGHT: f32 = 560.0;
237/// 찾기 결과 한 줄(이름과 상위 경로 두 줄)의 높이.
238const FIND_ROW: f32 = 48.0;
239
240/// 찾기 창 상태.
241#[derive(Default)]
242struct FindState {
243 open: bool,
244 /// true면 압축파일 전체의 전체 경로에서 찾음(Ctrl+Shift+F).
245 /// false면 연 폴더 아래의 하위 폴더를 따라 이름에서 찾음(Ctrl+F).
246 whole_path: bool,
247 /// Ctrl+F를 누른 때 보고 있던 폴더.
248 base: String,
249 query: String,
250 results: Vec<browser::Found>,
251 truncated: bool,
252 /// 결과를 마지막으로 계산한 조건. 바뀐 경우에만 다시 찾음.
253 key: Option<(String, bool, String, usize)>,
254 cursor: Option<usize>,
255 focus_query: bool,
256 scroll_to_cursor: bool,
257 offset: f32,
258 win: WorkWindow,
259}
260
261/// 파일 목록의 오른쪽 클릭 메뉴에서 고른 동작.
262enum MenuAction {
263 NewFolder,
264 ChooseFolder,
265}
266
267type Opener = Box<dyn FnMut(&Path) -> Result<(), String>>;
268
269pub struct ArchiveApp {
270 pub model: Model,
271 factory: Box<dyn Factory>,
272 destination: PathBuf,
273 automatic_destination: bool,
274 owned_destination: Option<PathBuf>,
275 gzip_name: String,
276 sources: Vec<PathBuf>,
277 zip_folder: PathBuf,
278 zip_name: String,
279 password: String,
280 password_confirm: String,
281 password_visible: bool,
282 password_challenge: Option<u64>,
283 conflict_challenge: Option<(u64, u64)>,
284 conflict_apply: bool,
285 aes256: bool,
286 create: bool,
287 selected_only: bool,
288 method: Method,
289 seven_zip: bool,
290 /// 7z 만들기에서 "쪼갤 용량 설정"을 켰는지와 입력한 볼륨 크기.
291 split: bool,
292 split_amount: String,
293 split_unit: present::VolumeUnit,
294 dialogs: Box<dyn Dialogs>,
295 picker: Option<(Purpose, std::sync::mpsc::Receiver<DialogAnswer>)>,
296 preview_open: bool,
297 preview_name: String,
298 preview_text: String,
299 preview_texture: Option<egui::TextureHandle>,
300 preview_return_focus: Option<egui::Id>,
301 preview_initial_focus: bool,
302 work: WorkWindow,
303 work_in_parent: bool,
304 create_win: WorkWindow,
305 /// ZIP 만들기 창에서 보고 있는 폴더 (고른 폴더 기준 상대 경로, 비어 있으면 최상위).
306 create_folder: String,
307 create_listing: Option<(PathBuf, Option<std::rc::Rc<Vec<SourceRow>>>)>,
308 /// 마지막으로 누른 폴더 행 (이름, 프레임 번호, 시각). 두 번 누름을 직접 판단할 때 씀.
309 create_last_click: Option<(String, u64, f64)>,
310 /// ZIP 만들기 목록에서 한 번 눌러 선택한 항목 이름. 보고 있는 폴더가 바뀌면 지움.
311 create_selected: Option<String>,
312 zip_password: String,
313 zip_password_confirm: String,
314 zip_password_visible: bool,
315 /// 암호를 지웠으면 입력창의 실행 취소 기록도 다음 그리기 전에 지움.
316 forget_password_history: Vec<&'static str>,
317 /// 작업을 시작한 뒤 작업자가 암호를 요청하면 넘길 암호. 넘기거나 작업이 끝나면 지움.
318 pending_zip_password: Option<String>,
319 custom_frame: bool,
320 release_after_move: bool,
321 folder: String,
322 search: String,
323 list_anchor: Option<usize>,
324 list_cursor: Option<usize>,
325 list_offset: f32,
326 list_focused: bool,
327 marquee: Option<Marquee>,
328 last_request: Option<Start>,
329 recovery_warning: Option<(PathBuf, String)>,
330 targets: Option<BTreeSet<String>>,
331 directories: BTreeSet<String>,
332 dismissed: bool,
333 details: bool,
334 checked_destination: bool,
335 ui_error: Option<String>,
336 initialized: bool,
337 opening: Option<OpenRequest>,
338 /// 마지막 풀기가 기본 프로그램으로 열기였으면 그 항목. 다시 시도할 때 다시 엶.
339 last_open: Option<u32>,
340 /// 압축파일별 열기용 임시 폴더. 앱을 닫을 때 지움.
341 open_roots: Vec<(PathBuf, present::OpenRoot)>,
342 open_count: u64,
343 opener: Opener,
344 /// 운영체제 끌어 놓기 구현. 지원하지 않는 환경에서는 없음.
345 drag_out: Option<Box<dyn crate::drag_out::DragOut>>,
346 /// 끌기를 놓지 않고 취소해 풀던 작업을 취소했는지. 결과 창을 띄우지 않음.
347 drag_cancelled: bool,
348 /// 이번 버튼 누름에서 이미 창 밖 끌기를 시작했는지. 한 번 누름에 한 번만 시작함.
349 drag_out_fired: bool,
350 /// 끌어 놓으려고 마지막으로 풀어 둔 항목과 풀린 경로. 같은 항목을 다시 끌면 다시 씀.
351 drag_prepared: Option<(Option<DragKey>, Vec<PathBuf>)>,
352 find: FindState,
353 /// 이번 화면에서 목록 선택 해제 등 다른 곳이 Esc를 이미 처리했는지.
354 escape_handled: bool,
355 /// 찾기 결과로 이동한 뒤 다음 화면에서 목록에 키보드 초점을 줌.
356 focus_list: bool,
357 /// 지난 화면 끝에 입력란(전체, 목록 위 검색란)에 초점이 있었는지.
358 /// egui는 Esc를 누른 화면이 시작될 때 초점을 먼저 해제하므로 지난 값을 씀.
359 text_focus_before: (bool, bool),
360 #[cfg(all(feature = "ui-fixture", debug_assertions))]
361 scenario_marquee: Option<egui::Rect>,
362 #[cfg(all(feature = "ui-fixture", debug_assertions))]
363 scenario_sources: Option<std::rc::Rc<Vec<SourceRow>>>,
364}
365
366impl ArchiveApp {
367 pub fn new(factory: Box<dyn Factory>, startup: Option<PathBuf>, _fixture: bool) -> Self {
368 let mut app = Self {
369 model: Model::default(),
370 factory,
371 destination: PathBuf::new(),
372 automatic_destination: true,
373 owned_destination: None,
374 gzip_name: String::new(),
375 sources: Vec::new(),
376 zip_folder: present::home_directory(),
377 zip_name: String::new(),
378 password: String::new(),
379 password_confirm: String::new(),
380 password_visible: false,
381 password_challenge: None,
382 conflict_challenge: None,
383 conflict_apply: false,
384 aes256: false,
385 create: false,
386 selected_only: false,
387 method: Method::Deflate,
388 seven_zip: false,
389 split: false,
390 split_amount: "100".into(),
391 split_unit: present::VolumeUnit::Mb,
392 dialogs: Box::new(NativeDialogs),
393 picker: None,
394 preview_open: false,
395 preview_name: String::new(),
396 preview_text: String::new(),
397 preview_texture: None,
398 preview_return_focus: None,
399 preview_initial_focus: false,
400 work: WorkWindow::default(),
401 work_in_parent: false,
402 create_win: WorkWindow::default(),
403 create_folder: String::new(),
404 create_listing: None,
405 create_last_click: None,
406 create_selected: None,
407 zip_password: String::new(),
408 zip_password_confirm: String::new(),
409 zip_password_visible: false,
410 forget_password_history: Vec::new(),
411 pending_zip_password: None,
412 custom_frame: false,
413 release_after_move: false,
414 folder: String::new(),
415 search: String::new(),
416 list_anchor: None,
417 list_cursor: None,
418 list_offset: 0.0,
419 list_focused: false,
420 marquee: None,
421 last_request: None,
422 recovery_warning: None,
423 targets: None,
424 directories: BTreeSet::new(),
425 dismissed: false,
426 details: false,
427 checked_destination: false,
428 ui_error: None,
429 initialized: false,
430 opening: None,
431 last_open: None,
432 open_roots: Vec::new(),
433 open_count: 0,
434 opener: Box::new(present::open_with_default),
435 drag_out: None,
436 drag_cancelled: false,
437 drag_out_fired: false,
438 drag_prepared: None,
439 find: FindState::default(),
440 escape_handled: false,
441 focus_list: false,
442 text_focus_before: (false, false),
443 #[cfg(all(feature = "ui-fixture", debug_assertions))]
444 scenario_marquee: None,
445 #[cfg(all(feature = "ui-fixture", debug_assertions))]
446 scenario_sources: None,
447 };
448 if let Some(path) = startup {
449 app.open_path(path);
450 }
451 app
452 }
453
454 pub fn set_dialogs(&mut self, dialogs: Box<dyn Dialogs>) {
455 self.dialogs = dialogs;
456 }
457
458 /// 파일을 기본 프로그램으로 여는 방법을 바꿈. 시험에서 실제 프로그램 실행을 막을 때 씀.
459 pub fn set_opener(&mut self, opener: Opener) {
460 self.opener = opener;
461 }
462
463 /// 압축파일 안 파일 하나를 임시 폴더에 풀고 기본 프로그램으로 엶.
464 pub fn open_entry(&mut self, entry_id: u32) -> bool {
465 self.release_open();
466 if !self.model.can_extract() || self.opening.is_some() {
467 return false;
468 }
469 let Some(entry) = self.model.entries.iter().find(|e| e.id == entry_id) else {
470 return false;
471 };
472 if entry.kind != Kind::File {
473 return false;
474 }
475 let name = if self
476 .model
477 .list_id
478 .as_ref()
479 .is_some_and(|id| id.format == Format::Gzip)
480 {
481 self.gzip_name.clone()
482 } else {
483 entry.name.clone()
484 };
485 if present::blocked_open(&name) {
486 // 압축을 풀지 않고 바로 안내만 함.
487 self.dismissed = false;
488 self.ui_error = Some(present::open_blocked_text(&name));
489 return false;
490 }
491 let Some(folder) = self.new_open_folder() else {
492 return false;
493 };
494 let request = OpenRequest {
495 folder: folder.clone(),
496 name: name.replace('\\', "/"),
497 destination: std::mem::replace(&mut self.destination, folder),
498 automatic: std::mem::replace(&mut self.automatic_destination, true),
499 drag: None,
500 key: None,
501 };
502 self.opening = Some(request);
503 if self.extract_selection(Selection::EntryIds(vec![entry_id])) {
504 self.last_open = Some(entry_id);
505 true
506 } else {
507 self.finish_open(false);
508 false
509 }
510 }
511
512 /// 압축파일별 임시 폴더 아래에 이번 열기(또는 끌어 놓기)용 새 하위 폴더 경로를 정함.
513 /// 같은 파일을 여러 번 열어도 충돌하지 않도록 매번 새 하위 폴더에 풂.
514 fn new_open_folder(&mut self) -> Option<PathBuf> {
515 let archive = self.model.archive.clone()?;
516 let root = match self.open_roots.iter().find(|(a, _)| *a == archive) {
517 Some((_, root)) if root.is_current() => root.path().to_path_buf(),
518 _ => match present::create_open_root(&archive) {
519 Ok(root) => {
520 self.open_roots.retain(|(a, _)| *a != archive);
521 let path = root.path().to_path_buf();
522 self.open_roots.push((archive, root));
523 path
524 }
525 Err(_) => {
526 self.dismissed = false;
527 self.ui_error = Some(present::FOLDER_ERROR.into());
528 return None;
529 }
530 },
531 };
532 self.open_count += 1;
533 Some(present::unique_folder(
534 &root.join(self.open_count.to_string()),
535 ))
536 }
537
538 /// 운영체제 끌어 놓기 구현을 정함. Wayland처럼 지원하는 환경에서만 씀.
539 pub fn set_drag_out(&mut self, drag_out: Box<dyn crate::drag_out::DragOut>) {
540 self.drag_out = Some(drag_out);
541 }
542
543 /// 목록에서 선택한 항목을 창 밖으로 끌기 시작함. 운영체제 끌기를 시작한 뒤 선택
544 /// 항목을 임시 폴더에 풀고, 다 풀리면 받는 쪽에 파일 경로를 넘김.
545 pub fn begin_drag_out(&mut self) -> bool {
546 self.release_open();
547 if self.drag_out.is_none()
548 || !self.model.can_extract()
549 || self.opening.is_some()
550 || self.model.selected.is_empty()
551 {
552 return false;
553 }
554 let gzip = self
555 .model
556 .list_id
557 .as_ref()
558 .is_some_and(|id| id.format == Format::Gzip);
559 let names: Vec<String> = if gzip {
560 vec![self.gzip_name.clone()]
561 } else {
562 browser::rows(&self.model.entries, &self.folder, &self.search)
563 .into_iter()
564 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
565 .map(|row| row.path)
566 .collect()
567 };
568 if names.is_empty() {
569 return false;
570 }
571 let key: DragKey = (
572 self.model.archive.clone().unwrap_or_default(),
573 self.model.list_id.clone(),
574 self.model.selected.clone(),
575 names.clone(),
576 );
577 if let Some((Some(prepared), paths)) = &self.drag_prepared
578 && *prepared == key
579 && paths.iter().all(|path| path.exists())
580 {
581 // 같은 항목을 이미 풀어 두었으면 다시 풀지 않고 바로 끎.
582 let paths = paths.clone();
583 crate::log_debug!("풀어 둔 파일로 바로 끌기: {}개", paths.len());
584 let ready = paths.clone();
585 let drag = self.drag_out.as_mut().unwrap();
586 // Wayland와 X11은 시작할 때 이전 경로를 지우므로 시작한 뒤 넘김.
587 let started = drag.start(&paths, &mut |_| {
588 crate::drag_out::PumpState::Ready(ready.clone())
589 });
590 if started {
591 drag.provide(&paths);
592 self.release_after_move = true;
593 self.marquee = None;
594 }
595 return started;
596 }
597 self.marquee = None;
598 self.drag_cancelled = false;
599 self.last_open = None;
600 let Some(folder) = self.new_open_folder() else {
601 return false;
602 };
603 let request = OpenRequest {
604 folder: folder.clone(),
605 name: String::new(),
606 destination: std::mem::replace(&mut self.destination, folder.clone()),
607 automatic: std::mem::replace(&mut self.automatic_destination, true),
608 drag: Some(names.clone()),
609 key: Some(key),
610 };
611 self.opening = Some(request);
612 let selection = Selection::EntryIds(
613 browser::expand_selection(&self.model.entries, &self.model.selected)
614 .into_iter()
615 .collect(),
616 );
617 // 풀기를 먼저 시작함. Windows처럼 놓을 때까지 돌아오지 않는 끌기는 그동안 pump로
618 // 작업 진행을 받아 다 풀린 파일을 넘김.
619 if !self.extract_selection(selection) {
620 self.finish_open(false);
621 return false;
622 }
623 crate::log_debug!("창 밖으로 끌기 시작: {names:?}");
624 let planned = planned_paths(&folder, &names);
625 let started = {
626 use crate::drag_out::PumpState;
627 let model = &mut self.model;
628 let mut pump = move |cancel: bool| {
629 if cancel && model.busy() && !model.cancellation_requested() {
630 crate::log_debug!("끌기 중 취소: 풀던 작업을 취소함");
631 model.cancel();
632 }
633 model.poll();
634 if model.busy() {
635 // 암호, 큰 작업 승인 등 사용자 응답이 필요하면 끌기 중에는 넘길 수 없음.
636 if model.challenge.is_some()
637 || model.resource.is_some()
638 || model.conflict.is_some()
639 || model.cancellation_requested()
640 {
641 return PumpState::Failed;
642 }
643 let (done, total) = model
644 .progress
645 .map_or((0, None), |(_, done, total, _)| (done, total));
646 return PumpState::Waiting { done, total };
647 }
648 let completed = model.confirmed
649 && model
650 .terminal
651 .as_ref()
652 .is_some_and(|t| t.outcome == Outcome::Completed);
653 let paths = drag_paths(&folder, &names);
654 if completed && !paths.is_empty() {
655 PumpState::Ready(paths)
656 } else {
657 PumpState::Failed
658 }
659 };
660 self.drag_out.as_mut().unwrap().start(&planned, &mut pump)
661 };
662 if !started {
663 crate::log_warn!("운영체제 끌기를 시작하지 못함");
664 // 받을 곳이 없으므로 풀던 작업을 취소하고 결과 창은 띄우지 않음.
665 self.drag_cancelled = true;
666 self.clear_password();
667 self.model.cancel();
668 return false;
669 }
670 // 운영체제가 끌기를 넘겨받으면 버튼 놓기가 이 창에 오지 않으므로 대신 넣어 줌.
671 self.release_after_move = true;
672 // 끌기 동안 pump가 작업을 끝까지 받았으면 다음 화면의 끝남 감지를 거치지 않으므로
673 // 여기서 마무리함.
674 if !self.model.busy() && self.opening.is_some() {
675 let completed = self.model.confirmed
676 && self
677 .model
678 .terminal
679 .as_ref()
680 .is_some_and(|t| t.outcome == Outcome::Completed);
681 self.owned_destination = None;
682 self.finish_open(completed);
683 }
684 true
685 }
686
687 /// 운영체제 끌기에서 온 사건을 처리함.
688 fn poll_drag_out(&mut self) {
689 while let Some(event) = self.drag_out.as_mut().and_then(|drag| drag.poll()) {
690 crate::log_debug!("끌어 놓기 사건: {event:?}");
691 let dragging = self.opening.as_ref().is_some_and(|r| r.drag.is_some());
692 let waiting_for_user = self.model.challenge.is_some()
693 || self.model.resource.is_some()
694 || self.model.conflict.is_some();
695 if event == crate::drag_out::DragEvent::Cancelled
696 && dragging
697 && self.model.busy()
698 && !waiting_for_user
699 {
700 // 받을 곳이 없으므로 풀던 작업을 취소하고 결과 창은 띄우지 않음.
701 self.drag_cancelled = true;
702 self.clear_password();
703 self.model.cancel();
704 } else if event == crate::drag_out::DragEvent::Cancelled && waiting_for_user {
705 // 암호 등 사용자 응답이 필요해 끌기를 끝낸 경우 작업은 그대로 두고 그 창을
706 // 보여 줌. 다 풀린 뒤 같은 항목을 다시 끌면 풀어 둔 파일로 바로 끎.
707 crate::log_debug!("끌기를 끝내고 사용자 응답을 기다림");
708 }
709 }
710 }
711
712 /// 한도를 늘려 다시 시도할 수 있는 결과가 화면에 남아 있는 동안은 열기 상태를 유지함.
713 fn open_retry_pending(&self) -> bool {
714 self.opening.is_some() && !self.dismissed && self.model.can_retry_expanded()
715 }
716
717 /// 다시 시도를 기다리던 열기를 접고 원래 풀 위치로 되돌림. 다른 작업을 시작하기 전에 씀.
718 fn release_open(&mut self) {
719 if self.opening.is_some() && !self.model.busy() {
720 self.finish_open(false);
721 }
722 }
723
724 /// 열기용 풀기가 끝나면 원래 풀 위치를 되돌리고, 성공했으면 기본 프로그램을 실행함.
725 fn finish_open(&mut self, completed: bool) {
726 let Some(request) = self.opening.take() else {
727 return;
728 };
729 self.destination = request.destination;
730 self.automatic_destination = request.automatic;
731 if let Some(names) = request.drag {
732 let cancelled = std::mem::take(&mut self.drag_cancelled);
733 let paths = if completed {
734 drag_paths(&request.folder, &names)
735 } else {
736 Vec::new()
737 };
738 let Some(drag) = self.drag_out.as_mut() else {
739 return;
740 };
741 if paths.is_empty() {
742 drag.fail();
743 if cancelled {
744 self.dismissed = true;
745 } else if completed {
746 self.ui_error = Some(present::OPEN_MISSING.into());
747 }
748 } else {
749 crate::log_debug!("끌어 놓을 파일 준비 끝: {}개", paths.len());
750 // 결과 창 없이 받는 쪽이 파일을 가져가게 함.
751 self.dismissed = true;
752 drag.provide(&paths);
753 self.drag_prepared = Some((request.key, paths));
754 }
755 return;
756 }
757 if !completed {
758 return;
759 }
760 let Some(name) = self
761 .model
762 .outputs
763 .iter()
764 .filter(|(_, d)| *d == Disposition::Created)
765 .map(|(name, _)| name.replace('\\', "/"))
766 .find(|name| name.trim_end_matches('/') == request.name)
767 else {
768 self.ui_error = Some(present::OPEN_MISSING.into());
769 return;
770 };
771 let path = name
772 .split('/')
773 .fold(request.folder, |path, part| path.join(part));
774 match (self.opener)(&path) {
775 // 결과 창 없이 바로 열린 파일을 보여 줌.
776 Ok(()) => self.dismissed = true,
777 Err(error) => self.ui_error = Some(error),
778 }
779 }
780
781 /// 압축파일 이름으로 새 폴더를 만들고(같은 이름이 있으면 번호를 붙임) 선택 항목을 풂.
782 fn extract_to_new_folder(&mut self) -> bool {
783 self.release_open();
784 let Some(archive) = self.model.archive.clone() else {
785 return false;
786 };
787 self.destination = present::unique_folder(&present::default_destination(&archive));
788 self.automatic_destination = true;
789 self.begin_extract()
790 }
791
792 /// 창 순서를 지정할 수 없는 환경에서는 부모 안에 작업 화면을 그림.
793 pub fn set_work_window_in_parent(&mut self, enabled: bool) {
794 self.work_in_parent = enabled;
795 }
796
797 /// 운영체제가 창 테두리를 그려 주지 않을 때(GNOME Wayland) 제목 표시줄을 직접 그림.
798 pub fn set_custom_frame(&mut self, custom: bool) {
799 self.custom_frame = custom;
800 }
801
802 pub fn browse_folder(&mut self, folder: &str) {
803 self.folder = folder.trim_matches('/').to_owned();
804 crate::log_trace!("폴더 이동: /{}", self.folder);
805 self.search.clear();
806 self.clear_list_selection();
807 }
808
809 /// 찾기 창이 열려 있는지.
810 pub fn find_open(&self) -> bool {
811 self.find.open
812 }
813
814 /// 찾기 창의 검색어. 시험과 UI 상황 미리보기에서 씀.
815 pub fn set_find_query(&mut self, query: &str) {
816 self.find.query = query.to_owned();
817 }
818
819 /// 찾기 창의 현재 결과.
820 pub fn find_results(&mut self) -> &[browser::Found] {
821 self.refresh_find();
822 &self.find.results
823 }
824
825 /// 찾기 창을 엶. `whole_path`가 false면(Ctrl+F) 지금 보고 있는 폴더 아래에서
826 /// 이름으로 찾고, true면(Ctrl+Shift+F) 압축파일 전체 경로에서 찾음.
827 /// 이미 열려 있으면 찾는 범위만 바꾸고 검색어는 유지함.
828 pub fn open_find(&mut self, whole_path: bool) -> bool {
829 if self.model.archive.is_none() || self.model.list_id.is_none() || self.model.busy() {
830 return false;
831 }
832 if !self.find.open {
833 self.find.win = WorkWindow::default();
834 }
835 self.find.open = true;
836 self.find.whole_path = whole_path;
837 self.find.base = if whole_path {
838 String::new()
839 } else {
840 self.folder.clone()
841 };
842 self.find.key = None;
843 self.find.cursor = None;
844 self.find.focus_query = true;
845 crate::log_debug!(
846 "찾기 창 열기: {}",
847 if whole_path {
848 "전체 경로".to_owned()
849 } else {
850 format!("/{} 아래", self.find.base)
851 }
852 );
853 true
854 }
855
856 pub fn close_find(&mut self) {
857 if self.find.open {
858 crate::log_debug!("찾기 창 닫기");
859 }
860 self.find.open = false;
861 self.find.win = WorkWindow::default();
862 self.find.results.clear();
863 self.find.key = None;
864 self.find.cursor = None;
865 }
866
867 fn refresh_find(&mut self) {
868 let key = (
869 self.find.query.clone(),
870 self.find.whole_path,
871 self.find.base.clone(),
872 self.model.entries.len(),
873 );
874 if self.find.key.as_ref() == Some(&key) {
875 return;
876 }
877 let (results, truncated) = browser::find(
878 &self.model.entries,
879 &self.find.base,
880 &self.find.query,
881 self.find.whole_path,
882 browser::FIND_LIMIT,
883 );
884 crate::log_trace!(
885 "찾기 '{}': {}개{}",
886 self.find.query,
887 results.len(),
888 if truncated { " (일부만 표시)" } else { "" }
889 );
890 self.find.results = results;
891 self.find.truncated = truncated;
892 self.find.cursor = self
893 .find
894 .cursor
895 .filter(|index| *index < self.find.results.len());
896 self.find.key = Some(key);
897 }
898
899 /// 찾기 결과로 이동함. 찾기 창을 닫고, 폴더면 그 폴더를 열고
900 /// 파일이면 들어 있는 폴더를 연 뒤 그 파일을 선택함.
901 pub fn go_to_found(&mut self, found: &browser::Found) {
902 crate::log_debug!("찾기 결과로 이동: /{}", found.path);
903 self.close_find();
904 if found.directory {
905 self.browse_folder(&found.path);
906 } else {
907 let parent = found
908 .path
909 .rsplit_once('/')
910 .map_or("", |(parent, _)| parent)
911 .to_owned();
912 self.browse_folder(&parent);
913 let rows = browser::rows(&self.model.entries, &self.folder, "");
914 if let Some(index) = rows.iter().position(|row| row.name == found.name) {
915 self.select_row(&rows, index, false, false);
916 // 선택한 행이 목록 위쪽에 보이도록 스크롤함.
917 self.list_offset = (index as f32 * LIST_ROW - 2.0 * LIST_ROW).max(0.0);
918 }
919 }
920 self.focus_list = true;
921 }
922
923 pub fn show_create(&mut self, encrypted: bool) {
924 if !self.model.busy() {
925 self.create = true;
926 self.aes256 = encrypted && !self.seven_zip;
927 self.ui_error = None;
928 }
929 }
930
931 fn clear_password(&mut self) {
932 for value in [&mut self.password, &mut self.password_confirm] {
933 let mut bytes = std::mem::take(value).into_bytes();
934 bytes.fill(0);
935 }
936 self.password_visible = false;
937 // 이 함수는 암호 요청이 없는 동안 매 프레임 불리므로, 암호 창을 쓴 뒤에만 기록을 지움.
938 if self.password_challenge.is_some() {
939 self.forget_password_history
940 .extend(["archive-password-input", "archive-password-confirm"]);
941 }
942 }
943
944 /// 지운 암호가 입력창의 실행 취소(Ctrl+Z)로 되살아나지 않게 egui가 보관하는
945 /// 입력창 상태(실행 취소 기록 포함)를 지움.
946 fn forget_password_history(&mut self, ctx: &egui::Context) {
947 if self.forget_password_history.is_empty() {
948 return;
949 }
950 let names = std::mem::take(&mut self.forget_password_history);
951 ctx.data_mut(|data| {
952 for name in names {
953 data.remove::<egui::text_edit::TextEditState>(egui::Id::unique(name));
954 }
955 });
956 }
957
958 fn clear_zip_password(&mut self) {
959 wipe(&mut self.zip_password);
960 wipe(&mut self.zip_password_confirm);
961 if let Some(mut pending) = self.pending_zip_password.take() {
962 wipe(&mut pending);
963 }
964 self.zip_password_visible = false;
965 self.forget_password_history
966 .extend(["zip-password-input", "zip-password-confirm"]);
967 }
968
969 /// 암호로 보호하지 않거나, 두 암호가 같고 1~1024바이트이면 만들 수 있음.
970 fn zip_password_ready(&self) -> bool {
971 !self.aes256
972 || (!self.zip_password.is_empty()
973 && self.zip_password.len() <= 1024
974 && self.zip_password == self.zip_password_confirm)
975 }
976
977 /// 7z 분할을 켰으면 볼륨 바이트 수. 입력이 잘못됐으면 화면에 보일 오류.
978 fn split_volume(&self) -> Result<Option<u64>, &'static str> {
979 if !self.seven_zip || !self.split {
980 return Ok(None);
981 }
982 present::volume_size(&self.split_amount, self.split_unit).map(Some)
983 }
984
985 fn close_create(&mut self) {
986 self.create = false;
987 self.ui_error = None;
988 self.clear_zip_password();
989 self.create_win = WorkWindow::default();
990 }
991
992 /// 압축하기: 묶을 폴더를 운영체제 폴더 선택 창에서 고른 뒤 ZIP 만들기 창을 엶.
993 fn choose_zip_folder(&mut self) {
994 if self.model.busy() || self.picker.is_some() {
995 return;
996 }
997 // 이미 열린 ZIP 만들기 창의 목록과 암호 설정은 새 폴더를 실제로 고른 뒤에만 바꿈.
998 // 선택을 취소하면 그대로 남음(apply_picker의 Purpose::Folder).
999 self.open_picker(Purpose::Folder);
1000 }
1001
1002 /// 폴더 하나를 골랐으면 그 폴더 안을 목록으로 보여 줌. 여러 항목이면 그 항목들을 보여 줌.
1003 fn create_root(&self) -> Option<PathBuf> {
1004 (self.sources.len() == 1 && self.sources[0].is_dir()).then(|| self.sources[0].clone())
1005 }
1006
1007 fn create_rows(&mut self) -> Option<std::rc::Rc<Vec<SourceRow>>> {
1008 #[cfg(all(feature = "ui-fixture", debug_assertions))]
1009 if let Some(rows) = &self.scenario_sources {
1010 return Some(rows.clone());
1011 }
1012 let Some(root) = self.create_root() else {
1013 return Some(std::rc::Rc::new(
1014 self.sources.iter().map(|path| source_row(path)).collect(),
1015 ));
1016 };
1017 let dir = if self.create_folder.is_empty() {
1018 root
1019 } else {
1020 root.join(&self.create_folder)
1021 };
1022 // 프레임마다 디스크를 읽지 않도록 보고 있는 폴더가 바뀔 때만 다시 읽음.
1023 if self
1024 .create_listing
1025 .as_ref()
1026 .is_none_or(|(path, _)| path != &dir)
1027 {
1028 let rows = read_source_dir(&dir);
1029 self.create_listing = Some((dir, rows));
1030 }
1031 self.create_listing
1032 .as_ref()
1033 .and_then(|(_, rows)| rows.clone())
1034 }
1035
1036 pub fn open_path(&mut self, archive: PathBuf) {
1037 if self.model.busy() {
1038 return;
1039 }
1040 self.release_open();
1041 if self
1042 .recovery_warning
1043 .as_ref()
1044 .is_some_and(|(path, _)| path != &archive)
1045 {
1046 self.recovery_warning = None;
1047 }
1048 self.clear_password();
1049 self.destination = present::default_destination(&archive);
1050 self.automatic_destination = true;
1051 self.gzip_name = present::gzip_output_name(&archive);
1052 self.selected_only = false;
1053 self.folder.clear();
1054 self.search.clear();
1055 self.clear_list_selection();
1056 self.close_find();
1057 self.drag_prepared = None;
1058 self.targets = None;
1059 self.directories.clear();
1060 crate::log_debug!("압축파일 열기: {}", archive.display());
1061 self.start(Start::List { archive });
1062 }
1063
1064 fn start(&mut self, request: Start) -> bool {
1065 // 파일 선택 창이 응답을 기다리는 동안에는 어느 창에서도 새 작업을 시작하지 않음.
1066 if self.picker.is_some() {
1067 return false;
1068 }
1069 if matches!(request, Start::RecoverZip { .. }) {
1070 self.work = WorkWindow {
1071 height: 480.0,
1072 ..WorkWindow::default()
1073 };
1074 }
1075 self.last_request = Some(request.clone());
1076 self.dismissed = false;
1077 self.details = false;
1078 self.checked_destination = false;
1079 self.ui_error = None;
1080 self.model.begin(request, self.factory.as_mut())
1081 }
1082
1083 pub fn choose_destination(&mut self, path: PathBuf) {
1084 self.destination = path;
1085 self.automatic_destination = false;
1086 self.ui_error = None;
1087 }
1088
1089 pub fn add_sources(&mut self, paths: Vec<PathBuf>) {
1090 if self.model.busy() {
1091 return;
1092 }
1093 let mut validated = Vec::new();
1094 for path in paths {
1095 let Ok(metadata) = std::fs::symlink_metadata(&path) else {
1096 self.ui_error = Some("파일이나 폴더를 찾지 못했습니다. 다시 선택하세요".into());
1097 return;
1098 };
1099 if metadata.file_type().is_symlink() || !(metadata.is_file() || metadata.is_dir()) {
1100 self.ui_error = Some("일반 파일과 폴더만 추가할 수 있습니다".into());
1101 return;
1102 }
1103 let Ok(path) = path.canonicalize() else {
1104 return;
1105 };
1106 if path.to_str().is_none()
1107 || !path
1108 .file_name()
1109 .and_then(|name| name.to_str())
1110 .is_some_and(valid_leaf)
1111 {
1112 self.ui_error = Some("파일이나 폴더의 이름을 확인하세요".into());
1113 return;
1114 }
1115 validated.push(crate::archive_path::worker_path(&path));
1116 }
1117 let paths = validated;
1118 if self.sources.is_empty() {
1119 if let Some(first) = paths.first() {
1120 self.zip_folder = first.parent().unwrap_or(Path::new("/")).to_path_buf();
1121 let name = if first.is_dir() {
1122 first.file_name()
1123 } else {
1124 first.file_stem()
1125 };
1126 self.zip_name = format!(
1127 "{}.{}",
1128 name.unwrap_or_default().to_string_lossy(),
1129 if self.seven_zip { "7z" } else { "zip" }
1130 );
1131 }
1132 }
1133 for path in paths {
1134 if !self.sources.contains(&path) {
1135 self.sources.push(path);
1136 }
1137 }
1138 self.create_folder.clear();
1139 self.create_listing = None;
1140 self.create_selected = None;
1141 self.create = true;
1142 }
1143
1144 pub fn begin_extract(&mut self) -> bool {
1145 self.release_open();
1146 self.selected_only = !self.model.selected.is_empty();
1147 let selection = if self.selected_only {
1148 Selection::EntryIds(
1149 browser::expand_selection(&self.model.entries, &self.model.selected)
1150 .into_iter()
1151 .collect(),
1152 )
1153 } else {
1154 Selection::All
1155 };
1156 self.extract_selection(selection)
1157 }
1158
1159 fn extract_selection(&mut self, selection: Selection) -> bool {
1160 if !self.model.can_extract()
1161 || matches!(&selection, Selection::EntryIds(ids) if ids.is_empty())
1162 {
1163 return false;
1164 }
1165 self.selected_only = matches!(&selection, Selection::EntryIds(_));
1166 if self.opening.is_none() {
1167 self.last_open = None;
1168 }
1169 match present::prepare_destination(&self.destination, self.automatic_destination) {
1170 Ok(true) => self.owned_destination = Some(self.destination.clone()),
1171 Ok(false) => self.owned_destination = None,
1172 Err(_) => {
1173 self.ui_error = Some(present::FOLDER_ERROR.into());
1174 return false;
1175 }
1176 }
1177 let gzip = self
1178 .model
1179 .list_id
1180 .as_ref()
1181 .is_some_and(|id| id.format == Format::Gzip);
1182 self.targets = present::target_files(
1183 &self.model.entries,
1184 &selection,
1185 gzip.then_some(self.gzip_name.as_str()),
1186 );
1187 self.directories = if gzip {
1188 BTreeSet::new()
1189 } else {
1190 present::target_directories(&self.model.entries, &selection)
1191 };
1192 let request = Start::Extract {
1193 archive: self.model.archive.clone().unwrap(),
1194 destination: self.destination.clone(),
1195 selection,
1196 list_id: self.model.list_id.clone().unwrap(),
1197 gzip_output_name: gzip.then(|| self.gzip_name.clone()),
1198 };
1199 if self.start(request) {
1200 true
1201 } else {
1202 if let Some(path) = self.owned_destination.take() {
1203 present::remove_owned_empty(&path);
1204 }
1205 false
1206 }
1207 }
1208
1209 fn begin_zip(&mut self) {
1210 if self.sources.is_empty() {
1211 return;
1212 }
1213 let extension = if self.seven_zip { ".7z" } else { ".zip" };
1214 if !self.zip_name.to_ascii_lowercase().ends_with(extension) {
1215 self.zip_name.push_str(extension);
1216 }
1217 if !valid_leaf(&self.zip_name) {
1218 self.ui_error = Some("압축파일 이름을 확인하세요".into());
1219 return;
1220 }
1221 let volume_size = match self.split_volume() {
1222 Ok(size) => size,
1223 Err(error) => {
1224 self.ui_error = Some(error.into());
1225 return;
1226 }
1227 };
1228 let output_file = self.zip_folder.join(&self.zip_name);
1229 if volume_size.is_some() {
1230 // 분할 읽기는 같은 이름의 숫자 조각을 모두 한 묶음으로 보므로 하나라도 있으면 막음.
1231 if let Some(existing) = present::existing_volume(&output_file) {
1232 self.ui_error = Some(format!(
1233 "같은 이름의 분할 파일({existing})이 이미 있습니다. 다른 이름을 입력하세요"
1234 ));
1235 return;
1236 }
1237 } else if std::fs::symlink_metadata(&output_file).is_ok() {
1238 self.ui_error = Some("같은 이름의 파일이 이미 있습니다. 다른 이름을 입력하세요".into());
1239 return;
1240 }
1241 let mut sources = Vec::new();
1242 for path in &self.sources {
1243 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
1244 self.ui_error = Some(
1245 "이름을 읽을 수 없는 파일이 있습니다. 파일 이름을 바꾼 뒤 다시 추가하세요"
1246 .into(),
1247 );
1248 return;
1249 };
1250 sources.push((path.clone(), name.to_owned()));
1251 }
1252 if self.seven_zip
1253 && (self.aes256
1254 || !self.zip_password.is_empty()
1255 || !self.zip_password_confirm.is_empty())
1256 {
1257 self.ui_error =
1258 Some("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요".into());
1259 return;
1260 }
1261 if !self.zip_password_ready() {
1262 self.ui_error = Some("두 암호가 같은지 확인하세요".into());
1263 return;
1264 }
1265 // 분할하면 볼륨 수를 미리 알 수 없으므로 결과 화면에서 보고된 수로 이름을 다시 정함.
1266 self.targets = Some(
1267 [if volume_size.is_some() {
1268 format!("{}.001", self.zip_name)
1269 } else {
1270 self.zip_name.clone()
1271 }]
1272 .into_iter()
1273 .collect(),
1274 );
1275 self.directories.clear();
1276 // 암호는 ZIP 만들기 창에서 받아 두었다가 작업자가 요청하면 넘김.
1277 let password = self.aes256.then(|| std::mem::take(&mut self.zip_password));
1278 let request = if self.seven_zip {
1279 Start::CreateSevenZip {
1280 sources,
1281 output_file,
1282 volume_size,
1283 }
1284 } else {
1285 Start::CreateZip {
1286 sources,
1287 output_file,
1288 method: self.method,
1289 aes256: self.aes256,
1290 }
1291 };
1292 // 한도 초과 뒤 보류된 열기는 만들기와 무관하므로 시작 전에 접음.
1293 self.release_open();
1294 if self.start(request) {
1295 self.create = false;
1296 self.create_win = WorkWindow::default();
1297 self.clear_zip_password();
1298 self.pending_zip_password = password;
1299 } else if let Some(password) = password {
1300 self.zip_password = password;
1301 }
1302 }
1303
1304 fn open_picker(&mut self, purpose: Purpose) {
1305 if self.model.busy() || self.picker.is_some() {
1306 return;
1307 }
1308 let gzip = self
1309 .model
1310 .list_id
1311 .as_ref()
1312 .is_some_and(|id| id.format == Format::Gzip);
1313 let purpose = match (purpose, gzip) {
1314 (Purpose::Destination, true) => Purpose::SaveGzip,
1315 (Purpose::Retry, true) => Purpose::RetryGzip,
1316 _ => purpose,
1317 };
1318 let directory = match purpose {
1319 Purpose::SaveZip | Purpose::SaveSevenZip => self.zip_folder.clone(),
1320 Purpose::SaveRecoveryZip | Purpose::Destination | Purpose::SaveGzip => self
1321 .model
1322 .archive
1323 .as_ref()
1324 .and_then(|path| path.parent())
1325 .map(Path::to_path_buf)
1326 .unwrap_or_else(present::home_directory),
1327 Purpose::Retry | Purpose::RetryGzip => self.destination.clone(),
1328 _ => self
1329 .sources
1330 .last()
1331 .and_then(|path| path.parent())
1332 .map(Path::to_path_buf)
1333 .unwrap_or_else(present::home_directory),
1334 };
1335 let request = DialogRequest {
1336 purpose,
1337 directory,
1338 file_name: if purpose == Purpose::SaveRecoveryZip {
1339 let stem = self
1340 .model
1341 .archive
1342 .as_ref()
1343 .and_then(|p| p.file_stem())
1344 .unwrap_or_default()
1345 .to_string_lossy();
1346 format!("{stem}-recovered.zip")
1347 } else if matches!(purpose, Purpose::SaveGzip | Purpose::RetryGzip) {
1348 self.gzip_name.clone()
1349 } else {
1350 self.zip_name.clone()
1351 },
1352 };
1353 match self.dialogs.start(request) {
1354 PendingDialog::Ready(answer) => self.apply_picker(purpose, answer),
1355 PendingDialog::Waiting(receiver) => self.picker = Some((purpose, receiver)),
1356 }
1357 }
1358
1359 fn poll_picker(&mut self) {
1360 let Some((purpose, receiver)) = &self.picker else {
1361 return;
1362 };
1363 let purpose = *purpose;
1364 let answer = match receiver.try_recv() {
1365 Ok(answer) => answer,
1366 Err(std::sync::mpsc::TryRecvError::Empty) => return,
1367 Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(DIALOG_UNAVAILABLE.into()),
1368 };
1369 self.picker = None;
1370 self.apply_picker(purpose, answer);
1371 }
1372
1373 fn apply_picker(&mut self, purpose: Purpose, answer: DialogAnswer) {
1374 if answer.is_ok() && self.ui_error.as_deref() == Some(DIALOG_UNAVAILABLE) {
1375 self.ui_error = None;
1376 }
1377 match answer {
1378 Ok(Some(paths)) if !paths.is_empty() => {
1379 let path = paths[0].clone();
1380 match purpose {
1381 Purpose::SaveRecoveryZip => {
1382 if let Some(archive) = self.model.archive.clone() {
1383 self.start(Start::RecoverZip {
1384 archive,
1385 output_file: path,
1386 });
1387 }
1388 }
1389 Purpose::Open => {
1390 if std::fs::symlink_metadata(&path)
1391 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
1392 {
1393 self.open_path(path);
1394 } else {
1395 self.ui_error = Some("일반 압축파일을 선택하세요".into());
1396 }
1397 }
1398 Purpose::Files => self.add_sources(paths),
1399 Purpose::Folder => {
1400 // 새 폴더로 처음부터 시작함. 고른 폴더가 쓸 수 없으면 기존 내용을 되돌림.
1401 let previous = std::mem::take(&mut self.sources);
1402 self.add_sources(paths);
1403 if self.sources.is_empty() {
1404 self.sources = previous;
1405 } else {
1406 self.aes256 = false;
1407 self.clear_zip_password();
1408 self.ui_error = None;
1409 }
1410 }
1411 Purpose::Destination | Purpose::Retry => {
1412 // 다른 폴더를 골랐으면 기본 프로그램 열기가 아닌 일반 풀기로 다시 함.
1413 self.release_open();
1414 self.last_open = None;
1415 self.choose_destination(path);
1416 self.selected_only = !self.model.selected.is_empty();
1417 if purpose == Purpose::Retry {
1418 self.retry();
1419 } else {
1420 self.begin_extract();
1421 }
1422 }
1423 Purpose::SaveGzip | Purpose::RetryGzip => {
1424 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
1425 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
1426 return;
1427 };
1428 if !present::valid_output_leaf(name) {
1429 self.ui_error = Some("저장할 파일 이름을 확인하세요".into());
1430 return;
1431 }
1432 let name = name.to_owned();
1433 self.choose_destination(
1434 path.parent().unwrap_or(Path::new("/")).to_path_buf(),
1435 );
1436 self.gzip_name = name.clone();
1437 self.selected_only = !self.model.selected.is_empty();
1438 if purpose == Purpose::RetryGzip {
1439 if let Some(Start::Extract {
1440 gzip_output_name, ..
1441 }) = &mut self.last_request
1442 {
1443 *gzip_output_name = Some(name);
1444 }
1445 self.retry();
1446 } else {
1447 self.begin_extract();
1448 }
1449 }
1450 // 저장 위치를 고르는 사이 ZIP 만들기 창을 닫았으면 아무 작업도 시작하지 않음.
1451 Purpose::SaveZip | Purpose::SaveSevenZip if !self.create => {}
1452 Purpose::SaveZip | Purpose::SaveSevenZip => {
1453 if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
1454 self.zip_name = name.to_owned();
1455 self.zip_folder = path.parent().unwrap_or(Path::new("/")).to_path_buf();
1456 self.begin_zip();
1457 }
1458 }
1459 }
1460 }
1461 Ok(_) => {}
1462 Err(error) => self.ui_error = Some(error),
1463 }
1464 }
1465
1466 fn retry(&mut self) {
1467 if let Some(request) = self.last_request.clone() {
1468 match request {
1469 Start::List { archive } => self.open_path(archive),
1470 Start::Preview { .. } | Start::RecoverZip { .. } => {}
1471 Start::Extract { .. } if let Some(entry_id) = self.last_open => {
1472 self.open_entry(entry_id);
1473 }
1474 Start::Extract {
1475 selection,
1476 gzip_output_name,
1477 ..
1478 } => {
1479 if let Some(name) = gzip_output_name {
1480 self.gzip_name = name;
1481 }
1482 self.extract_selection(selection);
1483 }
1484 Start::CreateSevenZip { volume_size, .. } => {
1485 self.set_seven_zip(true);
1486 self.create = true;
1487 self.split = volume_size.is_some();
1488 if let Some(size) = volume_size {
1489 let (amount, unit) = if size % (1 << 30) == 0 {
1490 (size >> 30, present::VolumeUnit::Gb)
1491 } else {
1492 (size >> 20, present::VolumeUnit::Mb)
1493 };
1494 self.split_amount = amount.to_string();
1495 self.split_unit = unit;
1496 }
1497 self.begin_zip();
1498 }
1499 Start::CreateZip { aes256, .. } => {
1500 self.set_seven_zip(false);
1501 self.create = true;
1502 if aes256 {
1503 // 암호는 보관하지 않으므로 ZIP 만들기 창에서 다시 받음.
1504 self.aes256 = true;
1505 } else {
1506 self.begin_zip();
1507 }
1508 }
1509 }
1510 }
1511 }
1512
1513 fn on_drop(&mut self, paths: Vec<PathBuf>) {
1514 if paths.is_empty() {
1515 return;
1516 }
1517 // 목록 항목을 끌다가 Zipelo 창 위에 놓으면 Zipelo가 넘긴 임시 폴더의 경로가 다시
1518 // 들어옴. 그 파일을 압축파일로 열지 않고 무시함.
1519 if paths.iter().any(|path| {
1520 self.open_roots
1521 .iter()
1522 .any(|(_, root)| path.starts_with(root.path()))
1523 }) {
1524 crate::log_debug!("Zipelo 임시 폴더의 항목을 자기 창에 놓음: 무시");
1525 return;
1526 }
1527 if self.preview_open || self.model.busy() {
1528 return;
1529 }
1530 if paths.len() == 1 && !self.create && !paths[0].is_dir() {
1531 if std::fs::symlink_metadata(&paths[0])
1532 .is_ok_and(|m| m.is_file() && !m.file_type().is_symlink())
1533 {
1534 self.open_path(paths[0].clone());
1535 } else {
1536 self.ui_error = Some("일반 압축파일을 선택하세요".into());
1537 }
1538 } else {
1539 self.add_sources(paths);
1540 }
1541 }
1542
1543 fn poll(&mut self) {
1544 let busy = self.model.busy();
1545 let close_before = self.model.close;
1546 self.model.poll();
1547 if close_before == Close::Confirm && self.model.close == Close::Review {
1548 // 종료 확인 창에 답하기 전에 작업이 끝났음. 사용자가 닫기를 승인하지 않았으므로
1549 // 바로 닫지 않고 계속 물음(close_dialog가 작업이 끝난 문구로 바꿔 보여 줌).
1550 self.model.close = Close::Confirm;
1551 }
1552 if busy && !self.model.busy() {
1553 let completed = self.model.confirmed
1554 && self
1555 .model
1556 .terminal
1557 .as_ref()
1558 .is_some_and(|t| t.outcome == Outcome::Completed);
1559 if self.opening.is_some() {
1560 // 열기용 폴더는 앱을 닫을 때 지우므로 풀 위치 소유 기록만 정리함.
1561 self.owned_destination = None;
1562 // 한도 실패는 늘려서 다시 시도할 수 있으므로 열기 상태를 남김.
1563 if completed || !self.open_retry_pending() {
1564 self.finish_open(completed);
1565 }
1566 }
1567 if let Some(path) = self.owned_destination.take() {
1568 if !self.model.confirmed
1569 || self
1570 .model
1571 .terminal
1572 .as_ref()
1573 .is_none_or(|t| t.outcome != Outcome::Completed)
1574 {
1575 present::remove_owned_empty(&path);
1576 }
1577 }
1578 }
1579 if self.opening.is_some() && !self.model.busy() && !self.open_retry_pending() {
1580 // 결과를 닫았거나 다시 시도할 수 없게 되었으면 원래 풀 위치로 되돌림.
1581 self.finish_open(false);
1582 }
1583 }
1584
1585 pub fn show(&mut self, root: &mut egui::Ui) {
1586 let ctx = root.ctx().clone();
1587 self.forget_password_history(&ctx);
1588 if !self.initialized {
1589 theme::apply(&ctx);
1590 self.initialized = true;
1591 }
1592 self.poll();
1593 self.poll_drag_out();
1594 let preview_was_open = self.preview_open;
1595 self.poll_picker();
1596 if self.model.challenge.is_some_and(|(_, _, encrypt)| encrypt)
1597 && let Some(password) = self.pending_zip_password.take()
1598 {
1599 // ZIP 만들기 창에서 받은 암호를 작업자의 암호 요청에 바로 넘김.
1600 self.model.password(password);
1601 }
1602 if !self.model.busy()
1603 && let Some(mut pending) = self.pending_zip_password.take()
1604 {
1605 wipe(&mut pending);
1606 }
1607 let challenge = self.model.challenge.map(|(id, _, _)| id);
1608 let new_challenge = challenge != self.password_challenge;
1609 if new_challenge || challenge.is_none() {
1610 self.clear_password();
1611 }
1612 self.password_challenge = challenge;
1613 // Esc 처리에 쓰려고 그리기 전에 입력란 초점과 열린 자식 창을 기억함.
1614 self.escape_handled = false;
1615 let (text_focused, main_search_focused) = self.text_focus_before;
1616 let child_open = self.child_window_open();
1617 if self.model.archive.is_some()
1618 && !self.main_modal_open()
1619 && !self.preview_open
1620 && self.model.close == Close::Open
1621 {
1622 // 더 구체적인 Ctrl+Shift+F를 먼저 확인함.
1623 if ctx.input_mut(|i| {
1624 i.consume_key(
1625 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1626 egui::Key::F,
1627 )
1628 }) {
1629 self.open_find(true);
1630 } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)) {
1631 self.open_find(false);
1632 }
1633 }
1634 let dropped = ctx.input(|i| {
1635 i.raw
1636 .dropped_files
1637 .iter()
1638 .map(|file| file.path().to_path_buf())
1639 .collect()
1640 });
1641 if self.picker.is_none() {
1642 self.on_drop(dropped);
1643 }
1644 if ctx.input(|i| i.viewport().close_requested()) {
1645 self.model.request_close();
1646 // 실행 중인 작업이 없으면 결과 확인 안내 없이 바로 닫음.
1647 self.model.acknowledge_close();
1648 if self.model.close != Close::Allowed {
1649 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
1650 }
1651 }
1652 if self.model.close == Close::Review {
1653 // 작업을 취소하고 닫기로 한 뒤 정리가 끝난 경우도 안내 없이 닫음.
1654 self.model.acknowledge_close();
1655 }
1656 if self.model.close == Close::Allowed {
1657 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
1658 }
1659 let title = self
1660 .model
1661 .archive
1662 .as_ref()
1663 .map(|path| {
1664 let full = if path.is_absolute() {
1665 path.clone()
1666 } else {
1667 std::env::current_dir().unwrap_or_default().join(path)
1668 };
1669 format!("{} — Zipelo", full.display())
1670 })
1671 .unwrap_or_else(|| "Zipelo".into());
1672 let short_title = if let Some(path) = title.strip_suffix(" — Zipelo") {
1673 format!(
1674 "{} — Zipelo",
1675 theme::window_title(root, path, ctx.content_rect().width() - 300.0)
1676 )
1677 } else {
1678 title.clone()
1679 };
1680 ctx.send_viewport_cmd(egui::ViewportCommand::Title(short_title));
1681 if self.custom_frame
1682 && window_frame::title_bar(
1683 root,
1684 "main",
1685 &title,
1686 window_frame::Buttons {
1687 minimize: true,
1688 maximize: true,
1689 },
1690 )
1691 {
1692 self.release_after_move = true;
1693 }
1694 egui::Panel::top("archive-actions")
1695 .frame(
1696 theme::panel(theme::PANEL)
1697 .corner_radius(0)
1698 .inner_margin(egui::Margin {
1699 left: 12,
1700 right: 12,
1701 // 버튼 안 내용은 보이는 모양 기준으로 가운데에 두므로 위아래를 같게 둠.
1702 top: 4,
1703 bottom: 4,
1704 }),
1705 )
1706 .show(root, |ui| {
1707 ui.horizontal(|ui| {
1708 ui.spacing_mut().item_spacing.x = 2.0;
1709 let idle = !self.model.busy()
1710 && self.model.close == Close::Open
1711 && self.picker.is_none();
1712 if theme::tool(ui, "열기", theme::OPEN, idle, false)
1713 .on_hover_text(&title)
1714 .clicked()
1715 {
1716 self.open_picker(Purpose::Open);
1717 }
1718 if theme::tool(
1719 ui,
1720 "미리보기",
1721 theme::PREVIEW,
1722 idle && self.can_preview() && !self.preview_open,
1723 false,
1724 )
1725 .on_disabled_hover_text(
1726 if self.model.list_id.as_ref().is_some_and(ListId::is_split) {
1727 "분할 압축파일은 미리보기를 지원하지 않습니다"
1728 } else {
1729 "일반 파일 하나를 선택하세요"
1730 },
1731 )
1732 .clicked()
1733 {
1734 self.begin_preview(ui.ctx());
1735 }
1736 if theme::tool(ui, "압축하기", theme::CREATE, idle, false).clicked() {
1737 self.choose_zip_folder();
1738 }
1739 if theme::tool(
1740 ui,
1741 "압축해제",
1742 theme::EXTRACT,
1743 self.model.can_extract(),
1744 true,
1745 )
1746 .clicked()
1747 {
1748 self.open_picker(Purpose::Destination);
1749 }
1750 });
1751 });
1752 egui::Panel::bottom("archive-status")
1753 .exact_size(theme::STATUS_HEIGHT)
1754 .resizable(false)
1755 .frame(
1756 egui::Frame::new()
1757 .fill(theme::STRIPE)
1758 .inner_margin(egui::Margin::symmetric(16, 0)),
1759 )
1760 .show(root, |ui| {
1761 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
1762 let selected = rows
1763 .iter()
1764 .filter(|row| !row.ids.is_empty() && row.ids.is_subset(&self.model.selected))
1765 .count();
1766 let rect = ui.max_rect();
1767 let half = (rect.width() - theme::SPACE) / 2.0;
1768 theme::status_text(
1769 ui,
1770 rect,
1771 &format!("{}개 항목", rows.len()),
1772 half,
1773 Align::Min,
1774 );
1775 theme::status_text(ui, rect, &format!("선택 {selected}개"), half, Align::Max);
1776 });
1777 if ctx.embed_viewports()
1778 && !self.work_in_parent
1779 && self.work_visible()
1780 && !self.limit_result_visible()
1781 {
1782 // 별도 창을 만들 수 없을 때만 쓰는 대체 배치. 목록을 가리지 않도록 하단에 둠.
1783 egui::Panel::bottom("archive-work")
1784 .frame(theme::panel(theme::PANEL).corner_radius(0))
1785 .show(root, |ui| self.work_area(ui));
1786 }
1787 egui::CentralPanel::default()
1788 .frame(
1789 theme::panel(theme::PANEL)
1790 .corner_radius(0)
1791 .inner_margin(egui::Margin::ZERO),
1792 )
1793 .show(root, |ui| {
1794 if let Some((_, warning)) = &self.recovery_warning {
1795 ui.colored_label(theme::WARNING, warning);
1796 }
1797 if self.model.archive.is_some() {
1798 self.archive_list(ui);
1799 } else {
1800 self.empty(ui);
1801 }
1802 });
1803 self.forget_password_history(&ctx);
1804 self.preview_dialog(&ctx);
1805 self.work_window(&ctx);
1806 self.limit_result_dialog(&ctx);
1807 self.create_window(&ctx);
1808 self.find_window(&ctx);
1809 if self.model.challenge.is_some() {
1810 self.password_dialog(&ctx, new_challenge);
1811 }
1812 self.resource_dialog(&ctx);
1813 if self.model.conflict.is_some() && self.model.close == Close::Open {
1814 self.conflict_dialog(&ctx);
1815 }
1816 self.close_dialog(&ctx);
1817 self.picker_notice(&ctx);
1818 self.handle_escape(&ctx, text_focused, main_search_focused, child_open);
1819 self.text_focus_before = (
1820 ctx.text_edit_focused(),
1821 ctx.memory(|m| m.has_focus(egui::Id::unique("archive-search"))),
1822 );
1823 if !preview_was_open
1824 && !self.preview_open
1825 && !self.model.busy()
1826 && let Some(id) = self.preview_return_focus.take()
1827 {
1828 ctx.memory_mut(|m| m.request_focus(id));
1829 }
1830 if self.custom_frame {
1831 window_frame::edges(&ctx, true);
1832 }
1833 if self.model.busy() {
1834 ctx.request_repaint_after(std::time::Duration::from_millis(30));
1835 }
1836 }
1837
1838 /// 메인 창 위에 자식 창(모달, 작업 창, 만들기 창, 찾기 창 등)이 떠 있는지.
1839 fn child_window_open(&self) -> bool {
1840 self.find.open
1841 || self.preview_open
1842 || self.create
1843 || self.picker.is_some()
1844 || self.model.challenge.is_some()
1845 || self.model.resource.is_some()
1846 || self.model.conflict.is_some()
1847 || self.model.close != Close::Open
1848 || self.work_visible()
1849 }
1850
1851 /// 다른 곳에서 처리하지 않은 Esc를 처리함. 자식 창이 떠 있으면 그 창을 닫고,
1852 /// 아무 창도 없으면 프로그램을 종료함(작업 중이면 기존 종료 확인을 거침).
1853 /// 암호 입력, 미리보기 등 모달은 Esc를 직접 받아 닫으므로 여기까지 오지 않음.
1854 fn handle_escape(
1855 &mut self,
1856 ctx: &egui::Context,
1857 text_focused: bool,
1858 main_search_focused: bool,
1859 child_open: bool,
1860 ) {
1861 if self.escape_handled
1862 || self.picker.is_some()
1863 || !ctx.input(|i| i.key_pressed(egui::Key::Escape))
1864 {
1865 return;
1866 }
1867 let consume = |ctx: &egui::Context| {
1868 ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
1869 };
1870 if child_open {
1871 if self.find.open && !main_search_focused {
1872 consume(ctx);
1873 crate::log_debug!("Esc: 찾기 창 닫기");
1874 self.close_find();
1875 } else if matches!(self.model.close, Close::Confirm | Close::Waiting) {
1876 consume(ctx);
1877 crate::log_debug!("Esc: 종료 확인 취소");
1878 self.model.keep_open();
1879 } else if self.create && !self.model.busy() {
1880 consume(ctx);
1881 crate::log_debug!("Esc: 만들기 창 닫기");
1882 self.close_create();
1883 } else if !self.model.busy() && self.work_visible() {
1884 consume(ctx);
1885 crate::log_debug!("Esc: 작업 결과 창 닫기");
1886 self.dismissed = true;
1887 self.ui_error = None;
1888 self.model.input_error = None;
1889 }
1890 // 진행 중인 작업 창은 Esc로 닫지 않음. 취소는 [취소] 버튼으로 함.
1891 return;
1892 }
1893 if text_focused {
1894 // 입력란에서 누른 Esc는 입력란 초점만 해제함.
1895 return;
1896 }
1897 consume(ctx);
1898 crate::log_info!("Esc: 프로그램 종료 요청");
1899 ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close);
1900 }
1901
1902 /// 찾기 창. 진행·결과 창처럼 부모 창을 따라가는 별도 창으로 띄우고,
1903 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 창으로 띄움.
1904 fn find_window(&mut self, ctx: &egui::Context) {
1905 if !self.find.open {
1906 return;
1907 }
1908 if self.model.archive.is_none() || self.model.list_id.is_none() {
1909 self.close_find();
1910 return;
1911 }
1912 if self.main_modal_open() || self.preview_open {
1913 // 암호 입력 등 모달을 가리지 않게 잠시 숨김.
1914 self.find.win.open = false;
1915 return;
1916 }
1917 let title = if self.find.whole_path {
1918 "전체 경로에서 찾기"
1919 } else {
1920 "찾기"
1921 };
1922 let mut chosen = None;
1923 let mut close = false;
1924 if ctx.embed_viewports() || self.work_in_parent {
1925 egui::Window::new(title)
1926 .id(egui::Id::unique("archive-find-in-parent"))
1927 .title_bar(false)
1928 .default_pos(ctx.content_rect().right_top() + egui::vec2(-FIND_WIDTH - 24.0, 24.0))
1929 .default_width(FIND_WIDTH)
1930 .min_width(FIND_WIDTH)
1931 .max_width(FIND_WIDTH)
1932 .collapsible(false)
1933 .resizable(false)
1934 .fade_in(false)
1935 .fade_out(false)
1936 .frame(
1937 egui::Frame::new()
1938 .fill(theme::PANEL)
1939 .stroke(egui::Stroke::new(1.0, theme::BORDER))
1940 .inner_margin(egui::Margin::ZERO)
1941 .corner_radius(0),
1942 )
1943 .show(ctx, |ui| {
1944 let spacing = ui.spacing().item_spacing.y;
1945 ui.spacing_mut().item_spacing.y = 0.0;
1946 close = window_frame::in_parent_title(ui, "find-in-parent", title, true);
1947 egui::Frame::new()
1948 .inner_margin(egui::Margin::same(theme::PAD))
1949 .show(ui, |ui| {
1950 ui.spacing_mut().item_spacing.y = spacing;
1951 ui.set_width(FIND_WIDTH - 2.0 * theme::PAD as f32);
1952 let list_height = (ctx.content_rect().height() - 260.0)
1953 .clamp(120.0, FIND_HEIGHT - 200.0);
1954 chosen = self.find_contents(ui, list_height, false);
1955 });
1956 });
1957 } else {
1958 let id = egui::ViewportId::from_hash_of("archive-find");
1959 let window_title = format!("{title} — Zipelo");
1960 let custom_frame = self.custom_frame;
1961 let builder = self.find.win.builder(
1962 ctx,
1963 id,
1964 egui::vec2(FIND_WIDTH, FIND_HEIGHT),
1965 &window_title,
1966 !custom_frame,
1967 self.picker.is_some(),
1968 );
1969 ctx.show_viewport_immediate(id, builder, |ui, class| {
1970 if ui.ctx().input(|i| i.viewport().close_requested()) {
1971 close = true;
1972 }
1973 if ui
1974 .ctx()
1975 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
1976 {
1977 crate::log_debug!("Esc: 찾기 창 닫기");
1978 close = true;
1979 }
1980 // 찾기 창 안에서도 단축키로 찾는 범위를 바꿀 수 있음.
1981 if ui.ctx().input_mut(|i| {
1982 i.consume_key(
1983 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1984 egui::Key::F,
1985 )
1986 }) {
1987 self.find.whole_path = true;
1988 self.find.base.clear();
1989 self.find.focus_query = true;
1990 } else if ui
1991 .ctx()
1992 .input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F))
1993 {
1994 self.find.whole_path = false;
1995 self.find.base = self.folder.clone();
1996 self.find.focus_query = true;
1997 }
1998 if class == egui::ViewportClass::EmbeddedWindow {
1999 ui.set_width(FIND_WIDTH);
2000 chosen = self.find_contents(ui, FIND_HEIGHT - 200.0, false);
2001 return;
2002 }
2003 if custom_frame {
2004 window_frame::title_bar(
2005 ui,
2006 "find",
2007 &window_title,
2008 window_frame::Buttons {
2009 minimize: false,
2010 maximize: false,
2011 },
2012 );
2013 window_frame::edges(ui.ctx(), false);
2014 }
2015 egui::CentralPanel::default()
2016 .frame(
2017 theme::panel(theme::PANEL)
2018 .corner_radius(0)
2019 .inner_margin(egui::Margin::same(theme::PAD)),
2020 )
2021 .show(ui, |ui| {
2022 chosen = self.find_contents(ui, 0.0, true);
2023 });
2024 });
2025 }
2026 if let Some(found) = chosen {
2027 self.go_to_found(&found);
2028 } else if close {
2029 self.close_find();
2030 }
2031 }
2032
2033 /// 찾기 창 내용: 위쪽 검색어 입력란과 그 아래 세로로 긴 결과 목록.
2034 /// `list_height`가 0이면 남은 높이를 모두 목록에 씀. `own_keyboard`가 true면
2035 /// 창 전체가 찾기 창이므로 입력란에 초점이 없어도 화살표와 Enter를 받음.
2036 /// 결과를 골랐으면(더블클릭 또는 Enter) 그 결과를 돌려줌.
2037 fn find_contents(
2038 &mut self,
2039 ui: &mut egui::Ui,
2040 list_height: f32,
2041 own_keyboard: bool,
2042 ) -> Option<browser::Found> {
2043 self.refresh_find();
2044 let scope = if self.find.whole_path {
2045 "압축파일 전체 경로에서 찾습니다".to_owned()
2046 } else {
2047 format!("/{} 아래 모든 폴더에서 이름으로 찾습니다", self.find.base)
2048 };
2049 let width = ui.available_width();
2050 ui.add(egui::Label::new(RichText::new(&scope).color(theme::MUTED)).truncate())
2051 .on_hover_text(&scope);
2052 ui.add_space(theme::SPACE / 2.0);
2053 let query_id = egui::Id::unique("archive-find-query");
2054 let edit = ui.add(
2055 egui::TextEdit::singleline(&mut self.find.query)
2056 .id(query_id)
2057 .char_limit(512)
2058 .desired_width(width)
2059 .hint_text(if self.find.whole_path {
2060 "찾을 경로 입력"
2061 } else {
2062 "찾을 이름 입력"
2063 }),
2064 );
2065 theme::focus(&edit);
2066 if std::mem::take(&mut self.find.focus_query) {
2067 edit.request_focus();
2068 }
2069 if edit.changed() {
2070 self.refresh_find();
2071 self.find.cursor = (!self.find.results.is_empty()).then_some(0);
2072 self.find.offset = 0.0;
2073 self.find.scroll_to_cursor = true;
2074 }
2075 // 결과를 한 번 누르면 입력란 대신 결과 목록이 초점을 가지므로, 목록에 초점이 있을
2076 // 때도 화살표와 Enter를 받음(부모 안 찾기 창에서도 결과를 고른 뒤 Enter로 이동).
2077 let list_id = egui::Id::unique("archive-find-results");
2078 let keyboard = own_keyboard
2079 || edit.has_focus()
2080 || edit.lost_focus()
2081 || ui.memory(|m| m.has_focus(list_id));
2082 let count = self.find.results.len();
2083 let mut chosen = None;
2084 if keyboard && count > 0 {
2085 let (down, up, enter) = ui.input(|i| {
2086 (
2087 i.key_pressed(egui::Key::ArrowDown),
2088 i.key_pressed(egui::Key::ArrowUp),
2089 i.key_pressed(egui::Key::Enter),
2090 )
2091 });
2092 if down || up {
2093 let index = match self.find.cursor {
2094 None => 0,
2095 Some(index) if down => (index + 1).min(count - 1),
2096 Some(index) => index.saturating_sub(1),
2097 };
2098 self.find.cursor = Some(index);
2099 self.find.scroll_to_cursor = true;
2100 }
2101 if enter {
2102 chosen = Some(self.find.cursor.unwrap_or(0));
2103 }
2104 }
2105 ui.add_space(theme::SPACE / 2.0);
2106 let status = if self.find.query.trim().is_empty() {
2107 "검색어를 입력하세요".to_owned()
2108 } else if count == 0 {
2109 "찾은 항목이 없습니다".to_owned()
2110 } else if self.find.truncated {
2111 format!("처음 {count}개만 표시합니다. 검색어를 더 구체적으로 입력하세요")
2112 } else {
2113 format!("{count}개 찾음 · 두 번 누르거나 Enter로 이동")
2114 };
2115 ui.add(
2116 egui::Label::new(
2117 RichText::new(status)
2118 .size(theme::FONT_SMALL)
2119 .color(theme::MUTED),
2120 )
2121 .truncate(),
2122 );
2123 ui.add_space(theme::SPACE / 2.0);
2124 let height = if list_height > 0.0 {
2125 list_height
2126 } else {
2127 ui.available_height().max(FIND_ROW)
2128 };
2129 let (frame_rect, _) =
2130 ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
2131 // 결과 목록 전체가 키보드 초점을 받는 목록 상자임. 행 누름은 위에 그리는 행이 받음.
2132 let list = ui.interact(frame_rect, list_id, egui::Sense::click());
2133 list.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, true, "찾기 결과"));
2134 if list.has_focus() {
2135 ui.memory_mut(|memory| {
2136 memory.set_focus_lock_filter(
2137 list_id,
2138 egui::EventFilter {
2139 vertical_arrows: true,
2140 ..Default::default()
2141 },
2142 )
2143 });
2144 }
2145 theme::boxed_field(ui, frame_rect);
2146 let mut list_ui = ui.new_child(
2147 egui::UiBuilder::new()
2148 .max_rect(frame_rect.shrink(1.0))
2149 .layout(Layout::top_down(Align::Min)),
2150 );
2151 let viewport_height = frame_rect.height() - 2.0;
2152 if self.find.scroll_to_cursor
2153 && let Some(index) = self.find.cursor
2154 {
2155 let top = index as f32 * FIND_ROW;
2156 if top < self.find.offset {
2157 self.find.offset = top;
2158 } else if top + FIND_ROW > self.find.offset + viewport_height {
2159 self.find.offset = top + FIND_ROW - viewport_height;
2160 }
2161 }
2162 let mut area = egui::ScrollArea::vertical()
2163 .id_salt("archive-find-results")
2164 .auto_shrink([false, false]);
2165 if std::mem::take(&mut self.find.scroll_to_cursor) {
2166 area = area.vertical_scroll_offset(self.find.offset);
2167 }
2168 let output = area.show_rows(&mut list_ui, FIND_ROW, count, |ui, range| {
2169 ui.spacing_mut().item_spacing.y = 0.0;
2170 let row_width = ui.available_width();
2171 for index in range {
2172 let found = &self.find.results[index];
2173 let (rect, response) =
2174 ui.allocate_exact_size(egui::vec2(row_width, FIND_ROW), egui::Sense::click());
2175 theme::pointer(&response);
2176 let parent = format!(
2177 "/{}",
2178 found.path.rsplit_once('/').map_or("", |(parent, _)| parent)
2179 );
2180 response.widget_info(|| {
2181 egui::WidgetInfo::selected(
2182 egui::Role::ListBoxOption,
2183 true,
2184 self.find.cursor == Some(index),
2185 &found.path,
2186 )
2187 });
2188 theme::row_background(
2189 ui,
2190 rect,
2191 self.find.cursor == Some(index),
2192 response.hovered(),
2193 );
2194 ui.scope_builder(
2195 egui::UiBuilder::new()
2196 .max_rect(rect.shrink2(egui::vec2(10.0, 4.0)))
2197 .layout(Layout::left_to_right(Align::Center)),
2198 |ui| {
2199 ui.style_mut().interaction.selectable_labels = false;
2200 theme::icon(
2201 ui,
2202 if found.directory {
2203 Icon::Folder
2204 } else {
2205 Icon::File
2206 },
2207 20.0,
2208 );
2209 ui.add_space(6.0);
2210 let text_width = ui.available_width();
2211 ui.vertical(|ui| {
2212 ui.spacing_mut().item_spacing.y = 0.0;
2213 theme::bounded_text_hover(ui, &found.name, &found.path, text_width);
2214 ui.add_sized(
2215 egui::vec2(text_width, 18.0),
2216 egui::Label::new(
2217 RichText::new(&parent)
2218 .size(theme::FONT_SMALL)
2219 .color(theme::MUTED),
2220 )
2221 .truncate(),
2222 );
2223 });
2224 },
2225 );
2226 if response.clicked() {
2227 self.find.cursor = Some(index);
2228 ui.memory_mut(|m| m.request_focus(list_id));
2229 }
2230 if response.double_clicked() {
2231 chosen = Some(index);
2232 }
2233 }
2234 });
2235 self.find.offset = output.state.clamped_offset().y;
2236 chosen.and_then(|index| self.find.results.get(index).cloned())
2237 }
2238
2239 // 선택 창이 열려 있는 동안 다른 조작을 막고, 응답을 받도록 화면을 계속 갱신함.
2240 fn picker_notice(&mut self, ctx: &egui::Context) {
2241 if self.picker.is_none() {
2242 return;
2243 }
2244 egui::Modal::new(egui::Id::unique("archive-picker")).show(ctx, |ui| {
2245 ui.set_width(360.0);
2246 ui.label("파일 선택 창에서 선택을 마쳐 주세요");
2247 });
2248 ctx.request_repaint_after(std::time::Duration::from_millis(100));
2249 }
2250
2251 fn empty(&mut self, ui: &mut egui::Ui) {
2252 let hovered = ui.ctx().input(|i| !i.raw.hovered_files.is_empty());
2253 let width = (ui.available_width() * 0.60)
2254 .max(480.0)
2255 .min(ui.available_width());
2256 let y = ((ui.available_height() - theme::DROP_HEIGHT - theme::SPACE * 8.0) / 2.0).max(0.0);
2257 ui.add_space(y);
2258 ui.vertical_centered(|ui| {
2259 let drop_frame = egui::Frame::new()
2260 .fill(if hovered { theme::DROP } else { theme::PANEL })
2261 .corner_radius(theme::DROP_RADIUS)
2262 .inner_margin(egui::Margin::same(theme::DROP_PAD))
2263 .show(ui, |ui| {
2264 ui.set_width(width - 2.0 * theme::DROP_PAD as f32);
2265 ui.set_min_height(theme::DROP_HEIGHT - 2.0 * theme::DROP_PAD as f32);
2266 ui.vertical_centered(|ui| {
2267 ui.add_space(theme::PAD as f32);
2268 theme::icon(ui, Icon::Archive, 48.0);
2269 ui.add_space(theme::PAD as f32);
2270 ui.label(
2271 RichText::new(if hovered {
2272 "놓으면 엽니다"
2273 } else {
2274 "압축파일을 여기에 끌어 놓으세요"
2275 })
2276 .size(theme::FONT_LARGE)
2277 .strong(),
2278 );
2279 ui.label("또는");
2280 if theme::action(ui, "파일 열기", true, !self.model.busy()).clicked() {
2281 self.open_picker(Purpose::Open);
2282 }
2283 });
2284 });
2285 let rect = drop_frame.response.rect;
2286 if hovered {
2287 ui.painter().rect_stroke(
2288 rect,
2289 12,
2290 egui::Stroke::new(2.0, theme::BLUE),
2291 egui::StrokeKind::Inside,
2292 );
2293 } else {
2294 let stroke = egui::Stroke::new(2.0, theme::DASH);
2295 for (a, b) in [
2296 (rect.left_top(), rect.right_top()),
2297 (rect.right_top(), rect.right_bottom()),
2298 (rect.right_bottom(), rect.left_bottom()),
2299 (rect.left_bottom(), rect.left_top()),
2300 ] {
2301 let direction = (b - a).normalized();
2302 let mut distance = theme::DROP_RADIUS as f32;
2303 while distance < a.distance(b) - theme::DROP_RADIUS as f32 {
2304 ui.painter().line_segment(
2305 [
2306 a + direction * distance,
2307 a + direction
2308 * (distance + theme::SPACE)
2309 .min(a.distance(b) - theme::DROP_RADIUS as f32),
2310 ],
2311 stroke,
2312 );
2313 distance += theme::PAD as f32;
2314 }
2315 }
2316 }
2317 ui.add_space(theme::PAD as f32);
2318 ui.colored_label(
2319 theme::MUTED,
2320 "ZIP, 7z, TAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ 파일을 열 수 있습니다",
2321 );
2322 });
2323 }
2324
2325 fn archive_list(&mut self, ui: &mut egui::Ui) {
2326 // 경로 줄은 입력란 높이만 차지하고 창 너비 전체를 회색으로 채움.
2327 let path_row = egui::Frame::new()
2328 .fill(theme::STRIPE)
2329 .inner_margin(egui::Margin {
2330 left: 8,
2331 right: 12,
2332 top: 0,
2333 bottom: 0,
2334 })
2335 .show(ui, |ui| {
2336 ui.set_min_width(ui.available_width());
2337 ui.horizontal(|ui| {
2338 ui.set_height(theme::FIELD);
2339 // 간격은 아래에서 직접 넣어 위치가 흔들리지 않게 함.
2340 ui.spacing_mut().item_spacing.x = 0.0;
2341 let up = theme::flat_icon_button(
2342 ui,
2343 "위로",
2344 theme::UP,
2345 !self.folder.is_empty() && !self.model.busy(),
2346 egui::vec2(theme::FIELD, theme::FIELD),
2347 );
2348 if up.clicked() {
2349 let parent = self
2350 .folder
2351 .rsplit_once('/')
2352 .map_or("", |(parent, _)| parent)
2353 .to_owned();
2354 self.browse_folder(&parent);
2355 }
2356 ui.add_space(6.0);
2357 let path = format!("/{}", self.folder);
2358 let search_width = 240.0;
2359 let gap = 8.0;
2360 let path_width = (ui.available_width() - search_width - gap).max(0.0);
2361 // 두 입력란은 같은 높이의 칸을 받아 같은 세로 위치에 그림.
2362 let (path_rect, _) = ui.allocate_exact_size(
2363 egui::vec2(path_width, theme::FIELD),
2364 egui::Sense::hover(),
2365 );
2366 theme::field_frame(ui, path_rect, false);
2367 // 부모 배치에 영향을 주지 않는 하위 영역에 경로 글자를 그림.
2368 let mut text_ui = ui.new_child(
2369 egui::UiBuilder::new()
2370 .max_rect(path_rect.shrink2(egui::vec2(10.0, 0.0)))
2371 .layout(Layout::left_to_right(Align::Center)),
2372 );
2373 theme::bounded_text(&mut text_ui, &path, (path_width - 20.0).max(0.0));
2374 ui.add_space(gap);
2375 let (search_rect, _) = ui.allocate_exact_size(
2376 egui::vec2(search_width, theme::FIELD),
2377 egui::Sense::hover(),
2378 );
2379 let search_id = egui::Id::unique("archive-search");
2380 let focused = ui.memory(|m| m.has_focus(search_id));
2381 theme::field_frame(ui, search_rect, focused);
2382 let icon = egui::Rect::from_center_size(
2383 egui::pos2(search_rect.left() + 20.0, search_rect.center().y),
2384 egui::vec2(16.0, 16.0),
2385 );
2386 theme::svg_icon(ui.painter(), icon, theme::SEARCH, theme::MUTED);
2387 let search = ui.put(
2388 egui::Rect::from_min_max(
2389 egui::pos2(icon.right() + 8.0, search_rect.top() + 1.0),
2390 egui::pos2(search_rect.right() - 8.0, search_rect.bottom() - 1.0),
2391 ),
2392 egui::TextEdit::singleline(&mut self.search)
2393 .id(search_id)
2394 .frame(egui::Frame::NONE)
2395 .margin(egui::Margin::ZERO)
2396 .align(egui::Align2::LEFT_CENTER)
2397 .hint_text("파일 검색"),
2398 );
2399 if search.changed() {
2400 self.clear_list_selection();
2401 }
2402 });
2403 })
2404 .response
2405 .rect;
2406 // 경로 줄 아래 한 줄이 목록과의 경계이자 입력란의 아래 테두리 역할을 함.
2407 ui.painter().hline(
2408 path_row.x_range(),
2409 path_row.bottom() - 0.5,
2410 egui::Stroke::new(1.0, theme::BORDER),
2411 );
2412 let rows = browser::rows(&self.model.entries, &self.folder, &self.search);
2413
2414 // 열 제목 줄 없이 바로 목록을 보여 줌. 이름과 크기는 내용으로 구분됨.
2415 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 40.0).max(120.0);
2416 let active = !self.preview_open
2417 && !self.model.busy()
2418 && !self.create
2419 && self.model.challenge.is_none()
2420 && self.model.close == Close::Open;
2421 let list_id = egui::Id::unique("archive-list");
2422 let background = ui.interact(
2423 ui.available_rect_before_wrap(),
2424 list_id,
2425 if active {
2426 egui::Sense::click_and_drag()
2427 } else {
2428 egui::Sense::hover()
2429 },
2430 );
2431 background
2432 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, active, "파일 목록"));
2433 if active && std::mem::take(&mut self.focus_list) {
2434 background.request_focus();
2435 }
2436 if background.has_focus() {
2437 ui.ctx().memory_mut(|memory| {
2438 memory.set_focus_lock_filter(
2439 list_id,
2440 egui::EventFilter {
2441 vertical_arrows: true,
2442 escape: true,
2443 ..Default::default()
2444 },
2445 )
2446 });
2447 }
2448 let mut focused = None;
2449 let mut open = None;
2450 let mut open_file = None;
2451 let mut menu_action = None;
2452 let mut drag_out = false;
2453 let mut next_offset = None;
2454 let output = egui::ScrollArea::vertical()
2455 .id_salt("archive-rows")
2456 .auto_shrink([false, false])
2457 .vertical_scroll_offset(self.list_offset)
2458 .show_viewport(ui, |ui, viewport| {
2459 let origin = ui.max_rect().min;
2460 let clip = ui.clip_rect();
2461 // 행을 누르는 영역은 오른쪽 24px을 비워 둠. 목록이 길어도 그 빈 곳에서
2462 // 끌어서 선택을 시작할 수 있음. 행 배경(선택, 마우스 올림)은 너비를 꽉 채움.
2463 let full_width = ui.available_width();
2464 let width = (full_width - 24.0).max(0.0);
2465 ui.set_min_height((rows.len() as f32 * LIST_ROW).max(viewport.height()));
2466 let point = ui.input(|i| i.pointer.interact_pos());
2467 if active && let Some(point) = point {
2468 let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(point);
2469 let relative = press - origin;
2470 let in_row = relative.x >= 0.0
2471 && relative.x <= width
2472 && relative.y >= 0.0
2473 && relative.y < rows.len() as f32 * LIST_ROW;
2474 // 목록 위에 떠 있는 창(부모 안 작업 창 등)을 누른 경우는 목록 조작이 아님.
2475 let on_list = ui.ctx().layer_id_at(press) == Some(ui.layer_id());
2476 if clip.contains(press)
2477 && on_list
2478 && !in_row
2479 && ui.input(|i| i.pointer.primary_pressed())
2480 {
2481 background.request_focus();
2482 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
2483 self.marquee = Some(Marquee {
2484 origin: relative.to_pos2(),
2485 base: if ctrl {
2486 self.model.selected.clone()
2487 } else {
2488 BTreeSet::new()
2489 },
2490 moved: false,
2491 });
2492 if !ctrl {
2493 self.model.selected.clear();
2494 self.list_anchor = None;
2495 self.list_cursor = None;
2496 }
2497 }
2498 if let Some(drag) = &mut self.marquee {
2499 let end = (point.clamp(clip.min, clip.max) - origin).to_pos2();
2500 drag.moved |= drag.origin.distance(end) > 3.0;
2501 if drag.moved {
2502 let rect = egui::Rect::from_two_pos(drag.origin, end);
2503 self.model.selected = drag.base.clone();
2504 if rect.left() < width && rect.right() > 0.0 {
2505 let first = (rect.top().max(0.0) / LIST_ROW).floor() as usize;
2506 let last = ((rect.bottom().max(0.0) / LIST_ROW).ceil() as usize)
2507 .min(rows.len());
2508 for row in rows.iter().take(last).skip(first) {
2509 self.model.selected.extend(&row.ids);
2510 }
2511 if first < last {
2512 self.list_anchor = Some(first);
2513 self.list_cursor = Some(last - 1);
2514 }
2515 }
2516 let speed = if point.y > clip.bottom() - 24.0 {
2517 ((point.y - clip.bottom() + 24.0) / 24.0).clamp(0.0, 3.0)
2518 } else if point.y < clip.top() + 24.0 {
2519 -((clip.top() + 24.0 - point.y) / 24.0).clamp(0.0, 3.0)
2520 } else {
2521 0.0
2522 };
2523 if ui.input(|i| i.pointer.primary_down()) && speed != 0.0 {
2524 let dt = ui.input(|i| i.stable_dt).clamp(0.001, 0.05);
2525 next_offset = Some((viewport.min.y + speed * 500.0 * dt).clamp(
2526 0.0,
2527 (rows.len() as f32 * LIST_ROW - viewport.height()).max(0.0),
2528 ));
2529 ui.ctx().request_repaint();
2530 }
2531 }
2532 }
2533 }
2534 let first = (viewport.min.y / LIST_ROW).floor() as usize;
2535 let last = ((viewport.max.y / LIST_ROW).ceil() as usize + 1).min(rows.len());
2536 for index in first.min(rows.len())..last {
2537 let row = &rows[index];
2538 let rect = egui::Rect::from_min_size(
2539 origin + egui::vec2(0.0, index as f32 * LIST_ROW),
2540 egui::vec2(width, LIST_ROW),
2541 );
2542 let selected = !row.ids.is_empty() && row.ids.is_subset(&self.model.selected);
2543 let response = ui
2544 .interact(
2545 rect,
2546 egui::Id::unique(("archive-row", &row.path)),
2547 if active && self.drag_out.is_some() {
2548 // 선택한 항목을 창 밖으로 끌어 놓을 수 있게 끌기도 받음.
2549 egui::Sense::click_and_drag()
2550 } else if active {
2551 egui::Sense::click()
2552 } else {
2553 egui::Sense::hover()
2554 },
2555 )
2556 .on_hover_text(&row.name);
2557 theme::pointer(&response);
2558 response.widget_info(|| {
2559 egui::WidgetInfo::selected(
2560 egui::Role::ListBoxOption,
2561 active,
2562 selected,
2563 &row.name,
2564 )
2565 });
2566 if response.has_focus() {
2567 focused = Some(index);
2568 ui.ctx().memory_mut(|memory| {
2569 memory.set_focus_lock_filter(
2570 response.id,
2571 egui::EventFilter {
2572 vertical_arrows: true,
2573 escape: true,
2574 ..Default::default()
2575 },
2576 )
2577 });
2578 }
2579 theme::row_background(
2580 ui,
2581 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW)),
2582 selected,
2583 response.hovered(),
2584 );
2585 if response.clicked() {
2586 background.request_focus();
2587 let modifiers = ui.input(|i| i.modifiers);
2588 self.select_row(
2589 &rows,
2590 index,
2591 modifiers.ctrl || modifiers.command,
2592 modifiers.shift,
2593 );
2594 }
2595 // 오래 누르기만 해도 egui는 끌기로 보므로, 실제로 움직였을 때만 시작함.
2596 if active
2597 && self.drag_out.is_some()
2598 && !self.drag_out_fired
2599 && response.dragged()
2600 && ui.input(|i| {
2601 i.pointer
2602 .press_origin()
2603 .zip(i.pointer.interact_pos())
2604 .is_some_and(|(from, to)| from.distance(to) >= DRAG_OUT_DISTANCE)
2605 })
2606 {
2607 self.drag_out_fired = true;
2608 if !selected {
2609 // 선택하지 않은 행을 끌면 그 행만 선택한 뒤 끎.
2610 self.select_row(&rows, index, false, false);
2611 }
2612 drag_out = true;
2613 }
2614 if response.double_clicked() {
2615 if row.directory {
2616 open = Some(row.path.clone());
2617 } else if let [id] = row.ids.iter().copied().collect::<Vec<_>>()[..] {
2618 open_file = Some(id);
2619 }
2620 }
2621 if active && response.secondary_clicked() && !selected {
2622 // 선택하지 않은 행을 오른쪽 클릭하면 그 행만 선택한 뒤 메뉴를 엶.
2623 self.select_row(&rows, index, false, false);
2624 }
2625 if active {
2626 response.context_menu(|ui| {
2627 if ui
2628 .button("압축 파일명으로 새 폴더를 만들어 압축 풀기")
2629 .clicked()
2630 {
2631 menu_action = Some(MenuAction::NewFolder);
2632 }
2633 if ui.button("특정 폴더에 압축 풀기").clicked() {
2634 menu_action = Some(MenuAction::ChooseFolder);
2635 }
2636 });
2637 }
2638 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
2639 let name = if row.encrypted {
2640 format!("*{}", row.name)
2641 } else {
2642 row.name.clone()
2643 };
2644 Self::entry_cells(
2645 ui,
2646 rect,
2647 row.directory,
2648 &name,
2649 &row.name,
2650 row.bytes
2651 .map(present::bytes_text)
2652 .unwrap_or_else(|| "—".into()),
2653 name_width,
2654 );
2655 if active
2656 && self.list_cursor == Some(index)
2657 && (response.has_focus() || background.has_focus())
2658 {
2659 ui.painter().rect_stroke(
2660 egui::Rect::from_min_size(rect.min, egui::vec2(full_width, LIST_ROW))
2661 .shrink(1.0),
2662 0,
2663 egui::Stroke::new(1.0, theme::BLUE),
2664 egui::StrokeKind::Inside,
2665 );
2666 }
2667 }
2668 if rows.is_empty()
2669 && !(self.model.busy() && matches!(self.last_request, Some(Start::List { .. })))
2670 {
2671 ui.scope_builder(egui::UiBuilder::new().max_rect(clip), |ui| {
2672 ui.centered_and_justified(|ui| {
2673 ui.label(if self.search.is_empty() {
2674 "이 폴더는 비어 있습니다"
2675 } else {
2676 "일치하는 항목이 없습니다"
2677 })
2678 });
2679 });
2680 }
2681 #[cfg(all(feature = "ui-fixture", debug_assertions))]
2682 if let Some(rect) = self.scenario_marquee {
2683 ui.painter().with_clip_rect(clip).rect(
2684 rect.translate(origin.to_vec2()),
2685 0,
2686 theme::BLUE.gamma_multiply(0.16),
2687 egui::Stroke::new(1.0, theme::BLUE),
2688 egui::StrokeKind::Inside,
2689 );
2690 }
2691 if let Some(drag) = &self.marquee
2692 && drag.moved
2693 && let Some(point) = point
2694 {
2695 let rect = egui::Rect::from_two_pos(
2696 origin + drag.origin.to_vec2(),
2697 point.clamp(clip.min, clip.max),
2698 );
2699 ui.painter().with_clip_rect(clip).rect(
2700 rect,
2701 0,
2702 theme::BLUE.gamma_multiply(0.16),
2703 egui::Stroke::new(1.0, theme::BLUE),
2704 egui::StrokeKind::Inside,
2705 );
2706 }
2707 });
2708 self.list_offset = next_offset.unwrap_or(output.state.clamped_offset().y);
2709 if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) {
2710 self.marquee = None;
2711 self.drag_out_fired = false;
2712 }
2713 let escape_from_list = self.list_focused
2714 && ui.ctx().memory(|memory| memory.focused()).is_none()
2715 && ui.input(|i| i.key_pressed(egui::Key::Escape));
2716 self.list_focused =
2717 active && (background.has_focus() || focused.is_some() || escape_from_list);
2718 if self.list_focused {
2719 if let Some(index) = focused {
2720 self.list_cursor = Some(index);
2721 }
2722 let modifiers = ui.input(|i| i.modifiers);
2723 let ctrl = modifiers.ctrl || modifiers.command;
2724 // 선택이 있으면 Esc는 선택만 해제함. 선택이 없으면 창 닫기로 넘김.
2725 if (!self.model.selected.is_empty() || self.marquee.is_some())
2726 && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
2727 {
2728 self.model.selected.clear();
2729 self.marquee = None;
2730 background.request_focus();
2731 self.escape_handled = true;
2732 }
2733 if ctrl && ui.input(|i| i.key_pressed(egui::Key::A)) {
2734 self.model.selected = rows
2735 .iter()
2736 .flat_map(|row| row.ids.iter().copied())
2737 .collect();
2738 self.list_cursor = (!rows.is_empty()).then_some(0);
2739 self.list_anchor = self.list_cursor;
2740 }
2741 if !rows.is_empty() {
2742 let direction = if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
2743 Some(1isize)
2744 } else if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
2745 Some(-1)
2746 } else {
2747 None
2748 };
2749 if let Some(direction) = direction {
2750 let index = self.list_cursor.map_or(0, |index| {
2751 index.saturating_add_signed(direction).min(rows.len() - 1)
2752 });
2753 if ctrl && !modifiers.shift {
2754 self.list_cursor = Some(index);
2755 } else {
2756 self.select_row(&rows, index, ctrl, modifiers.shift);
2757 }
2758 background.request_focus();
2759 let top = index as f32 * LIST_ROW;
2760 if top < self.list_offset {
2761 self.list_offset = top;
2762 } else if top + LIST_ROW > self.list_offset + output.inner_rect.height() {
2763 self.list_offset = top + LIST_ROW - output.inner_rect.height();
2764 }
2765 ui.ctx().request_repaint();
2766 }
2767 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
2768 let index = self
2769 .list_cursor
2770 .or(focused)
2771 .unwrap_or(0)
2772 .min(rows.len() - 1);
2773 if rows[index].directory {
2774 open = Some(rows[index].path.clone());
2775 } else if let [id] = rows[index].ids.iter().copied().collect::<Vec<_>>()[..] {
2776 open_file = Some(id);
2777 }
2778 }
2779 }
2780 if ui.input(|i| i.key_pressed(egui::Key::Backspace)) && !self.folder.is_empty() {
2781 open = Some(
2782 self.folder
2783 .rsplit_once('/')
2784 .map_or("", |(parent, _)| parent)
2785 .to_owned(),
2786 );
2787 }
2788 }
2789 // 마우스 옆 버튼(뒤로)을 목록 위에서 누르면 상위 폴더로 이동함.
2790 if active
2791 && !self.folder.is_empty()
2792 && ui.input(|i| {
2793 i.pointer.button_pressed(egui::PointerButton::Extra1)
2794 && i.pointer
2795 .interact_pos()
2796 .is_some_and(|pos| path_row.union(background.rect).contains(pos))
2797 })
2798 {
2799 open = Some(
2800 self.folder
2801 .rsplit_once('/')
2802 .map_or("", |(parent, _)| parent)
2803 .to_owned(),
2804 );
2805 }
2806 if let Some(folder) = open {
2807 self.browse_folder(&folder);
2808 background.request_focus();
2809 }
2810 if let Some(id) = open_file {
2811 self.open_entry(id);
2812 }
2813 if drag_out {
2814 self.begin_drag_out();
2815 }
2816 match menu_action {
2817 Some(MenuAction::NewFolder) => {
2818 self.extract_to_new_folder();
2819 }
2820 Some(MenuAction::ChooseFolder) => self.open_picker(Purpose::Destination),
2821 None => {}
2822 }
2823 }
2824
2825 fn clear_list_selection(&mut self) {
2826 self.model.selected.clear();
2827 self.list_anchor = None;
2828 self.list_cursor = None;
2829 self.list_offset = 0.0;
2830 self.marquee = None;
2831 }
2832
2833 fn select_row(&mut self, rows: &[browser::Row], index: usize, ctrl: bool, shift: bool) {
2834 if shift {
2835 let anchor = self
2836 .list_anchor
2837 .unwrap_or(self.list_cursor.unwrap_or(index))
2838 .min(rows.len() - 1);
2839 if !ctrl {
2840 self.model.selected.clear();
2841 }
2842 for row in &rows[anchor.min(index)..=anchor.max(index)] {
2843 self.model.selected.extend(&row.ids);
2844 }
2845 self.list_anchor = Some(anchor);
2846 } else {
2847 if !ctrl {
2848 self.model.selected.clear();
2849 }
2850 if ctrl && rows[index].ids.is_subset(&self.model.selected) {
2851 // 폴더 이동 시 선택을 지우므로 현재 행의 ID만 제거함.
2852 self.model
2853 .selected
2854 .retain(|id| !rows[index].ids.contains(id));
2855 } else {
2856 self.model.selected.extend(&rows[index].ids);
2857 }
2858 self.list_anchor = Some(index);
2859 }
2860 self.list_cursor = Some(index);
2861 }
2862
2863 fn result_visible(&self) -> bool {
2864 !self.dismissed
2865 && !self
2866 .last_request
2867 .as_ref()
2868 .is_some_and(|r| matches!(r, Start::Preview { .. }))
2869 && !self.model.busy()
2870 && self.last_request.as_ref().is_some_and(|request| {
2871 !matches!(request, Start::List { .. })
2872 || self.model.error.is_some()
2873 || self
2874 .model
2875 .terminal
2876 .as_ref()
2877 .is_some_and(|t| t.outcome != Outcome::Completed)
2878 })
2879 }
2880
2881 fn can_preview(&self) -> bool {
2882 self.model.can_preview()
2883 && browser::rows(&self.model.entries, &self.folder, &self.search)
2884 .iter()
2885 .any(|row| !row.directory && row.ids == self.model.selected)
2886 }
2887
2888 fn begin_preview(&mut self, ctx: &egui::Context) {
2889 if !self.can_preview() || self.picker.is_some() {
2890 return;
2891 }
2892 self.preview_texture = None;
2893 self.preview_text.clear();
2894 self.preview_name = self
2895 .model
2896 .entries
2897 .iter()
2898 .find(|e| self.model.selected.contains(&e.id))
2899 .unwrap()
2900 .name
2901 .clone();
2902 self.preview_return_focus = Some(
2903 ctx.memory(|m| m.focused())
2904 .unwrap_or_else(|| egui::Id::unique("archive-list")),
2905 );
2906 self.preview_initial_focus = true;
2907 let request = Start::Preview {
2908 archive: self.model.archive.clone().unwrap(),
2909 entry_id: *self.model.selected.first().unwrap(),
2910 list_id: self.model.list_id.clone().unwrap(),
2911 };
2912 self.preview_open = true;
2913 self.start(request);
2914 }
2915
2916 fn close_preview(&mut self) {
2917 self.preview_open = false;
2918 self.model.dismiss_preview();
2919 self.preview_texture = None;
2920 self.preview_text.clear();
2921 self.dismissed = true;
2922 }
2923
2924 fn preview_dialog(&mut self, ctx: &egui::Context) {
2925 if !self.preview_open
2926 || self.model.challenge.is_some()
2927 || self.model.resource.is_some()
2928 || self.model.close != Close::Open
2929 {
2930 return;
2931 }
2932 if let Some(preview) = self.model.preview.as_mut()
2933 && (!preview.data.is_empty() || preview.info.total_bytes == 0)
2934 {
2935 match preview.info.format {
2936 PreviewFormat::Utf8Text => {
2937 self.preview_text =
2938 String::from_utf8(std::mem::take(&mut preview.data)).unwrap_or_default();
2939 }
2940 PreviewFormat::Rgba8 => {
2941 let width = preview.info.width as usize;
2942 let height = preview.info.height as usize;
2943 let limit = ctx.input(|i| i.max_texture_side).max(1);
2944 let step = width.div_ceil(limit).max(height.div_ceil(limit)).max(1);
2945 let size = [width.div_ceil(step), height.div_ceil(step)];
2946 let mut colors = Vec::with_capacity(size[0] * size[1]);
2947 for y in (0..height).step_by(step) {
2948 for x in (0..width).step_by(step) {
2949 let index = (y * width + x) * 4;
2950 colors.push(egui::Color32::from_rgba_unmultiplied(
2951 preview.data[index],
2952 preview.data[index + 1],
2953 preview.data[index + 2],
2954 preview.data[index + 3],
2955 ));
2956 }
2957 }
2958 let pixels = egui::ColorImage::new(size, colors);
2959 preview.data = Vec::new();
2960 self.preview_texture = Some(ctx.load_texture(
2961 "archive-preview",
2962 pixels,
2963 egui::TextureOptions::LINEAR,
2964 ));
2965 }
2966 }
2967 }
2968 let mut close = false;
2969 let modal = egui::Modal::new(egui::Id::unique("archive-preview")).show(ctx, |ui| {
2970 ui.set_width((ctx.content_rect().width() - 64.0).clamp(240.0, 760.0));
2971 ui.horizontal(|ui| {
2972 ui.heading("미리보기");
2973 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
2974 let button = theme::flat_icon_button(
2975 ui,
2976 "미리보기 닫기",
2977 theme::CLOSE,
2978 true,
2979 egui::vec2(36.0, 36.0),
2980 );
2981 if self.preview_initial_focus {
2982 button.request_focus();
2983 self.preview_initial_focus = false;
2984 }
2985 close |= button.clicked();
2986 });
2987 });
2988 ui.add(egui::Label::new(&self.preview_name).truncate())
2989 .on_hover_text(&self.preview_name);
2990 let max_height = (ctx.content_rect().height() - 220.0).clamp(100.0, 560.0);
2991 if self.model.busy() {
2992 ui.label("미리보기를 불러오는 중입니다");
2993 if ui.button("취소").clicked() {
2994 close = true;
2995 }
2996 } else if let Some(error) = self.model.error.as_ref() {
2997 Self::error_notice(ui, error);
2998 } else if let Some(texture) = self.preview_texture.as_ref() {
2999 ui.add(
3000 egui::Image::new(texture)
3001 .max_size(egui::vec2(ui.available_width(), max_height))
3002 .shrink_to_fit(),
3003 );
3004 } else if self.model.preview.is_some() {
3005 egui::ScrollArea::both()
3006 .id_salt("preview-text")
3007 .max_height(max_height)
3008 .show(ui, |ui| {
3009 let mut text = self.preview_text.as_str();
3010 ui.add(
3011 egui::TextEdit::multiline(&mut text)
3012 .desired_width(ui.available_width())
3013 .desired_rows(12)
3014 .frame(egui::Frame::NONE),
3015 );
3016 });
3017 if self.preview_text.is_empty() {
3018 ui.label("빈 텍스트 파일입니다");
3019 }
3020 } else {
3021 let code = self.model.terminal.as_ref().and_then(|t| t.error);
3022 ui.label(match code {
3023 Some(ErrorCode::Limit) => "미리보기 크기 또는 처리 한도를 초과했습니다.",
3024 Some(ErrorCode::Integrity) => "파일이 손상됐거나 UTF-8 텍스트가 아닙니다.",
3025 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature) => {
3026 "이 파일 형식은 미리보기를 지원하지 않습니다."
3027 }
3028 Some(ErrorCode::SourceChanged) => "압축파일이 변경됐습니다. 다시 열어 주세요.",
3029 Some(ErrorCode::WrongPassword) => "암호가 올바르지 않습니다.",
3030 _ => "미리보기를 불러오지 못했습니다.",
3031 });
3032 ui.label("닫은 뒤 파일을 선택하고 [압축해제]를 사용할 수 있습니다.");
3033 }
3034 });
3035 if close || modal.should_close() {
3036 self.close_preview();
3037 }
3038 }
3039
3040 fn limit_result_visible(&self) -> bool {
3041 self.result_visible()
3042 && (self.model.volume_problem.is_some()
3043 || self.model.terminal.as_ref().is_some_and(|terminal| {
3044 terminal.error == Some(ErrorCode::Limit)
3045 || (matches!(
3046 terminal.error,
3047 Some(ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature)
3048 ) && self
3049 .model
3050 .archive
3051 .as_ref()
3052 .is_some_and(|p| present::excluded_split(p)))
3053 }))
3054 }
3055
3056 fn limit_result_dialog(&mut self, ctx: &egui::Context) {
3057 if !self.limit_result_visible() || self.main_modal_open() {
3058 return;
3059 }
3060 egui::Modal::new(egui::Id::new("archive-limit-result")).show(ctx, |ui| {
3061 ui.set_width((ctx.content_rect().width() - 64.0).min(WORK_WIDTH));
3062 ui.heading("작업 결과");
3063 self.work_area(ui);
3064 });
3065 }
3066
3067 fn error_notice(ui: &mut egui::Ui, error: &str) {
3068 let response = theme::panel(theme::ERROR_BG)
3069 .show(ui, |ui| {
3070 ui.horizontal_wrapped(|ui| {
3071 theme::icon(ui, Icon::Error, 24.0);
3072 ui.colored_label(theme::ERROR, error);
3073 });
3074 })
3075 .response;
3076 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Alert, true, error));
3077 }
3078
3079 fn work_visible(&self) -> bool {
3080 !self
3081 .last_request
3082 .as_ref()
3083 .is_some_and(|r| matches!(r, Start::Preview { .. }))
3084 && (self.model.busy()
3085 || self.result_visible()
3086 || (self.ui_error.is_some() && !self.create))
3087 }
3088
3089 /// 메인 창 가운데에 모달(암호 입력, 종료 확인, 파일 선택 안내)이나 같은 자리에 뜨는
3090 /// ZIP 만들기 창이 떠 있는지. 닫기가 정해진 뒤(Allowed)에도 결과 창을 다시 띄우지 않음.
3091 /// 모달이 늘어도 진행·결과 창 숨김 규칙은 이 한 곳만 보면 되도록 모음.
3092 fn main_modal_open(&self) -> bool {
3093 (self.create && !self.model.busy())
3094 || self.picker.is_some()
3095 || self.model.challenge.is_some()
3096 || self.model.resource.is_some()
3097 || self.model.conflict.is_some()
3098 || self.model.close != Close::Open
3099 }
3100
3101 fn work_window(&mut self, ctx: &egui::Context) {
3102 if !self.work_visible() {
3103 self.work = WorkWindow::default();
3104 return;
3105 }
3106 if self.limit_result_visible() {
3107 self.work.open = false;
3108 return;
3109 }
3110 if ctx.embed_viewports() && !self.work_in_parent {
3111 // 별도 창을 만들 수 없는 환경(시험 등)은 show()에서 하단에 그림.
3112 return;
3113 }
3114 if self.main_modal_open() {
3115 // 메인 창 가운데에 뜨는 모달을 항상 위에 뜨는 진행·결과 창이 가리지 않게
3116 // 그동안 창을 닫음. 부모 기준 위치는 기억해 두고 다시 엶.
3117 self.work.open = false;
3118 return;
3119 }
3120 let id = egui::ViewportId::from_hash_of("archive-work");
3121 let title = if self.model.busy() {
3122 present::activity_text(
3123 &self.model,
3124 matches!(
3125 self.last_request,
3126 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3127 ),
3128 )
3129 .to_owned()
3130 } else {
3131 "작업 결과".to_owned()
3132 };
3133 if self.work_in_parent {
3134 // Wayland는 창 올리기를 지원하지 않으므로 부모 안에서 같은 내용을 그림.
3135 // egui 기본 제목 줄의 닫기 버튼은 마우스를 올려도 모양이 바뀌지 않으므로
3136 // 제목 줄을 직접 그리고 별도 창과 같은 닫기 버튼을 씀.
3137 let mut close = false;
3138 let busy = self.model.busy();
3139 egui::Window::new(RichText::new(&title).size(theme::FONT_SMALL))
3140 .id(egui::Id::new("archive-work-in-parent"))
3141 .title_bar(false)
3142 .default_pos(
3143 ctx.content_rect().center() - egui::vec2(WORK_WIDTH, self.work.height) / 2.0,
3144 )
3145 .default_width(WORK_WIDTH)
3146 .min_width(WORK_WIDTH)
3147 .max_width(WORK_WIDTH)
3148 .max_height(WORK_MAX_HEIGHT)
3149 .collapsible(false)
3150 .resizable(false)
3151 .fade_in(false)
3152 .fade_out(false)
3153 .frame(
3154 egui::Frame::new()
3155 .fill(theme::PANEL)
3156 .stroke(egui::Stroke::new(1.0, theme::BORDER))
3157 .inner_margin(egui::Margin::ZERO)
3158 .corner_radius(0),
3159 )
3160 .show(ctx, |ui| {
3161 let spacing = ui.spacing().item_spacing.y;
3162 ui.spacing_mut().item_spacing.y = 0.0;
3163 close = window_frame::in_parent_title(ui, "work-in-parent", &title, !busy);
3164 egui::Frame::new()
3165 .inner_margin(egui::Margin::same(theme::PAD))
3166 .show(ui, |ui| {
3167 ui.spacing_mut().item_spacing.y = spacing;
3168 ui.set_width(WORK_WIDTH - 2.0 * theme::PAD as f32);
3169 self.work_area(ui)
3170 });
3171 });
3172 if close {
3173 self.dismissed = true;
3174 self.ui_error = None;
3175 self.model.input_error = None;
3176 }
3177 return;
3178 }
3179 let window_title = format!("{title} — Zipelo");
3180 let custom_frame = self.custom_frame;
3181 let size = egui::vec2(WORK_WIDTH, self.work.height);
3182 let builder = self.work.builder(
3183 ctx,
3184 id,
3185 size,
3186 &window_title,
3187 !custom_frame,
3188 self.picker.is_some(),
3189 );
3190 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
3191 // 끝난 작업의 결과 창은 Esc로 닫음. 진행 중에는 [취소] 버튼을 씀.
3192 if !self.model.busy()
3193 && ui
3194 .ctx()
3195 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
3196 {
3197 crate::log_debug!("Esc: 작업 결과 창 닫기");
3198 self.dismissed = true;
3199 self.ui_error = None;
3200 self.model.input_error = None;
3201 }
3202 if ui.ctx().input(|i| i.viewport().close_requested()) {
3203 if self.model.busy() {
3204 ui.ctx()
3205 .send_viewport_cmd(egui::ViewportCommand::CancelClose);
3206 } else {
3207 self.dismissed = true;
3208 self.ui_error = None;
3209 self.model.input_error = None;
3210 }
3211 }
3212 if class == egui::ViewportClass::EmbeddedWindow {
3213 ui.set_width(WORK_WIDTH);
3214 self.work_area(ui);
3215 return None;
3216 }
3217 let mut chrome = 0.0;
3218 if custom_frame {
3219 window_frame::title_bar(
3220 ui,
3221 "work",
3222 &window_title,
3223 window_frame::Buttons {
3224 minimize: false,
3225 maximize: false,
3226 },
3227 );
3228 window_frame::edges(ui.ctx(), false);
3229 chrome = window_frame::TITLE_HEIGHT;
3230 }
3231 let margin = theme::PAD as f32;
3232 egui::CentralPanel::default()
3233 .frame(theme::panel(theme::PANEL).corner_radius(0))
3234 .show(ui, |ui| {
3235 let content = ui.vertical(|ui| self.work_area(ui)).response.rect;
3236 Some(content.height() + 2.0 * margin + chrome)
3237 })
3238 .inner
3239 });
3240 if let Some(height) = height {
3241 let height = height.clamp(WORK_MIN_HEIGHT, WORK_MAX_HEIGHT).ceil();
3242 if (height - self.work.height).abs() > 1.0 {
3243 self.work.height = height;
3244 }
3245 }
3246 }
3247
3248 fn work_area(&mut self, ui: &mut egui::Ui) {
3249 // 선택 창 안내 모달은 메인 창만 막으므로, 별도 진행 창의 버튼은 여기서 막음.
3250 let enabled = self.picker.is_none();
3251 ui.add_enabled_ui(enabled, |ui| self.work_contents(ui));
3252 }
3253
3254 fn work_contents(&mut self, ui: &mut egui::Ui) {
3255 if self.model.busy() {
3256 self.progress(ui);
3257 } else if self.result_visible() {
3258 self.result(ui);
3259 }
3260 if !self.create
3261 && let Some(error) = &self.ui_error
3262 {
3263 Self::error_notice(ui, error);
3264 if error == present::FOLDER_ERROR
3265 && theme::action(ui, "폴더 바꾸기", false, true).clicked()
3266 {
3267 self.open_picker(Purpose::Destination);
3268 }
3269 }
3270 if let Some(error) = &self.model.input_error {
3271 ui.colored_label(
3272 theme::ERROR,
3273 if error.starts_with("암호는") {
3274 error.as_str()
3275 } else {
3276 if matches!(
3277 self.last_request,
3278 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3279 ) {
3280 "저장 위치와 추가한 항목을 확인하세요"
3281 } else {
3282 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
3283 "원본과 다른 새 복구본 저장 위치를 선택하세요"
3284 } else {
3285 "풀 위치와 선택한 항목을 확인하세요"
3286 }
3287 }
3288 },
3289 );
3290 }
3291 }
3292
3293 fn progress(&mut self, ui: &mut egui::Ui) {
3294 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
3295 ui.strong("ZIP 복구 중");
3296 ui.label(if self.model.recovery_end.is_some() {
3297 "분석 완료 / 복구본 저장과 작업자 종료 확인 중"
3298 } else {
3299 "원본을 분석하고 있습니다. 전체 항목 수는 아직 알 수 없습니다."
3300 });
3301 ui.label(format!(
3302 "확인한 항목 {}개",
3303 self.model.recovery_entries.len()
3304 ));
3305 self.cancel_action(ui, false);
3306 return;
3307 }
3308 if self.model.resource.is_some() {
3309 ui.horizontal(|ui| {
3310 ui.label("사용자 허용을 기다리고 있습니다");
3311 self.cancel_action(ui, false);
3312 });
3313 return;
3314 }
3315 let creating = matches!(
3316 self.last_request,
3317 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3318 );
3319 let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some();
3320 let title = present::activity_text(&self.model, creating);
3321 ui.strong(title);
3322 if let Some((stage, done, total, count)) = self.model.progress {
3323 // 원본을 읽는 단계에서는 아직 처리한 항목이 없으므로 개수를 표시하지 않음.
3324 let processed = if stage == Stage::Read {
3325 String::new()
3326 } else {
3327 format!("{count}개 처리함, ")
3328 };
3329 if let Some(total) = total.filter(|n| *n > 0) {
3330 ui.scope(|ui| {
3331 ui.visuals_mut().extreme_bg_color = theme::BORDER;
3332 ui.add(
3333 egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32)
3334 .fill(theme::BLUE)
3335 .desired_height(theme::SPACE * 2.0),
3336 );
3337 });
3338 ui.horizontal(|ui| {
3339 ui.label(format!(
3340 "{:.0}% / {processed}{} / {}",
3341 (done as f64 / total as f64).clamp(0.0, 1.0) * 100.0,
3342 present::bytes_text(done),
3343 present::bytes_text(total)
3344 ));
3345 self.cancel_action(ui, cancelling);
3346 });
3347 } else {
3348 theme::indeterminate(ui);
3349 ui.horizontal(|ui| {
3350 ui.label(format!("{processed}{}", present::bytes_text(done)));
3351 self.cancel_action(ui, cancelling);
3352 });
3353 }
3354 } else {
3355 theme::indeterminate(ui);
3356 ui.horizontal(|ui| {
3357 ui.label("작업을 진행하고 있습니다");
3358 self.cancel_action(ui, cancelling);
3359 });
3360 }
3361 }
3362
3363 fn cancel_action(&mut self, ui: &mut egui::Ui, cancelling: bool) {
3364 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3365 if theme::action(ui, "취소", false, !cancelling).clicked() {
3366 self.clear_password();
3367 self.model.cancel();
3368 }
3369 });
3370 }
3371
3372 fn recovery_result(&mut self, ui: &mut egui::Ui) {
3373 let t = self.model.terminal.as_ref();
3374 let summary = self.model.recovery_end.as_ref();
3375 let confirmed = self.model.confirmed && self.model.error.is_none();
3376 let saved = confirmed
3377 && t.is_some_and(|t| t.publication == Publication::Complete && t.created_count == 1)
3378 && summary.is_some_and(|s| s.verified_entries > 0);
3379 let partial = summary.is_some_and(|s| !s.complete());
3380 let title = if !confirmed {
3381 "복구 결과를 확정할 수 없음"
3382 } else if saved && partial {
3383 "일부 항목만 복구함"
3384 } else if saved && t.is_some_and(|t| t.outcome == Outcome::Completed) {
3385 "복구본 저장 완료"
3386 } else if t.is_some_and(|t| t.error == Some(ErrorCode::RecoveryImpossible)) {
3387 "복구 가능한 항목 없음"
3388 } else if t.is_some_and(|t| t.outcome == Outcome::Cancelled) {
3389 "복구를 취소했습니다"
3390 } else {
3391 "복구본 저장을 완료하지 못했습니다"
3392 };
3393 ui.heading(title);
3394 ui.label(
3395 "원본은 수정하지 않습니다. 검증 통과는 손상 전 내용과 동일하다는 보증이 아닙니다.",
3396 );
3397 let output = match &self.last_request {
3398 Some(Start::RecoverZip { output_file, .. }) => output_file.clone(),
3399 _ => return,
3400 };
3401 if saved
3402 || self
3403 .model
3404 .outputs
3405 .iter()
3406 .any(|(_, d)| matches!(d, Disposition::Created | Disposition::CommitUncertain))
3407 {
3408 theme::bounded_text(ui, &output.display().to_string(), ui.available_width());
3409 }
3410 for (name, _) in self
3411 .model
3412 .outputs
3413 .iter()
3414 .filter(|(_, d)| *d == Disposition::PartialRetained)
3415 {
3416 let retained = output.parent().unwrap_or(Path::new("")).join(name);
3417 theme::bounded_text(
3418 ui,
3419 &format!("남은 임시 파일: {}", retained.display()),
3420 ui.available_width(),
3421 );
3422 }
3423 if let Some(error) = &self.model.error {
3424 ui.colored_label(theme::WARNING, error);
3425 }
3426 if let Some(t) = t {
3427 if let Some(code) = t.error {
3428 ui.label(present::error_text(code));
3429 }
3430 for warning in present::publication_warnings(
3431 Some(t),
3432 self.model.confirmed,
3433 Some(&BTreeSet::from([output
3434 .file_name()
3435 .unwrap_or_default()
3436 .to_string_lossy()
3437 .into_owned()])),
3438 &BTreeSet::new(),
3439 &self.model.outputs,
3440 ) {
3441 ui.colored_label(theme::WARNING, warning);
3442 }
3443 if let Some(warning) = present::durability_warning(t.durability) {
3444 ui.colored_label(theme::WARNING, warning);
3445 }
3446 }
3447 let notice = summary.map(|s| {
3448 format!(
3449 "검증되어 포함됨 {}개 / 유실됨 {}개 / 무결성 미확인 {}개{}",
3450 s.verified_entries,
3451 s.lost_entries,
3452 s.unverified_entries,
3453 if s.unknown_loss {
3454 " / 전체 목록을 알 수 없어 추가 유실 여부를 확인할 수 없습니다"
3455 } else {
3456 ""
3457 }
3458 )
3459 });
3460 if let Some(notice) = &notice {
3461 ui.label(notice);
3462 }
3463 egui::ScrollArea::vertical()
3464 .id_salt("recovery-findings")
3465 .max_height(220.0)
3466 .show_rows(ui, 24.0, self.model.recovery_entries.len(), |ui, rows| {
3467 for entry in &self.model.recovery_entries[rows] {
3468 let status = match entry.status {
3469 RecoveryStatus::Verified => "검증되어 포함됨",
3470 RecoveryStatus::Lost => "유실됨",
3471 RecoveryStatus::Unverified => "무결성 미확인",
3472 };
3473 let reason = match entry.reason {
3474 RecoveryReason::None => "내용 검증 통과",
3475 RecoveryReason::HeaderRebuilt => "헤더 재구성",
3476 RecoveryReason::Truncated => "파일 절단",
3477 RecoveryReason::CrcMismatch => "CRC 불일치",
3478 RecoveryReason::DecodeFailure => "압축 데이터 손상",
3479 RecoveryReason::BoundaryUnknown => "항목 경계 불명",
3480 RecoveryReason::UnsupportedFeature => "지원하지 않는 기능",
3481 RecoveryReason::MetadataMissing => "메타정보 누락",
3482 };
3483 theme::bounded_text(
3484 ui,
3485 &format!(
3486 "{status} / {reason}: {}",
3487 entry.name.as_deref().unwrap_or("이름 확인 불가")
3488 ),
3489 ui.available_width(),
3490 );
3491 }
3492 });
3493 if saved && theme::action(ui, "복구본 열기", true, true).clicked() {
3494 self.recovery_warning = partial.then(|| (output.clone(), notice.unwrap_or_default()));
3495 self.open_path(output);
3496 }
3497 if self.model.can_retry_expanded()
3498 && theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked()
3499 {
3500 self.model.retry_expanded(self.factory.as_mut());
3501 }
3502 }
3503
3504 fn result(&mut self, ui: &mut egui::Ui) {
3505 if matches!(self.last_request, Some(Start::RecoverZip { .. })) {
3506 self.recovery_result(ui);
3507 return;
3508 }
3509 if self.model.confirmed
3510 && self.model.error.is_none()
3511 && self
3512 .model
3513 .terminal
3514 .as_ref()
3515 .is_some_and(|t| t.error == Some(ErrorCode::Integrity))
3516 && matches!(
3517 self.last_request,
3518 Some(Start::List { .. } | Start::Extract { .. })
3519 )
3520 {
3521 ui.label("원본을 바꾸지 않고 새 ZIP 복구본을 만듭니다. 일부 항목은 복구되지 않을 수 있습니다.");
3522 if theme::action(ui, "복구본 저장 위치 선택", true, true).clicked() {
3523 self.open_picker(Purpose::SaveRecoveryZip);
3524 }
3525 }
3526 let t = self.model.terminal.clone();
3527 let listing = matches!(self.last_request, Some(Start::List { .. }));
3528 let creating = matches!(
3529 self.last_request,
3530 Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. })
3531 );
3532 // 분할 7z는 작업자가 보고한 볼륨 수로 기대 이름(이름.7z.001…)을 정함.
3533 let split_targets = match (&self.last_request, t.as_ref()) {
3534 (
3535 Some(Start::CreateSevenZip {
3536 output_file,
3537 volume_size: Some(_),
3538 ..
3539 }),
3540 Some(t),
3541 ) => output_file.file_name().map(|name| {
3542 (1..=t.created_count.clamp(1, present::MAX_VOLUMES))
3543 .map(|index| format!("{}.{index:03}", name.to_string_lossy()))
3544 .collect::<BTreeSet<_>>()
3545 }),
3546 _ => None,
3547 };
3548 let resolved_targets = present::resolved_targets(
3549 split_targets.as_ref().or(self.targets.as_ref()),
3550 &self.model.entries,
3551 matches!(
3552 self.last_request,
3553 Some(Start::Extract {
3554 gzip_output_name: Some(_),
3555 ..
3556 })
3557 )
3558 .then_some(self.gzip_name.as_str()),
3559 &self.model.resolutions,
3560 );
3561 let skipped = self
3562 .model
3563 .resolutions
3564 .iter()
3565 .filter(|r| r.choice == ConflictChoice::Skip)
3566 .count();
3567 let created_names = self
3568 .model
3569 .outputs
3570 .iter()
3571 .filter(|(_, disposition)| *disposition == Disposition::Created)
3572 .map(|(name, _)| name.replace('\\', "/"))
3573 .collect::<BTreeSet<_>>();
3574 let warnings = if listing {
3575 Vec::new()
3576 } else {
3577 present::publication_warnings(
3578 t.as_ref(),
3579 self.model.confirmed,
3580 resolved_targets.as_ref(),
3581 &self.directories,
3582 &self.model.outputs,
3583 )
3584 };
3585 let success = self.model.confirmed
3586 && self.model.error.is_none()
3587 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
3588 && warnings
3589 .iter()
3590 .all(|warning| !creating && *warning == present::CLEANUP_WARNING);
3591 let durability_warning = t
3592 .as_ref()
3593 .filter(|_| self.model.confirmed && !listing)
3594 .and_then(|t| present::durability_warning(t.durability));
3595 let durability_in_details = success
3596 && t.as_ref()
3597 .is_some_and(|t| t.durability == Durability::Unconfirmed);
3598 let cancelled =
3599 self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled);
3600 let title = if success {
3601 if creating {
3602 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3603 "7z 파일을 만들었습니다"
3604 } else {
3605 "ZIP 파일을 만들었습니다"
3606 }
3607 } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) {
3608 "모든 파일을 건너뛰었습니다"
3609 } else {
3610 "압축을 풀었습니다"
3611 }
3612 } else if cancelled {
3613 "작업을 취소했습니다"
3614 } else if listing {
3615 "압축파일을 열지 못했습니다"
3616 } else if creating {
3617 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3618 "7z 파일을 만들지 못했습니다"
3619 } else {
3620 "ZIP 파일을 만들지 못했습니다"
3621 }
3622 } else {
3623 "압축을 풀지 못했습니다"
3624 };
3625 let fill = if success {
3626 theme::SUCCESS_BG
3627 } else if cancelled {
3628 theme::STRIPE
3629 } else {
3630 theme::ERROR_BG
3631 };
3632 let mut choose = false;
3633 let mut retry = false;
3634 let mut expand = false;
3635 let mut reopen = false;
3636 let mut folder = false;
3637 theme::panel(fill).show(ui, |ui| {
3638 ui.horizontal(|ui| {
3639 theme::icon(
3640 ui,
3641 if success {
3642 Icon::Success
3643 } else if cancelled {
3644 Icon::Warning
3645 } else {
3646 Icon::Error
3647 },
3648 24.0,
3649 );
3650 ui.strong(title);
3651 });
3652 let max_height = WORK_RESULT_MAX_HEIGHT;
3653 egui::ScrollArea::vertical()
3654 .id_salt("result-message")
3655 .max_height(max_height)
3656 .show(ui, |ui| {
3657 if success && t.as_ref().is_some_and(|t| t.created_count > 0) {
3658 let path = match self.last_request.as_ref() {
3659 Some(Start::CreateSevenZip {
3660 output_file,
3661 volume_size: Some(_),
3662 ..
3663 }) => present::volume_path(output_file, 1).display().to_string(),
3664 Some(
3665 Start::CreateZip { output_file, .. }
3666 | Start::CreateSevenZip { output_file, .. },
3667 ) => output_file.display().to_string(),
3668 _ => format!("{} 폴더에 저장했습니다.", self.destination.display()),
3669 };
3670 theme::bounded_text(ui, &path, ui.available_width());
3671 if matches!(
3672 self.last_request,
3673 Some(Start::CreateSevenZip {
3674 volume_size: Some(_),
3675 ..
3676 })
3677 ) {
3678 ui.label(format!(
3679 "볼륨 {}개로 나누어 저장했습니다. 풀 때는 첫 볼륨(.001)을 여세요.",
3680 t.as_ref().map_or(0, |t| t.created_count)
3681 ));
3682 }
3683 } else if let Some(problem) = &self.model.volume_problem {
3684 ui.add(egui::Label::new(present::volume_problem_text(problem)).wrap());
3685 } else if let Some(code) = t.as_ref().and_then(|t| t.error) {
3686 ui.label(
3687 if matches!(
3688 code,
3689 ErrorCode::UnsupportedFormat | ErrorCode::UnsupportedFeature
3690 ) && self
3691 .model
3692 .archive
3693 .as_ref()
3694 .is_some_and(|p| present::excluded_split(p))
3695 {
3696 present::SPLIT_SUPPORT.to_owned()
3697 } else if creating && code == ErrorCode::SourceChanged {
3698 "묶을 파일이 바뀌었습니다. 파일을 확인한 뒤 다시 만드세요"
3699 .to_owned()
3700 } else if code == ErrorCode::Limit
3701 && matches!(
3702 self.last_request,
3703 Some(Start::CreateSevenZip {
3704 volume_size: Some(_),
3705 ..
3706 })
3707 )
3708 {
3709 present::VOLUME_LIMIT_ERROR.to_owned()
3710 } else {
3711 present::operation_text(present::error_text(code), creating)
3712 },
3713 );
3714 } else if let Some(error) = &self.model.error {
3715 ui.label(present::operation_text(
3716 present::client_error_text(error),
3717 creating,
3718 ));
3719 }
3720 if skipped > 0 {
3721 ui.label(format!("건너뛴 파일 {skipped}개"));
3722 }
3723 for resolution in self.model.resolutions.iter().filter(|r| {
3724 r.choice == ConflictChoice::Rename
3725 && created_names.contains(&r.relative_name.replace('\\', "/"))
3726 }) {
3727 theme::bounded_text(
3728 ui,
3729 &format!("이름 바꿔 저장: {}", resolution.relative_name),
3730 ui.available_width(),
3731 );
3732 }
3733 for warning in warnings
3734 .iter()
3735 .copied()
3736 .chain(durability_warning.filter(|_| !durability_in_details))
3737 {
3738 ui.horizontal_wrapped(|ui| {
3739 theme::icon(ui, Icon::Warning, 20.0);
3740 ui.colored_label(
3741 theme::WARNING,
3742 present::operation_text(warning, creating),
3743 );
3744 });
3745 }
3746 if !success
3747 && !listing
3748 && present::definitely_unsaved(
3749 t.as_ref(),
3750 self.model.confirmed,
3751 &self.model.outputs,
3752 )
3753 {
3754 ui.label(if creating {
3755 if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) {
3756 "7z 파일을 만들지 않았습니다"
3757 } else {
3758 "ZIP 파일을 만들지 않았습니다"
3759 }
3760 } else {
3761 "아무 파일도 풀지 않았습니다"
3762 });
3763 }
3764 if t.as_ref().is_some_and(|t| {
3765 t.error == Some(ErrorCode::Limit)
3766 && (t.created_count > 0
3767 || t.retained_partial_count > 0
3768 || t.publication != Publication::None)
3769 }) {
3770 ui.label(format!(
3771 "{}개 파일이 저장되었거나 일부 남아 있습니다. 저장 위치를 확인하세요.",
3772 t.as_ref().unwrap().created_count
3773 ));
3774 theme::bounded_text(
3775 ui,
3776 &self.destination.display().to_string(),
3777 ui.available_width(),
3778 );
3779 }
3780 if self.details {
3781 theme::panel(theme::STRIPE).show(ui, |ui| {
3782 if durability_in_details {
3783 if let Some(warning) = durability_warning {
3784 ui.label(present::operation_text(warning, creating));
3785 }
3786 }
3787 if let Some(t) = &t {
3788 for line in terminal_lines(t) {
3789 ui.label(line);
3790 }
3791 }
3792 if let Some(error) = &self.model.error {
3793 ui.label(error);
3794 }
3795 for (name, state) in &self.model.outputs {
3796 theme::bounded_text(
3797 ui,
3798 &format!("{name}: {}", disposition_label(*state)),
3799 ui.available_width(),
3800 );
3801 }
3802 });
3803 }
3804 });
3805 let conflict = t
3806 .as_ref()
3807 .is_some_and(|t| t.error == Some(ErrorCode::Conflict))
3808 && !creating;
3809 let uncertain = warnings.contains(&present::UNCERTAIN);
3810 if conflict && uncertain {
3811 let response = ui.checkbox(
3812 &mut self.checked_destination,
3813 "기존 풀 위치 폴더를 확인했습니다",
3814 );
3815 theme::pointer(&response);
3816 theme::focus(&response);
3817 }
3818 ui.horizontal(|ui| {
3819 if theme::action(
3820 ui,
3821 if self.details {
3822 "자세히 닫기"
3823 } else {
3824 "자세히 보기"
3825 },
3826 false,
3827 true,
3828 )
3829 .clicked()
3830 {
3831 self.details = !self.details;
3832 }
3833 let action = if success {
3834 Some(("폴더 열기", true))
3835 } else if conflict {
3836 Some((
3837 if self
3838 .model
3839 .list_id
3840 .as_ref()
3841 .is_some_and(|id| id.format == Format::Gzip)
3842 {
3843 "다른 이름으로 저장"
3844 } else {
3845 "다른 폴더에 풀기"
3846 },
3847 !uncertain || self.checked_destination,
3848 ))
3849 } else if t
3850 .as_ref()
3851 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
3852 {
3853 Some((
3854 if creating {
3855 "다시 만들기"
3856 } else {
3857 "압축파일 다시 열기"
3858 },
3859 true,
3860 ))
3861 } else if self.model.can_retry_expanded() {
3862 None
3863 } else if t
3864 .as_ref()
3865 .is_some_and(|t| t.error == Some(ErrorCode::Limit))
3866 {
3867 None
3868 } else if !cancelled && (!uncertain || listing) {
3869 Some(("다시 시도", true))
3870 } else {
3871 None
3872 };
3873 let (confirm, primary) = theme::action_pair(ui, "확인", action);
3874 if confirm {
3875 self.dismissed = true;
3876 self.ui_error = None;
3877 self.model.input_error = None;
3878 }
3879 if primary {
3880 match action.map(|(label, _)| label) {
3881 Some("폴더 열기") => folder = true,
3882 Some("다른 폴더에 풀기" | "다른 이름으로 저장") => {
3883 choose = true
3884 }
3885 Some("압축파일 다시 열기") => reopen = true,
3886 Some("다시 시도" | "다시 만들기") => retry = true,
3887 _ => {}
3888 }
3889 }
3890 });
3891 if self.model.can_retry_expanded() {
3892 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3893 expand = theme::action(ui, "한도를 늘려 다시 시도", true, true).clicked();
3894 });
3895 }
3896 });
3897 if choose {
3898 self.open_picker(Purpose::Retry);
3899 }
3900 if retry {
3901 self.retry();
3902 }
3903 if expand {
3904 let ready = if matches!(self.last_request, Some(Start::Extract { .. })) {
3905 match present::prepare_destination(&self.destination, self.automatic_destination) {
3906 Ok(created) => {
3907 self.owned_destination = created.then(|| self.destination.clone());
3908 true
3909 }
3910 Err(_) => {
3911 self.ui_error = Some(present::FOLDER_ERROR.into());
3912 false
3913 }
3914 }
3915 } else {
3916 true
3917 };
3918 if ready && self.model.retry_expanded(self.factory.as_mut()) {
3919 self.dismissed = false;
3920 self.details = false;
3921 self.ui_error = None;
3922 }
3923 }
3924 if reopen {
3925 if let Some(path) = self.model.archive.clone() {
3926 self.open_path(path);
3927 }
3928 }
3929 if folder {
3930 let path = match self.last_request.as_ref() {
3931 Some(
3932 Start::CreateZip { output_file, .. }
3933 | Start::CreateSevenZip { output_file, .. },
3934 ) => output_file.parent().unwrap_or(Path::new("/")),
3935 _ => self.destination.as_path(),
3936 };
3937 match present::folder_command(path).spawn() {
3938 Ok(mut child) => {
3939 std::thread::spawn(move || {
3940 let _ = child.wait();
3941 });
3942 }
3943 Err(_) => {
3944 self.ui_error = Some(
3945 "폴더를 열지 못했습니다. 파일 탐색기에서 저장 위치를 확인하세요".into(),
3946 )
3947 }
3948 }
3949 }
3950 }
3951
3952 /// 파일 목록 한 행의 아이콘, 이름, 크기 칸. 메인 목록과 ZIP 만들기 창이 같이 씀.
3953 fn entry_cells(
3954 ui: &mut egui::Ui,
3955 rect: egui::Rect,
3956 directory: bool,
3957 name: &str,
3958 hover: &str,
3959 size: String,
3960 name_width: f32,
3961 ) {
3962 ui.scope_builder(
3963 egui::UiBuilder::new()
3964 .max_rect(rect.shrink2(egui::vec2(0.0, 2.0)))
3965 .layout(Layout::left_to_right(Align::Center)),
3966 |ui| {
3967 ui.style_mut().interaction.selectable_labels = false;
3968 ui.add_space(16.0);
3969 theme::icon(ui, if directory { Icon::Folder } else { Icon::File }, 20.0);
3970 theme::bounded_text_hover(ui, name, hover, name_width);
3971 theme::column_label(ui, size, 96.0, Align::Max);
3972 },
3973 );
3974 }
3975
3976 /// ZIP 만들기를 진행 창처럼 부모 창을 따라가는 별도 창으로 띄움.
3977 /// 별도 창을 만들 수 없는 환경(시험 등)에서는 메인 창 안의 모달로 띄움.
3978 fn create_window(&mut self, ctx: &egui::Context) {
3979 if !self.create || self.model.busy() {
3980 self.create_win = WorkWindow::default();
3981 return;
3982 }
3983 if ctx.embed_viewports() {
3984 let mut close = false;
3985 let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| {
3986 ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH));
3987 ui.horizontal(|ui| {
3988 ui.heading(if self.seven_zip {
3989 "7z 만들기"
3990 } else {
3991 "ZIP 만들기"
3992 });
3993 ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
3994 let button = theme::icon_button(ui, "닫기", theme::CLOSE, true);
3995 close = button.clicked();
3996 });
3997 });
3998 close |= self.create_area(ui);
3999 ui.add_space(theme::SPACE);
4000 close |= self.create_actions(ui);
4001 });
4002 if close || modal.should_close() {
4003 self.close_create();
4004 }
4005 return;
4006 }
4007 let id = egui::ViewportId::from_hash_of("archive-create");
4008 let title = if self.seven_zip {
4009 "7z 만들기 — Zipelo"
4010 } else {
4011 "ZIP 만들기 — Zipelo"
4012 };
4013 let custom_frame = self.custom_frame;
4014 if !self.create_win.open {
4015 self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT);
4016 }
4017 let size = egui::vec2(CREATE_WIDTH, self.create_win.height);
4018 let builder =
4019 self.create_win
4020 .builder(ctx, id, size, title, !custom_frame, self.picker.is_some());
4021 let mut close = false;
4022 let picker_open = self.picker.is_some();
4023 let height = ctx.show_viewport_immediate(id, builder, |ui, class| {
4024 if ui.ctx().input(|i| i.viewport().close_requested()) {
4025 close = true;
4026 }
4027 if !picker_open
4028 && ui
4029 .ctx()
4030 .input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
4031 {
4032 crate::log_debug!("Esc: 만들기 창 닫기");
4033 close = true;
4034 }
4035 if class == egui::ViewportClass::EmbeddedWindow {
4036 ui.set_width(CREATE_WIDTH);
4037 close |= self.create_area(ui);
4038 close |= self.create_actions(ui);
4039 return None;
4040 }
4041 let mut chrome = 0.0;
4042 if custom_frame {
4043 window_frame::title_bar(
4044 ui,
4045 "create",
4046 title,
4047 window_frame::Buttons {
4048 minimize: false,
4049 maximize: false,
4050 },
4051 );
4052 window_frame::edges(ui.ctx(), false);
4053 chrome = window_frame::TITLE_HEIGHT;
4054 }
4055 // 버튼은 창 오른쪽 아래에 여백을 두고 고정함. 위 내용이 바뀌어도 자리가 같음.
4056 let actions = egui::Panel::bottom(egui::Id::unique("create-actions"))
4057 .resizable(false)
4058 .show_separator_line(false)
4059 .frame(
4060 egui::Frame::new()
4061 .fill(theme::PANEL)
4062 .inner_margin(egui::Margin {
4063 left: theme::PAD,
4064 right: theme::PAD,
4065 top: 0,
4066 bottom: theme::PAD,
4067 }),
4068 )
4069 .show(ui, |ui| close |= self.create_actions(ui))
4070 .response
4071 .rect
4072 .height();
4073 let margin = theme::PAD as f32;
4074 egui::CentralPanel::default()
4075 .frame(theme::panel(theme::PANEL).corner_radius(0))
4076 .show(ui, |ui| {
4077 let content = ui
4078 .vertical(|ui| close |= self.create_area(ui))
4079 .response
4080 .rect;
4081 Some(content.height() + 2.0 * margin + chrome + actions)
4082 })
4083 .inner
4084 });
4085 if let Some(height) = height {
4086 let height = height.clamp(CREATE_MIN_HEIGHT, 900.0).ceil();
4087 if (height - self.create_win.height).abs() > 1.0 {
4088 self.create_win.height = height;
4089 }
4090 }
4091 if close {
4092 self.close_create();
4093 }
4094 }
4095
4096 /// ZIP 만들기 내용. 닫기를 눌렀으면 true를 돌려줌.
4097 fn create_area(&mut self, ui: &mut egui::Ui) -> bool {
4098 // 저장 위치 선택 창이 응답을 기다리는 동안에는 버튼을 막음.
4099 let enabled = self.picker.is_none();
4100 ui.add_enabled_ui(enabled, |ui| self.create_contents(ui))
4101 .inner
4102 }
4103
4104 fn set_seven_zip(&mut self, selected: bool) {
4105 if self.seven_zip == selected {
4106 return;
4107 }
4108 self.seven_zip = selected;
4109 self.aes256 = false;
4110 self.clear_zip_password();
4111 self.ui_error = None;
4112 let name = self.zip_name.clone();
4113 let lower = name.to_ascii_lowercase();
4114 let stem = if lower.ends_with(".zip") {
4115 &name[..name.len() - 4]
4116 } else if lower.ends_with(".7z") {
4117 &name[..name.len() - 3]
4118 } else {
4119 &name
4120 };
4121 self.zip_name = format!("{stem}{}", if selected { ".7z" } else { ".zip" });
4122 }
4123
4124 fn create_contents(&mut self, ui: &mut egui::Ui) -> bool {
4125 let mut selected = self.seven_zip;
4126 ui.horizontal(|ui| {
4127 ui.label("형식");
4128 ui.selectable_value(&mut selected, false, "ZIP");
4129 ui.selectable_value(&mut selected, true, "7z");
4130 if selected {
4131 ui.label("LZMA2");
4132 }
4133 });
4134 self.set_seven_zip(selected);
4135
4136 let rows = self.create_rows();
4137 let root = self.create_root();
4138
4139 // 경로 줄: 메인 화면처럼 위로 버튼과 현재 폴더 경로.
4140 ui.horizontal(|ui| {
4141 ui.set_height(theme::FIELD);
4142 ui.spacing_mut().item_spacing.x = 0.0;
4143 let up = theme::flat_icon_button(
4144 ui,
4145 "위로",
4146 theme::UP,
4147 !self.create_folder.is_empty(),
4148 egui::vec2(theme::FIELD, theme::FIELD),
4149 );
4150 if up.clicked() {
4151 self.create_folder = self
4152 .create_folder
4153 .rsplit_once('/')
4154 .map_or("", |(parent, _)| parent)
4155 .to_owned();
4156 self.create_selected = None;
4157 }
4158 ui.add_space(6.0);
4159 let path = match &root {
4160 Some(root) => {
4161 let name = root.file_name().unwrap_or_default().to_string_lossy();
4162 if self.create_folder.is_empty() {
4163 format!("/{name}")
4164 } else {
4165 format!("/{name}/{}", self.create_folder)
4166 }
4167 }
4168 None => "/".to_owned(),
4169 };
4170 let (rect, _) = ui.allocate_exact_size(
4171 egui::vec2(ui.available_width(), theme::FIELD),
4172 egui::Sense::hover(),
4173 );
4174 theme::boxed_field(ui, rect);
4175 theme::field_text(ui, rect, &path);
4176 });
4177 ui.add_space(theme::SPACE);
4178
4179 // 파일 목록: 메인 화면 목록과 같은 행 모양. 폴더를 두 번 누르면 들어감.
4180 let mut enter = None;
4181 egui::Frame::new()
4182 .stroke(egui::Stroke::new(1.0, theme::BORDER))
4183 .show(ui, |ui| {
4184 ui.set_min_size(egui::vec2(ui.available_width(), CREATE_LIST_HEIGHT));
4185 ui.set_max_height(CREATE_LIST_HEIGHT);
4186 let message = match &rows {
4187 None => Some("폴더를 읽지 못했습니다"),
4188 Some(rows) if rows.is_empty() => Some("이 폴더는 비어 있습니다"),
4189 Some(_) => None,
4190 };
4191 if let Some(message) = message {
4192 ui.centered_and_justified(|ui| ui.label(message));
4193 return;
4194 }
4195 let rows = rows.unwrap();
4196 let name_width = (ui.available_width() - 16.0 - 28.0 - 96.0 - 24.0).max(80.0);
4197 egui::ScrollArea::vertical()
4198 .id_salt("create-rows")
4199 .auto_shrink([false, false])
4200 .max_height(CREATE_LIST_HEIGHT)
4201 .show_rows(ui, LIST_ROW, rows.len(), |ui, range| {
4202 for row in &rows[range] {
4203 let (rect, response) = ui.allocate_exact_size(
4204 egui::vec2(ui.available_width(), LIST_ROW),
4205 egui::Sense::click(),
4206 );
4207 let response = response.on_hover_text(&row.name);
4208 theme::pointer(&response);
4209 response.widget_info(|| {
4210 egui::WidgetInfo::labeled(
4211 egui::Role::ListBoxOption,
4212 true,
4213 &row.name,
4214 )
4215 });
4216 if response.clicked() {
4217 self.create_selected = Some(row.name.clone());
4218 }
4219 theme::row_background(
4220 ui,
4221 rect,
4222 self.create_selected.as_deref() == Some(row.name.as_str()),
4223 response.hovered(),
4224 );
4225 if row.directory && root.is_some() && response.clicked() {
4226 // egui가 한 프레임을 다시 그리면 두 번 누름 정보가 사라질 수 있어
4227 // 같은 폴더를 다른 프레임에서 0.4초 안에 다시 누르면 두 번 누름으로 봄.
4228 let frame = ui.ctx().cumulative_frame_nr();
4229 let time = ui.input(|i| i.time);
4230 match &self.create_last_click {
4231 Some((name, last_frame, last_time))
4232 if name == &row.name
4233 && *last_frame != frame
4234 && time - last_time < 0.4 =>
4235 {
4236 enter = Some(row.name.clone());
4237 self.create_last_click = None;
4238 }
4239 Some((name, last_frame, _))
4240 if name == &row.name && *last_frame == frame => {}
4241 _ => {
4242 self.create_last_click =
4243 Some((row.name.clone(), frame, time));
4244 }
4245 }
4246 }
4247 Self::entry_cells(
4248 ui,
4249 rect,
4250 row.directory,
4251 &row.name,
4252 &row.name,
4253 row.bytes.map(present::bytes_text).unwrap_or_default(),
4254 name_width,
4255 );
4256 }
4257 });
4258 });
4259 if let Some(name) = enter {
4260 self.create_folder = if self.create_folder.is_empty() {
4261 name
4262 } else {
4263 format!("{}/{name}", self.create_folder)
4264 };
4265 self.create_selected = None;
4266 }
4267 ui.add_space(theme::SPACE);
4268
4269 if let Some(error) = &self.ui_error {
4270 Self::error_notice(ui, error);
4271 }
4272
4273 // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌.
4274 if self.seven_zip {
4275 ui.label("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요");
4276 self.split_rows(ui);
4277 return false;
4278 }
4279 let check = ui.checkbox(&mut self.aes256, "암호로 보호하기");
4280 theme::pointer(&check);
4281 theme::focus(&check);
4282 if self.aes256 {
4283 let label_width = 72.0;
4284 ui.horizontal(|ui| {
4285 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호"));
4286 let toggle = if self.zip_password_visible {
4287 "숨기기"
4288 } else {
4289 "보기"
4290 };
4291 let toggle_width = 72.0;
4292 let edit = ui.add_sized(
4293 [
4294 (ui.available_width() - toggle_width - theme::SPACE).max(80.0),
4295 theme::FIELD,
4296 ],
4297 egui::TextEdit::singleline(&mut self.zip_password)
4298 .password(!self.zip_password_visible)
4299 .id(egui::Id::unique("zip-password-input"))
4300 .char_limit(1024)
4301 .align(egui::Align2::LEFT_CENTER),
4302 );
4303 theme::focus(&edit);
4304 if theme::action(ui, toggle, false, true).clicked() {
4305 self.zip_password_visible = !self.zip_password_visible;
4306 }
4307 });
4308 ui.horizontal(|ui| {
4309 ui.add_sized([label_width, theme::FIELD], egui::Label::new("암호 확인"));
4310 let edit = ui.add_sized(
4311 [
4312 (ui.available_width() - 72.0 - theme::SPACE).max(80.0),
4313 theme::FIELD,
4314 ],
4315 egui::TextEdit::singleline(&mut self.zip_password_confirm)
4316 .password(!self.zip_password_visible)
4317 .id(egui::Id::unique("zip-password-confirm"))
4318 .char_limit(1024)
4319 .align(egui::Align2::LEFT_CENTER),
4320 );
4321 theme::focus(&edit);
4322 });
4323 if self.zip_password.len() > 1024 {
4324 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
4325 } else if !self.zip_password_confirm.is_empty()
4326 && self.zip_password != self.zip_password_confirm
4327 {
4328 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
4329 }
4330 ui.label(RichText::new("암호를 잊으면 파일을 열 수 없습니다.").color(theme::MUTED));
4331 } else if check.changed()
4332 || !self.zip_password.is_empty()
4333 || !self.zip_password_confirm.is_empty()
4334 {
4335 // 체크를 해제하면 입력한 암호와 그 실행 취소 기록을 남겨 두지 않음.
4336 // 입력했다가 모두 지운 경우도 기록에는 남아 있으므로 해제한 순간 함께 지움.
4337 self.clear_zip_password();
4338 }
4339 false
4340 }
4341
4342 /// 쪼갤 용량: 체크하면 바로 아래에 볼륨 크기 칸과 MB/GB 선택을 보여 줌.
4343 fn split_rows(&mut self, ui: &mut egui::Ui) {
4344 let check = ui.checkbox(&mut self.split, "쪼갤 용량 설정");
4345 theme::pointer(&check);
4346 theme::focus(&check);
4347 if !self.split {
4348 return;
4349 }
4350 ui.horizontal(|ui| {
4351 ui.add_sized([72.0, theme::FIELD], egui::Label::new("볼륨 크기"));
4352 let edit = ui.add_sized(
4353 [120.0, theme::FIELD],
4354 egui::TextEdit::singleline(&mut self.split_amount)
4355 .id(egui::Id::unique("split-volume-size"))
4356 .char_limit(9)
4357 .align(egui::Align2::LEFT_CENTER),
4358 );
4359 theme::focus(&edit);
4360 for unit in [present::VolumeUnit::Mb, present::VolumeUnit::Gb] {
4361 let choice = ui.selectable_value(&mut self.split_unit, unit, unit.label());
4362 theme::pointer(&choice);
4363 }
4364 });
4365 match self.split_volume() {
4366 Err(error) => {
4367 ui.colored_label(theme::ERROR, error);
4368 }
4369 Ok(_) => {
4370 let name = if self.zip_name.is_empty() {
4371 "이름.7z"
4372 } else {
4373 &self.zip_name
4374 };
4375 ui.label(
4376 RichText::new(format!(
4377 "{name}.001, {name}.002 …로 나누어 저장합니다. 볼륨은 최대 {}개입니다.",
4378 present::MAX_VOLUMES
4379 ))
4380 .color(theme::MUTED),
4381 );
4382 }
4383 }
4384 }
4385
4386 /// 취소와 압축하기 버튼. 취소를 눌렀으면 true.
4387 fn create_actions(&mut self, ui: &mut egui::Ui) -> bool {
4388 let ready =
4389 !self.sources.is_empty() && self.zip_password_ready() && self.split_volume().is_ok();
4390 let enabled = self.picker.is_none();
4391 let (cancel, compress) = ui
4392 .add_enabled_ui(enabled, |ui| {
4393 theme::action_pair(ui, "취소", Some(("압축하기", ready)))
4394 })
4395 .inner;
4396 if compress {
4397 self.open_picker(if self.seven_zip {
4398 Purpose::SaveSevenZip
4399 } else {
4400 Purpose::SaveZip
4401 });
4402 }
4403 cancel
4404 }
4405
4406 fn resource_dialog(&mut self, ctx: &egui::Context) {
4407 let Some(question) = self.model.resource.clone() else {
4408 return;
4409 };
4410 let Some(job) = self.model.job_id() else {
4411 return;
4412 };
4413 let mut allow = false;
4414 let mut cancel = false;
4415 let modal = egui::Modal::new(egui::Id::unique(("archive-resource", job, question.id)))
4416 .show(ctx, |ui| {
4417 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
4418 ui.heading(if question.scope.ratio {
4419 "압축률이 매우 높습니다"
4420 } else {
4421 "큰 작업을 허용할까요?"
4422 });
4423 ui.label(match question.action {
4424 ActionKind::List => "압축파일 목록 열기",
4425 ActionKind::Extract => "압축 해제",
4426 ActionKind::CreateZip => "ZIP 만들기",
4427 ActionKind::CreateSevenZip => "7z 만들기",
4428 ActionKind::RecoverZip => "ZIP 복구",
4429 ActionKind::Preview => "파일 미리보기",
4430 });
4431 if question.scope.ratio {
4432 ui.label("작은 압축파일도 많은 저장 공간을 사용할 수 있습니다.");
4433 }
4434 if question.scope.output {
4435 ui.label(format!(
4436 "총량 한도: {}에서 {}로",
4437 present::bytes_text(question.soft_limits.output),
4438 present::limit_text(question.ceiling.output)
4439 ));
4440 }
4441 if question.scope.entries {
4442 ui.label(format!(
4443 "항목 한도: {}개에서 {}개로",
4444 question.soft_limits.entries, question.ceiling.entries
4445 ));
4446 }
4447 let mut u = question.usage;
4448 let estimated = self.model.estimated_usage();
4449 u.estimated_bytes = u.estimated_bytes.or(estimated.estimated_bytes);
4450 u.estimated_entries = u.estimated_entries.or(estimated.estimated_entries);
4451 let bytes = |value: Option<u64>| {
4452 value
4453 .map(present::bytes_text)
4454 .unwrap_or_else(|| "미확인".into())
4455 };
4456 let entries = |value: Option<u32>| {
4457 value
4458 .map(|n| format!("{n}개"))
4459 .unwrap_or_else(|| "미확인".into())
4460 };
4461 ui.label(format!(
4462 "예상 총량: {} / 실제 총량: {}",
4463 bytes(u.estimated_bytes),
4464 bytes(u.actual_bytes)
4465 ));
4466 ui.label(format!(
4467 "예상 항목: {} / 실제 항목: {}",
4468 entries(u.estimated_entries),
4469 entries(u.actual_entries)
4470 ));
4471 if question.scope.ratio {
4472 ui.label(format!(
4473 "압축 크기: {} / 풀린 크기: {}",
4474 bytes(u.compressed_bytes),
4475 bytes(u.ratio_output_bytes)
4476 ));
4477 }
4478 ui.label(format!(
4479 "확인한 저장 볼륨의 여유 공간: {}",
4480 bytes(u.available_bytes)
4481 ));
4482 ui.label(format!(
4483 "이 작업의 상한: {} / {}개",
4484 present::limit_text(question.ceiling.output),
4485 question.ceiling.entries
4486 ));
4487 ui.label("이 작업에만 적용합니다. 공간 부족이나 자원 상한에 도달하면 중단합니다.");
4488 ui.horizontal(|ui| {
4489 cancel = theme::action(ui, "취소", false, true).clicked();
4490 allow = theme::action(ui, "이 작업 허용", true, true).clicked();
4491 });
4492 });
4493 if cancel || modal.should_close() {
4494 self.clear_password();
4495 self.model.cancel();
4496 } else if allow {
4497 self.model.resource_reply(job, question.id, true);
4498 }
4499 }
4500
4501 fn conflict_dialog(&mut self, ctx: &egui::Context) {
4502 let conflict = self.model.conflict.clone().unwrap();
4503 let question = (self.model.job_id().unwrap_or(0), conflict.challenge_id);
4504 if self.conflict_challenge != Some(question) {
4505 self.conflict_challenge = Some(question);
4506 self.conflict_apply = false;
4507 }
4508 let mut choice = None;
4509 let mut cancel = false;
4510 let modal = egui::Modal::new(egui::Id::unique("archive-conflict")).show(ctx, |ui| {
4511 ui.set_width((ctx.content_rect().width() - 64.0).min(460.0));
4512 ui.heading("같은 이름의 파일이 있습니다");
4513 theme::bounded_text(ui, &conflict.relative_name, ui.available_width());
4514 ui.add_space(theme::SPACE);
4515 egui::Grid::new("conflict-sizes")
4516 .spacing([24.0, 8.0])
4517 .show(ui, |ui| {
4518 ui.label("기존 파일");
4519 ui.label(present::bytes_text(conflict.existing_size));
4520 ui.end_row();
4521 ui.label("압축파일 안의 파일");
4522 ui.label(present::bytes_text(conflict.incoming_size));
4523 ui.end_row();
4524 });
4525 ui.add_space(theme::SPACE);
4526 ui.checkbox(&mut self.conflict_apply, "나머지 파일에도 같게 적용");
4527 ui.add_space(theme::SPACE);
4528 ui.horizontal_wrapped(|ui| {
4529 for (label, value) in [
4530 ("덮어쓰기", ConflictChoice::Overwrite),
4531 ("건너뛰기", ConflictChoice::Skip),
4532 ("이름 바꿔 저장", ConflictChoice::Rename),
4533 ] {
4534 if theme::action(ui, label, false, self.model.error.is_none()).clicked() {
4535 choice = Some(value);
4536 }
4537 }
4538 });
4539 ui.label("이름 바꿔 저장하면 같은 폴더에 번호를 붙입니다.");
4540 if let Some(error) = &self.model.error {
4541 Self::error_notice(ui, present::client_error_text(error));
4542 }
4543 cancel = theme::action(ui, "작업 취소", false, true).clicked();
4544 });
4545 if modal.should_close() || cancel {
4546 self.model.cancel();
4547 } else if let Some(choice) = choice {
4548 self.model.resolve_conflict(choice, self.conflict_apply);
4549 }
4550 }
4551
4552 fn password_dialog(&mut self, ctx: &egui::Context, new_challenge: bool) {
4553 let (_, attempt, encrypt) = self.model.challenge.unwrap();
4554 let mut submit = false;
4555 let mut cancel = false;
4556 let password_enter = ctx.memory(|memory| memory.focused()).is_some_and(|id| {
4557 id == egui::Id::unique("archive-password-input")
4558 || id == egui::Id::unique("archive-password-confirm")
4559 }) && ctx.input(|input| input.key_pressed(egui::Key::Enter));
4560 let modal = egui::Modal::new(egui::Id::unique("archive-password")).show(ctx, |ui| {
4561 ui.set_width((ctx.content_rect().width() - 64.0).min(420.0));
4562 ui.heading(if encrypt {
4563 "ZIP 암호 설정"
4564 } else {
4565 "암호가 필요합니다"
4566 });
4567 if encrypt {
4568 ui.label("암호를 잊으면 파일을 열 수 없습니다.");
4569 } else if let Some(path) = &self.model.archive {
4570 ui.label(format!(
4571 "{}은 암호로 보호되어 있습니다.",
4572 present::middle_text(
4573 &path.file_name().unwrap_or_default().to_string_lossy(),
4574 24
4575 )
4576 ));
4577 }
4578 ui.horizontal(|ui| {
4579 ui.label("암호");
4580 let edit = ui.add(
4581 egui::TextEdit::singleline(&mut self.password)
4582 .password(!self.password_visible)
4583 .id(egui::Id::unique("archive-password-input"))
4584 .char_limit(1024)
4585 .desired_width(232.0),
4586 );
4587 theme::focus(&edit);
4588 if new_challenge {
4589 edit.request_focus();
4590 }
4591 if theme::action(
4592 ui,
4593 if self.password_visible {
4594 "숨기기"
4595 } else {
4596 "보기"
4597 },
4598 false,
4599 true,
4600 )
4601 .clicked()
4602 {
4603 self.password_visible = !self.password_visible;
4604 }
4605 });
4606 if encrypt {
4607 ui.horizontal(|ui| {
4608 ui.label("암호 확인");
4609 let edit = ui.add(
4610 egui::TextEdit::singleline(&mut self.password_confirm)
4611 .password(!self.password_visible)
4612 .id(egui::Id::unique("archive-password-confirm"))
4613 .char_limit(1024)
4614 .desired_width(232.0),
4615 );
4616 theme::focus(&edit);
4617 });
4618 if self.password != self.password_confirm {
4619 ui.colored_label(theme::ERROR, "두 암호가 같지 않습니다");
4620 }
4621 } else if attempt > 1 {
4622 ui.colored_label(theme::ERROR, "암호가 맞지 않습니다. 다시 입력하세요");
4623 }
4624 if self.password.len() > 1024 {
4625 ui.colored_label(theme::ERROR, "암호는 UTF-8 1~1024바이트로 입력하세요");
4626 }
4627 let valid = !self.password.is_empty()
4628 && self.password.len() <= 1024
4629 && (!encrypt || self.password == self.password_confirm);
4630 let actions = theme::action_pair(ui, "취소", Some(("확인", valid)));
4631 cancel = actions.0;
4632 submit = actions.1 || (valid && password_enter);
4633 });
4634 if modal.should_close() || cancel {
4635 self.clear_password();
4636 self.model.cancel();
4637 } else if submit {
4638 let password = std::mem::take(&mut self.password);
4639 self.clear_password();
4640 self.model.password(password);
4641 }
4642 }
4643
4644 fn close_dialog(&mut self, ctx: &egui::Context) {
4645 // Review(결과 확인 후 닫기)는 show()에서 바로 확인 처리하므로 그리지 않음.
4646 if matches!(
4647 self.model.close,
4648 Close::Open | Close::Allowed | Close::Review
4649 ) {
4650 return;
4651 }
4652 egui::Modal::new(egui::Id::unique("archive-close")).show(ctx, |ui| {
4653 ui.set_width(420.0);
4654 match self.model.close {
4655 Close::Confirm => {
4656 // 답하기 전에 작업이 끝났으면 취소할 작업이 없으므로 닫을지만 물음.
4657 let busy = self.model.busy();
4658 let (heading, text, keep, close) = if busy {
4659 (
4660 "작업 중 닫기",
4661 "작업을 취소하고 닫을까요?",
4662 "계속 작업",
4663 "취소하고 닫기",
4664 )
4665 } else {
4666 (
4667 "닫기",
4668 "작업이 끝났습니다. 창을 닫을까요?",
4669 "열어 두기",
4670 "닫기",
4671 )
4672 };
4673 ui.heading(heading);
4674 ui.label(text);
4675 ui.horizontal(|ui| {
4676 if theme::action(ui, keep, false, true).clicked() {
4677 self.model.keep_open();
4678 }
4679 if theme::action(ui, close, true, true).clicked() {
4680 self.clear_password();
4681 self.model.confirm_close();
4682 }
4683 });
4684 }
4685 Close::Waiting => {
4686 ui.heading("종료 확인 중");
4687 ui.label("마무리하는 중입니다. 잠시만 기다려 주세요");
4688 if theme::action(ui, "닫기 취소", false, true).clicked() {
4689 self.model.keep_open();
4690 }
4691 }
4692 _ => {}
4693 }
4694 });
4695 }
4696}
4697
4698impl eframe::App for ArchiveApp {
4699 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
4700 self.show(root);
4701 }
4702
4703 fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
4704 // 운영체제가 창 이동을 맡으면 버튼 놓기가 오지 않으므로 대신 넣어 눌림 상태를 풀어 줌.
4705 if std::mem::take(&mut self.release_after_move) {
4706 let pos = ctx.input(|i| i.pointer.latest_pos()).unwrap_or_default();
4707 raw_input.events.insert(
4708 0,
4709 egui::Event::PointerButton {
4710 pos,
4711 button: egui::PointerButton::Primary,
4712 pressed: false,
4713 modifiers: ctx.input(|i| i.modifiers),
4714 },
4715 );
4716 }
4717 }
4718}
4719impl Drop for ArchiveApp {
4720 fn drop(&mut self) {
4721 self.clear_password();
4722 for (_, root) in self.open_roots.drain(..) {
4723 present::remove_open_root(root);
4724 }
4725 }
4726}