Debian Codegraph @

src/desktop/print.rs

raw
1 //! # Examples
2 //!
3 //! Print a file
4 //!
5 //! ```rust,no_run
6 //! use std::{fs::File, os::fd::AsFd};
7 //!
8 //! use ashpd::desktop::print::{PreparePrintOptions, PrintOptions, PrintProxy};
9 //!
10 //! async fn run() -> ashpd::Result<()> {
11 //! let proxy = PrintProxy::new().await?;
12 //!
13 //! let file =
14 //! File::open("/home/bilelmoussaoui/gitlog.pdf").expect("file to print was not found");
15 //! let pre_print = proxy
16 //! .prepare_print(
17 //! None,
18 //! "prepare print",
19 //! Default::default(),
20 //! Default::default(),
21 //! PreparePrintOptions::default().set_modal(true),
22 //! )
23 //! .await?
24 //! .response()?;
25 //! proxy
26 //! .print(
27 //! None,
28 //! "test",
29 //! &file.as_fd(),
30 //! PrintOptions::default()
31 //! .set_token(pre_print.token)
32 //! .set_modal(true),
33 //! )
34 //! .await?;
35 //!
36 //! Ok(())
37 //! }
38 //! ```
39
40 use std::{fmt, os::fd::AsFd, str::FromStr};
41
42 use serde::{Deserialize, Serialize};
43 use zbus::zvariant::{
44 Fd, Optional, Type,
45 as_value::{self, optional},
46 };
47
48 use super::{HandleToken, Request};
49 use crate::{Error, Uri, WindowIdentifier, proxy::Proxy};
50
51 #[cfg_attr(feature = "glib", derive(glib::Enum))]
52 #[cfg_attr(feature = "glib", enum_type(name = "AshpdOrientation"))]
53 #[derive(Debug, Copy, Clone, Deserialize, Serialize, PartialEq, Eq, Type)]
54 #[zvariant(signature = "s")]
55 #[serde(rename_all = "snake_case")]
56 /// The page orientation.
57 pub enum Orientation {
58 /// Landscape.
59 Landscape,
60 /// Portrait.
61 Portrait,
62 /// Reverse landscape.
63 ReverseLandscape,
64 /// Reverse portrait.
65 ReversePortrait,
66 }
67
68 impl fmt::Display for Orientation {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 match self {
71 Self::Landscape => write!(f, "Landscape"),
72 Self::Portrait => write!(f, "Portrait"),
73 Self::ReverseLandscape => write!(f, "Reverse Landscape"),
74 Self::ReversePortrait => write!(f, "Reverse Portrait"),
75 }
76 }
77 }
78
79 impl AsRef<str> for Orientation {
80 fn as_ref(&self) -> &str {
81 match self {
82 Self::Landscape => "Landscape",
83 Self::Portrait => "Portrait",
84 Self::ReverseLandscape => "Reverse Landscape",
85 Self::ReversePortrait => "Reverse Portrait",
86 }
87 }
88 }
89
90 impl From<Orientation> for &'static str {
91 fn from(o: Orientation) -> Self {
92 match o {
93 Orientation::Landscape => "Landscape",
94 Orientation::Portrait => "Portrait",
95 Orientation::ReverseLandscape => "Reverse Landscape",
96 Orientation::ReversePortrait => "Reverse Portrait",
97 }
98 }
99 }
100
101 impl FromStr for Orientation {
102 type Err = Error;
103
104 fn from_str(s: &str) -> Result<Self, Self::Err> {
105 match s {
106 "Landscape" | "landscape" => Ok(Orientation::Landscape),
107 "Portrait" | "portrait" => Ok(Orientation::Portrait),
108 "ReverseLandscape" | "reverse_landscape" => Ok(Orientation::ReverseLandscape),
109 "ReversePortrait" | "reverse_portrait" => Ok(Orientation::ReversePortrait),
110 _ => Err(Error::ParseError(
111 "Failed to parse orientation, invalid value",
112 )),
113 }
114 }
115 }
116
117 #[cfg_attr(feature = "glib", derive(glib::Enum))]
118 #[cfg_attr(feature = "glib", enum_type(name = "AshpdQuality"))]
119 #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Type)]
120 #[zvariant(signature = "s")]
121 #[serde(rename_all = "lowercase")]
122 /// The print quality.
123 pub enum Quality {
124 /// Draft quality.
125 Draft,
126 /// Low quality.
127 Low,
128 /// Normal quality.
129 Normal,
130 /// High quality.
131 High,
132 }
133
134 impl fmt::Display for Quality {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 match self {
137 Self::Draft => write!(f, "Draft"),
138 Self::Low => write!(f, "Low"),
139 Self::Normal => write!(f, "Normal"),
140 Self::High => write!(f, "High"),
141 }
142 }
143 }
144
145 impl AsRef<str> for Quality {
146 fn as_ref(&self) -> &str {
147 match self {
148 Self::Draft => "Draft",
149 Self::Low => "Low",
150 Self::Normal => "Normal",
151 Self::High => "High",
152 }
153 }
154 }
155
156 impl From<Quality> for &'static str {
157 fn from(q: Quality) -> Self {
158 match q {
159 Quality::Draft => "Draft",
160 Quality::Low => "Low",
161 Quality::Normal => "Normal",
162 Quality::High => "High",
163 }
164 }
165 }
166
167 impl FromStr for Quality {
168 type Err = Error;
169
170 fn from_str(s: &str) -> Result<Self, Self::Err> {
171 match s {
172 "Draft" | "draft" => Ok(Quality::Draft),
173 "Low" | "low" => Ok(Quality::Low),
174 "Normal" | "normal" => Ok(Quality::Normal),
175 "High" | "high" => Ok(Quality::High),
176 _ => Err(Error::ParseError("Failed to parse quality, invalid value")),
177 }
178 }
179 }
180
181 #[cfg_attr(feature = "glib", derive(glib::Enum))]
182 #[cfg_attr(feature = "glib", enum_type(name = "AshpdDuplex"))]
183 #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Type)]
184 #[zvariant(signature = "s")]
185 #[serde(rename_all = "lowercase")]
186 /// Duplex printing mode.
187 pub enum Duplex {
188 /// Simplex (single-sided) printing.
189 Simplex,
190 /// Horizontal duplex (flip on short edge).
191 Horizontal,
192 /// Vertical duplex (flip on long edge).
193 Vertical,
194 }
195
196 #[cfg_attr(feature = "glib", derive(glib::Enum))]
197 #[cfg_attr(feature = "glib", enum_type(name = "AshpdPrintPages"))]
198 #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Type)]
199 #[zvariant(signature = "s")]
200 #[serde(rename_all = "lowercase")]
201 /// What pages to print.
202 pub enum PrintPages {
203 /// Print all pages.
204 All,
205 /// Print selected pages.
206 Selection,
207 /// Print current page.
208 Current,
209 /// Print page ranges.
210 Ranges,
211 }
212
213 #[cfg_attr(feature = "glib", derive(glib::Enum))]
214 #[cfg_attr(feature = "glib", enum_type(name = "AshpdPageSet"))]
215 #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Type)]
216 #[zvariant(signature = "s")]
217 #[serde(rename_all = "lowercase")]
218 /// What pages to print.
219 pub enum PageSet {
220 /// Print all pages.
221 All,
222 /// Print even pages only.
223 Even,
224 /// Print odd pages only.
225 Odd,
226 }
227
228 #[cfg_attr(feature = "glib", derive(glib::Enum))]
229 #[cfg_attr(feature = "glib", enum_type(name = "AshpdNumberUpLayout"))]
230 #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Type)]
231 #[zvariant(signature = "s")]
232 #[serde(rename_all = "lowercase")]
233 /// Layout for number-up printing.
234 pub enum NumberUpLayout {
235 /// Left to right, top to bottom.
236 #[serde(rename = "lrtb")]
237 Lrtb,
238 /// Left to right, bottom to top.
239 #[serde(rename = "lrbt")]
240 Lrbt,
241 /// Right to left, top to bottom.
242 #[serde(rename = "rltb")]
243 Rltb,
244 /// Right to left, bottom to top.
245 #[serde(rename = "rlbt")]
246 Rlbt,
247 /// Top to bottom, left to right.
248 #[serde(rename = "tblr")]
249 Tblr,
250 /// Top to bottom, right to left.
251 #[serde(rename = "tbrl")]
252 Tbrl,
253 /// Bottom to top, left to right.
254 #[serde(rename = "btlr")]
255 Btlr,
256 /// Bottom to top, right to left.
257 #[serde(rename = "btrl")]
258 Btrl,
259 }
260
261 #[cfg_attr(feature = "glib", derive(glib::Enum))]
262 #[cfg_attr(feature = "glib", enum_type(name = "AshpdOutputFileFormat"))]
263 #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Type)]
264 #[zvariant(signature = "s")]
265 #[serde(rename_all = "UPPERCASE")]
266 /// Output file format for print-to-file.
267 pub enum OutputFileFormat {
268 /// PDF format.
269 Pdf,
270 /// PostScript format.
271 Ps,
272 /// SVG format.
273 Svg,
274 }
275
276 #[cfg_attr(feature = "glib", derive(glib::Enum))]
277 #[cfg_attr(feature = "glib", enum_type(name = "AshpdDither"))]
278 #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Type)]
279 #[zvariant(signature = "s")]
280 #[serde(rename_all = "kebab-case")]
281 /// Dithering to use for printing.
282 pub enum Dither {
283 /// Fine dithering.
284 Fine,
285 /// No dithering.
286 None,
287 /// Coarse dithering.
288 Coarse,
289 /// Line art dithering.
290 Lineart,
291 /// Grayscale dithering.
292 Grayscale,
293 /// Error diffusion dithering.
294 ErrorDiffusion,
295 }
296
297 // Custom serialization modules for string-wrapped types
298 mod string_bool {
299 use serde::{Deserializer, Serializer, de::Error};
300 use zbus::zvariant::as_value::optional;
301
302 pub fn serialize<S>(value: &Option<bool>, serializer: S) -> Result<S::Ok, S::Error>
303 where
304 S: Serializer,
305 {
306 match value {
307 Some(true) => optional::serialize(&Some("true"), serializer),
308 Some(false) => optional::serialize(&Some("false"), serializer),
309 None => optional::serialize(&None::<&str>, serializer),
310 }
311 }
312
313 pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
314 where
315 D: Deserializer<'de>,
316 {
317 let opt: Option<String> = optional::deserialize(deserializer)?;
318 opt.map(|s| match s.as_str() {
319 "true" => Ok(true),
320 "false" => Ok(false),
321 _ => Err(D::Error::custom(format!("invalid boolean string: {}", s))),
322 })
323 .transpose()
324 }
325 }
326
327 mod string_u32 {
328 use serde::{Deserializer, Serializer, de::Error};
329 use zbus::zvariant::as_value::optional;
330
331 pub fn serialize<S>(value: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error>
332 where
333 S: Serializer,
334 {
335 let str_value = value.map(|v| v.to_string());
336 optional::serialize(&str_value, serializer)
337 }
338
339 pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<u32>, D::Error>
340 where
341 D: Deserializer<'de>,
342 {
343 let opt: Option<String> = optional::deserialize(deserializer)?;
344 opt.map(|s| s.parse::<u32>().map_err(D::Error::custom))
345 .transpose()
346 }
347 }
348
349 mod string_i32 {
350 use serde::{Deserializer, Serializer, de::Error};
351 use zbus::zvariant::as_value::optional;
352
353 pub fn serialize<S>(value: &Option<i32>, serializer: S) -> Result<S::Ok, S::Error>
354 where
355 S: Serializer,
356 {
357 let str_value = value.map(|v| v.to_string());
358 optional::serialize(&str_value, serializer)
359 }
360
361 pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<i32>, D::Error>
362 where
363 D: Deserializer<'de>,
364 {
365 let opt: Option<String> = optional::deserialize(deserializer)?;
366 opt.map(|s| s.parse::<i32>().map_err(D::Error::custom))
367 .transpose()
368 }
369 }
370
371 #[derive(Serialize, Deserialize, Type, Debug, Default)]
372 /// Print settings to set in the print dialog.
373 #[zvariant(signature = "dict")]
374 #[serde(rename_all = "kebab-case")]
375 pub struct Settings {
376 /// One of landscape, portrait, reverse_landscape or reverse_portrait.
377 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
378 pub orientation: Option<Orientation>,
379 /// A paper name according to [PWG 5101.1-2002](ftp://ftp.pwg.org/pub/pwg/candidates/cs-pwgmsn10-20020226-5101.1.pdf)
380 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
381 pub paper_format: Option<String>,
382 /// Paper width, in millimeters.
383 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
384 pub paper_width: Option<String>,
385 /// Paper height, in millimeters.
386 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
387 pub paper_height: Option<String>,
388 /// The number of copies to print.
389 #[serde(with = "string_u32", skip_serializing_if = "Option::is_none")]
390 pub n_copies: Option<u32>,
391 /// The default paper source.
392 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
393 pub default_source: Option<String>,
394 /// Print quality.
395 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
396 pub quality: Option<Quality>,
397 /// The resolution, sets both resolution-x & resolution-y
398 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
399 pub resolution: Option<String>,
400 /// Whether to use color.
401 #[serde(with = "string_bool", skip_serializing_if = "Option::is_none")]
402 pub use_color: Option<bool>,
403 /// Duplex printing mode.
404 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
405 pub duplex: Option<Duplex>,
406 /// Whether to collate copies.
407 #[serde(with = "string_bool", skip_serializing_if = "Option::is_none")]
408 pub collate: Option<bool>,
409 /// Whether to reverse the order of printed pages.
410 #[serde(with = "string_bool", skip_serializing_if = "Option::is_none")]
411 pub reverse: Option<bool>,
412 /// A media type according to [PWG 5101.1-2002](ftp://ftp.pwg.org/pub/pwg/candidates/cs-pwgmsn10-20020226-5101.1.pdf)
413 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
414 pub media_type: Option<String>,
415 /// The dithering to use.
416 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
417 pub dither: Option<Dither>,
418 /// The scale in percent.
419 #[serde(with = "string_u32", skip_serializing_if = "Option::is_none")]
420 pub scale: Option<u32>,
421 /// What pages to print.
422 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
423 pub print_pages: Option<PrintPages>,
424 /// A list of page ranges, formatted like this: 0-2,4,9-11.
425 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
426 pub page_ranges: Option<String>,
427 /// Whether to print all, even, or odd pages.
428 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
429 pub page_set: Option<PageSet>,
430 /// The finishings.
431 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
432 pub finishings: Option<String>,
433 /// The number of pages per sheet.
434 #[serde(with = "string_u32", skip_serializing_if = "Option::is_none")]
435 pub number_up: Option<u32>,
436 /// Layout for number-up printing.
437 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
438 pub number_up_layout: Option<NumberUpLayout>,
439 /// The output bin.
440 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
441 pub output_bin: Option<String>,
442 /// The horizontal resolution in dpi.
443 #[serde(with = "string_i32", skip_serializing_if = "Option::is_none")]
444 pub resolution_x: Option<i32>,
445 /// The vertical resolution in dpi.
446 #[serde(with = "string_i32", skip_serializing_if = "Option::is_none")]
447 pub resolution_y: Option<i32>,
448 /// The resolution in lpi (lines per inch).
449 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
450 pub printer_lpi: Option<String>,
451 /// Basename to use for print-to-file.
452 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
453 pub output_basename: Option<String>,
454 /// Format to use for print-to-file.
455 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
456 pub output_file_format: Option<OutputFileFormat>,
457 /// The uri used for print-to file.
458 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
459 pub output_uri: Option<Uri>,
460 }
461
462 impl Settings {
463 /// Sets the orientation.
464 #[must_use]
465 pub fn set_orientation(mut self, orientation: impl Into<Option<Orientation>>) -> Self {
466 self.orientation = orientation.into();
467 self
468 }
469
470 /// Sets the paper name.
471 #[must_use]
472 pub fn set_paper_format<'a>(mut self, paper_format: impl Into<Option<&'a str>>) -> Self {
473 self.paper_format = paper_format.into().map(ToOwned::to_owned);
474 self
475 }
476
477 /// Sets the paper width.
478 #[must_use]
479 pub fn set_paper_width<'a>(mut self, paper_width: impl Into<Option<&'a str>>) -> Self {
480 self.paper_width = paper_width.into().map(ToOwned::to_owned);
481 self
482 }
483
484 /// Sets the paper height.
485 #[must_use]
486 pub fn set_paper_height<'a>(mut self, paper_height: impl Into<Option<&'a str>>) -> Self {
487 self.paper_height = paper_height.into().map(ToOwned::to_owned);
488 self
489 }
490
491 /// Sets the number of copies to print.
492 #[must_use]
493 pub fn set_n_copies(mut self, n_copies: impl Into<Option<u32>>) -> Self {
494 self.n_copies = n_copies.into();
495 self
496 }
497
498 /// Sets the default paper source.
499 #[must_use]
500 pub fn set_default_source<'a>(mut self, default_source: impl Into<Option<&'a str>>) -> Self {
501 self.default_source = default_source.into().map(ToOwned::to_owned);
502 self
503 }
504
505 /// Sets the print quality.
506 #[must_use]
507 pub fn set_quality(mut self, quality: impl Into<Option<Quality>>) -> Self {
508 self.quality = quality.into();
509 self
510 }
511
512 /// Sets the resolution, both resolution-x & resolution-y.
513 #[must_use]
514 pub fn set_resolution<'a>(mut self, resolution: impl Into<Option<&'a str>>) -> Self {
515 self.resolution = resolution.into().map(ToOwned::to_owned);
516 self
517 }
518
519 /// Sets whether to use color.
520 #[must_use]
521 pub fn set_use_color(mut self, use_color: impl Into<Option<bool>>) -> Self {
522 self.use_color = use_color.into();
523 self
524 }
525
526 /// Sets the duplex printing mode.
527 #[must_use]
528 pub fn set_duplex(mut self, duplex: impl Into<Option<Duplex>>) -> Self {
529 self.duplex = duplex.into();
530 self
531 }
532
533 /// Whether to collate copies.
534 #[must_use]
535 pub fn set_collate(mut self, collate: impl Into<Option<bool>>) -> Self {
536 self.collate = collate.into();
537 self
538 }
539
540 /// Sets whether to reverse the order of the printed pages.
541 #[must_use]
542 pub fn set_reverse(mut self, reverse: impl Into<Option<bool>>) -> Self {
543 self.reverse = reverse.into();
544 self
545 }
546
547 /// Sets the media type.
548 #[must_use]
549 pub fn set_media_type<'a>(mut self, media_type: impl Into<Option<&'a str>>) -> Self {
550 self.media_type = media_type.into().map(ToOwned::to_owned);
551 self
552 }
553
554 /// Sets the dithering to use.
555 #[must_use]
556 pub fn set_dither(mut self, dither: impl Into<Option<Dither>>) -> Self {
557 self.dither = dither.into();
558 self
559 }
560
561 /// Sets the page scale in percent.
562 #[must_use]
563 pub fn set_scale(mut self, scale: impl Into<Option<u32>>) -> Self {
564 self.scale = scale.into();
565 self
566 }
567
568 /// Sets what pages to print.
569 #[must_use]
570 pub fn set_print_pages(mut self, print_pages: impl Into<Option<PrintPages>>) -> Self {
571 self.print_pages = print_pages.into();
572 self
573 }
574
575 /// Sets a list of page ranges, formatted like this: 0-2,4,9-11.
576 #[must_use]
577 pub fn set_page_ranges<'a>(mut self, page_ranges: impl Into<Option<&'a str>>) -> Self {
578 self.page_ranges = page_ranges.into().map(ToOwned::to_owned);
579 self
580 }
581
582 /// Sets whether to print all, even, or odd pages.
583 #[must_use]
584 pub fn set_page_set(mut self, page_set: impl Into<Option<PageSet>>) -> Self {
585 self.page_set = page_set.into();
586 self
587 }
588
589 /// Sets the finishings.
590 #[must_use]
591 pub fn set_finishings<'a>(mut self, finishings: impl Into<Option<&'a str>>) -> Self {
592 self.finishings = finishings.into().map(ToOwned::to_owned);
593 self
594 }
595
596 /// Sets the number of pages per sheet.
597 #[must_use]
598 pub fn set_number_up(mut self, number_up: impl Into<Option<u32>>) -> Self {
599 self.number_up = number_up.into();
600 self
601 }
602
603 /// Sets the number-up layout.
604 #[must_use]
605 pub fn set_number_up_layout(
606 mut self,
607 number_up_layout: impl Into<Option<NumberUpLayout>>,
608 ) -> Self {
609 self.number_up_layout = number_up_layout.into();
610 self
611 }
612
613 /// Sets the output bin
614 #[must_use]
615 pub fn set_output_bin<'a>(mut self, output_bin: impl Into<Option<&'a str>>) -> Self {
616 self.output_bin = output_bin.into().map(ToOwned::to_owned);
617 self
618 }
619
620 /// Sets the horizontal resolution in dpi.
621 #[must_use]
622 pub fn set_resolution_x(mut self, resolution_x: impl Into<Option<i32>>) -> Self {
623 self.resolution_x = resolution_x.into();
624 self
625 }
626
627 /// Sets the vertical resolution in dpi.
628 #[must_use]
629 pub fn set_resolution_y(mut self, resolution_y: impl Into<Option<i32>>) -> Self {
630 self.resolution_y = resolution_y.into();
631 self
632 }
633
634 /// Sets the resolution in lines per inch.
635 #[must_use]
636 pub fn set_printer_lpi<'a>(mut self, printer_lpi: impl Into<Option<&'a str>>) -> Self {
637 self.printer_lpi = printer_lpi.into().map(ToOwned::to_owned);
638 self
639 }
640
641 /// Sets the print-to-file base name.
642 #[must_use]
643 pub fn set_output_basename<'a>(mut self, output_basename: impl Into<Option<&'a str>>) -> Self {
644 self.output_basename = output_basename.into().map(ToOwned::to_owned);
645 self
646 }
647
648 /// Sets the print-to-file format.
649 #[must_use]
650 pub fn set_output_file_format(
651 mut self,
652 output_file_format: impl Into<Option<OutputFileFormat>>,
653 ) -> Self {
654 self.output_file_format = output_file_format.into();
655 self
656 }
657
658 /// Sets the print-to-file output uri.
659 #[must_use]
660 pub fn set_output_uri<'a>(mut self, output_uri: impl Into<Option<&'a Uri>>) -> Self {
661 self.output_uri = output_uri.into().map(ToOwned::to_owned);
662 self
663 }
664 }
665
666 #[derive(Serialize, Deserialize, Type, Debug, Default)]
667 /// Setup the printed pages.
668 #[zvariant(signature = "dict")]
669 #[serde(rename_all = "PascalCase")]
670 pub struct PageSetup {
671 /// the PPD name. It's the name to select a given driver.
672 #[serde(rename = "PPDName")]
673 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
674 pub ppdname: Option<String>,
675 /// The name of the page setup.
676 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
677 pub name: Option<String>,
678 /// The user-visible name of the page setup.
679 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
680 pub display_name: Option<String>,
681 /// Paper width in millimeters.
682 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
683 pub width: Option<f64>,
684 /// Paper height in millimeters.
685 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
686 pub height: Option<f64>,
687 /// Top margin in millimeters.
688 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
689 pub margin_top: Option<f64>,
690 /// Bottom margin in millimeters.
691 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
692 pub margin_bottom: Option<f64>,
693 /// Right margin in millimeters.
694 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
695 pub margin_right: Option<f64>,
696 /// Left margin in millimeters.
697 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
698 pub margin_left: Option<f64>,
699 /// The page orientation.
700 #[serde(with = "optional", skip_serializing_if = "Option::is_none")]
701 pub orientation: Option<Orientation>,
702 }
703
704 impl PageSetup {
705 /// Sets the ppdname.
706 #[must_use]
707 pub fn set_ppdname<'a>(mut self, ppdname: impl Into<Option<&'a str>>) -> Self {
708 self.ppdname = ppdname.into().map(ToOwned::to_owned);
709 self
710 }
711
712 /// Sets the name of the page setup.
713 #[must_use]
714 pub fn set_name<'a>(mut self, name: impl Into<Option<&'a str>>) -> Self {
715 self.name = name.into().map(ToOwned::to_owned);
716 self
717 }
718
719 /// Sets the user visible name of the page setup.
720 #[must_use]
721 pub fn set_display_name<'a>(mut self, display_name: impl Into<Option<&'a str>>) -> Self {
722 self.display_name = display_name.into().map(ToOwned::to_owned);
723 self
724 }
725
726 /// Sets the orientation.
727 #[must_use]
728 pub fn set_orientation(mut self, orientation: impl Into<Option<Orientation>>) -> Self {
729 self.orientation = orientation.into();
730 self
731 }
732
733 /// Sets the page width.
734 #[must_use]
735 pub fn set_width(mut self, width: impl Into<Option<f64>>) -> Self {
736 self.width = width.into();
737 self
738 }
739
740 /// Sets the page height.
741 #[must_use]
742 pub fn set_height(mut self, height: impl Into<Option<f64>>) -> Self {
743 self.height = height.into();
744 self
745 }
746
747 /// Sets the page top margin.
748 #[must_use]
749 pub fn set_margin_top(mut self, margin_top: impl Into<Option<f64>>) -> Self {
750 self.margin_top = margin_top.into();
751 self
752 }
753
754 /// Sets the page bottom margin.
755 #[must_use]
756 pub fn set_margin_bottom(mut self, margin_bottom: impl Into<Option<f64>>) -> Self {
757 self.margin_bottom = margin_bottom.into();
758 self
759 }
760
761 /// Sets the page right margin.
762 #[must_use]
763 pub fn set_margin_right(mut self, margin_right: impl Into<Option<f64>>) -> Self {
764 self.margin_right = margin_right.into();
765 self
766 }
767
768 /// Sets the page margin left.
769 #[must_use]
770 pub fn set_margin_left(mut self, margin_left: impl Into<Option<f64>>) -> Self {
771 self.margin_left = margin_left.into();
772 self
773 }
774 }
775
776 #[derive(Serialize, Deserialize, Type, Debug, Default)]
777 /// Specified options for a [`PrintProxy::prepare_print`] request.
778 #[zvariant(signature = "dict")]
779 #[serde(rename_all = "kebab-case")]
780 pub struct PreparePrintOptions {
781 /// A string that will be used as the last element of the handle.
782 #[serde(rename = "handle_token", with = "as_value", skip_deserializing)]
783 handle_token: HandleToken,
784 /// Whether to make the dialog modal.
785 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
786 modal: Option<bool>,
787 /// Label for the accept button. Mnemonic underlines are allowed.
788 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
789 accept_label: Option<String>,
790 /// File formats supported by the app for print-to-file.
791 /// Added in version 3.
792 #[serde(
793 default,
794 with = "as_value",
795 skip_serializing_if = "Vec::is_empty",
796 skip_deserializing
797 )]
798 supported_output_file_formats: Vec<OutputFileFormat>,
799 /// Whether it makes sense to return "current" for the print-pages setting.
800 /// Added in version 4.
801 #[serde(
802 default,
803 with = "optional",
804 skip_serializing_if = "Option::is_none",
805 skip_deserializing
806 )]
807 has_current_page: Option<bool>,
808 /// Whether it makes sense to return "selection" for the print-pages
809 /// setting. Added in version 4.
810 #[serde(
811 default,
812 with = "optional",
813 skip_serializing_if = "Option::is_none",
814 skip_deserializing
815 )]
816 has_selected_pages: Option<bool>,
817 }
818
819 impl PreparePrintOptions {
820 /// Sets whether the dialog should be a modal.
821 #[must_use]
822 pub fn set_modal(mut self, modal: impl Into<Option<bool>>) -> Self {
823 self.modal = modal.into();
824 self
825 }
826
827 /// Gets whether the dialog should be a modal.
828 #[cfg(feature = "backend")]
829 pub fn modal(&self) -> Option<bool> {
830 self.modal
831 }
832
833 /// Sets the label for the accept button. Mnemonic underlines are allowed.
834 #[must_use]
835 pub fn set_accept_label<'a>(mut self, accept_label: impl Into<Option<&'a str>>) -> Self {
836 self.accept_label = accept_label.into().map(ToOwned::to_owned);
837 self
838 }
839
840 /// Gets the label for the accept button.
841 #[cfg(feature = "backend")]
842 pub fn accept_label(&self) -> Option<&str> {
843 self.accept_label.as_deref()
844 }
845
846 /// Sets the supported output file formats for print-to-file.
847 /// Added in version 3.
848 #[must_use]
849 pub fn set_supported_output_file_formats(
850 mut self,
851 formats: impl IntoIterator<Item = OutputFileFormat>,
852 ) -> Self {
853 self.supported_output_file_formats = formats.into_iter().collect();
854 self
855 }
856
857 /// Sets whether it makes sense to return "current" for print-pages.
858 /// Added in version 4.
859 #[must_use]
860 pub fn set_has_current_page(mut self, has_current_page: impl Into<Option<bool>>) -> Self {
861 self.has_current_page = has_current_page.into();
862 self
863 }
864
865 /// Sets whether it makes sense to return "selection" for print-pages.
866 /// Added in version 4.
867 #[must_use]
868 pub fn set_has_selected_pages(mut self, has_selected_pages: impl Into<Option<bool>>) -> Self {
869 self.has_selected_pages = has_selected_pages.into();
870 self
871 }
872 }
873
874 #[derive(Serialize, Deserialize, Type, Debug, Default)]
875 /// Specified options for a [`PrintProxy::print`] request.
876 #[zvariant(signature = "dict")]
877 #[serde(rename_all = "kebab-case")]
878 pub struct PrintOptions {
879 /// A string that will be used as the last element of the handle.
880 #[serde(rename = "handle_token", with = "as_value", skip_deserializing)]
881 handle_token: HandleToken,
882 /// Whether to make the dialog modal.
883 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
884 modal: Option<bool>,
885 /// Token that was returned by a previous [`PrintProxy::prepare_print`]
886 /// call.
887 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
888 token: Option<u32>,
889 /// File formats supported by the app for print-to-file.
890 /// Added in version 3.
891 #[serde(
892 default,
893 with = "as_value",
894 skip_serializing_if = "Vec::is_empty",
895 skip_deserializing
896 )]
897 supported_output_file_formats: Vec<OutputFileFormat>,
898 }
899
900 impl PrintOptions {
901 /// Sets the token retrieved from [`PrintProxy::prepare_print`].
902 #[must_use]
903 pub fn set_token(mut self, token: impl Into<Option<u32>>) -> Self {
904 self.token = token.into();
905 self
906 }
907
908 /// Gets the token.
909 #[cfg(feature = "backend")]
910 pub fn token(&self) -> Option<u32> {
911 self.token
912 }
913
914 /// Sets whether the dialog should be a modal.
915 #[must_use]
916 pub fn set_modal(mut self, modal: impl Into<Option<bool>>) -> Self {
917 self.modal = modal.into();
918 self
919 }
920
921 /// Gets whether the dialog should be a modal.
922 #[cfg(feature = "backend")]
923 pub fn modal(&self) -> Option<bool> {
924 self.modal
925 }
926
927 /// Sets the supported output file formats for print-to-file.
928 /// Added in version 3.
929 #[must_use]
930 pub fn set_supported_output_file_formats(
931 mut self,
932 formats: impl IntoIterator<Item = OutputFileFormat>,
933 ) -> Self {
934 self.supported_output_file_formats = formats.into_iter().collect();
935 self
936 }
937 }
938
939 #[derive(Deserialize, Serialize, Type, Debug)]
940 /// A response to a [`PrintProxy::prepare_print`] request.
941 #[zvariant(signature = "dict")]
942 pub struct PreparePrint {
943 /// The printing settings.
944 #[serde(with = "as_value")]
945 pub settings: Settings,
946 /// The printed pages setup.
947 #[serde(rename = "page-setup", with = "as_value")]
948 pub page_setup: PageSetup,
949 /// A token to pass to the print request.
950 #[serde(with = "as_value")]
951 pub token: u32,
952 }
953
954 /// The interface lets sandboxed applications print.
955 ///
956 /// Wrapper of the DBus interface: [`org.freedesktop.portal.Print`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Print.html).
957 #[derive(Debug)]
958 #[doc(alias = "org.freedesktop.portal.Print")]
959 pub struct PrintProxy(Proxy<'static>);
960
961 impl PrintProxy {
962 /// Create a new instance of [`PrintProxy`].
963 pub async fn new() -> Result<Self, Error> {
964 let proxy = Proxy::new_desktop("org.freedesktop.portal.Print").await?;
965 Ok(Self(proxy))
966 }
967
968 /// Create a new instance of [`PrintProxy`].
969 pub async fn with_connection(connection: zbus::Connection) -> Result<Self, Error> {
970 let proxy =
971 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.Print").await?;
972 Ok(Self(proxy))
973 }
974
975 /// Returns the version of the portal interface.
976 pub fn version(&self) -> u32 {
977 self.0.version()
978 }
979
980 /// Presents a print dialog to the user and returns print settings and page
981 /// setup.
982 ///
983 /// # Arguments
984 ///
985 /// * `identifier` - Identifier for the application window.
986 /// * `title` - Title for the print dialog.
987 /// * `settings` - [`Settings`].
988 /// * `page_setup` - [`PageSetup`].
989 /// * `options` - [`PreparePrintOptions`]. allowed.
990 ///
991 /// # Specifications
992 ///
993 /// See also [`PreparePrint`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Print.html#org-freedesktop-portal-print-prepareprint).
994 #[doc(alias = "PreparePrint")]
995 #[doc(alias = "xdp_portal_prepare_print")]
996 pub async fn prepare_print(
997 &self,
998 identifier: Option<&WindowIdentifier>,
999 title: &str,
1000 settings: Settings,
1001 page_setup: PageSetup,
1002 mut options: PreparePrintOptions,
1003 ) -> Result<Request<PreparePrint>, Error> {
1004 let version = self.version();
1005
1006 // Clear version-specific fields if not supported
1007 if version < 2 {
1008 options.accept_label = None;
1009 }
1010 if version < 3 {
1011 options.supported_output_file_formats.clear();
1012 }
1013 if version < 4 {
1014 options.has_current_page = None;
1015 options.has_selected_pages = None;
1016 }
1017
1018 let identifier = Optional::from(identifier);
1019 self.0
1020 .request(
1021 &options.handle_token,
1022 "PreparePrint",
1023 &(identifier, title, settings, page_setup, &options),
1024 )
1025 .await
1026 }
1027
1028 /// Asks to print a file.
1029 /// The file must be passed in the form of a file descriptor open for
1030 /// reading. This ensures that sandboxed applications only print files
1031 /// that they have access to.
1032 ///
1033 /// # Arguments
1034 ///
1035 /// * `identifier` - The application window identifier.
1036 /// * `title` - The title for the print dialog.
1037 /// * `fd` - File descriptor for reading the content to print.
1038 /// * `options` - [`PrintOptions`].
1039 ///
1040 /// # Specifications
1041 ///
1042 /// See also [`Print`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Print.html#org-freedesktop-portal-print-print).
1043 #[doc(alias = "Print")]
1044 #[doc(alias = "xdp_portal_print_file")]
1045 pub async fn print(
1046 &self,
1047 identifier: Option<&WindowIdentifier>,
1048 title: &str,
1049 fd: &impl AsFd,
1050 mut options: PrintOptions,
1051 ) -> Result<Request<()>, Error> {
1052 let version = self.version();
1053
1054 // Clear version-specific fields if not supported
1055 if version < 3 {
1056 options.supported_output_file_formats.clear();
1057 }
1058
1059 let identifier = Optional::from(identifier);
1060
1061 self.0
1062 .empty_request(
1063 &options.handle_token,
1064 "Print",
1065 &(identifier, title, Fd::from(fd), &options),
1066 )
1067 .await
1068 }
1069 }
1070
1071 impl std::ops::Deref for PrintProxy {
1072 type Target = zbus::Proxy<'static>;
1073
1074 fn deref(&self) -> &Self::Target {
1075 &self.0
1076 }
1077 }