team-ljyzipelo

공개

Merge pull request #144 from Team-LJY/fix/archive-open-and-context-extract

압축파일 안 파일 열기와 선택 항목 풀기 메뉴 추가
작성자
LeeJunyoung
작성 시각
커밋
8bd3e627725ad29af8fc67289f6333f148192ce5
이 시점의 파일 보기

변경된 파일 23개

+2,356-29

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

수정experiments/rust-archive-worker/Cargo.lock+97-0
@@ -200,6 +200,12 @@ dependencies = [
200200 "generic-array",
201201]
202202
203추가: [[package]]
204추가: name = "itoa"
205추가: version = "1.0.19"
206추가: source = "registry+https://github.com/rust-lang/crates.io-index"
207추가: checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
208추가:
203209[[package]]
204210name = "libbz2-rs-sys"
205211version = "0.2.6"
@@ -221,6 +227,12 @@ dependencies = [
221227 "sha2 0.11.1",
222228]
223229
230추가: [[package]]
231추가: name = "memchr"
232추가: version = "2.8.3"
233추가: source = "registry+https://github.com/rust-lang/crates.io-index"
234추가: checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
235추가:
224236[[package]]
225237name = "miniz_oxide"
226238version = "0.8.9"
@@ -264,6 +276,66 @@ dependencies = [
264276 "miniz_oxide 0.8.9",
265277]
266278
279추가: [[package]]
280추가: name = "proc-macro2"
281추가: version = "1.0.107"
282추가: source = "registry+https://github.com/rust-lang/crates.io-index"
283추가: checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
284추가: dependencies = [
285추가: "unicode-ident",
286추가: ]
287추가:
288추가: [[package]]
289추가: name = "quote"
290추가: version = "1.0.47"
291추가: source = "registry+https://github.com/rust-lang/crates.io-index"
292추가: checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
293추가: dependencies = [
294추가: "proc-macro2",
295추가: ]
296추가:
297추가: [[package]]
298추가: name = "serde"
299추가: version = "1.0.229"
300추가: source = "registry+https://github.com/rust-lang/crates.io-index"
301추가: checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
302추가: dependencies = [
303추가: "serde_core",
304추가: ]
305추가:
306추가: [[package]]
307추가: name = "serde_core"
308추가: version = "1.0.229"
309추가: source = "registry+https://github.com/rust-lang/crates.io-index"
310추가: checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
311추가: dependencies = [
312추가: "serde_derive",
313추가: ]
314추가:
315추가: [[package]]
316추가: name = "serde_derive"
317추가: version = "1.0.229"
318추가: source = "registry+https://github.com/rust-lang/crates.io-index"
319추가: checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
320추가: dependencies = [
321추가: "proc-macro2",
322추가: "quote",
323추가: "syn",
324추가: ]
325추가:
326추가: [[package]]
327추가: name = "serde_json"
328추가: version = "1.0.154"
329추가: source = "registry+https://github.com/rust-lang/crates.io-index"
330추가: checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
331추가: dependencies = [
332추가: "itoa",
333추가: "memchr",
334추가: "serde",
335추가: "serde_core",
336추가: "zmij",
337추가: ]
338추가:
267339[[package]]
268340name = "sha1"
269341version = "0.10.7"
@@ -309,12 +381,29 @@ version = "2.6.1"
309381source = "registry+https://github.com/rust-lang/crates.io-index"
310382checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
311383
384추가: [[package]]
385추가: name = "syn"
386추가: version = "3.0.10"
387추가: source = "registry+https://github.com/rust-lang/crates.io-index"
388추가: checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
389추가: dependencies = [
390추가: "proc-macro2",
391추가: "quote",
392추가: "unicode-ident",
393추가: ]
394추가:
312395[[package]]
313396name = "typenum"
314397version = "1.20.1"
315398source = "registry+https://github.com/rust-lang/crates.io-index"
316399checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
317400
401추가: [[package]]
402추가: name = "unicode-ident"
403추가: version = "1.0.27"
404추가: source = "registry+https://github.com/rust-lang/crates.io-index"
405추가: checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
406추가:
318407[[package]]
319408name = "version_check"
320409version = "0.9.5"
@@ -337,6 +426,8 @@ dependencies = [
337426 "lzma-rust2",
338427 "pbkdf2",
339428 "png",
429추가: "serde",
430추가: "serde_json",
340431 "sha1",
341432 "sha2 0.10.9",
342433 "subtle",
@@ -359,6 +450,12 @@ version = "0.6.8"
359450source = "registry+https://github.com/rust-lang/crates.io-index"
360451checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
361452
453추가: [[package]]
454추가: name = "zmij"
455추가: version = "1.0.23"
456추가: source = "registry+https://github.com/rust-lang/crates.io-index"
457추가: checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
458추가:
362459[[package]]
363460name = "zune-core"
364461version = "0.5.3"
수정experiments/rust-archive-worker/Cargo.toml+4-0
@@ -21,6 +21,10 @@ zeroize = "=1.9.1"
2121sha2 = "=0.10.9"
2222zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] }
2323
24추가: [target.'cfg(target_os = "linux")'.dependencies]
25추가: serde = "=1.0.229"
26추가: serde_json = "=1.0.154"
27추가:
2428[workspace]
2529exclude = ["vendor/zune-jpeg"]
2630
수정experiments/rust-archive-worker/src/filesystem.rs+212-1
@@ -194,6 +194,210 @@ mod platform {
194194 fn renameat(fd: i32, path: *const i8, newfd: i32, newpath: *const i8) -> i32;
195195 fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
196196 fn geteuid() -> u32;
197추가: fn getegid() -> u32;
198추가: fn fgetxattr(
199추가: fd: i32,
200추가: name: *const std::ffi::c_char,
201추가: value: *mut std::ffi::c_void,
202추가: size: usize,
203추가: ) -> isize;
204추가: fn getgrgid_r(
205추가: gid: u32,
206추가: group: *mut Group,
207추가: buffer: *mut i8,
208추가: length: usize,
209추가: result: *mut *mut Group,
210추가: ) -> i32;
211추가: }
212추가: #[repr(C)]
213추가: struct Group {
214추가: name: *mut i8,
215추가: password: *mut i8,
216추가: gid: u32,
217추가: members: *mut *mut i8,
218추가: }
219추가: // 없는 경로만 허용하며 중간 심볼릭 링크와 확인 오류는 거부함.
220추가: fn path_is_absent(path: &Path) -> bool {
221추가: let mut prefix = std::path::PathBuf::new();
222추가: for component in path.components() {
223추가: prefix.push(component.as_os_str());
224추가: match std::fs::symlink_metadata(&prefix) {
225추가: Ok(metadata) if metadata.is_dir() => {}
226추가: Ok(_) => return false,
227추가: Err(error) if error.kind() == std::io::ErrorKind::NotFound => return true,
228추가: Err(_) => return false,
229추가: }
230추가: }
231추가: false
232추가: }
233추가:
234추가: fn sss_is_unused(socket: &Path, cache: &Path) -> bool {
235추가: path_is_absent(socket)
236추가: && ["passwd", "group", "initgr"]
237추가: .iter()
238추가: .all(|name| path_is_absent(&cache.join(name)))
239추가: }
240추가:
241추가: // sss는 소켓과 캐시가 모두 없을 때만 빈 소스로 취급함.
242추가: fn primary_group_is_private(gid: u32) -> bool {
243추가: let Ok(policy) = std::fs::read_to_string("/etc/nsswitch.conf") else {
244추가: return false;
245추가: };
246추가: let mut databases = [None, None, None];
247추가: for line in policy.lines() {
248추가: let line = line.split('#').next().unwrap_or_default();
249추가: let Some((database, sources)) = line.split_once(':') else {
250추가: continue;
251추가: };
252추가: let index = match database.trim() {
253추가: "passwd" => 0,
254추가: "group" => 1,
255추가: "initgroups" => 2,
256추가: _ => continue,
257추가: };
258추가: if databases[index]
259추가: .replace(sources.split_whitespace().collect::<Vec<_>>())
260추가: .is_some()
261추가: {
262추가: return false;
263추가: }
264추가: }
265추가: let [Some(passwd), Some(group), initgroups] = databases else {
266추가: return false;
267추가: };
268추가: let mut has_systemd = false;
269추가: let mut has_sss = false;
270추가: // initgroups가 생략되어도 기본값인 group 소스를 검사함.
271추가: for source in [Some(passwd), Some(group), initgroups]
272추가: .into_iter()
273추가: .flatten()
274추가: {
275추가: if !matches!(
276추가: source.as_slice(),
277추가: ["files"] | ["files", "systemd"] | ["files", "sss"] | ["files", "systemd", "sss"]
278추가: ) {
279추가: return false;
280추가: }
281추가: has_systemd |= source.contains(&"systemd");
282추가: has_sss |= source.contains(&"sss");
283추가: }
284추가: if has_sss
285추가: && !sss_is_unused(
286추가: Path::new("/var/lib/sss/pipes/nss"),
287추가: Path::new("/var/lib/sss/mc"),
288추가: )
289추가: {
290추가: return false;
291추가: }
292추가: let Ok(accounts) = std::fs::read_to_string("/etc/passwd") else {
293추가: return false;
294추가: };
295추가: let current_uid = unsafe { geteuid() };
296추가: let mut current_name = None;
297추가: for account in accounts.lines() {
298추가: if account.trim().is_empty() || account.starts_with('#') {
299추가: continue;
300추가: }
301추가: let fields: Vec<_> = account.split(':').collect();
302추가: if fields.len() != 7 || fields[0].is_empty() {
303추가: return false;
304추가: }
305추가: let (Ok(uid), Ok(primary_gid)) = (fields[2].parse::<u32>(), fields[3].parse::<u32>())
306추가: else {
307추가: return false;
308추가: };
309추가: if primary_gid == gid {
310추가: if uid != current_uid {
311추가: return false;
312추가: }
313추가: if current_name.replace(fields[0]).is_some() {
314추가: return false;
315추가: }
316추가: }
317추가: }
318추가: let Some(current_name) = current_name else {
319추가: return false;
320추가: };
321추가: !has_systemd
322추가: || crate::systemd_userdb::group_is_private(
323추가: gid,
324추가: current_uid,
325추가: current_name,
326추가: Path::new("/run/systemd/userdb/"),
327추가: &[
328추가: Path::new("/etc/userdb"),
329추가: Path::new("/run/userdb"),
330추가: Path::new("/run/host/userdb"),
331추가: Path::new("/usr/local/lib/userdb"),
332추가: Path::new("/usr/lib/userdb"),
333추가: ],
334추가: )
335추가: }
336추가:
337추가: // 기본 구성원과 보조 구성원을 모두 확인함.
338추가: fn private_group(gid: u32) -> bool {
339추가: if gid != unsafe { getegid() } || !primary_group_is_private(gid) {
340추가: return false;
341추가: }
342추가: let mut group = Group {
343추가: name: std::ptr::null_mut(),
344추가: password: std::ptr::null_mut(),
345추가: gid: 0,
346추가: members: std::ptr::null_mut(),
347추가: };
348추가: let mut result = std::ptr::null_mut();
349추가: let mut buffer = vec![0i8; 16 * 1024];
350추가: let status = unsafe {
351추가: getgrgid_r(
352추가: gid,
353추가: &mut group,
354추가: buffer.as_mut_ptr(),
355추가: buffer.len(),
356추가: &mut result,
357추가: )
358추가: };
359추가: // 그룹 정보를 읽지 못하면 안전하다고 볼 근거가 없으므로 거부함.
360추가: status == 0
361추가: && !result.is_null()
362추가: && group.gid == gid
363추가: && !group.members.is_null()
364추가: && unsafe { *group.members }.is_null()
365추가: }
366추가: fn access_acl_has_no_named_entries(file: &File) -> bool {
367추가: // 이름 없는 ACL은 소유자, 그룹, other와 선택적 mask의 최대 4항목임.
368추가: let mut bytes = [0u8; 4 + 4 * 8];
369추가: // 경로를 다시 해석하지 않고 판정 대상 폴더의 접근 ACL을 읽음.
370추가: let length = unsafe {
371추가: fgetxattr(
372추가: file.as_raw_fd(),
373추가: c"system.posix_acl_access".as_ptr(),
374추가: bytes.as_mut_ptr().cast(),
375추가: bytes.len(),
376추가: )
377추가: };
378추가: if length < 0 {
379추가: // 속성 없음과 미지원 외에는 ERANGE를 포함해 거부함.
380추가: return matches!(
381추가: std::io::Error::last_os_error().raw_os_error(),
382추가: Some(61 | 95)
383추가: );
384추가: }
385추가: let tags: &[u16] = match length {
386추가: 28 => &[1, 4, 32],
387추가: 36 => &[1, 4, 16, 32],
388추가: _ => return false,
389추가: };
390추가: if u32::from_le_bytes(bytes[..4].try_into().unwrap()) != 2 {
391추가: return false;
392추가: }
393추가: bytes[4..length as usize]
394추가: .chunks_exact(8)
395추가: .zip(tags)
396추가: .all(|(entry, expected)| {
397추가: u16::from_le_bytes(entry[..2].try_into().unwrap()) == *expected
398추가: && u16::from_le_bytes(entry[2..4].try_into().unwrap()) & !7 == 0
399추가: && u32::from_le_bytes(entry[4..8].try_into().unwrap()) == u32::MAX
400추가: })
197401 }
198402 pub struct Dir {
199403 file: File,
@@ -242,7 +446,14 @@ mod platform {
242446 fn trusted(&self) -> Result<()> {
243447 let m = self.file.metadata().map_err(|_| ErrorCode::Io)?;
244448 // 다른 계정이 바꿀 수 있는 출력 폴더를 거부함.
245삭제: if !m.is_dir() || m.uid() != unsafe { geteuid() } || m.mode() & 0o022 != 0 {
449추가: // 그룹 쓰기는 이름 있는 접근 ACL이 없고 개인 그룹일 때만 허용함.
450추가: let group_writable = m.mode() & 0o020 != 0;
451추가: if !m.is_dir()
452추가: || m.uid() != unsafe { geteuid() }
453추가: || m.mode() & 0o002 != 0
454추가: || (group_writable
455추가: && (!access_acl_has_no_named_entries(&self.file) || !private_group(m.gid())))
456추가: {
246457 return Err(ErrorCode::UnsafePath);
247458 }
248459 Ok(())
수정experiments/rust-archive-worker/src/lib.rs+4-0
@@ -16,6 +16,10 @@ mod space;
1616mod split_seven_zip;
1717mod spool;
1818mod streaming;
19추가: pub mod tree_remove;
1920pub mod wire;
2021mod zip_extra;
2122mod zip_recovery;
23추가:
24추가: #[cfg(target_os = "linux")]
25추가: mod systemd_userdb;
추가experiments/rust-archive-worker/src/systemd_userdb.rs+363-0
@@ -0,0 +1,363 @@
1추가: use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
2추가: use serde_json::{Map, Value};
3추가: use std::collections::BTreeMap;
4추가: use std::fs;
5추가: use std::io::{BufRead, BufReader, Write};
6추가: use std::os::unix::{ffi::OsStrExt, fs::FileTypeExt, io::FromRawFd, net::UnixStream};
7추가: use std::path::Path;
8추가: use std::time::{Duration, Instant};
9추가:
10추가: // 중복 키는 해석 순서에 따라 판정이 달라질 수 있어 모든 깊이에서 거부함.
11추가: struct Strict(Value);
12추가: impl<'de> Deserialize<'de> for Strict {
13추가: fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
14추가: struct Json;
15추가: impl<'de> Visitor<'de> for Json {
16추가: type Value = Strict;
17추가: fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
18추가: f.write_str("unambiguous JSON")
19추가: }
20추가: fn visit_bool<E: de::Error>(self, v: bool) -> Result<Strict, E> {
21추가: Ok(Strict(Value::Bool(v)))
22추가: }
23추가: fn visit_i64<E: de::Error>(self, v: i64) -> Result<Strict, E> {
24추가: Ok(Strict(v.into()))
25추가: }
26추가: fn visit_u64<E: de::Error>(self, v: u64) -> Result<Strict, E> {
27추가: Ok(Strict(v.into()))
28추가: }
29추가: fn visit_f64<E: de::Error>(self, v: f64) -> Result<Strict, E> {
30추가: serde_json::Number::from_f64(v)
31추가: .map(|v| Strict(Value::Number(v)))
32추가: .ok_or_else(|| E::custom("invalid number"))
33추가: }
34추가: fn visit_str<E: de::Error>(self, v: &str) -> Result<Strict, E> {
35추가: Ok(Strict(Value::String(v.into())))
36추가: }
37추가: fn visit_unit<E: de::Error>(self) -> Result<Strict, E> {
38추가: Ok(Strict(Value::Null))
39추가: }
40추가: fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Strict, A::Error> {
41추가: let mut values = Vec::new();
42추가: while let Some(Strict(v)) = seq.next_element()? {
43추가: values.push(v);
44추가: }
45추가: Ok(Strict(Value::Array(values)))
46추가: }
47추가: fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Strict, A::Error> {
48추가: let mut values = Map::new();
49추가: while let Some((key, Strict(v))) = map.next_entry::<String, Strict>()? {
50추가: if values.insert(key, v).is_some() {
51추가: return Err(de::Error::custom("duplicate key"));
52추가: }
53추가: }
54추가: Ok(Strict(Value::Object(values)))
55추가: }
56추가: }
57추가: deserializer.deserialize_any(Json)
58추가: }
59추가: }
60추가:
61추가: type Check<T> = Result<T, ()>;
62추가: const MAX_FRAME: usize = 1024 * 1024;
63추가: const MAX_TOTAL: usize = 16 * MAX_FRAME;
64추가: const MAX_RECORDS: usize = 65_536;
65추가:
66추가: fn directory(path: &Path) -> Check<bool> {
67추가: let mut prefix = std::path::PathBuf::new();
68추가: for part in path.components() {
69추가: prefix.push(part.as_os_str());
70추가: match fs::symlink_metadata(&prefix) {
71추가: Ok(m) if m.is_dir() => {}
72추가: Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
73추가: _ => return Err(()),
74추가: }
75추가: }
76추가: Ok(true)
77추가: }
78추가:
79추가: fn name(value: &Value) -> Check<&str> {
80추가: value
81추가: .as_str()
82추가: .filter(|s| !s.is_empty() && !s.chars().any(char::is_control))
83추가: .ok_or(())
84추가: }
85추가: fn id(value: &Value) -> Check<u32> {
86추가: value
87추가: .as_u64()
88추가: .and_then(|v| u32::try_from(v).ok())
89추가: .filter(|v| *v != u32::MAX)
90추가: .ok_or(())
91추가: }
92추가: fn strings(value: Option<&Value>) -> Check<Vec<&str>> {
93추가: match value {
94추가: None => Ok(Vec::new()),
95추가: Some(Value::Array(values)) => values.iter().map(name).collect(),
96추가: _ => Err(()),
97추가: }
98추가: }
99추가: fn record(parameters: &Value) -> Check<&Value> {
100추가: match parameters.get("incomplete") {
101추가: None | Some(Value::Bool(false)) => {}
102추가: _ => return Err(()),
103추가: }
104추가: let record = parameters
105추가: .get("record")
106추가: .filter(|v| v.is_object())
107추가: .ok_or(())?;
108추가: // 기기별 덮어쓰기를 해석하지 않은 상태에서는 거부함.
109추가: for key in ["binding", "perMachine"] {
110추가: match record.get(key) {
111추가: None => {}
112추가: Some(Value::Object(v)) if key == "binding" && v.is_empty() => {}
113추가: Some(Value::Array(v)) if key == "perMachine" && v.is_empty() => {}
114추가: _ => return Err(()),
115추가: }
116추가: }
117추가: Ok(record)
118추가: }
119추가:
120추가: struct Budget {
121추가: deadline: Instant,
122추가: bytes: usize,
123추가: records: usize,
124추가: }
125추가: impl Budget {
126추가: fn remaining(&self) -> Check<Duration> {
127추가: self.deadline
128추가: .checked_duration_since(Instant::now())
129추가: .filter(|d| !d.is_zero())
130추가: .ok_or(())
131추가: }
132추가: }
133추가:
134추가: // Unix 소켓의 대기열이 가득 차도 연결 단계에서 무한히 기다리지 않음.
135추가: fn connect(path: &Path) -> Check<UnixStream> {
136추가: #[repr(C)]
137추가: struct Address {
138추가: family: u16,
139추가: path: [u8; 108],
140추가: }
141추가: unsafe extern "C" {
142추가: fn socket(domain: i32, kind: i32, protocol: i32) -> i32;
143추가: fn connect(fd: i32, address: *const Address, size: u32) -> i32;
144추가: }
145추가: let bytes = path.as_os_str().as_bytes();
146추가: if bytes.contains(&0) || bytes.len() >= 108 {
147추가: return Err(());
148추가: }
149추가: let mut address = Address {
150추가: family: 1,
151추가: path: [0; 108],
152추가: };
153추가: address.path[..bytes.len()].copy_from_slice(bytes);
154추가: let fd = unsafe { socket(1, 1 | 0x80000 | 0x800, 0) };
155추가: if fd < 0 {
156추가: return Err(());
157추가: }
158추가: let stream = unsafe { UnixStream::from_raw_fd(fd) };
159추가: if unsafe { connect(fd, &address, (2 + bytes.len() + 1) as u32) } != 0 {
160추가: return Err(());
161추가: }
162추가: stream.set_nonblocking(false).map_err(|_| ())?;
163추가: Ok(stream)
164추가: }
165추가:
166추가: fn query(
167추가: path: &Path,
168추가: service: &str,
169추가: method: &str,
170추가: budget: &mut Budget,
171추가: mut check: impl FnMut(&Value) -> Check<()>,
172추가: ) -> Check<()> {
173추가: let mut stream = connect(path)?;
174추가: stream
175추가: .set_write_timeout(Some(budget.remaining()?))
176추가: .map_err(|_| ())?;
177추가: let request = serde_json::json!({
178추가: "method": format!("io.systemd.UserDatabase.{method}"),
179추가: "parameters": {"service": service}, "more": true,
180추가: });
181추가: stream
182추가: .write_all(request.to_string().as_bytes())
183추가: .map_err(|_| ())?;
184추가: stream.write_all(&[0]).map_err(|_| ())?;
185추가: let mut reader = BufReader::new(stream);
186추가: loop {
187추가: let mut frame = Vec::new();
188추가: loop {
189추가: reader
190추가: .get_ref()
191추가: .set_read_timeout(Some(budget.remaining()?))
192추가: .map_err(|_| ())?;
193추가: let chunk = reader.fill_buf().map_err(|_| ())?;
194추가: if chunk.is_empty() {
195추가: return Err(());
196추가: }
197추가: let end = chunk.iter().position(|b| *b == 0);
198추가: let n = end.map_or(chunk.len(), |i| i + 1);
199추가: budget.bytes = budget
200추가: .bytes
201추가: .checked_add(n)
202추가: .filter(|n| *n <= MAX_TOTAL)
203추가: .ok_or(())?;
204추가: if frame.len() + n > MAX_FRAME {
205추가: return Err(());
206추가: }
207추가: frame.extend_from_slice(&chunk[..n]);
208추가: reader.consume(n);
209추가: if end.is_some() {
210추가: frame.pop();
211추가: break;
212추가: }
213추가: }
214추가: budget.records += 1;
215추가: if budget.records > MAX_RECORDS {
216추가: return Err(());
217추가: }
218추가: let Strict(reply) = serde_json::from_slice::<Strict>(&frame).map_err(|_| ())?;
219추가: let object = reply.as_object().ok_or(())?;
220추가: if object
221추가: .keys()
222추가: .any(|key| !matches!(key.as_str(), "parameters" | "error" | "continues"))
223추가: {
224추가: return Err(());
225추가: }
226추가: let continues = match reply.get("continues") {
227추가: None | Some(Value::Bool(false)) => false,
228추가: Some(Value::Bool(true)) => true,
229추가: _ => return Err(()),
230추가: };
231추가: if let Some(error) = reply.get("error") {
232추가: return if error.as_str() == Some("io.systemd.UserDatabase.NoRecordFound")
233추가: && !continues
234추가: && reply
235추가: .get("parameters")
236추가: .is_none_or(|v| v.as_object().is_some_and(|v| v.is_empty()))
237추가: {
238추가: Ok(())
239추가: } else {
240추가: Err(())
241추가: };
242추가: }
243추가: let parameters = reply
244추가: .get("parameters")
245추가: .filter(|v| v.is_object())
246추가: .ok_or(())?;
247추가: check(parameters)?;
248추가: if !continues {
249추가: return Ok(());
250추가: }
251추가: }
252추가: }
253추가:
254추가: fn inspect(gid: u32, uid: u32, owner: &str, sockets: &Path, dropins: &[&Path]) -> Check<()> {
255추가: for path in dropins {
256추가: if directory(path)? && fs::read_dir(path).map_err(|_| ())?.next().is_some() {
257추가: return Err(());
258추가: }
259추가: }
260추가: let mut groups = BTreeMap::<String, u32>::new();
261추가: let local = fs::read_to_string("/etc/group").map_err(|_| ())?;
262추가: for line in local
263추가: .lines()
264추가: .filter(|v| !v.is_empty() && !v.starts_with('#'))
265추가: {
266추가: let fields: Vec<_> = line.split(':').collect();
267추가: if fields.len() != 4 || fields[0].is_empty() {
268추가: return Err(());
269추가: }
270추가: let group_gid = fields[2].parse::<u32>().map_err(|_| ())?;
271추가: if group_gid == gid && fields[3].split(',').any(|v| !v.is_empty() && v != owner) {
272추가: return Err(());
273추가: }
274추가: if groups.insert(fields[0].into(), group_gid).is_some() {
275추가: return Err(());
276추가: }
277추가: }
278추가: let mut services = Vec::new();
279추가: if directory(sockets)? {
280추가: for entry in fs::read_dir(sockets).map_err(|_| ())? {
281추가: let entry = entry.map_err(|_| ())?;
282추가: let service = entry.file_name().into_string().map_err(|_| ())?;
283추가: // 중계 서비스도 소켓 형식인지는 확인함.
284추가: if !entry.file_type().map_err(|_| ())?.is_socket() {
285추가: return Err(());
286추가: }
287추가: if matches!(
288추가: service.as_str(),
289추가: "io.systemd.Multiplexer" | "io.systemd.NameServiceSwitch"
290추가: ) {
291추가: continue;
292추가: }
293추가: services.push((service, entry.path()));
294추가: if services.len() > 256 {
295추가: return Err(());
296추가: }
297추가: }
298추가: }
299추가: let mut budget = Budget {
300추가: deadline: Instant::now() + Duration::from_secs(5),
301추가: bytes: 0,
302추가: records: 0,
303추가: };
304추가: // 모든 서비스의 그룹 이름을 먼저 모아 서비스 간 구성원도 검사함.
305추가: for (service, path) in &services {
306추가: query(path, service, "GetGroupRecord", &mut budget, |p| {
307추가: let r = record(p)?;
308추가: let group_name = name(&r["groupName"])?;
309추가: let group_gid = id(&r["gid"])?;
310추가: let members = strings(r.get("members"))?;
311추가: if group_gid == gid && members.iter().any(|v| *v != owner) {
312추가: return Err(());
313추가: }
314추가: if groups
315추가: .insert(group_name.into(), group_gid)
316추가: .is_some_and(|v| v != group_gid)
317추가: {
318추가: return Err(());
319추가: }
320추가: Ok(())
321추가: })?;
322추가: }
323추가: for (service, path) in &services {
324추가: query(path, service, "GetUserRecord", &mut budget, |p| {
325추가: let r = record(p)?;
326추가: let user = name(&r["userName"])?;
327추가: let user_uid = id(&r["uid"])?;
328추가: let primary = id(&r["gid"])?;
329추가: let is_owner = user_uid == uid && user == owner;
330추가: if primary == gid && !is_owner {
331추가: return Err(());
332추가: }
333추가: for group in strings(r.get("memberOf"))? {
334추가: let target = groups.get(group).ok_or(())?;
335추가: if *target == gid && !is_owner {
336추가: return Err(());
337추가: }
338추가: }
339추가: Ok(())
340추가: })?;
341추가: query(path, service, "GetMemberships", &mut budget, |p| {
342추가: let user = name(&p["userName"])?;
343추가: let group = name(&p["groupName"])?;
344추가: let target = groups.get(group).ok_or(())?;
345추가: if *target == gid && user != owner {
346추가: Err(())
347추가: } else {
348추가: Ok(())
349추가: }
350추가: })?;
351추가: }
352추가: Ok(())
353추가: }
354추가:
355추가: pub(crate) fn group_is_private(
356추가: gid: u32,
357추가: uid: u32,
358추가: owner: &str,
359추가: sockets: &Path,
360추가: dropins: &[&Path],
361추가: ) -> bool {
362추가: inspect(gid, uid, owner, sockets, dropins).is_ok()
363추가: }
추가experiments/rust-archive-worker/src/tree_remove.rs+194-0
@@ -0,0 +1,194 @@
1추가: //! 열어 둔 폴더 핸들에 묶어서 폴더 안의 내용을 지움.
2추가: //! 경로를 다시 해석하지 않으므로 확인한 뒤 경로가 바뀌어도 다른 폴더를 지우지 않음.
3추가:
4추가: use std::fs::File;
5추가: use std::io;
6추가: use std::path::Path;
7추가:
8추가: /// `dir` 핸들이 가리키는 폴더 안의 모든 항목을 지움. 폴더 자체는 지우지 않음.
9추가: /// Linux는 핸들 기준 `unlinkat`으로 지우며 `path`는 쓰지 않음.
10추가: /// Windows는 호출한 쪽이 공유 삭제를 허용하지 않고 `dir`을 열어 두어 폴더 이름이
11추가: /// 바뀌지 않게 한 상태에서만 `path`를 씀.
12추가: pub fn remove_contents(dir: &File, path: &Path) -> io::Result<()> {
13추가: platform::remove_contents(dir, path)
14추가: }
15추가:
16추가: /// `dir` 핸들이 가리키는 폴더가 비어 있는지 확인함. 새로 만든 폴더를 핸들로 잡은 직후 쓰임.
17추가: pub fn is_empty(dir: &File, path: &Path) -> io::Result<bool> {
18추가: platform::is_empty(dir, path)
19추가: }
20추가:
21추가: #[cfg(target_os = "linux")]
22추가: mod platform {
23추가: use std::ffi::{CStr, CString};
24추가: use std::fs::File;
25추가: use std::io;
26추가: use std::os::unix::{
27추가: fs::MetadataExt,
28추가: io::{AsRawFd, FromRawFd},
29추가: };
30추가: use std::path::Path;
31추가:
32추가: #[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
33추가: const NOFOLLOW_DIRECTORY: i32 = 0x8000 | 0x4000;
34추가: #[cfg(not(any(target_arch = "aarch64", target_arch = "arm")))]
35추가: const NOFOLLOW_DIRECTORY: i32 = 0x20000 | 0x10000;
36추가: const CLOEXEC: i32 = 0x80000;
37추가: const AT_REMOVEDIR: i32 = 0x200;
38추가: const ENOENT: i32 = 2;
39추가: const EPERM: i32 = 1;
40추가: const EISDIR: i32 = 21;
41추가: /// 깊게 중첩된 폴더에서 파일 디스크립터가 바닥나지 않게 하는 한도.
42추가: const MAX_DEPTH: usize = 256;
43추가:
44추가: #[repr(C)]
45추가: struct Dirent64 {
46추가: inode: u64,
47추가: offset: i64,
48추가: length: u16,
49추가: kind: u8,
50추가: name: [i8; 256],
51추가: }
52추가:
53추가: unsafe extern "C" {
54추가: fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32;
55추가: fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
56추가: fn fdopendir(fd: i32) -> *mut std::ffi::c_void;
57추가: fn readdir64(stream: *mut std::ffi::c_void) -> *mut Dirent64;
58추가: fn rewinddir(stream: *mut std::ffi::c_void);
59추가: fn closedir(stream: *mut std::ffi::c_void) -> i32;
60추가: }
61추가:
62추가: pub fn remove_contents(dir: &File, _path: &Path) -> io::Result<()> {
63추가: let device = dir.metadata()?.dev();
64추가: remove_children(dir, device, 0)
65추가: }
66추가:
67추가: pub fn is_empty(dir: &File, _path: &Path) -> io::Result<bool> {
68추가: Ok(names(dir)?.is_empty())
69추가: }
70추가:
71추가: fn names(dir: &File) -> io::Result<Vec<CString>> {
72추가: let copy = dir.try_clone()?;
73추가: let fd = std::os::unix::io::IntoRawFd::into_raw_fd(copy);
74추가: // 복제한 디스크립터의 소유권은 폴더 스트림이 가져가며 closedir이 닫음.
75추가: let stream = unsafe { fdopendir(fd) };
76추가: if stream.is_null() {
77추가: let error = io::Error::last_os_error();
78추가: // 스트림을 만들지 못했으므로 복제한 디스크립터를 직접 돌려받아 닫음.
79추가: drop(unsafe { File::from_raw_fd(fd) });
80추가: return Err(error);
81추가: }
82추가: // 복제한 디스크립터는 원본과 읽기 위치를 공유하므로 처음부터 읽음.
83추가: unsafe { rewinddir(stream) };
84추가: let mut found = Vec::new();
85추가: loop {
86추가: let entry = unsafe { readdir64(stream) };
87추가: if entry.is_null() {
88추가: break;
89추가: }
90추가: // 반환된 항목은 다음 readdir64 호출 전까지 유효하며 바로 복사함.
91추가: let name = unsafe { CStr::from_ptr((*entry).name.as_ptr()) };
92추가: let bytes = name.to_bytes();
93추가: if bytes != b"." && bytes != b".." {
94추가: found.push(name.to_owned());
95추가: }
96추가: }
97추가: unsafe { closedir(stream) };
98추가: Ok(found)
99추가: }
100추가:
101추가: fn unlink(dir: &File, name: &CString, flags: i32) -> io::Result<()> {
102추가: // 부모 핸들 기준으로 이름 하나만 지움.
103추가: if unsafe { unlinkat(dir.as_raw_fd(), name.as_ptr(), flags) } == 0 {
104추가: Ok(())
105추가: } else {
106추가: Err(io::Error::last_os_error())
107추가: }
108추가: }
109추가:
110추가: fn open_directory(dir: &File, name: &CString) -> io::Result<File> {
111추가: // 심볼릭 링크를 따르지 않고 폴더만 부모 핸들 기준으로 엶.
112추가: let fd = unsafe {
113추가: openat(
114추가: dir.as_raw_fd(),
115추가: name.as_ptr(),
116추가: NOFOLLOW_DIRECTORY | CLOEXEC,
117추가: )
118추가: };
119추가: if fd < 0 {
120추가: return Err(io::Error::last_os_error());
121추가: }
122추가: Ok(unsafe { File::from_raw_fd(fd) })
123추가: }
124추가:
125추가: fn remove_children(dir: &File, device: u64, depth: usize) -> io::Result<()> {
126추가: let mut failure = None;
127추가: for name in names(dir)? {
128추가: if let Err(error) = remove_entry(dir, &name, device, depth) {
129추가: if error.raw_os_error() != Some(ENOENT) {
130추가: failure.get_or_insert(error);
131추가: }
132추가: }
133추가: }
134추가: failure.map_or(Ok(()), Err)
135추가: }
136추가:
137추가: fn remove_entry(dir: &File, name: &CString, device: u64, depth: usize) -> io::Result<()> {
138추가: match unlink(dir, name, 0) {
139추가: Ok(()) => return Ok(()),
140추가: Err(error) if matches!(error.raw_os_error(), Some(EISDIR | EPERM)) => {}
141추가: Err(error) => return Err(error),
142추가: }
143추가: if depth >= MAX_DEPTH {
144추가: return Err(io::Error::other("폴더가 너무 깊음"));
145추가: }
146추가: let child = match open_directory(dir, name) {
147추가: Ok(child) => child,
148추가: // 그 사이 폴더가 아닌 항목으로 바뀌었으면 항목 자체를 지움.
149추가: Err(_) => return unlink(dir, name, 0),
150추가: };
151추가: // 다른 파일 시스템이 연결된 폴더 안은 지우지 않음.
152추가: if child.metadata()?.dev() != device {
153추가: return Err(io::Error::other("다른 파일 시스템의 폴더"));
154추가: }
155추가: remove_children(&child, device, depth + 1)?;
156추가: drop(child);
157추가: unlink(dir, name, AT_REMOVEDIR)
158추가: }
159추가: }
160추가:
161추가: #[cfg(windows)]
162추가: mod platform {
163추가: use std::fs::{self, File};
164추가: use std::io;
165추가: use std::path::Path;
166추가:
167추가: pub fn is_empty(_dir: &File, path: &Path) -> io::Result<bool> {
168추가: // 호출한 쪽의 핸들이 이름 변경을 막고 있으므로 경로가 같은 폴더를 가리킴.
169추가: Ok(fs::read_dir(path)?.next().is_none())
170추가: }
171추가:
172추가: pub fn remove_contents(_dir: &File, path: &Path) -> io::Result<()> {
173추가: let mut failure = None;
174추가: // 호출한 쪽의 핸들이 폴더 이름 변경을 막고 있으므로 경로가 같은 폴더를 가리킴.
175추가: for entry in fs::read_dir(path)? {
176추가: let result = entry.and_then(|entry| {
177추가: let path = entry.path();
178추가: let kind = fs::symlink_metadata(&path)?.file_type();
179추가: if kind.is_symlink() {
180추가: // 링크는 따라가지 않고 링크 자체만 지움.
181추가: fs::remove_file(&path).or_else(|_| fs::remove_dir(&path))
182추가: } else if kind.is_dir() {
183추가: fs::remove_dir_all(&path)
184추가: } else {
185추가: fs::remove_file(&path)
186추가: }
187추가: });
188추가: if let Err(error) = result {
189추가: failure.get_or_insert(error);
190추가: }
191추가: }
192추가: failure.map_or(Ok(()), Err)
193추가: }
194추가: }
수정experiments/rust-ui-memory-app/Cargo.lock+27-0
@@ -1733,6 +1733,12 @@ dependencies = [
17331733 "either",
17341734]
17351735
1736추가: [[package]]
1737추가: name = "itoa"
1738추가: version = "1.0.19"
1739추가: source = "registry+https://github.com/rust-lang/crates.io-index"
1740추가: checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
1741추가:
17361742[[package]]
17371743name = "jni"
17381744version = "0.22.4"
@@ -3002,6 +3008,19 @@ dependencies = [
30023008 "syn 3.0.10",
30033009]
30043010
3011추가: [[package]]
3012추가: name = "serde_json"
3013추가: version = "1.0.154"
3014추가: source = "registry+https://github.com/rust-lang/crates.io-index"
3015추가: checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
3016추가: dependencies = [
3017추가: "itoa",
3018추가: "memchr",
3019추가: "serde",
3020추가: "serde_core",
3021추가: "zmij",
3022추가: ]
3023추가:
30053024[[package]]
30063025name = "serde_repr"
30073026version = "0.1.21"
@@ -4586,6 +4605,8 @@ dependencies = [
45864605 "lzma-rust2",
45874606 "pbkdf2",
45884607 "png",
4608추가: "serde",
4609추가: "serde_json",
45894610 "sha1",
45904611 "sha2 0.10.9",
45914612 "subtle",
@@ -4621,6 +4642,12 @@ version = "0.6.8"
46214642source = "registry+https://github.com/rust-lang/crates.io-index"
46224643checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
46234644
4645추가: [[package]]
4646추가: name = "zmij"
4647추가: version = "1.0.23"
4648추가: source = "registry+https://github.com/rust-lang/crates.io-index"
4649추가: checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
4650추가:
46244651[[package]]
46254652name = "zune-core"
46264653version = "0.5.3"
수정experiments/rust-ui-memory-app/src/archive_present.rs+230-0
@@ -479,3 +479,233 @@ pub fn excluded_split(path: &Path) -> bool {
479479 .to_ascii_lowercase();
480480 name.ends_with(".zip.001") || name.ends_with(".z01") || name.ends_with(".rar")
481481}
482추가:
483추가: /// 같은 이름이 이미 있으면 `이름 (1)`, `이름 (2)`처럼 비어 있는 이름을 찾음.
484추가: pub fn unique_folder(base: &Path) -> PathBuf {
485추가: let taken = |path: &Path| fs::symlink_metadata(path).is_ok();
486추가: if !taken(base) {
487추가: return base.to_path_buf();
488추가: }
489추가: let name = base.file_name().unwrap_or_default().to_string_lossy();
490추가: (1..)
491추가: .map(|n| base.with_file_name(format!("{name} ({n})")))
492추가: .find(|path| !taken(path))
493추가: .unwrap()
494추가: }
495추가:
496추가: fn private_dir(path: &Path) -> io::Result<()> {
497추가: let mut builder = fs::DirBuilder::new();
498추가: #[cfg(unix)]
499추가: {
500추가: use std::os::unix::fs::DirBuilderExt;
501추가: builder.mode(0o700);
502추가: }
503추가: builder.create(path)
504추가: }
505추가:
506추가: pub struct OpenRoot {
507추가: path: PathBuf,
508추가: handle: fs::File,
509추가: identity: worker_protocol::protocol::SourceObject,
510추가: }
511추가:
512추가: impl OpenRoot {
513추가: fn capture(path: PathBuf) -> io::Result<Self> {
514추가: let handle = open_root_handle(&path)?;
515추가: // 만든 직후에는 비어 있어야 함. 만든 뒤 핸들을 잡기 전에 다른 폴더로 바뀌었다면
516추가: // 사용자 데이터가 들어 있을 수 있으므로 원본으로 기록하지 않음.
517추가: if !worker_protocol::tree_remove::is_empty(&handle, &path)? {
518추가: return Err(io::Error::other("만든 임시 폴더가 아님"));
519추가: }
520추가: let identity = worker_protocol::filesystem::object(&handle)
521추가: .map_err(|_| io::Error::other("임시 폴더 식별 실패"))?;
522추가: Ok(Self {
523추가: path,
524추가: handle,
525추가: identity,
526추가: })
527추가: }
528추가:
529추가: pub fn path(&self) -> &Path {
530추가: &self.path
531추가: }
532추가:
533추가: pub fn is_current(&self) -> bool {
534추가: // 원본 핸들을 유지해 삭제된 inode가 재사용되어도 같다고 판정하지 않음.
535추가: self.handle.metadata().is_ok()
536추가: && open_root_handle(&self.path)
537추가: .ok()
538추가: .and_then(|file| worker_protocol::filesystem::object(&file).ok())
539추가: .is_some_and(|identity| identity == self.identity)
540추가: }
541추가: }
542추가:
543추가: fn open_root_handle(path: &Path) -> io::Result<fs::File> {
544추가: let mut options = fs::OpenOptions::new();
545추가: options.read(true);
546추가: #[cfg(target_os = "linux")]
547추가: {
548추가: use std::os::unix::fs::OpenOptionsExt;
549추가: options.custom_flags(0x20000); // 심볼릭 링크를 따라가지 않음.
550추가: }
551추가: #[cfg(windows)]
552추가: {
553추가: use std::os::windows::fs::OpenOptionsExt;
554추가: // 폴더 자체를 열며 재분석 지점을 따라가지 않음.
555추가: // 삭제 공유를 허용하지 않아 열어 둔 동안 폴더 이름을 바꾸거나 지울 수 없게 함.
556추가: options.share_mode(1 | 2).custom_flags(0x02000000 | 0x00200000);
557추가: }
558추가: let file = options.open(path)?;
559추가: let metadata = file.metadata()?;
560추가: if !metadata.is_dir() || fs::symlink_metadata(path)?.file_type().is_symlink() {
561추가: return Err(io::Error::other("임시 폴더가 아님"));
562추가: }
563추가: #[cfg(windows)]
564추가: {
565추가: use std::os::windows::fs::MetadataExt;
566추가: if metadata.file_attributes() & 0x400 != 0 {
567추가: return Err(io::Error::other("재분석 지점은 임시 폴더로 쓰지 않음"));
568추가: }
569추가: }
570추가: Ok(file)
571추가: }
572추가:
573추가: /// 압축파일 안 파일을 기본 프로그램으로 열 때 쓸 임시 폴더를 만듦.
574추가: /// 압축파일과 같은 폴더에 만들고, 그곳에 만들 수 없으면 시스템 임시 폴더를 씀.
575추가: /// 숨김 폴더로 만들지 않음. snap으로 설치한 Firefox 등은 홈 바로 아래 숨김 폴더와
576추가: /// 시스템 임시 폴더의 파일을 읽지 못해 열기 요청을 조용히 무시함.
577추가: pub fn create_open_root(archive: &Path) -> io::Result<OpenRoot> {
578추가: create_open_root_with(archive, |_| {})
579추가: }
580추가:
581추가: /// `create_open_root`와 같고, 폴더를 만든 직후 핸들을 잡기 전에 `after_create`를 실행함.
582추가: /// 만든 뒤 경로가 바뀌는 경우를 시험하려고 둠.
583추가: /// 폴더를 만든 뒤 핸들을 잡기까지의 틈에 경로가 바뀌어도, 핸들로 확인한 폴더가 비어 있지
584추가: /// 않으면 원본으로 쓰지 않고 다른 이름으로 다시 만듦. 바뀐 폴더는 건드리지 않음.
585추가: pub fn create_open_root_with(
586추가: archive: &Path,
587추가: mut after_create: impl FnMut(&Path),
588추가: ) -> io::Result<OpenRoot> {
589추가: let name = archive.file_name().unwrap_or_default().to_string_lossy();
590추가: let mut error = None;
591추가: if let Some(parent) = archive.parent().filter(|p| !p.as_os_str().is_empty()) {
592추가: let base = parent.join(open_root_name(&name));
593추가: for _ in 0..8 {
594추가: let path = unique_folder(&base);
595추가: match private_dir(&path) {
596추가: Ok(()) => {
597추가: after_create(&path);
598추가: match OpenRoot::capture(path.clone()) {
599추가: Ok(root) => return Ok(root),
600추가: Err(e) => {
601추가: // 비어 있는 폴더만 지워지므로 바뀐 폴더의 내용은 남음.
602추가: let _ = fs::remove_dir(&path);
603추가: error = Some(e);
604추가: continue;
605추가: }
606추가: }
607추가: }
608추가: Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
609추가: Err(e) => {
610추가: error = Some(e);
611추가: break;
612추가: }
613추가: }
614추가: }
615추가: }
616추가: let base = std::env::temp_dir().join(format!("zipelo-{}-{name}", std::process::id()));
617추가: let path = unique_folder(&base);
618추가: private_dir(&path).map_err(|e| error.unwrap_or(e))?;
619추가: after_create(&path);
620추가: OpenRoot::capture(path.clone()).inspect_err(|_| {
621추가: let _ = fs::remove_dir(&path);
622추가: })
623추가: }
624추가:
625추가: /// 열기용 임시 폴더 이름. 예: `자료.zip (Zipelo 임시)`.
626추가: pub fn open_root_name(archive_name: &str) -> String {
627추가: format!("{archive_name} (Zipelo 임시)")
628추가: }
629추가:
630추가: /// 이 앱이 만든 열기용 폴더를 지움. 다른 프로그램이 파일을 쓰고 있으면 남을 수 있음.
631추가: pub fn remove_open_root(root: OpenRoot) {
632추가: remove_open_root_with(root, || {});
633추가: }
634추가:
635추가: /// `remove_open_root`와 같고, 정체를 확인한 직후 삭제 전에 `after_check`를 실행함.
636추가: /// 확인과 삭제 사이에 경로가 바뀌는 경우를 시험하려고 둠.
637추가: /// 내용은 만들 때 열어 둔 폴더 핸들에 묶어 지우므로 경로가 바뀌어도 다른 폴더는 건드리지 않음.
638추가: pub fn remove_open_root_with(root: OpenRoot, after_check: impl FnOnce()) {
639추가: if !root.is_current() {
640추가: return;
641추가: }
642추가: after_check();
643추가: let OpenRoot { path, handle, .. } = root;
644추가: let _ = worker_protocol::tree_remove::remove_contents(&handle, &path);
645추가: // Windows는 핸들을 닫아야 폴더를 지울 수 있음.
646추가: drop(handle);
647추가: // 비어 있지 않거나 링크로 바뀐 경로는 지워지지 않으므로 다른 내용이 사라지지 않음.
648추가: let _ = fs::remove_dir(&path);
649추가: }
650추가:
651추가: /// 기본 프로그램으로 열면 실행될 수 있는 파일은 바로 열지 않음.
652추가: /// Windows는 스크립트도 연결 프로그램이 바로 실행하므로 범위가 넓고,
653추가: /// Linux는 스크립트를 편집기로 열므로 실행·설치 파일만 막음.
654추가: pub fn blocked_open(name: &str) -> bool {
655추가: #[cfg(windows)]
656추가: const EXECUTABLE: &[&str] = &[
657추가: "exe", "com", "bat", "cmd", "scr", "pif", "msi", "msp", "msc", "ps1", "psm1", "vbs",
658추가: "vbe", "js", "jse", "wsf", "wsh", "hta", "cpl", "lnk", "url", "reg", "jar", "inf", "scf",
659추가: "chm", "dll", "sys", "appref-ms", "application", "gadget", "settingcontent-ms",
660추가: ];
661추가: #[cfg(not(windows))]
662추가: const EXECUTABLE: &[&str] = &[
663추가: "desktop", "appimage", "run", "bin", "jar", "deb", "rpm", "snap", "flatpakref",
664추가: "flatpak", "exe", "msi",
665추가: ];
666추가: open_extension(name).is_some_and(|ext| EXECUTABLE.contains(&ext.to_ascii_lowercase().as_str()))
667추가: }
668추가:
669추가: fn open_extension(name: &str) -> Option<&str> {
670추가: let leaf = name.rsplit(['/', '\\']).next().unwrap_or(name);
671추가: leaf.rsplit_once('.')
672추가: .map(|(_, ext)| ext)
673추가: .filter(|ext| !ext.is_empty())
674추가: }
675추가:
676추가: /// 실행 파일이라 열지 않았다는 짧은 안내. 압축은 풀지 않음.
677추가: pub fn open_blocked_text(name: &str) -> String {
678추가: match open_extension(name) {
679추가: Some(ext) => format!("실행 파일(.{ext})은 안전을 위해 바로 열 수 없습니다"),
680추가: None => "실행 파일은 안전을 위해 바로 열 수 없습니다".into(),
681추가: }
682추가: }
683추가:
684추가: pub const OPEN_FAILED: &str = "파일을 열 프로그램을 실행하지 못했습니다";
685추가: pub const OPEN_MISSING: &str = "풀린 파일을 찾지 못해 열지 못했습니다";
686추가:
687추가: /// 운영체제에 설정된 기본 프로그램으로 파일을 엶.
688추가: pub fn open_with_default(path: &Path) -> Result<(), String> {
689추가: #[cfg(windows)]
690추가: let mut command = {
691추가: let mut command = std::process::Command::new("explorer.exe");
692추가: command.arg(path);
693추가: command
694추가: };
695추가: #[cfg(not(windows))]
696추가: let mut command = {
697추가: let mut command = std::process::Command::new("xdg-open");
698추가: command.arg(path);
699추가: command
700추가: };
701추가: command
702추가: .stdin(std::process::Stdio::null())
703추가: .stdout(std::process::Stdio::null())
704추가: .stderr(std::process::Stdio::null());
705추가: let mut child = command.spawn().map_err(|_| OPEN_FAILED.to_owned())?;
706추가: // 끝난 자식 프로세스를 거둬 좀비로 남지 않게 함.
707추가: std::thread::spawn(move || {
708추가: let _ = child.wait();
709추가: });
710추가: Ok(())
711추가: }
수정experiments/rust-ui-memory-app/src/archive_screen.rs+269-17
@@ -198,6 +198,24 @@ struct Marquee {
198198/// 파일 목록 한 행의 높이. 행 안의 크기 칸(theme::ROW)이 위아래 2px 여백으로 들어감.
199199const LIST_ROW: f32 = 36.0;
200200
201추가: /// 기본 프로그램으로 열려고 임시 폴더에 푸는 작업. 끝나면 원래 풀 위치로 되돌림.
202추가: struct OpenRequest {
203추가: folder: PathBuf,
204추가: /// 풀린 뒤 열 파일의 압축파일 안 경로. 작업자는 새로 만든 상위 폴더도 출력으로 알리므로
205추가: /// 출력 목록에서 이 경로와 같은 항목을 찾아 엶.
206추가: name: String,
207추가: destination: PathBuf,
208추가: automatic: bool,
209추가: }
210추가:
211추가: /// 파일 목록의 오른쪽 클릭 메뉴에서 고른 동작.
212추가: enum MenuAction {
213추가: NewFolder,
214추가: ChooseFolder,
215추가: }
216추가:
217추가: type Opener = Box<dyn FnMut(&Path) -> Result<(), String>>;
218추가:
201219pub struct ArchiveApp {
202220 pub model: Model,
203221 factory: Box<dyn Factory>,
@@ -262,6 +280,13 @@ pub struct ArchiveApp {
262280 checked_destination: bool,
263281 ui_error: Option<String>,
264282 initialized: bool,
283추가: opening: Option<OpenRequest>,
284추가: /// 마지막 풀기가 기본 프로그램으로 열기였으면 그 항목. 다시 시도할 때 다시 엶.
285추가: last_open: Option<u32>,
286추가: /// 압축파일별 열기용 임시 폴더. 앱을 닫을 때 지움.
287추가: open_roots: Vec<(PathBuf, present::OpenRoot)>,
288추가: open_count: u64,
289추가: opener: Opener,
265290 #[cfg(all(feature = "ui-fixture", debug_assertions))]
266291 scenario_marquee: Option<egui::Rect>,
267292 #[cfg(all(feature = "ui-fixture", debug_assertions))]
@@ -329,6 +354,11 @@ impl ArchiveApp {
329354 checked_destination: false,
330355 ui_error: None,
331356 initialized: false,
357추가: opening: None,
358추가: last_open: None,
359추가: open_roots: Vec::new(),
360추가: open_count: 0,
361추가: opener: Box::new(present::open_with_default),
332362 #[cfg(all(feature = "ui-fixture", debug_assertions))]
333363 scenario_marquee: None,
334364 #[cfg(all(feature = "ui-fixture", debug_assertions))]
@@ -344,6 +374,131 @@ impl ArchiveApp {
344374 self.dialogs = dialogs;
345375 }
346376
377추가: /// 파일을 기본 프로그램으로 여는 방법을 바꿈. 시험에서 실제 프로그램 실행을 막을 때 씀.
378추가: pub fn set_opener(&mut self, opener: Opener) {
379추가: self.opener = opener;
380추가: }
381추가:
382추가: /// 압축파일 안 파일 하나를 임시 폴더에 풀고 기본 프로그램으로 엶.
383추가: pub fn open_entry(&mut self, entry_id: u32) -> bool {
384추가: self.release_open();
385추가: if !self.model.can_extract() || self.opening.is_some() {
386추가: return false;
387추가: }
388추가: let Some(entry) = self.model.entries.iter().find(|e| e.id == entry_id) else {
389추가: return false;
390추가: };
391추가: if entry.kind != Kind::File {
392추가: return false;
393추가: }
394추가: let name = if self
395추가: .model
396추가: .list_id
397추가: .as_ref()
398추가: .is_some_and(|id| id.format == Format::Gzip)
399추가: {
400추가: self.gzip_name.clone()
401추가: } else {
402추가: entry.name.clone()
403추가: };
404추가: if present::blocked_open(&name) {
405추가: // 압축을 풀지 않고 바로 안내만 함.
406추가: self.dismissed = false;
407추가: self.ui_error = Some(present::open_blocked_text(&name));
408추가: return false;
409추가: }
410추가: let Some(archive) = self.model.archive.clone() else {
411추가: return false;
412추가: };
413추가: let root = match self.open_roots.iter().find(|(a, _)| *a == archive) {
414추가: Some((_, root)) if root.is_current() => root.path().to_path_buf(),
415추가: _ => match present::create_open_root(&archive) {
416추가: Ok(root) => {
417추가: self.open_roots.retain(|(a, _)| *a != archive);
418추가: let path = root.path().to_path_buf();
419추가: self.open_roots.push((archive, root));
420추가: path
421추가: }
422추가: Err(_) => {
423추가: self.dismissed = false;
424추가: self.ui_error = Some(present::FOLDER_ERROR.into());
425추가: return false;
426추가: }
427추가: },
428추가: };
429추가: // 같은 파일을 여러 번 열어도 충돌하지 않도록 열 때마다 새 하위 폴더에 풂.
430추가: self.open_count += 1;
431추가: let folder = present::unique_folder(&root.join(self.open_count.to_string()));
432추가: let request = OpenRequest {
433추가: folder: folder.clone(),
434추가: name: name.replace('\\', "/"),
435추가: destination: std::mem::replace(&mut self.destination, folder),
436추가: automatic: std::mem::replace(&mut self.automatic_destination, true),
437추가: };
438추가: self.opening = Some(request);
439추가: if self.extract_selection(Selection::EntryIds(vec![entry_id])) {
440추가: self.last_open = Some(entry_id);
441추가: true
442추가: } else {
443추가: self.finish_open(false);
444추가: false
445추가: }
446추가: }
447추가:
448추가: /// 한도를 늘려 다시 시도할 수 있는 결과가 화면에 남아 있는 동안은 열기 상태를 유지함.
449추가: fn open_retry_pending(&self) -> bool {
450추가: self.opening.is_some() && !self.dismissed && self.model.can_retry_expanded()
451추가: }
452추가:
453추가: /// 다시 시도를 기다리던 열기를 접고 원래 풀 위치로 되돌림. 다른 작업을 시작하기 전에 씀.
454추가: fn release_open(&mut self) {
455추가: if self.opening.is_some() && !self.model.busy() {
456추가: self.finish_open(false);
457추가: }
458추가: }
459추가:
460추가: /// 열기용 풀기가 끝나면 원래 풀 위치를 되돌리고, 성공했으면 기본 프로그램을 실행함.
461추가: fn finish_open(&mut self, completed: bool) {
462추가: let Some(request) = self.opening.take() else {
463추가: return;
464추가: };
465추가: self.destination = request.destination;
466추가: self.automatic_destination = request.automatic;
467추가: if !completed {
468추가: return;
469추가: }
470추가: let Some(name) = self
471추가: .model
472추가: .outputs
473추가: .iter()
474추가: .filter(|(_, d)| *d == Disposition::Created)
475추가: .map(|(name, _)| name.replace('\\', "/"))
476추가: .find(|name| name.trim_end_matches('/') == request.name)
477추가: else {
478추가: self.ui_error = Some(present::OPEN_MISSING.into());
479추가: return;
480추가: };
481추가: let path = name
482추가: .split('/')
483추가: .fold(request.folder, |path, part| path.join(part));
484추가: match (self.opener)(&path) {
485추가: // 결과 창 없이 바로 열린 파일을 보여 줌.
486추가: Ok(()) => self.dismissed = true,
487추가: Err(error) => self.ui_error = Some(error),
488추가: }
489추가: }
490추가:
491추가: /// 압축파일 이름으로 새 폴더를 만들고(같은 이름이 있으면 번호를 붙임) 선택 항목을 풂.
492추가: fn extract_to_new_folder(&mut self) -> bool {
493추가: self.release_open();
494추가: let Some(archive) = self.model.archive.clone() else {
495추가: return false;
496추가: };
497추가: self.destination = present::unique_folder(&present::default_destination(&archive));
498추가: self.automatic_destination = true;
499추가: self.begin_extract()
500추가: }
501추가:
347502 /// 창 순서를 지정할 수 없는 환경에서는 부모 안에 작업 화면을 그림.
348503 pub fn set_work_window_in_parent(&mut self, enabled: bool) {
349504 self.work_in_parent = enabled;
@@ -469,6 +624,7 @@ impl ArchiveApp {
469624 if self.model.busy() {
470625 return;
471626 }
627추가: self.release_open();
472628 if self
473629 .recovery_warning
474630 .as_ref()
@@ -570,6 +726,7 @@ impl ArchiveApp {
570726 }
571727
572728 pub fn begin_extract(&mut self) -> bool {
729추가: self.release_open();
573730 self.selected_only = !self.model.selected.is_empty();
574731 let selection = if self.selected_only {
575732 Selection::EntryIds(
@@ -590,6 +747,9 @@ impl ArchiveApp {
590747 return false;
591748 }
592749 self.selected_only = matches!(&selection, Selection::EntryIds(_));
750추가: if self.opening.is_none() {
751추가: self.last_open = None;
752추가: }
593753 match present::prepare_destination(&self.destination, self.automatic_destination) {
594754 Ok(true) => self.owned_destination = Some(self.destination.clone()),
595755 Ok(false) => self.owned_destination = None,
@@ -688,6 +848,8 @@ impl ArchiveApp {
688848 aes256: self.aes256,
689849 }
690850 };
851추가: // 한도 초과 뒤 보류된 열기는 만들기와 무관하므로 시작 전에 접음.
852추가: self.release_open();
691853 if self.start(request) {
692854 self.create = false;
693855 self.create_win = WorkWindow::default();
@@ -806,6 +968,9 @@ impl ArchiveApp {
806968 }
807969 }
808970 Purpose::Destination | Purpose::Retry => {
971추가: // 다른 폴더를 골랐으면 기본 프로그램 열기가 아닌 일반 풀기로 다시 함.
972추가: self.release_open();
973추가: self.last_open = None;
809974 self.choose_destination(path);
810975 self.selected_only = !self.model.selected.is_empty();
811976 if purpose == Purpose::Retry {
@@ -862,6 +1027,9 @@ impl ArchiveApp {
8621027 match request {
8631028 Start::List { archive } => self.open_path(archive),
8641029 Start::Preview { .. } | Start::RecoverZip { .. } => {}
1030추가: Start::Extract { .. } if let Some(entry_id) = self.last_open => {
1031추가: self.open_entry(entry_id);
1032추가: }
8651033 Start::Extract {
8661034 selection,
8671035 gzip_output_name,
@@ -918,6 +1086,20 @@ impl ArchiveApp {
9181086 self.model.close = Close::Confirm;
9191087 }
9201088 if busy && !self.model.busy() {
1089추가: let completed = self.model.confirmed
1090추가: && self
1091추가: .model
1092추가: .terminal
1093추가: .as_ref()
1094추가: .is_some_and(|t| t.outcome == Outcome::Completed);
1095추가: if self.opening.is_some() {
1096추가: // 열기용 폴더는 앱을 닫을 때 지우므로 풀 위치 소유 기록만 정리함.
1097추가: self.owned_destination = None;
1098추가: // 한도 실패는 늘려서 다시 시도할 수 있으므로 열기 상태를 남김.
1099추가: if completed || !self.open_retry_pending() {
1100추가: self.finish_open(completed);
1101추가: }
1102추가: }
9211103 if let Some(path) = self.owned_destination.take() {
9221104 if !self.model.confirmed
9231105 || self
@@ -930,6 +1112,10 @@ impl ArchiveApp {
9301112 }
9311113 }
9321114 }
1115추가: if self.opening.is_some() && !self.model.busy() && !self.open_retry_pending() {
1116추가: // 결과를 닫았거나 다시 시도할 수 없게 되었으면 원래 풀 위치로 되돌림.
1117추가: self.finish_open(false);
1118추가: }
9331119 }
9341120
9351121 pub fn show(&mut self, root: &mut egui::Ui) {
@@ -1365,6 +1551,8 @@ impl ArchiveApp {
13651551 }
13661552 let mut focused = None;
13671553 let mut open = None;
1554추가: let mut open_file = None;
1555추가: let mut menu_action = None;
13681556 let mut next_offset = None;
13691557 let output = egui::ScrollArea::vertical()
13701558 .id_salt("archive-rows")
@@ -1386,7 +1574,12 @@ impl ArchiveApp {
13861574 && relative.x <= width
13871575 && relative.y >= 0.0
13881576 && relative.y < rows.len() as f32 * LIST_ROW;
1389삭제: if clip.contains(press) && !in_row && ui.input(|i| i.pointer.primary_pressed())
1577추가: // 목록 위에 떠 있는 창(부모 안 작업 창 등)을 누른 경우는 목록 조작이 아님.
1578추가: let on_list = ui.ctx().layer_id_at(press) == Some(ui.layer_id());
1579추가: if clip.contains(press)
1580추가: && on_list
1581추가: && !in_row
1582추가: && ui.input(|i| i.pointer.primary_pressed())
13901583 {
13911584 background.request_focus();
13921585 let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command);
@@ -1499,8 +1692,26 @@ impl ArchiveApp {
14991692 modifiers.shift,
15001693 );
15011694 }
1502삭제: if row.directory && response.double_clicked() {
1503삭제: open = Some(row.path.clone());
1695추가: if response.double_clicked() {
1696추가: if row.directory {
1697추가: open = Some(row.path.clone());
1698추가: } else if let [id] = row.ids.iter().copied().collect::<Vec<_>>()[..] {
1699추가: open_file = Some(id);
1700추가: }
1701추가: }
1702추가: if active && response.secondary_clicked() && !selected {
1703추가: // 선택하지 않은 행을 오른쪽 클릭하면 그 행만 선택한 뒤 메뉴를 엶.
1704추가: self.select_row(&rows, index, false, false);
1705추가: }
1706추가: if active {
1707추가: response.context_menu(|ui| {
1708추가: if ui.button("압축 파일명으로 새 폴더를 만들어 압축 풀기").clicked() {
1709추가: menu_action = Some(MenuAction::NewFolder);
1710추가: }
1711추가: if ui.button("특정 폴더에 압축 풀기").clicked() {
1712추가: menu_action = Some(MenuAction::ChooseFolder);
1713추가: }
1714추가: });
15041715 }
15051716 // 암호가 걸린 항목은 이름 앞에 *를 붙이고, 툴팁은 실제 이름을 보여 줌.
15061717 let name = if row.encrypted {
@@ -1638,6 +1849,8 @@ impl ArchiveApp {
16381849 .min(rows.len() - 1);
16391850 if rows[index].directory {
16401851 open = Some(rows[index].path.clone());
1852추가: } else if let [id] = rows[index].ids.iter().copied().collect::<Vec<_>>()[..] {
1853추가: open_file = Some(id);
16411854 }
16421855 }
16431856 }
@@ -1650,10 +1863,37 @@ impl ArchiveApp {
16501863 );
16511864 }
16521865 }
1866추가: // 마우스 옆 버튼(뒤로)을 목록 위에서 누르면 상위 폴더로 이동함.
1867추가: if active
1868추가: && !self.folder.is_empty()
1869추가: && ui.input(|i| {
1870추가: i.pointer.button_pressed(egui::PointerButton::Extra1)
1871추가: && i.pointer
1872추가: .interact_pos()
1873추가: .is_some_and(|pos| path_row.union(background.rect).contains(pos))
1874추가: })
1875추가: {
1876추가: open = Some(
1877추가: self.folder
1878추가: .rsplit_once('/')
1879추가: .map_or("", |(parent, _)| parent)
1880추가: .to_owned(),
1881추가: );
1882추가: }
16531883 if let Some(folder) = open {
16541884 self.browse_folder(&folder);
16551885 background.request_focus();
16561886 }
1887추가: if let Some(id) = open_file {
1888추가: self.open_entry(id);
1889추가: }
1890추가: match menu_action {
1891추가: Some(MenuAction::NewFolder) => {
1892추가: self.extract_to_new_folder();
1893추가: }
1894추가: Some(MenuAction::ChooseFolder) => self.open_picker(Purpose::Destination),
1895추가: None => {}
1896추가: }
16571897 }
16581898
16591899 fn clear_list_selection(&mut self) {
@@ -1966,9 +2206,13 @@ impl ArchiveApp {
19662206 };
19672207 if self.work_in_parent {
19682208 // Wayland는 창 올리기를 지원하지 않으므로 부모 안에서 같은 내용을 그림.
1969삭제: let mut open = true;
1970삭제: let mut window = egui::Window::new(RichText::new(title).size(theme::FONT_SMALL))
2209추가: // egui 기본 제목 줄의 닫기 버튼은 마우스를 올려도 모양이 바뀌지 않으므로
2210추가: // 제목 줄을 직접 그리고 별도 창과 같은 닫기 버튼을 씀.
2211추가: let mut close = false;
2212추가: let busy = self.model.busy();
2213추가: egui::Window::new(RichText::new(&title).size(theme::FONT_SMALL))
19712214 .id(egui::Id::new("archive-work-in-parent"))
2215추가: .title_bar(false)
19722216 .default_pos(
19732217 ctx.content_rect().center() - egui::vec2(WORK_WIDTH, self.work.height) / 2.0,
19742218 )
@@ -1980,21 +2224,26 @@ impl ArchiveApp {
19802224 .resizable(false)
19812225 .fade_in(false)
19822226 .fade_out(false)
1983삭제: .title_frame(
1984삭제: theme::panel(theme::STRIPE)
1985삭제: .inner_margin(egui::Margin::symmetric(16, 8))
1986삭제: .corner_radius(0),
1987삭제: )
19882227 .frame(
1989삭제: theme::panel(theme::PANEL)
2228추가: egui::Frame::new()
2229추가: .fill(theme::PANEL)
19902230 .stroke(egui::Stroke::new(1.0, theme::BORDER))
2231추가: .inner_margin(egui::Margin::ZERO)
19912232 .corner_radius(0),
1992삭제: );
1993삭제: if !self.model.busy() {
1994삭제: window = window.open(&mut open);
1995삭제: }
1996삭제: window.show(ctx, |ui| self.work_area(ui));
1997삭제: if !open {
2233추가: )
2234추가: .show(ctx, |ui| {
2235추가: let spacing = ui.spacing().item_spacing.y;
2236추가: ui.spacing_mut().item_spacing.y = 0.0;
2237추가: close = window_frame::in_parent_title(ui, "work-in-parent", &title, !busy);
2238추가: egui::Frame::new()
2239추가: .inner_margin(egui::Margin::same(theme::PAD))
2240추가: .show(ui, |ui| {
2241추가: ui.spacing_mut().item_spacing.y = spacing;
2242추가: ui.set_width(WORK_WIDTH - 2.0 * theme::PAD as f32);
2243추가: self.work_area(ui)
2244추가: });
2245추가: });
2246추가: if close {
19982247 self.dismissed = true;
19992248 self.ui_error = None;
20002249 self.model.input_error = None;
@@ -3435,5 +3684,8 @@ impl eframe::App for ArchiveApp {
34353684impl Drop for ArchiveApp {
34363685 fn drop(&mut self) {
34373686 self.clear_password();
3687추가: for (_, root) in self.open_roots.drain(..) {
3688추가: present::remove_open_root(root);
3689추가: }
34383690 }
34393691}
수정experiments/rust-ui-memory-app/src/window_frame.rs+30-0
@@ -11,6 +11,7 @@ pub const TITLE_HEIGHT: f32 = 38.0;
1111const BUTTON_SIZE: Vec2 = egui::vec2(34.0, 26.0);
1212const RESIZE_EDGE: f32 = 6.0;
1313const DRAG_THRESHOLD: f32 = 4.0;
14추가: const IN_PARENT_TITLE: f32 = 36.0;
1415const TITLE_BG: Color32 = Color32::from_rgb(235, 238, 242);
1516
1617/// 창 테두리를 직접 그려야 하는지 판단함.
@@ -113,6 +114,35 @@ pub fn title_bar(root: &mut egui::Ui, id: &str, title: &str, buttons: Buttons) -
113114 moved
114115}
115116
117추가: /// 부모 창 안에 그리는 자식 창의 제목 줄. 닫기 버튼을 누르면 true를 돌려줌.
118추가: /// 별도 창의 제목 표시줄과 같은 닫기 버튼(마우스를 올리면 빨간 배경)을 씀.
119추가: pub fn in_parent_title(ui: &mut egui::Ui, id: &str, title: &str, closable: bool) -> bool {
120추가: let width = ui.available_width();
121추가: let (rect, _) = ui.allocate_exact_size(egui::vec2(width, IN_PARENT_TITLE), Sense::hover());
122추가: let painter = ui.painter();
123추가: painter.rect_filled(rect, 0.0, theme::STRIPE);
124추가: painter.hline(
125추가: rect.x_range(),
126추가: rect.bottom() - 0.5,
127추가: Stroke::new(1.0, theme::BORDER),
128추가: );
129추가: let button = Rect::from_center_size(
130추가: egui::pos2(rect.right() - 6.0 - BUTTON_SIZE.x / 2.0, rect.center().y),
131추가: BUTTON_SIZE,
132추가: );
133추가: let reserved = if closable { BUTTON_SIZE.x + 12.0 } else { 0.0 };
134추가: let font = FontId::proportional(theme::FONT_SMALL);
135추가: let text = fit(ui, title, &font, (rect.width() - 32.0 - reserved).max(0.0));
136추가: ui.painter().text(
137추가: egui::pos2(rect.left() + 16.0, rect.center().y),
138추가: Align2::LEFT_CENTER,
139추가: text,
140추가: font,
141추가: theme::TEXT,
142추가: );
143추가: closable && window_button(ui, id, button, Glyph::Close).clicked()
144추가: }
145추가:
116146/// 제목 표시줄을 누른 채 움직였는지를 원시 입력으로 판단함.
117147/// 창 이동 중에는 운영체제가 마우스를 가져가서 버튼 놓기가 앱에 오지 않으므로,
118148/// egui의 끌기 상태에 기대면 다음 끌기가 시작되지 않음.
수정packaging/licenses.py+4-0
@@ -13,6 +13,10 @@ ROOT = Path(__file__).resolve().parents[1]
1313
1414# 미리보기 디코더는 MIT 조건을 선택하며 원문 고지를 함께 수집함.
1515LICENSE_CHOICES = {
16추가: # userdb 응답은 직접 파서를 만들지 않고 검증된 JSON 해석기를 사용함.
17추가: ("serde", "1.0.229"): "MIT",
18추가: ("serde_core", "1.0.229"): "MIT",
19추가: ("serde_json", "1.0.154"): "MIT",
1620 ("png", "0.18.1"): "MIT",
1721 ("zune-jpeg", "0.5.15"): "MIT",
1822 ("zipelo-jpeg", "0.5.15"): "MIT",
추가tests/release-packages/test_userdb_licenses.py+32-0
@@ -0,0 +1,32 @@
1추가: """userdb JSON 해석기의 배포 고지 원문을 검증함."""
2추가:
3추가: import importlib.util
4추가: from pathlib import Path
5추가: import unittest
6추가:
7추가: ROOT = Path(__file__).resolve().parents[2]
8추가: SPEC = importlib.util.spec_from_file_location("userdb_licenses", ROOT / "packaging/licenses.py")
9추가: LICENSES = importlib.util.module_from_spec(SPEC)
10추가: SPEC.loader.exec_module(LICENSES)
11추가:
12추가:
13추가: class UserdbLicenses(unittest.TestCase):
14추가: def test_json_dependencies_preserve_selected_mit_notices(self):
15추가: records = LICENSES.inventory([ROOT / "experiments/rust-archive-worker/Cargo.toml"])
16추가: selected = {record["name"]: record for record in records}
17추가: for name, version in [("serde", "1.0.229"), ("serde_core", "1.0.229"), ("serde_json", "1.0.154")]:
18추가: with self.subTest(name=name):
19추가: record = selected[name]
20추가: self.assertEqual(record["version"], version)
21추가: self.assertEqual(record["selected_license"], "MIT")
22추가: self.assertIn("MIT", record["license"].split(" OR "))
23추가: self.assertTrue(record["files"])
24추가: notice = LICENSES.render([record])
25추가: for original in record["files"]:
26추가: self.assertIn(original["text"], notice)
27추가: self.assertIn(original["sha256"], notice)
28추가: self.assertTrue({"itoa", "memchr", "zmij"}.issubset(selected))
29추가:
30추가:
31추가: if __name__ == "__main__":
32추가: unittest.main()
수정tests/rust-app-real-worker/Cargo.lock+97-0
@@ -200,6 +200,12 @@ dependencies = [
200200 "generic-array",
201201]
202202
203추가: [[package]]
204추가: name = "itoa"
205추가: version = "1.0.19"
206추가: source = "registry+https://github.com/rust-lang/crates.io-index"
207추가: checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
208추가:
203209[[package]]
204210name = "libbz2-rs-sys"
205211version = "0.2.6"
@@ -221,6 +227,12 @@ dependencies = [
221227 "sha2 0.11.1",
222228]
223229
230추가: [[package]]
231추가: name = "memchr"
232추가: version = "2.8.3"
233추가: source = "registry+https://github.com/rust-lang/crates.io-index"
234추가: checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
235추가:
224236[[package]]
225237name = "miniz_oxide"
226238version = "0.8.9"
@@ -264,6 +276,66 @@ dependencies = [
264276 "miniz_oxide 0.8.9",
265277]
266278
279추가: [[package]]
280추가: name = "proc-macro2"
281추가: version = "1.0.107"
282추가: source = "registry+https://github.com/rust-lang/crates.io-index"
283추가: checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
284추가: dependencies = [
285추가: "unicode-ident",
286추가: ]
287추가:
288추가: [[package]]
289추가: name = "quote"
290추가: version = "1.0.47"
291추가: source = "registry+https://github.com/rust-lang/crates.io-index"
292추가: checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
293추가: dependencies = [
294추가: "proc-macro2",
295추가: ]
296추가:
297추가: [[package]]
298추가: name = "serde"
299추가: version = "1.0.229"
300추가: source = "registry+https://github.com/rust-lang/crates.io-index"
301추가: checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
302추가: dependencies = [
303추가: "serde_core",
304추가: ]
305추가:
306추가: [[package]]
307추가: name = "serde_core"
308추가: version = "1.0.229"
309추가: source = "registry+https://github.com/rust-lang/crates.io-index"
310추가: checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
311추가: dependencies = [
312추가: "serde_derive",
313추가: ]
314추가:
315추가: [[package]]
316추가: name = "serde_derive"
317추가: version = "1.0.229"
318추가: source = "registry+https://github.com/rust-lang/crates.io-index"
319추가: checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
320추가: dependencies = [
321추가: "proc-macro2",
322추가: "quote",
323추가: "syn",
324추가: ]
325추가:
326추가: [[package]]
327추가: name = "serde_json"
328추가: version = "1.0.154"
329추가: source = "registry+https://github.com/rust-lang/crates.io-index"
330추가: checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
331추가: dependencies = [
332추가: "itoa",
333추가: "memchr",
334추가: "serde",
335추가: "serde_core",
336추가: "zmij",
337추가: ]
338추가:
267339[[package]]
268340name = "sha1"
269341version = "0.10.7"
@@ -309,12 +381,29 @@ version = "2.6.1"
309381source = "registry+https://github.com/rust-lang/crates.io-index"
310382checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
311383
384추가: [[package]]
385추가: name = "syn"
386추가: version = "3.0.10"
387추가: source = "registry+https://github.com/rust-lang/crates.io-index"
388추가: checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
389추가: dependencies = [
390추가: "proc-macro2",
391추가: "quote",
392추가: "unicode-ident",
393추가: ]
394추가:
312395[[package]]
313396name = "typenum"
314397version = "1.20.1"
315398source = "registry+https://github.com/rust-lang/crates.io-index"
316399checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
317400
401추가: [[package]]
402추가: name = "unicode-ident"
403추가: version = "1.0.27"
404추가: source = "registry+https://github.com/rust-lang/crates.io-index"
405추가: checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
406추가:
318407[[package]]
319408name = "version_check"
320409version = "0.9.5"
@@ -337,6 +426,8 @@ dependencies = [
337426 "lzma-rust2",
338427 "pbkdf2",
339428 "png",
429추가: "serde",
430추가: "serde_json",
340431 "sha1",
341432 "sha2 0.10.9",
342433 "subtle",
@@ -366,6 +457,12 @@ version = "0.6.8"
366457source = "registry+https://github.com/rust-lang/crates.io-index"
367458checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
368459
460추가: [[package]]
461추가: name = "zmij"
462추가: version = "1.0.23"
463추가: source = "registry+https://github.com/rust-lang/crates.io-index"
464추가: checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
465추가:
369466[[package]]
370467name = "zune-core"
371468version = "0.5.3"
수정tests/rust-app-real-worker/selection_flows.rs+53-0
@@ -287,3 +287,56 @@ fn explorer_folder_click_and_escape_control_actual_extraction_scope() {
287287 ));
288288 assert_reaped(&observed);
289289}
290추가:
291추가: // 작업자는 새로 만든 상위 폴더도 출력으로 알림. 하위 폴더 안 파일도 그 파일 자체를 열어야 함.
292추가: #[test]
293추가: fn double_click_open_extracts_nested_file_and_opens_that_file() {
294추가: let scratch = Scratch::new();
295추가: let folder = make_directory(&scratch.path("site"));
296추가: fs::write(folder.join("index.html"), b"<p>zipelo</p>").unwrap();
297추가: fs::write(folder.join("style.css"), b"p{}").unwrap();
298추가: let archive = scratch.path("site.zip");
299추가: let (factory, observed) = observed_factory();
300추가: let mut screen = Screen::new(factory);
301추가: let opened = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
302추가: let record = opened.clone();
303추가: screen.app.set_opener(Box::new(move |path| {
304추가: record.borrow_mut().push(path.to_path_buf());
305추가: Ok(())
306추가: }));
307추가: screen.app.add_sources(vec![folder]);
308추가: screen.render(vec![]);
309추가: screen.set_text("zip-name", "site.zip");
310추가: screen.click("압축하기");
311추가: screen.settle();
312추가: screen.open(&archive);
313추가: for name in ["site/index.html", "site/style.css"] {
314추가: let id = screen
315추가: .app
316추가: .model
317추가: .entries
318추가: .iter()
319추가: .find(|entry| entry.name == name)
320추가: .unwrap()
321추가: .id;
322추가: assert!(screen.app.open_entry(id));
323추가: screen.settle();
324추가: screen.render(vec![]);
325추가: }
326추가: let root = scratch.path("site.zip (Zipelo 임시)");
327추가: assert_eq!(
328추가: *opened.borrow(),
329추가: vec![
330추가: root.join("1/site/index.html"),
331추가: root.join("2/site/style.css")
332추가: ]
333추가: );
334추가: assert_eq!(
335추가: fs::read(root.join("1/site/index.html")).unwrap(),
336추가: b"<p>zipelo</p>"
337추가: );
338추가: assert!(!root.join("1/site/style.css").exists());
339추가: assert_reaped(&observed);
340추가: drop(screen);
341추가: assert!(!root.exists());
342추가: }
수정tests/rust-app-ui/explorer_selection.rs+419-6
@@ -3,6 +3,7 @@ struct Explorer {
33 ctx: egui::Context,
44 factory: FakeFactory,
55 time: f64,
6추가: opened: std::rc::Rc<std::cell::RefCell<Vec<PathBuf>>>,
67}
78impl Explorer {
89 fn new(scratch: &Folder) -> Self {
@@ -25,11 +26,18 @@ impl Explorer {
2526 encrypted: false,
2627 })
2728 .into();
29추가: let opened = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
30추가: let record = opened.clone();
31추가: app.set_opener(Box::new(move |path| {
32추가: record.borrow_mut().push(path.to_path_buf());
33추가: Ok(())
34추가: }));
2835 let mut screen = Self {
2936 app,
3037 ctx: egui::Context::default(),
3138 factory,
3239 time: 0.0,
40추가: opened,
3341 };
3442 screen.frame(egui::Modifiers::NONE, vec![]);
3543 screen.frame(egui::Modifiers::NONE, vec![]);
@@ -115,6 +123,44 @@ impl Explorer {
115123 }],
116124 );
117125 }
126추가: fn button(&mut self, point: egui::Pos2, button: egui::PointerButton) {
127추가: self.time += 1.0;
128추가: for pressed in [true, false] {
129추가: self.frame(
130추가: egui::Modifiers::NONE,
131추가: vec![
132추가: egui::Event::PointerMoved(point),
133추가: egui::Event::PointerButton {
134추가: pos: point,
135추가: button,
136추가: pressed,
137추가: modifiers: egui::Modifiers::NONE,
138추가: },
139추가: ],
140추가: );
141추가: }
142추가: self.frame(egui::Modifiers::NONE, vec![]);
143추가: }
144추가: fn double_click(&mut self, path: &str) {
145추가: self.time += 1.0;
146추가: let point = self.row(path).center();
147추가: for _ in 0..2 {
148추가: self.pointer(point, true, egui::Modifiers::NONE);
149추가: self.pointer(point, false, egui::Modifiers::NONE);
150추가: }
151추가: for _ in 0..30 {
152추가: self.frame(egui::Modifiers::NONE, vec![]);
153추가: }
154추가: }
155추가: fn click_text(&mut self, label: &str) {
156추가: let output = self.frame(egui::Modifiers::NONE, vec![]);
157추가: let rect = layout_text(&output)
158추가: .into_iter()
159추가: .find(|(text, _, _)| text == label)
160추가: .unwrap_or_else(|| panic!("{label} 없음"))
161추가: .1;
162추가: self.button(rect.center(), egui::PointerButton::Primary);
163추가: }
118164 #[track_caller]
119165 fn selected(&self, ids: &[u32]) {
120166 assert_eq!(self.app.model.selected, ids.iter().copied().collect());
@@ -222,16 +268,383 @@ fn explorer_keyboard_ranges_enter_backspace_and_escape_are_scoped_to_the_list()
222268}
223269
224270#[test]
225삭제: fn explorer_double_click_opens_only_folders_and_resets_selection() {
271추가: fn explorer_double_click_opens_files_with_default_app_and_folders_in_place() {
226272 let scratch = Folder::new();
227273 let mut s = Explorer::new(&scratch);
228삭제: let point = s.row("alpha.txt").center();
229삭제: for _ in 0..2 {
230삭제: s.pointer(point, true, egui::Modifiers::NONE);
231삭제: s.pointer(point, false, egui::Modifiers::NONE);
274추가: let destination = s.app.model.archive.clone().unwrap().with_file_name("sample");
275추가: // 실제 작업자처럼 새로 만든 상위 폴더도 출력으로 알림.
276추가: s.factory.state.borrow_mut().outputs = Some(vec!["docs".into(), "docs/child.txt".into()]);
277추가: s.app.browse_folder("docs");
278추가: s.double_click("docs/child.txt");
279추가: s.selected(&[0]);
280추가: // 파일은 압축파일 옆 숨김 임시 폴더에 그 파일만 풀고 기본 프로그램으로 엶.
281추가: let root = scratch.0.join("sample.zip (Zipelo 임시)");
282추가: {
283추가: let state = s.factory.state.borrow();
284추가: assert_eq!(state.starts.len(), 2);
285추가: let Start::Extract {
286추가: destination: folder,
287추가: selection,
288추가: ..
289추가: } = state.starts.last().unwrap()
290추가: else {
291추가: panic!("{:?}", state.starts.last());
292추가: };
293추가: assert_eq!(selection, &Selection::EntryIds(vec![0]));
294추가: assert_eq!(folder, &root.join("1"));
232295 }
233삭제: s.selected(&[1]);
296추가: assert_eq!(
297추가: *s.opened.borrow(),
298추가: vec![root.join("1").join("docs").join("child.txt")]
299추가: );
300추가: let output = s.frame(egui::Modifiers::NONE, vec![]);
301추가: assert!(
302추가: !layout_text(&output)
303추가: .iter()
304추가: .any(|(text, _, _)| text == "작업 결과")
305추가: );
306추가: // 같은 파일을 다시 열면 새 하위 폴더를 씀.
307추가: s.double_click("docs/child.txt");
308추가: assert!(matches!(
309추가: s.factory.state.borrow().starts.last(),
310추가: Some(Start::Extract { destination, .. }) if destination == &root.join("2")
311추가: ));
312추가: assert_eq!(s.opened.borrow().len(), 2);
313추가: // 열 파일이 출력에 없으면 조용히 넘어가지 않고 알림.
314추가: s.factory.state.borrow_mut().outputs = Some(vec!["docs".into()]);
315추가: s.double_click("docs/child.txt");
316추가: assert_eq!(s.opened.borrow().len(), 2);
317추가: assert!(
318추가: layout_text(&s.frame(egui::Modifiers::NONE, vec![]))
319추가: .iter()
320추가: .any(|(text, _, _)| text == "풀린 파일을 찾지 못해 열지 못했습니다")
321추가: );
322추가: // 열기용 폴더는 압축파일 이름 폴더와 섞이지 않음.
323추가: assert!(!destination.exists());
324추가: // 앱을 닫으면 열기용 폴더를 지움.
325추가: assert!(root.is_dir());
326추가: drop(s);
327추가: assert!(!root.exists());
328추가: }
329추가:
330추가: /// 열기용 풀기가 한도 초과로 실패한 상태까지 진행함. 결과 창을 그리는 문맥도 함께 돌려줌.
331추가: fn double_click_open_hits_limit(s: &mut Explorer) -> egui::Context {
332추가: s.factory.state.borrow_mut().manual = true;
333추가: s.double_click("alpha.txt");
334추가: assert_eq!(s.factory.state.borrow().starts.len(), 2);
335추가: finish_limit(s);
336추가: let ctx = egui::Context::default();
337추가: ctx.set_embed_viewports(false);
338추가: for _ in 0..12 {
339추가: policy_render(&ctx, &mut s.app, vec![]);
340추가: }
341추가: assert!(s.app.model.can_retry_expanded());
342추가: assert!(s.opened.borrow().is_empty());
343추가: ctx
344추가: }
345추가:
346추가: fn finish_limit(s: &mut Explorer) {
347추가: {
348추가: let mut worker = s.factory.state.borrow_mut();
349추가: worker.frame(Event::Accepted { encryption: false });
350추가: worker.frame(Event::Terminal(Terminal {
351추가: outcome: Outcome::Failed,
352추가: error: Some(ErrorCode::Limit),
353추가: publication: Publication::None,
354추가: created_count: 0,
355추가: retained_partial_count: 0,
356추가: durability: Durability::NotApplicable,
357추가: cleanup: Cleanup::Complete,
358추가: }));
359추가: worker.queue.extend([
360추가: HostEvent::StdoutEof,
361추가: HostEvent::StderrEof,
362추가: HostEvent::Exited { success: true },
363추가: ]);
364추가: }
365추가: for _ in 0..30 {
366추가: s.frame(egui::Modifiers::NONE, vec![]);
367추가: }
368추가: }
369추가:
370추가: #[test]
371추가: fn explorer_open_keeps_pending_open_when_limit_retry_succeeds() {
372추가: let scratch = Folder::new();
373추가: let mut s = Explorer::new(&scratch);
374추가: let root = scratch.0.join("sample.zip (Zipelo 임시)");
375추가: let ctx = double_click_open_hits_limit(&mut s);
376추가: policy_click(&ctx, &mut s.app, "한도를 늘려 다시 시도");
377추가: assert!(s.app.model.busy());
378추가: assert!(s.factory.state.borrow().expanded);
379추가: assert!(matches!(
380추가: s.factory.state.borrow().starts.last(),
381추가: Some(Start::Extract { destination, .. }) if destination == &root.join("1")
382추가: ));
383추가: {
384추가: let mut worker = s.factory.state.borrow_mut();
385추가: worker.frame(Event::Accepted { encryption: false });
386추가: worker.frame(Event::Output {
387추가: entry_id: None,
388추가: relative_name: "alpha.txt".into(),
389추가: disposition: Disposition::Created,
390추가: });
391추가: worker.finish(Outcome::Completed, Publication::Complete);
392추가: }
393추가: for _ in 0..30 {
394추가: s.frame(egui::Modifiers::NONE, vec![]);
395추가: }
396추가: // 다시 시도가 성공하면 기본 프로그램이 열림.
397추가: assert_eq!(*s.opened.borrow(), vec![root.join("1").join("alpha.txt")]);
398추가: // 열기가 끝나면 풀 위치는 원래대로 돌아옴.
399추가: s.factory.state.borrow_mut().manual = false;
400추가: assert!(s.app.begin_extract());
401추가: assert!(matches!(
402추가: s.factory.state.borrow().starts.last(),
403추가: Some(Start::Extract { destination, .. }) if !destination.starts_with(&root)
404추가: ));
405추가: }
406추가:
407추가: #[test]
408추가: fn explorer_open_restores_destination_when_limit_result_is_dismissed() {
409추가: let scratch = Folder::new();
410추가: let mut s = Explorer::new(&scratch);
411추가: let root = scratch.0.join("sample.zip (Zipelo 임시)");
412추가: let ctx = double_click_open_hits_limit(&mut s);
413추가: policy_click(&ctx, &mut s.app, "확인");
414추가: for _ in 0..3 {
415추가: policy_render(&ctx, &mut s.app, vec![]);
416추가: }
417추가: assert!(s.opened.borrow().is_empty());
418추가: s.factory.state.borrow_mut().manual = false;
419추가: assert!(s.app.begin_extract());
420추가: let state = s.factory.state.borrow();
421추가: let Some(Start::Extract { destination, .. }) = state.starts.last() else {
422추가: panic!("{:?}", state.starts.last());
423추가: };
424추가: assert_eq!(destination, &scratch.0.join("sample"));
425추가: assert!(!destination.starts_with(&root));
426추가: }
427추가:
428추가: #[test]
429추가: fn explorer_open_restores_destination_when_expanded_retry_fails_again() {
430추가: let scratch = Folder::new();
431추가: let mut s = Explorer::new(&scratch);
432추가: let ctx = double_click_open_hits_limit(&mut s);
433추가: policy_click(&ctx, &mut s.app, "한도를 늘려 다시 시도");
434추가: assert!(s.app.model.busy());
435추가: finish_limit(&mut s);
436추가: assert!(s.opened.borrow().is_empty());
437추가: assert!(!s.app.model.can_retry_expanded());
438추가: s.factory.state.borrow_mut().manual = false;
439추가: assert!(s.app.begin_extract());
440추가: assert!(matches!(
441추가: s.factory.state.borrow().starts.last(),
442추가: Some(Start::Extract { destination, .. }) if destination == &scratch.0.join("sample")
443추가: ));
444추가: }
445추가:
446추가: #[test]
447추가: fn explorer_open_pending_after_limit_is_dropped_when_zip_creation_starts() {
448추가: let scratch = Folder::new();
449추가: let mut s = Explorer::new(&scratch);
450추가: let root = scratch.0.join("sample.zip (Zipelo 임시)");
451추가: let _limit_ctx = double_click_open_hits_limit(&mut s);
452추가: // 한도 초과 결과를 닫지 않고 폴더를 끌어 놓아 ZIP 만들기를 시작함.
453추가: let folder = scratch.0.join("photos");
454추가: std::fs::create_dir_all(&folder).unwrap();
455추가: std::fs::write(folder.join("a.txt"), b"abc").unwrap();
456추가: s.app.add_sources(vec![folder]);
457추가: let ctx = egui::Context::default();
458추가: policy_click(&ctx, &mut s.app, "압축하기");
459추가: assert!(s.app.model.busy());
460추가: assert!(matches!(
461추가: s.factory.state.borrow().starts.last(),
462추가: Some(Start::CreateZip { .. })
463추가: ));
464추가: {
465추가: let mut worker = s.factory.state.borrow_mut();
466추가: worker.frame(Event::Accepted { encryption: false });
467추가: worker.frame(Event::Output {
468추가: entry_id: None,
469추가: relative_name: "photos.zip".into(),
470추가: disposition: Disposition::Created,
471추가: });
472추가: worker.finish(Outcome::Completed, Publication::Complete);
473추가: }
474추가: for _ in 0..30 {
475추가: s.frame(egui::Modifiers::NONE, vec![]);
476추가: }
477추가: // 만들기가 끝나도 이전 열기가 적용되지 않아 오류가 뜨지 않음.
478추가: for _ in 0..3 {
479추가: policy_render(&ctx, &mut s.app, vec![]);
480추가: }
481추가: let shown = policy_render(&ctx, &mut s.app, vec![]);
482추가: assert!(
483추가: !shown.iter().any(|(text, _)| text.contains("열지 못했습니다")),
484추가: "{shown:?}"
485추가: );
486추가: assert!(s.opened.borrow().is_empty());
487추가: // 풀 위치도 원래대로 돌아옴.
488추가: s.factory.state.borrow_mut().manual = false;
489추가: assert!(s.app.begin_extract());
490추가: let state = s.factory.state.borrow();
491추가: let Some(Start::Extract { destination, .. }) = state.starts.last() else {
492추가: panic!("{:?}", state.starts.last());
493추가: };
494추가: assert_eq!(destination, &scratch.0.join("sample"));
495추가: assert!(!destination.starts_with(&root));
496추가: }
497추가:
498추가: #[test]
499추가: fn explorer_double_click_does_not_open_executables() {
500추가: let scratch = Folder::new();
501추가: let mut s = Explorer::new(&scratch);
502추가: s.app.model.entries[2].name = "setup.EXE".into();
503추가: s.double_click("setup.EXE");
234504 assert_eq!(s.factory.state.borrow().starts.len(), 1);
505추가: assert!(s.opened.borrow().is_empty());
506추가: let output = s.frame(egui::Modifiers::NONE, vec![]);
507추가: assert!(
508추가: layout_text(&output)
509추가: .iter()
510추가: .any(|(text, _, _)| text == "실행 파일(.EXE)은 안전을 위해 바로 열 수 없습니다")
511추가: );
512추가: // 실행 파일은 압축을 풀지 않으므로 임시 폴더도 만들지 않음.
513추가: assert!(!scratch.0.join("sample.zip (Zipelo 임시)").exists());
514추가: }
515추가:
516추가: #[test]
517추가: fn explorer_dragging_in_parent_work_window_does_not_select_rows() {
518추가: let scratch = Folder::new();
519추가: let mut s = Explorer::new(&scratch);
520추가: s.app.set_work_window_in_parent(true);
521추가: s.app.model.entries[2].name = "setup.EXE".into();
522추가: s.double_click("setup.EXE");
523추가: s.selected(&[2]);
524추가: let close = s
525추가: .ctx
526추가: .read_response(egui::Id::unique(("window-button", "work-in-parent", "닫기")))
527추가: .expect("부모 안 작업 창")
528추가: .rect;
529추가: // 행이 하나뿐인 폴더로 옮겨 작업 창 제목 줄 아래가 목록의 빈 곳이 되게 함.
530추가: s.app.browse_folder("docs");
531추가: let row = s.row("docs/child.txt");
532추가: s.selected(&[]);
533추가: // 작업 창 제목 줄을 누르고 목록 행 위로 끌어도 목록 선택 사각형이 생기지 않아야 함.
534추가: let start = egui::pos2(close.left() - 120.0, close.center().y);
535추가: assert!(start.y > row.bottom(), "{start:?} {row:?}");
536추가: s.pointer(start, true, egui::Modifiers::NONE);
537추가: let end = egui::pos2(row.center().x, row.center().y);
538추가: for step in 1..=6 {
539추가: let t = step as f32 / 6.0;
540추가: s.frame(
541추가: egui::Modifiers::NONE,
542추가: vec![egui::Event::PointerMoved(start + (end - start) * t)],
543추가: );
544추가: }
545추가: let output = s.frame(egui::Modifiers::NONE, vec![]);
546추가: s.selected(&[]);
547추가: assert!(!output.shapes.iter().any(|shape| matches!(
548추가: &shape.shape,
549추가: egui::epaint::Shape::Rect(rect) if rect.fill == theme_blue_fill()
550추가: )));
551추가: s.pointer(end, false, egui::Modifiers::NONE);
552추가: s.selected(&[]);
553추가: }
554추가:
555추가: fn theme_blue_fill() -> egui::Color32 {
556추가: zipelo_ui_memory_app::archive_theme::BLUE.gamma_multiply(0.16)
557추가: }
558추가:
559추가: #[test]
560추가: fn explorer_context_menu_extracts_selection_into_numbered_archive_folder() {
561추가: let scratch = Folder::new();
562추가: let mut s = Explorer::new(&scratch);
563추가: fs::create_dir(scratch.0.join("sample")).unwrap();
564추가: s.click("alpha.txt", egui::Modifiers::NONE);
565추가: // 선택하지 않은 행을 오른쪽 클릭하면 그 행만 선택하고 메뉴를 엶.
566추가: let point = s.row("docs").center();
567추가: s.button(point, egui::PointerButton::Secondary);
568추가: s.selected(&[0, 5]);
569추가: s.click_text("압축 파일명으로 새 폴더를 만들어 압축 풀기");
570추가: for _ in 0..30 {
571추가: s.frame(egui::Modifiers::NONE, vec![]);
572추가: }
573추가: let state = s.factory.state.borrow();
574추가: let Some(Start::Extract {
575추가: destination,
576추가: selection,
577추가: ..
578추가: }) = state.starts.last()
579추가: else {
580추가: panic!("{:?}", state.starts.last());
581추가: };
582추가: assert_eq!(destination, &scratch.0.join("sample (1)"));
583추가: assert_eq!(selection, &Selection::EntryIds(vec![0, 5]));
584추가: assert!(scratch.0.join("sample (1)").is_dir());
585추가: assert!(s.opened.borrow().is_empty());
586추가: }
587추가:
588추가: #[test]
589추가: fn explorer_context_menu_asks_for_folder_and_extracts_only_selection() {
590추가: let scratch = Folder::new();
591추가: let mut s = Explorer::new(&scratch);
592추가: let dialogs = crate::dialogs::TestDialogs::default();
593추가: let target = scratch.0.join("target");
594추가: fs::create_dir(&target).unwrap();
595추가: dialogs
596추가: .0
597추가: .borrow_mut()
598추가: .answers
599추가: .push_back(Some(vec![target.clone()]));
600추가: s.app.set_dialogs(Box::new(dialogs.clone()));
601추가: s.click("alpha.txt", egui::Modifiers::NONE);
602추가: s.click("beta.txt", explorer_ctrl());
603추가: let point = s.row("beta.txt").center();
604추가: s.button(point, egui::PointerButton::Secondary);
605추가: s.selected(&[1, 2]);
606추가: s.click_text("특정 폴더에 압축 풀기");
607추가: for _ in 0..30 {
608추가: s.frame(egui::Modifiers::NONE, vec![]);
609추가: }
610추가: assert_eq!(
611추가: dialogs.0.borrow().requests.last().unwrap().purpose,
612추가: zipelo_ui_memory_app::archive_dialog::Purpose::Destination
613추가: );
614추가: assert!(matches!(
615추가: s.factory.state.borrow().starts.last(),
616추가: Some(Start::Extract { destination, selection: Selection::EntryIds(ids), .. })
617추가: if destination == &target && ids == &vec![1, 2]
618추가: ));
619추가: }
620추가:
621추가: #[test]
622추가: fn explorer_mouse_back_button_goes_to_parent_folder() {
623추가: let scratch = Folder::new();
624추가: let mut s = Explorer::new(&scratch);
625추가: s.app.browse_folder("docs");
626추가: let point = s.row("docs/child.txt").center();
627추가: s.button(point, egui::PointerButton::Extra2);
628추가: assert!(s.ctx.read_response(egui::Id::unique(("archive-row", "docs/child.txt"))).is_some());
629추가: s.button(point, egui::PointerButton::Extra1);
630추가: assert!(
631추가: layout_text(&s.frame(egui::Modifiers::NONE, vec![]))
632추가: .iter()
633추가: .any(|(text, _, _)| text == "alpha.txt")
634추가: );
635추가: // 최상위에서는 아무 일도 하지 않음.
636추가: s.button(point, egui::PointerButton::Extra1);
637추가: assert!(
638추가: layout_text(&s.frame(egui::Modifiers::NONE, vec![]))
639추가: .iter()
640추가: .any(|(text, _, _)| text == "alpha.txt")
641추가: );
642추가: }
643추가:
644추가: #[test]
645추가: fn explorer_double_click_opens_only_folders_and_resets_selection() {
646추가: let scratch = Folder::new();
647추가: let mut s = Explorer::new(&scratch);
235648 s.time += 1.0;
236649 let point = s.row("docs").center();
237650 for _ in 0..2 {
수정tests/rust-app-ui/fake.rs+13-5
@@ -18,6 +18,8 @@ pub struct State {
1818 pub list_format: Option<Format>,
1919 pub fail_start: bool,
2020 pub dropped_connections: usize,
21추가: /// 풀기 출력으로 알릴 이름. 없으면 "읽어주세요.txt" 하나를 알림.
22추가: pub outputs: Option<Vec<String>>,
2123 pause: bool,
2224}
2325#[derive(Default, Clone)]
@@ -132,11 +134,17 @@ impl State {
132134 total: Some(31),
133135 completed_entries: 1,
134136 });
135삭제: self.frame(Event::Output {
136삭제: entry_id: Some(0),
137삭제: relative_name: "읽어주세요.txt".into(),
138삭제: disposition: Disposition::Created,
139삭제: });
137추가: let names = self
138추가: .outputs
139추가: .clone()
140추가: .unwrap_or_else(|| vec!["읽어주세요.txt".into()]);
141추가: for name in names {
142추가: self.frame(Event::Output {
143추가: entry_id: None,
144추가: relative_name: name,
145추가: disposition: Disposition::Created,
146추가: });
147추가: }
140148 self.finish(Outcome::Completed, Publication::Complete);
141149 }
142150 }
수정tests/rust-app-ui/presentation.rs+213-0
@@ -333,6 +333,21 @@ fn default_names_and_middle_truncation_preserve_unicode() {
333333 assert_eq!(default_destination(&path(name)), path("압축 해제"));
334334 }
335335 assert_eq!(default_destination(&path("자료.zip")), path("자료"));
336추가: assert!(blocked_open("폴더/setup.EXE"));
337추가: // desktop 항목은 Linux 차단 목록에만 있음.
338추가: #[cfg(not(windows))]
339추가: assert!(blocked_open("run.desktop"));
340추가: assert!(!blocked_open("사진.jpg"));
341추가: assert!(!blocked_open("exe"));
342추가: // Linux는 스크립트를 편집기로 열므로 막지 않음.
343추가: #[cfg(not(windows))]
344추가: assert!(!blocked_open("app.js"));
345추가: #[cfg(windows)]
346추가: assert!(blocked_open("app.js"));
347추가: assert_eq!(
348추가: open_blocked_text("폴더/setup.EXE"),
349추가: "실행 파일(.EXE)은 안전을 위해 바로 열 수 없습니다"
350추가: );
336351 assert_eq!(middle_text("가나다라마바사아자차", 7), "가나다…아자차");
337352 assert_eq!(bytes_text(21), "21 B");
338353}
@@ -358,6 +373,17 @@ impl Drop for Folder {
358373 }
359374}
360375
376추가: #[test]
377추가: fn unique_folder_numbers_existing_names() {
378추가: let scratch = Folder::new();
379추가: let base = scratch.0.join("자료");
380추가: assert_eq!(unique_folder(&base), base);
381추가: fs::create_dir(&base).unwrap();
382추가: assert_eq!(unique_folder(&base), scratch.0.join("자료 (1)"));
383추가: fs::write(scratch.0.join("자료 (1)"), b"").unwrap();
384추가: assert_eq!(unique_folder(&base), scratch.0.join("자료 (2)"));
385추가: }
386추가:
361387#[test]
362388fn automatic_destination_creation_and_failure_are_distinct() {
363389 let scratch = Folder::new();
@@ -1132,3 +1158,190 @@ fn client_protocol_errors_hide_internal_terms_but_preserve_exit_uncertainty() {
11321158 UNCONFIRMED_FINISH
11331159 );
11341160}
1161추가:
1162추가: #[cfg(feature = "ui")]
1163추가: #[cfg(unix)]
1164추가: #[test]
1165추가: fn app_exit_preserves_replaced_open_root() {
1166추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1167추가: let scratch = Folder::new();
1168추가: let mut app = ArchiveApp::new(
1169추가: Box::new(FakeFactory::default()),
1170추가: Some(scratch.0.join("sample.zip")),
1171추가: false,
1172추가: );
1173추가: pump(&mut app.model);
1174추가: assert!(app.open_entry(0));
1175추가: let root = scratch.0.join(open_root_name("sample.zip"));
1176추가: fs::rename(&root, scratch.0.join("original")).unwrap();
1177추가: fs::create_dir(&root).unwrap();
1178추가: let retained = root.join("keep.txt");
1179추가: fs::write(&retained, b"user data").unwrap();
1180추가: drop(app);
1181추가: assert_eq!(fs::read(retained).unwrap(), b"user data");
1182추가: }
1183추가:
1184추가: #[cfg(feature = "ui")]
1185추가: #[test]
1186추가: fn app_exit_removes_original_open_root() {
1187추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1188추가: let scratch = Folder::new();
1189추가: let mut app = ArchiveApp::new(
1190추가: Box::new(FakeFactory::default()),
1191추가: Some(scratch.0.join("sample.zip")),
1192추가: false,
1193추가: );
1194추가: pump(&mut app.model);
1195추가: assert!(app.open_entry(0));
1196추가: let root = scratch.0.join(open_root_name("sample.zip"));
1197추가: fs::write(root.join("opened.txt"), b"temporary").unwrap();
1198추가: drop(app);
1199추가: assert!(!root.exists());
1200추가: }
1201추가:
1202추가: #[cfg(feature = "ui")]
1203추가: #[cfg(windows)]
1204추가: #[test]
1205추가: fn open_root_cannot_be_renamed_while_app_holds_it() {
1206추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1207추가: let scratch = Folder::new();
1208추가: let mut app = ArchiveApp::new(
1209추가: Box::new(FakeFactory::default()),
1210추가: Some(scratch.0.join("sample.zip")),
1211추가: false,
1212추가: );
1213추가: pump(&mut app.model);
1214추가: assert!(app.open_entry(0));
1215추가: let root = scratch.0.join(open_root_name("sample.zip"));
1216추가: // 열어 둔 핸들이 이름 변경을 막아 경로가 다른 폴더로 바뀌지 않음.
1217추가: assert!(fs::rename(&root, scratch.0.join("original")).is_err());
1218추가: drop(app);
1219추가: assert!(!root.exists());
1220추가: }
1221추가:
1222추가: #[cfg(unix)]
1223추가: fn open_root_with_contents(scratch: &Folder) -> (OpenRoot, PathBuf) {
1224추가: let root = create_open_root(&scratch.0.join("sample.zip")).unwrap();
1225추가: let path = root.path().to_path_buf();
1226추가: fs::create_dir_all(path.join("a/b")).unwrap();
1227추가: fs::write(path.join("a/b/deep.txt"), b"temporary").unwrap();
1228추가: fs::write(path.join("top.txt"), b"temporary").unwrap();
1229추가: (root, path)
1230추가: }
1231추가:
1232추가: #[cfg(unix)]
1233추가: #[test]
1234추가: fn removal_is_bound_to_checked_folder_when_replaced_after_check() {
1235추가: let scratch = Folder::new();
1236추가: let (root, path) = open_root_with_contents(&scratch);
1237추가: let original = scratch.0.join("original");
1238추가: remove_open_root_with(root, || {
1239추가: fs::rename(&path, &original).unwrap();
1240추가: fs::create_dir(&path).unwrap();
1241추가: fs::write(path.join("keep.txt"), b"user data").unwrap();
1242추가: });
1243추가: assert_eq!(fs::read(path.join("keep.txt")).unwrap(), b"user data");
1244추가: // 확인한 폴더의 내용만 지움.
1245추가: assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1246추가: }
1247추가:
1248추가: #[cfg(unix)]
1249추가: #[test]
1250추가: fn removal_does_not_follow_link_swapped_in_after_check() {
1251추가: let scratch = Folder::new();
1252추가: let (root, path) = open_root_with_contents(&scratch);
1253추가: let victim = scratch.0.join("victim");
1254추가: fs::create_dir(&victim).unwrap();
1255추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1256추가: let original = scratch.0.join("original");
1257추가: remove_open_root_with(root, || {
1258추가: fs::rename(&path, &original).unwrap();
1259추가: std::os::unix::fs::symlink(&victim, &path).unwrap();
1260추가: });
1261추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1262추가: assert!(fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
1263추가: assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1264추가: }
1265추가:
1266추가: #[cfg(unix)]
1267추가: #[test]
1268추가: fn removal_does_not_follow_links_inside_folder() {
1269추가: let scratch = Folder::new();
1270추가: let (root, path) = open_root_with_contents(&scratch);
1271추가: let victim = scratch.0.join("victim");
1272추가: fs::create_dir(&victim).unwrap();
1273추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1274추가: std::os::unix::fs::symlink(&victim, path.join("a/link")).unwrap();
1275추가: std::os::unix::fs::symlink(victim.join("keep.txt"), path.join("file-link")).unwrap();
1276추가: remove_open_root(root);
1277추가: assert!(!path.exists());
1278추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1279추가: }
1280추가:
1281추가: #[cfg(unix)]
1282추가: #[test]
1283추가: fn removal_of_original_folder_clears_nested_contents() {
1284추가: let scratch = Folder::new();
1285추가: let (root, path) = open_root_with_contents(&scratch);
1286추가: remove_open_root(root);
1287추가: assert!(!path.exists());
1288추가: }
1289추가:
1290추가: #[cfg(unix)]
1291추가: #[test]
1292추가: fn creation_does_not_adopt_folder_replaced_before_handle_is_taken() {
1293추가: let scratch = Folder::new();
1294추가: let archive = scratch.0.join("sample.zip");
1295추가: let swapped = scratch.0.join(open_root_name("sample.zip"));
1296추가: let original = scratch.0.join("original");
1297추가: let mut swaps = 0;
1298추가: let root = create_open_root_with(&archive, |path| {
1299추가: swaps += 1;
1300추가: if swaps == 1 {
1301추가: fs::rename(path, &original).unwrap();
1302추가: fs::create_dir(path).unwrap();
1303추가: fs::write(path.join("keep.txt"), b"user data").unwrap();
1304추가: }
1305추가: })
1306추가: .unwrap();
1307추가: // 바뀐 폴더는 원본으로 기록하지 않고 다른 이름의 새 폴더를 씀.
1308추가: assert_ne!(root.path(), swapped);
1309추가: assert!(root.is_current());
1310추가: remove_open_root(root);
1311추가: assert_eq!(fs::read(swapped.join("keep.txt")).unwrap(), b"user data");
1312추가: }
1313추가:
1314추가: #[cfg(unix)]
1315추가: #[test]
1316추가: fn creation_does_not_adopt_link_replaced_before_handle_is_taken() {
1317추가: let scratch = Folder::new();
1318추가: let archive = scratch.0.join("sample.zip");
1319추가: let link = scratch.0.join(open_root_name("sample.zip"));
1320추가: let victim = scratch.0.join("victim");
1321추가: fs::create_dir(&victim).unwrap();
1322추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1323추가: let mut swaps = 0;
1324추가: let root = create_open_root_with(&archive, |path| {
1325추가: swaps += 1;
1326추가: if swaps == 1 {
1327추가: fs::remove_dir(path).unwrap();
1328추가: std::os::unix::fs::symlink(&victim, path).unwrap();
1329추가: }
1330추가: })
1331추가: .unwrap();
1332추가: assert_ne!(root.path(), link);
1333추가: remove_open_root(root);
1334추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1335추가: assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
1336추가: }
1337추가:
1338추가: #[test]
1339추가: fn creation_of_unchanged_folder_is_empty_and_current() {
1340추가: let scratch = Folder::new();
1341추가: let root = create_open_root(&scratch.0.join("sample.zip")).unwrap();
1342추가: let path = root.path().to_path_buf();
1343추가: assert!(root.is_current());
1344추가: assert_eq!(fs::read_dir(&path).unwrap().count(), 0);
1345추가: remove_open_root(root);
1346추가: assert!(!path.exists());
1347추가: }
수정tests/rust-app-ui/work_window.rs+83-0
@@ -938,3 +938,86 @@ fn scenario_window_hosting_survives_platform_frame_configuration() {
938938 }
939939 }
940940}
941추가:
942추가: #[test]
943추가: fn hosted_work_window_close_button_shows_hover_and_dismisses_result() {
944추가: let factory = FakeFactory::manual();
945추가: let mut app = ArchiveApp::new(Box::new(factory.clone()), Some("/sample.zip".into()), false);
946추가: app.set_work_window_in_parent(true);
947추가: let ctx = egui::Context::default();
948추가: ctx.set_embed_viewports(false);
949추가: install_work_child_renderer();
950추가: {
951추가: let mut worker = factory.state.borrow_mut();
952추가: worker.finish(Outcome::Failed, Publication::None);
953추가: for event in &mut worker.queue {
954추가: if let HostEvent::Frame {
955추가: event: Event::Terminal(terminal),
956추가: ..
957추가: } = event
958추가: {
959추가: terminal.error = Some(ErrorCode::Io);
960추가: }
961추가: }
962추가: }
963추가: let render = |app: &mut ArchiveApp, events: Vec<egui::Event>| {
964추가: let mut output = ctx.run_ui(
965추가: egui::RawInput {
966추가: screen_rect: Some(egui::Rect::from_min_size(
967추가: egui::Pos2::ZERO,
968추가: egui::vec2(1060.0, 720.0),
969추가: )),
970추가: events,
971추가: ..Default::default()
972추가: },
973추가: |ui| app.show(ui),
974추가: );
975추가: output.textures_delta.clear();
976추가: output
977추가: };
978추가: for _ in 0..4 {
979추가: render(&mut app, vec![]);
980추가: }
981추가: let close_id = egui::Id::unique(("window-button", "work-in-parent", "닫기"));
982추가: let close = ctx.read_response(close_id).expect("닫기 버튼").rect;
983추가: let red = egui::Color32::from_rgb(232, 17, 35);
984추가: fn has_fill(shapes: &[egui::epaint::ClippedShape], color: egui::Color32) -> bool {
985추가: fn walk(shape: &Shape, color: egui::Color32) -> bool {
986추가: match shape {
987추가: Shape::Rect(rect) => rect.fill == color,
988추가: Shape::Vec(shapes) => shapes.iter().any(|s| walk(s, color)),
989추가: _ => false,
990추가: }
991추가: }
992추가: shapes.iter().any(|s| walk(&s.shape, color))
993추가: }
994추가: let idle = render(&mut app, vec![egui::Event::PointerMoved(egui::pos2(5.0, 5.0))]);
995추가: assert!(!has_fill(&idle.shapes, red));
996추가: assert!(
997추가: labels(&idle.shapes)
998추가: .iter()
999추가: .any(|(text, _)| text == "압축파일을 열지 못했습니다")
1000추가: );
1001추가: render(&mut app, vec![egui::Event::PointerMoved(close.center())]);
1002추가: let hovered = render(&mut app, vec![]);
1003추가: assert!(has_fill(&hovered.shapes, red));
1004추가: for pressed in [true, false] {
1005추가: render(
1006추가: &mut app,
1007추가: vec![egui::Event::PointerButton {
1008추가: pos: close.center(),
1009추가: button: egui::PointerButton::Primary,
1010추가: pressed,
1011추가: modifiers: egui::Modifiers::NONE,
1012추가: }],
1013추가: );
1014추가: }
1015추가: render(&mut app, vec![]);
1016추가: let shown = labels(&render(&mut app, vec![]).shapes);
1017추가: assert!(
1018추가: !shown
1019추가: .iter()
1020추가: .any(|(text, _)| text == "압축파일을 열지 못했습니다"),
1021추가: "{shown:?}"
1022추가: );
1023추가: }
수정tests/rust-archive-worker/main.rs+12-0
@@ -523,6 +523,15 @@ fn symlink_parent_escape_is_rejected() {
523523 assert_eq!(fs::read_dir(s.0.join("outside")).unwrap().count(), 0);
524524}
525525
526추가: // 개인 그룹의 압축 해제만 허용하고 공유 쓰기는 거부함.
527추가: #[cfg(target_os = "linux")]
528추가: #[test]
529추가: fn private_group_writable_output_is_accepted() {
530추가: private_group::check_extraction("personal", true);
531추가: private_group::check_extraction("shared-primary", false);
532추가: private_group::check_extraction("world-writable", false);
533추가: }
534추가:
526535#[test]
527536fn changed_source_is_reopen_error_before_decode() {
528537 let s = Scratch::new();
@@ -1611,3 +1620,6 @@ mod spool_location;
16111620
16121621#[cfg(target_os = "linux")]
16131622mod spool_fallback;
1623추가:
1624추가: #[cfg(target_os = "linux")]
1625추가: mod private_group;
추가tests/rust-archive-worker/private_group.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/private_group_nss.c

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-large-archive-fixtures/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-zip64-compat/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기