team-ljyzipelo

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