team-ljyzipelo

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