team-ljyzipelo

공개
594줄23 KB
1use super::*;
2use std::ffi::OsString;
3
4#[path = "fake.rs"]
5mod fake;
6use fake::FakeFactory;
7
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct Scenario {
10 pub name: &'static str,
11 pub description: &'static str,
12}
13
14macro_rules! catalog {
15 ($($name:literal => $description:literal),+ $(,)?) => {
16 pub const SCENARIOS: &[Scenario] = &[$(Scenario {
17 name: $name,
18 description: $description,
19 }),+];
20 };
21}
22
23catalog! {
24 "gzip-conflict-choice" => "단일 GZ 파일의 충돌 선택",
25 "conflict-choice" => "같은 이름 파일의 세 가지 처리 선택",
26 "conflict-apply" => "남은 충돌에 같은 선택 적용",
27 "extract-skipped" => "모든 파일을 건너뛴 정상 완료",
28 "extract-renamed" => "이름을 바꿔 저장한 완료 결과",
29 "extract-rename-failed" => "새 이름을 정한 뒤 저장 전 I/O 실패",
30 "empty" => "빈 첫 화면",
31 "archive" => "폴더와 파일이 있는 압축파일",
32 "tar-bz2" => "TAR.BZ2 목록과 자동 해제 폴더",
33 "tar-xz" => "TAR.XZ 목록과 자동 해제 폴더",
34 "folder" => "사진 하위 폴더",
35 "many-items" => "500개 항목과 세로 스크롤",
36 "selection" => "여러 파일과 폴더 선택",
37 "marquee" => "반투명 사각형으로 끌어서 선택 중",
38 "search-empty" => "검색 결과 없음",
39 "password" => "압축 해제 암호 입력",
40 "password-retry" => "암호가 틀린 뒤 다시 입력",
41 "extract-progress" => "압축 해제 진행률 62%",
42 "extract-unknown" => "전체 크기를 모르는 압축 해제",
43 "extract-complete" => "압축 해제 완료",
44 "extract-cancelled" => "압축 해제 취소 완료",
45 "cancelling" => "취소 요청 후 작업 종료 대기",
46 "conflict" => "같은 이름 파일 충돌",
47 "unsupported" => "지원하지 않는 압축 형식",
48 "damaged" => "손상된 압축파일",
49 "create" => "암호 없는 ZIP 만들기 창",
50 "create-encrypted" => "암호 설정이 켜진 ZIP 만들기 창",
51 "create-progress" => "ZIP 만들기 진행률 62%",
52 "create-complete" => "ZIP 만들기 완료",
53 "folder-empty" => "항목이 없는 하위 폴더",
54 "gzip-conflict" => "단일 GZ 파일 이름 충돌",
55 "extract-partial" => "일부 파일만 풀린 결과",
56 "extract-uncertain" => "저장 여부를 확인할 수 없는 결과",
57 "extract-unsynced" => "완료 뒤 저장 확인 경고의 상세 정보",
58 "source-changed" => "목록을 연 뒤 원본이 바뀐 오류",
59 "dialog-error" => "운영체제 파일 선택 창 실행 실패",
60 "create-error" => "ZIP 만들기 중 디스크 공간 부족",
61 "password-create" => "암호 ZIP 생성의 작업자 암호 요청",
62 "close-confirm" => "진행 중 창 닫기 확인",
63 "uninstall-windows" => "Windows 제거 전 기본 앱 선택 안내",
64 "uninstall-settings-error" => "Windows 기본 앱 설정 실행 실패",
65 "uninstall-ubuntu-missing" => "Ubuntu 이전 기본 앱 복원 불가 안내",
66 "uninstall-ubuntu-unknown-user" => "Ubuntu 제거 사용자 확인 불가 안내",
67}
68
69pub fn listing() -> String {
70 SCENARIOS
71 .iter()
72 .map(|s| format!("{}\t{}\n", s.name, s.description))
73 .collect()
74}
75
76pub fn parse(name: &str) -> Result<Scenario, String> {
77 SCENARIOS
78 .iter()
79 .copied()
80 .find(|s| s.name == name)
81 .ok_or_else(|| {
82 format!(
83 "알 수 없는 UI 상황: {name}\n사용 가능한 상황:\n{}",
84 listing()
85 )
86 })
87}
88
89#[derive(Debug, PartialEq)]
90pub enum Launch {
91 Normal(Vec<OsString>),
92 Scenario(Scenario),
93 List,
94}
95
96pub fn launch(args: Vec<OsString>) -> Result<Launch, String> {
97 let requested = args
98 .iter()
99 .any(|a| a == "--ui-scenario" || a == "--list-ui-scenarios");
100 if !requested {
101 return Ok(Launch::Normal(args));
102 }
103 if args.len() == 1 && args[0] == "--list-ui-scenarios" {
104 return Ok(Launch::List);
105 }
106 if args.len() == 2 && args[0] == "--ui-scenario" {
107 return args[1]
108 .to_str()
109 .ok_or_else(|| format!("상황 이름은 UTF-8이어야 합니다\n{}", listing()))
110 .and_then(parse)
111 .map(Launch::Scenario);
112 }
113 Err(format!(
114 "사용법: --ui-scenario <이름> 또는 --list-ui-scenarios\n{}",
115 listing()
116 ))
117}
118
119fn sample_root() -> PathBuf {
120 PathBuf::from(if cfg!(target_os = "windows") {
121 "C:\\Samples"
122 } else {
123 "/Samples"
124 })
125}
126
127fn entries(many: bool) -> Vec<Entry> {
128 let mut entries = vec![
129 ("사진", Kind::Directory),
130 ("읽어주세요.txt", Kind::File),
131 ("여행 일정.pdf", Kind::File),
132 ("사진/바다.jpg", Kind::File),
133 ("사진/풍경.jpg", Kind::File),
134 ]
135 .into_iter()
136 .enumerate()
137 .map(|(id, (name, kind))| Entry {
138 id: id as u32,
139 name: name.into(),
140 kind,
141 bytes: Some(if kind == Kind::Directory {
142 0
143 } else {
144 1_287_952
145 }),
146 packed: Some(900_000),
147 encrypted: id == 2,
148 })
149 .collect::<Vec<_>>();
150 if many {
151 entries.extend((5..505).map(|id| Entry {
152 id,
153 name: format!("자료-{id:03}.txt"),
154 kind: Kind::File,
155 bytes: Some(4096),
156 packed: Some(1800),
157 encrypted: false,
158 }));
159 }
160 entries
161}
162
163impl Scenario {
164 /// 제거 안내는 외부 설치 화면의 문구만 재현하며 OS 동작은 실행하지 않음.
165 pub fn show(self, app: &mut ArchiveApp, ui: &mut egui::Ui) {
166 let (title, messages, button): (&str, Vec<&str>, Option<&str>) = match self.name {
167 "uninstall-windows" => (
168 "제거 전 기본 앱 선택",
169 vec![
170 "Zipelo를 기본 앱으로 사용했다면 제거 전에 다른 앱을 선택하세요. [기본 앱 설정 열기]에서 .zip, .7z, .tar, .gz, .tgz를 검색해 사용할 앱을 고를 수 있습니다. 다른 앱이 없으면 먼저 설치하세요.",
171 "직접 고른 기본 앱은 자동으로 바꾸지 않습니다. 제거 후 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [연결 프로그램]에서 다른 앱을 선택하세요.",
172 ],
173 Some("기본 앱 설정 열기"),
174 ),
175 "uninstall-settings-error" => (
176 "기본 앱 설정 실행 실패",
177 vec![
178 "Windows 설정을 열지 못했습니다. 설정 > 앱 > 기본 앱에서 확장자를 검색해 다른 앱을 선택하세요.",
179 ],
180 Some("확인"),
181 ),
182 "uninstall-ubuntu-missing" => (
183 "Ubuntu 제거 안내",
184 vec![
185 "Zipelo를 제거합니다. 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [다른 프로그램으로 열기]에서 다른 앱을 선택하세요.",
186 "이전 앱을 복원할 수 없습니다: application/zip. 파일을 오른쪽 클릭해 [다른 프로그램으로 열기]에서 앱을 선택하세요.",
187 ],
188 None,
189 ),
190 "uninstall-ubuntu-unknown-user" => (
191 "Ubuntu 제거 안내",
192 vec![
193 "Zipelo를 제거합니다. 파일이 열리지 않으면 파일을 오른쪽 클릭하고 [다른 프로그램으로 열기]에서 다른 앱을 선택하세요.",
194 "제거를 요청한 사용자를 확인할 수 없어 사용자 기본 앱 설정은 변경하지 않습니다.",
195 ],
196 None,
197 ),
198 _ => {
199 app.show(ui);
200 return;
201 }
202 };
203 egui::CentralPanel::default().show_inside(ui, |ui| {
204 ui.add_space(16.0);
205 ui.heading(title);
206 ui.add_space(16.0);
207 for message in messages {
208 ui.label(message);
209 ui.add_space(16.0);
210 }
211 if let Some(button) = button {
212 // 미리보기에서는 설정 열기와 제거를 실행하지 않음.
213 let _ = ui.button(button);
214 }
215 });
216 }
217
218 /// 실제 파일과 작업자를 사용하지 않고 기존 화면 상태를 준비함.
219 pub fn build(self) -> ArchiveApp {
220 let factory = FakeFactory::manual();
221 let state = factory.state.clone();
222 let mut app = ArchiveApp::new(Box::new(factory), None, true);
223 let base = sample_root();
224 app.destination = base.join("풀린 자료");
225 app.automatic_destination = false;
226 app.zip_folder = base.clone();
227 app.zip_name = "여행 자료.zip".into();
228 if self.name == "empty" || self.name.starts_with("uninstall-") {
229 return app;
230 }
231 let archive = base.join(match self.name {
232 "gzip-conflict" | "gzip-conflict-choice" => "여행 자료.gz",
233 "tar-bz2" => "여행 자료.TAR.BZ2",
234 "tar-xz" => "여행 자료.TaR.Xz",
235 _ => "여행 자료.zip",
236 });
237 app.model.archive = Some(archive.clone());
238 app.model.entries = entries(self.name == "many-items");
239 app.model.list_id = Some(ListId {
240 catalog_version: 1,
241 format: Format::Zip,
242 source_object: SourceObject::Unix {
243 device: 1,
244 inode: 1,
245 },
246 archive_bytes: 2_700_000,
247 archive_sha256: [7; 32],
248 });
249 app.model.confirmed = true;
250 match self.name {
251 "tar-bz2" | "tar-xz" => {
252 app.model.list_id.as_mut().unwrap().format = Format::Tar;
253 for entry in &mut app.model.entries {
254 entry.encrypted = false;
255 }
256 app.destination = present::default_destination(&archive);
257 app.automatic_destination = true;
258 return app;
259 }
260 "archive" | "many-items" => return app,
261 "folder-empty" => {
262 app.browse_folder("빈 폴더");
263 return app;
264 }
265 "dialog-error" => {
266 app.ui_error = Some(DIALOG_UNAVAILABLE.into());
267 return app;
268 }
269 "folder" => {
270 app.browse_folder("사진");
271 return app;
272 }
273 "search-empty" => {
274 app.search = "없는 파일".into();
275 return app;
276 }
277 "selection" | "marquee" => {
278 app.model
279 .selected
280 .extend([0, 3, 4, if self.name == "marquee" { 2 } else { 1 }]);
281 if self.name == "marquee" {
282 app.scenario_marquee = Some(egui::Rect::from_min_size(
283 egui::pos2(22.0, 8.0),
284 egui::vec2(360.0, 62.0),
285 ));
286 }
287 return app;
288 }
289 "create" | "create-encrypted" => {
290 app.sources = vec![base.join("읽어주세요.txt"), base.join("사진")];
291 app.scenario_sources = Some(std::rc::Rc::new(vec![
292 SourceRow {
293 name: "사진".into(),
294 directory: true,
295 bytes: Some(0),
296 },
297 SourceRow {
298 name: "읽어주세요.txt".into(),
299 directory: false,
300 bytes: Some(4096),
301 },
302 ]));
303 app.show_create(self.name == "create-encrypted");
304 return app;
305 }
306 _ => {}
307 }
308 let creating = self.name.starts_with("create-") || self.name == "password-create";
309 let listing_error = matches!(self.name, "unsupported" | "damaged");
310 if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
311 app.model.list_id.as_mut().unwrap().format = Format::Gzip;
312 app.model.entries = vec![Entry {
313 id: 0,
314 name: "여행 자료".into(),
315 kind: Kind::File,
316 bytes: Some(1_287_952),
317 packed: Some(900_000),
318 encrypted: false,
319 }];
320 app.gzip_name = "여행 자료".into();
321 }
322 let request = if creating {
323 Start::CreateZip {
324 sources: vec![(base.join("사진"), "사진".into())],
325 output_file: base.join("여행 자료.zip"),
326 method: Method::Deflate,
327 aes256: self.name == "password-create",
328 }
329 } else if listing_error {
330 Start::List { archive }
331 } else {
332 Start::Extract {
333 archive,
334 destination: app.destination.clone(),
335 selection: Selection::All,
336 list_id: app.model.list_id.clone().unwrap(),
337 gzip_output_name: (matches!(self.name, "gzip-conflict" | "gzip-conflict-choice"))
338 .then(|| app.gzip_name.clone()),
339 }
340 };
341 app.targets = Some(if creating {
342 BTreeSet::from(["여행 자료.zip".into()])
343 } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") {
344 BTreeSet::from(["여행 자료".into()])
345 } else {
346 BTreeSet::from([
347 "읽어주세요.txt".into(),
348 "여행 일정.pdf".into(),
349 "사진/바다.jpg".into(),
350 "사진/풍경.jpg".into(),
351 ])
352 });
353 if matches!(
354 self.name,
355 "extract-skipped" | "extract-renamed" | "extract-rename-failed"
356 ) {
357 app.targets = Some(["읽어주세요.txt".into()].into_iter().collect());
358 app.directories.clear();
359 }
360 assert!(app.start(request));
361 {
362 let mut state = state.borrow_mut();
363 state.frame(Event::Accepted { encryption: true });
364 match self.name {
365 "conflict-choice" | "conflict-apply" | "gzip-conflict-choice" => {
366 state.frame(Event::ConflictRequired(Conflict {
367 challenge_id: 29,
368 entry_id: if self.name == "gzip-conflict-choice" {
369 0
370 } else {
371 1
372 },
373 relative_name: if self.name == "gzip-conflict-choice" {
374 "여행 자료"
375 } else {
376 "읽어주세요.txt"
377 }
378 .into(),
379 incoming_size: 1_287_952,
380 existing_size: 2048,
381 }));
382 }
383 "extract-skipped" | "extract-renamed" | "extract-rename-failed" => {
384 let failed = self.name == "extract-rename-failed";
385 let skip = self.name == "extract-skipped";
386 let name = if skip {
387 "읽어주세요.txt"
388 } else {
389 "읽어주세요 (1).txt"
390 };
391 state.frame(Event::ConflictResolved(Resolution {
392 entry_id: 1,
393 relative_name: name.into(),
394 choice: if skip {
395 ConflictChoice::Skip
396 } else {
397 ConflictChoice::Rename
398 },
399 }));
400 if !skip && !failed {
401 state.frame(Event::Output {
402 entry_id: Some(1),
403 relative_name: name.into(),
404 disposition: Disposition::Created,
405 });
406 }
407 state.frame(Event::Terminal(Terminal {
408 outcome: if failed {
409 Outcome::Failed
410 } else {
411 Outcome::Completed
412 },
413 error: failed.then_some(ErrorCode::Io),
414 publication: if skip || failed {
415 Publication::None
416 } else {
417 Publication::Complete
418 },
419 created_count: u64::from(!skip && !failed),
420 retained_partial_count: 0,
421 durability: if skip || failed {
422 Durability::NotApplicable
423 } else {
424 Durability::Synced
425 },
426 cleanup: Cleanup::Complete,
427 }));
428 state.queue.extend([
429 HostEvent::StdoutEof,
430 HostEvent::StderrEof,
431 HostEvent::Exited { success: true },
432 ]);
433 }
434 "password" | "password-retry" | "password-create" => {
435 state.frame(Event::PasswordRequired {
436 challenge_id: 17,
437 attempt: if self.name == "password-retry" { 2 } else { 1 },
438 encrypt: self.name == "password-create",
439 })
440 }
441 "extract-complete" | "create-complete" | "extract-unsynced" => {
442 let names = app.targets.as_ref().unwrap();
443 for name in names {
444 state.frame(Event::Output {
445 entry_id: None,
446 relative_name: name.clone(),
447 disposition: Disposition::Created,
448 });
449 }
450 state.frame(Event::Terminal(Terminal {
451 outcome: Outcome::Completed,
452 error: None,
453 publication: Publication::Complete,
454 created_count: names.len() as u64,
455 retained_partial_count: 0,
456 durability: if self.name == "extract-unsynced" {
457 Durability::Unconfirmed
458 } else {
459 Durability::Synced
460 },
461 cleanup: Cleanup::Complete,
462 }));
463 state.queue.extend([
464 HostEvent::StdoutEof,
465 HostEvent::StderrEof,
466 HostEvent::Exited { success: true },
467 ]);
468 }
469 "extract-cancelled" => state.finish(Outcome::Cancelled, Publication::None),
470 "extract-partial" | "extract-uncertain" => {
471 let partial = self.name == "extract-partial";
472 if partial {
473 state.frame(Event::Output {
474 entry_id: Some(1),
475 relative_name: "읽어주세요.txt".into(),
476 disposition: Disposition::Created,
477 });
478 }
479 state.frame(Event::Terminal(Terminal {
480 outcome: Outcome::Failed,
481 error: Some(ErrorCode::Io),
482 publication: if partial {
483 Publication::Partial
484 } else {
485 Publication::Uncertain
486 },
487 created_count: u64::from(partial),
488 retained_partial_count: 0,
489 durability: Durability::Synced,
490 cleanup: Cleanup::Complete,
491 }));
492 state.queue.extend([
493 HostEvent::StdoutEof,
494 HostEvent::StderrEof,
495 HostEvent::Exited { success: true },
496 ]);
497 }
498 "conflict" | "gzip-conflict" | "unsupported" | "damaged" | "source-changed"
499 | "create-error" => {
500 state.frame(Event::Terminal(Terminal {
501 outcome: Outcome::Failed,
502 error: Some(match self.name {
503 "conflict" | "gzip-conflict" => ErrorCode::Conflict,
504 "source-changed" => ErrorCode::SourceChanged,
505 "create-error" => ErrorCode::DiskFull,
506 "unsupported" => ErrorCode::UnsupportedFormat,
507 _ => ErrorCode::Integrity,
508 }),
509 publication: Publication::None,
510 created_count: 0,
511 retained_partial_count: 0,
512 durability: Durability::NotApplicable,
513 cleanup: Cleanup::Complete,
514 }));
515 state.queue.extend([
516 HostEvent::StdoutEof,
517 HostEvent::StderrEof,
518 HostEvent::Exited { success: true },
519 ]);
520 }
521 _ => state.frame(Event::Progress {
522 stage: if creating {
523 Stage::Write
524 } else {
525 Stage::Decode
526 },
527 processed: 38 << 20,
528 total: (self.name != "extract-unknown").then_some(61 << 20),
529 completed_entries: 12,
530 }),
531 }
532 }
533 for _ in 0..64 {
534 app.model.poll();
535 }
536 if self.name == "conflict-apply" {
537 app.conflict_challenge = Some((app.model.job_id().unwrap(), 29));
538 app.conflict_apply = true;
539 }
540 if self.name == "extract-unsynced" {
541 app.details = true;
542 }
543 if self.name == "cancelling" {
544 app.model.cancel();
545 }
546 if self.name == "close-confirm" {
547 app.model.request_close();
548 }
549 app
550 }
551}
552
553/// 화면을 고정하고 실제 파일 조작을 막는 미리보기임.
554pub struct Preview(pub ArchiveApp, Option<Scenario>);
555impl Preview {
556 pub fn with_scenario(mut self, scenario: Scenario) -> Self {
557 self.1 = Some(scenario);
558 self
559 }
560
561 pub fn show(&mut self, ui: &mut egui::Ui) {
562 if let Some(scenario) = self.1 {
563 scenario.show(&mut self.0, ui);
564 } else {
565 self.0.show(ui);
566 }
567 }
568
569 pub fn new(app: ArchiveApp, ctx: &egui::Context) -> Self {
570 ctx.on_begin_pass(
571 "ui-scenario-readonly",
572 std::sync::Arc::new(|ctx| {
573 ctx.input_mut(|i| {
574 i.events.clear();
575 i.pointer = Default::default();
576 i.keys_down.clear();
577 i.modifiers = Default::default();
578 i.raw.dropped_files.clear();
579 i.raw.hovered_files.clear();
580 });
581 }),
582 );
583 Self(app, None)
584 }
585}
586impl eframe::App for Preview {
587 fn ui(&mut self, root: &mut egui::Ui, _: &mut eframe::Frame) {
588 if root.ctx().input(|i| i.viewport().close_requested()) {
589 root.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
590 return;
591 }
592 self.show(root);
593 }
594}