team-ljyzipelo

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