team-ljyzipelo

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