Skip to main content

easyofd_core/doc/permission/
ct_permission.rs

1//! 权限容器。
2
3use super::{Print, ValidPeriod};
4
5/// 对应 Java: org.ofdrw.core.basicStructure.CT_Permission
6///
7/// 文档权限控制容器,定义文档的打印权限和有效期。
8#[derive(Debug, Clone)]
9pub struct CtPermission {
10    /// 是否可打印。默认 true。
11    pub printable: bool,
12    /// 是否可编辑。默认 true。
13    pub editable: bool,
14    /// 是否可注释。默认 true。
15    pub annotatable: bool,
16    /// 打印权限详情。可选。
17    pub print: Option<Print>,
18    /// 有效期。可选。
19    pub valid_period: Option<ValidPeriod>,
20}
21
22impl CtPermission {
23    /// 创建默认权限(全部允许)。
24    #[must_use]
25    pub fn new() -> Self {
26        Self {
27            printable: true,
28            editable: true,
29            annotatable: true,
30            print: None,
31            valid_period: None,
32        }
33    }
34
35    /// 设置打印权限。
36    #[must_use]
37    pub fn with_print(mut self, print: Print) -> Self {
38        self.print = Some(print);
39        self
40    }
41
42    /// 设置有效期。
43    #[must_use]
44    pub fn with_valid_period(mut self, period: ValidPeriod) -> Self {
45        self.valid_period = Some(period);
46        self
47    }
48
49    /// 禁止编辑。
50    #[must_use]
51    pub fn read_only(mut self) -> Self {
52        self.editable = false;
53        self.annotatable = false;
54        self
55    }
56
57    /// 序列化为 XML 字符串。
58    #[must_use]
59    pub fn to_xml_string(&self) -> String {
60        let mut inner = String::new();
61        if let Some(p) = &self.print {
62            inner.push_str(&p.to_xml_string());
63        }
64        if let Some(vp) = &self.valid_period {
65            inner.push_str(&vp.to_xml_string());
66        }
67        format!(
68            "<CT_Permission Printable=\"{}\" Editable=\"{}\" Annotatable=\"{}\">{inner}</CT_Permission>",
69            self.printable, self.editable, self.annotatable
70        )
71    }
72}
73
74impl Default for CtPermission {
75    fn default() -> Self {
76        Self::new()
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn test_ct_permission_new() {
86        let p = CtPermission::new();
87        assert!(p.printable);
88        assert!(p.editable);
89        assert!(p.annotatable);
90        assert!(p.print.is_none());
91        assert!(p.valid_period.is_none());
92        let p2 = CtPermission::default();
93        assert!(p2.printable);
94    }
95
96    #[test]
97    fn test_ct_permission_read_only_and_xml() {
98        let p = CtPermission::new().read_only();
99        assert!(!p.editable);
100        assert!(!p.annotatable);
101        let xml = p.to_xml_string();
102        assert!(xml.contains("Editable=\"false\""));
103        assert!(xml.contains("Annotatable=\"false\""));
104        assert!(xml.contains("Printable=\"true\""));
105    }
106}