1# Copyright (c) 2023, Pubpub-ZZ
2#
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9# * Redistributions of source code must retain the above copyright notice,
10# this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above copyright notice,
12# this list of conditions and the following disclaimer in the documentation
13# and/or other materials provided with the distribution.
14# * The name of the author may not be used to endorse or promote products
15# derived from this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27# POSSIBILITY OF SUCH DAMAGE.
28
29import contextlib
30from typing import (
31 Any,
32 cast,
33)
34
35from .._utils import deprecate_no_replacement
36from ..constants import PageAttributes
37from ._base import BooleanObject, NameObject, NumberObject, PdfObject, is_null_or_none
38from ._data_structures import ArrayObject, DictionaryObject
39
40f_obj = BooleanObject(False)
41
42#: The page boundaries a viewer preference may name, per Table 147 in the 2.0
43#: reference.
44BOX_NAMES = [
45 PageAttributes.MEDIABOX,
46 PageAttributes.CROPBOX,
47 PageAttributes.BLEEDBOX,
48 PageAttributes.TRIMBOX,
49 PageAttributes.ARTBOX,
50]
51
52
53class ViewerPreferences(DictionaryObject):
54 def __init__(self, obj: DictionaryObject | None = None) -> None:
55 super().__init__(self)
56 if not is_null_or_none(obj):
57 self.update(obj.items()) # type: ignore[union-attr]
58 with contextlib.suppress(AttributeError):
59 self.indirect_reference = obj.indirect_reference # type: ignore[union-attr]
60
61 def _resolve(self, key: str, default: PdfObject | None) -> PdfObject | None:
62 # Any of these entries may be an indirect reference, which dict.get
63 # hands back as-is rather than resolving the way __getitem__ does.
64 value: PdfObject | None = self.get(key, default)
65 if value is None:
66 return None
67 return value.get_object()
68
69 def _get_bool(self, key: str, default: BooleanObject | None) -> BooleanObject | None:
70 return cast("BooleanObject | None", self._resolve(key, default))
71
72 def _set_bool(self, key: str, v: bool) -> None:
73 self[NameObject(key)] = BooleanObject(v is True)
74
75 def _get_name(self, key: str, default: NameObject | None) -> NameObject | None:
76 return cast("NameObject | None", self._resolve(key, default))
77
78 def _set_name(self, key: str, lst: list[str], v: NameObject) -> None:
79 if lst != [] and v not in lst:
80 raise ValueError(f"{v} is an unacceptable value")
81 self[NameObject(key)] = NameObject(v)
82
83 def _get_arr(self, key: str, default: list[Any] | None) -> ArrayObject | None:
84 return cast(
85 "ArrayObject | None",
86 self._resolve(key, None if default is None else ArrayObject(default)),
87 )
88
89 def _set_arr(self, key: str, v: ArrayObject | None) -> None:
90 if v is None:
91 with contextlib.suppress(KeyError):
92 del self[NameObject(key)]
93 return
94 if not isinstance(v, ArrayObject):
95 raise TypeError("ArrayObject is expected")
96 if key == "/PrintPageRange" and len(v) % 2:
97 # The array holds first/last page pairs, so an odd length leaves a
98 # range without its end.
99 raise ValueError(
100 f"/PrintPageRange holds page pairs, got {len(v)} entries: {v}"
101 )
102 self[NameObject(key)] = v
103
104 def _get_int(self, key: str, default: NumberObject | None) -> NumberObject | None:
105 return cast("NumberObject | None", self._resolve(key, default))
106
107 def _set_int(self, key: str, v: int) -> None:
108 if v < 0:
109 raise ValueError(f"{v} is an unacceptable value for {key}")
110 self[NameObject(key)] = NumberObject(v)
111
112 @property
113 def PRINT_SCALING(self) -> NameObject: # noqa: N802
114 """
115 The ``/PrintScaling`` name.
116
117 .. deprecated:: 7.3.0
118 ``ViewerPreferences.PRINT_SCALING`` is deprecated and will be removed
119 in pypdf 8.0.0. Use ``NameObject("/PrintScaling")`` instead.
120 """
121 deprecate_no_replacement("ViewerPreferences.PRINT_SCALING", "8.0.0")
122 return NameObject("/PrintScaling")
123
124 def __new__(cls: Any, value: Any = None) -> "ViewerPreferences": # noqa: PYI034
125 def _add_prop_bool(key: str, default: BooleanObject | None) -> property:
126 return property(
127 lambda self: self._get_bool(key, default),
128 lambda self, v: self._set_bool(key, v),
129 None,
130 f"""
131 Returns/Modify the status of {key}, Returns {default} if not defined
132 """,
133 )
134
135 def _add_prop_name(
136 key: str, lst: list[str], default: NameObject | None
137 ) -> property:
138 return property(
139 lambda self: self._get_name(key, default),
140 lambda self, v: self._set_name(key, lst, NameObject(v)),
141 None,
142 f"""
143 Returns/Modify the status of {key}, Returns {default} if not defined.
144 Acceptable values: {lst}
145 """,
146 )
147
148 def _add_prop_arr(key: str, default: ArrayObject | None) -> property:
149 return property(
150 lambda self: self._get_arr(key, default),
151 lambda self, v: self._set_arr(key, v),
152 None,
153 f"""
154 Returns/Modify the status of {key}, Returns {default} if not defined
155 """,
156 )
157
158 def _add_prop_int(key: str, default: int | None) -> property:
159 return property(
160 lambda self: self._get_int(key, default),
161 lambda self, v: self._set_int(key, v),
162 None,
163 f"""
164 Returns/Modify the status of {key}, Returns {default} if not defined
165 """,
166 )
167
168 cls.hide_toolbar = _add_prop_bool("/HideToolbar", f_obj)
169 cls.hide_menubar = _add_prop_bool("/HideMenubar", f_obj)
170 cls.hide_windowui = _add_prop_bool("/HideWindowUI", f_obj)
171 cls.fit_window = _add_prop_bool("/FitWindow", f_obj)
172 cls.center_window = _add_prop_bool("/CenterWindow", f_obj)
173 cls.display_doctitle = _add_prop_bool("/DisplayDocTitle", f_obj)
174
175 cls.non_fullscreen_pagemode = _add_prop_name(
176 "/NonFullScreenPageMode",
177 ["/UseNone", "/UseOutlines", "/UseThumbs", "/UseOC"],
178 NameObject("/UseNone"),
179 )
180 cls.direction = _add_prop_name(
181 "/Direction", ["/L2R", "/R2L"], NameObject("/L2R")
182 )
183 cls.view_area = _add_prop_name("/ViewArea", BOX_NAMES, None)
184 cls.view_clip = _add_prop_name("/ViewClip", BOX_NAMES, None)
185 cls.print_area = _add_prop_name("/PrintArea", BOX_NAMES, None)
186 cls.print_clip = _add_prop_name("/PrintClip", BOX_NAMES, None)
187 cls.print_scaling = _add_prop_name(
188 "/PrintScaling", ["/None", "/AppDefault"], None
189 )
190 cls.duplex = _add_prop_name(
191 "/Duplex", ["/Simplex", "/DuplexFlipShortEdge", "/DuplexFlipLongEdge"], None
192 )
193 cls.pick_tray_by_pdfsize = _add_prop_bool("/PickTrayByPDFSize", None)
194 cls.print_pagerange = _add_prop_arr("/PrintPageRange", None)
195 cls.num_copies = _add_prop_int("/NumCopies", None)
196
197 cls.enforce = _add_prop_arr("/Enforce", ArrayObject())
198
199 return cast("ViewerPreferences", DictionaryObject.__new__(cls))