ltk_webkit/wpe/print/
geometry.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Where the page is laid out and cut for print, from the paper and the device.

use std::collections::BTreeSet;

use crate::types::{ PrintError, PrintSettings };

/// CSS pixels are 1/96 of an inch, PDF points 1/72.
const CSS_PER_POINT: f64 = 96.0 / 72.0;
pub( super ) const PRINT_DPI: f64 = 200.0;
const MIN_DPI:       f64 = 24.0;
/// Of the view's logical size while printing, so WebKit is never asked for a huge buffer.
const MAX_SIDE:      f64 = 4096.0;
/// Margins may not leave less than half an inch to print on.
const MIN_AREA:      f64 = 36.0;

#[ derive( Clone, Copy, Debug, PartialEq ) ]
pub( super ) struct Geometry
{
	/// In points.
	pub paper: ( f64, f64 ),
	/// The printable area in points: left and bottom edges, as PDF counts them, then width and height.
	pub area:  ( f64, f64, f64, f64 ),
	/// The width the page is laid out at and the height of one page, in CSS pixels.
	pub css:   ( f64, f64 ),
	/// The view's logical size and zoom while it is laid out for print.
	pub view:  ( i32, i32 ),
	pub zoom:  f64,
}

/// The resolution at which the paper's width takes `width` pixels.
pub( super ) fn preview_dpi( settings: &PrintSettings, width: u32 ) -> f64
{
	let paper = settings.paper.0 as f64;
	if !( paper > 0.0 ) { return PRINT_DPI; }
	( width.max( 1 ) as f64 * 72.0 / paper ).clamp( MIN_DPI, PRINT_DPI )
}

pub( super ) fn geometry( settings: &PrintSettings, device_scale: f64, dpi: f64 ) -> Result<Geometry, PrintError>
{
	let ( width, height ) = ( settings.paper.0 as f64, settings.paper.1 as f64 );
	let [ top, right, bottom, left ] = settings.margins.map( |m| if m.is_finite() { m.max( 0.0 ) as f64 } else { 0.0 } );
	let ( area_width, area_height ) = ( width - left - right, height - top - bottom );
	if !( area_width >= MIN_AREA && area_height >= MIN_AREA )
	{
		return Err( PrintError::Failed( "the margins leave no room on the paper".to_string() ) );
	}
	let scale = if settings.scale.is_finite() { settings.scale.clamp( PrintSettings::MIN_SCALE, PrintSettings::MAX_SCALE ) as f64 } else { 1.0 };
	let css    = ( area_width * CSS_PER_POINT / scale, area_height * CSS_PER_POINT / scale );
	let device = if device_scale.is_finite() { device_scale.max( 0.5 ) } else { 1.0 };
	let mut zoom = area_width / 72.0 * dpi / device / css.0;
	let longest  = css.0.max( css.1 ) * zoom;
	if longest > MAX_SIDE { zoom *= MAX_SIDE / longest; }
	Ok( Geometry
	{
		paper: ( width, height ),
		area:  ( left, bottom, area_width, area_height ),
		css,
		view:  ( ( css.0 * zoom ).round() as i32, ( css.1 * zoom ).round() as i32 ),
		zoom,
	} )
}

pub( super ) fn check( ranges: &[ ( u32, u32 ) ] ) -> Result<(), PrintError>
{
	match ranges.iter().find( |( start, end )| start > end )
	{
		Some( ( start, end ) ) => Err( PrintError::Failed( format!( "the range {start}-{end} ends before it starts" ) ) ),
		None                   => Ok( () ),
	}
}

/// The pages to print, from 0, in the document's order and once each.
pub( super ) fn select( ranges: &[ ( u32, u32 ) ], total: usize ) -> Result<Vec<usize>, PrintError>
{
	check( ranges )?;
	let chosen: Vec<usize> = if ranges.is_empty()
	{
		( 0..total ).collect()
	} else {
		let mut set = BTreeSet::new();
		for &( start, end ) in ranges
		{
			let first = start.max( 1 ) as usize - 1;
			let last  = ( end as usize ).min( total );
			set.extend( first..last );
		}
		set.into_iter().collect()
	};
	if chosen.is_empty() { return Err( PrintError::Failed( "no page to print".to_string() ) ); }
	Ok( chosen )
}

#[ cfg( test ) ]
mod tests
{
	use super::*;

	#[ test ]
	fn a4_lays_out_as_wide_as_other_browsers_print_it()
	{
		let g = geometry( &PrintSettings::default(), 1.0, PRINT_DPI ).unwrap();
		assert!( ( g.css.0 - 718.1 ).abs() < 0.5, "{}", g.css.0 );
		assert!( ( g.view.0 as f64 / g.zoom - g.css.0 ).abs() < 1.0 );
	}

	#[ test ]
	fn the_image_is_as_sharp_whatever_the_device_scale()
	{
		let one = geometry( &PrintSettings::default(), 1.0, PRINT_DPI ).unwrap();
		let two = geometry( &PrintSettings::default(), 2.0, PRINT_DPI ).unwrap();
		assert!( ( one.view.0 as f64 - 2.0 * two.view.0 as f64 ).abs() <= 1.0 );
		assert!( ( one.css.0 - two.css.0 ).abs() < f64::EPSILON );
	}

	#[ test ]
	fn a_smaller_scale_lays_out_wider()
	{
		let half = geometry( &PrintSettings { scale: 0.5, ..PrintSettings::default() }, 1.0, PRINT_DPI ).unwrap();
		let full = geometry( &PrintSettings::default(), 1.0, PRINT_DPI ).unwrap();
		assert!( ( half.css.0 - 2.0 * full.css.0 ).abs() < 0.01 );
		assert!( half.view.0 as f64 <= MAX_SIDE && half.view.1 as f64 <= MAX_SIDE );
	}

	#[ test ]
	fn the_scale_is_kept_within_bounds()
	{
		let tiny = geometry( &PrintSettings { scale: 0.001, ..PrintSettings::default() }, 1.0, PRINT_DPI ).unwrap();
		let low  = geometry( &PrintSettings { scale: PrintSettings::MIN_SCALE, ..PrintSettings::default() }, 1.0, PRINT_DPI ).unwrap();
		assert_eq!( tiny.css, low.css );
	}

	#[ test ]
	fn margins_wider_than_the_paper_fail()
	{
		assert!( geometry( &PrintSettings { margins: [ 300.0; 4 ], ..PrintSettings::default() }, 1.0, PRINT_DPI ).is_err() );
	}

	#[ test ]
	fn a_preview_is_as_wide_as_asked()
	{
		let settings = PrintSettings::default();
		let g        = geometry( &settings, 1.0, preview_dpi( &settings, 480 ) ).unwrap();
		let sheet    = g.view.0 as f64 * g.paper.0 / g.area.2;
		assert!( ( sheet - 480.0 ).abs() < 2.0, "{sheet}" );
	}

	#[ test ]
	fn ranges_print_in_order_once_each()
	{
		assert_eq!( select( &[ ( 5, 6 ), ( 1, 2 ), ( 2, 3 ) ], 10 ).unwrap(), vec![ 0, 1, 2, 4, 5 ] );
	}

	#[ test ]
	fn no_ranges_print_everything()
	{
		assert_eq!( select( &[], 3 ).unwrap(), vec![ 0, 1, 2 ] );
	}

	#[ test ]
	fn pages_past_the_end_are_left_out()
	{
		assert_eq!( select( &[ ( 2, 9 ) ], 3 ).unwrap(), vec![ 1, 2 ] );
		assert!( select( &[ ( 5, 9 ) ], 3 ).is_err() );
	}

	#[ test ]
	fn a_backwards_range_fails()
	{
		assert!( select( &[ ( 3, 1 ) ], 5 ).is_err() );
	}
}