fontoxide-ttlib 0.1.0

Read and write OpenType/TrueType fonts and TTX; a port of fontTools.ttLib
Documentation
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! Simplifies glyphs by merging overlapping contours and components (a port of
//! `fontTools.ttLib.removeOverlaps`).
//!
//! fontTools uses skia-pathops for the boolean operations; here it is `linesweeper`,
//! which is pure Rust. The results are geometrically equivalent, not identical: the
//! contours can start at other points or come in another order, as they also do between
//! versions of Skia.
//!
//! Without the `pathops` feature (fontTools without skia-pathops),
//! [`remove_overlaps`] fails with [`Error::Import`], as importing
//! `fontTools.ttLib.removeOverlaps` does.

#[cfg(feature = "pathops")]
use fontoxide_misc::transform::Transform;
#[cfg(feature = "pathops")]
use fontoxide_pens::base_pen::{decompose_quadratic_segment, decompose_super_bezier_segment};
#[cfg(feature = "pathops")]
use fontoxide_pens::transform_pen::TransformPen;
#[cfg(feature = "pathops")]
use fontoxide_pens::{Pen, Point};
#[cfg(feature = "pathops")]
use kurbo::{BezPath, PathEl, Shape};
#[cfg(feature = "pathops")]
use linesweeper::topology::Contours;
#[cfg(feature = "pathops")]
use linesweeper::{BinaryOp, FillRule, binary_op};

#[cfg(feature = "pathops")]
use crate::Tag;
#[cfg(feature = "pathops")]
use crate::cff::charstring::{T2CharString, Token};
#[cfg(feature = "pathops")]
use crate::cff::font::CffFontSet;
#[cfg(feature = "pathops")]
use crate::cff::specializer::{
	Arg, Command, SpecializeOptions, commands_to_program, specialize_commands,
};
#[cfg(feature = "pathops")]
use crate::glyph_set::GlyphSet;
#[cfg(feature = "pathops")]
use crate::table::TableType;
#[cfg(feature = "pathops")]
use crate::tables::glyf::Glyph;
#[cfg(feature = "pathops")]
use crate::tables::{Cff, Cff2, Glyf, Hmtx};
use std::io::Write;

use fontoxide_misc::argparse::{Argument, Command as Parser, Nargs};

use crate::{Error, Font, ReadOptions, Result, WriteOptions};

#[cfg(feature = "pathops")]
const CFF: Tag = Tag::new(b"CFF ");
#[cfg(feature = "pathops")]
const CFF2: Tag = Tag::new(b"CFF2");

/// The options of [`remove_overlaps`].
#[derive(Debug, Clone)]
pub struct RemoveOverlapsOptions {
	/// The glyphs to remove overlaps from; by default, all (`glyphNames`).
	pub glyph_names: Option<Vec<String>>,
	/// Drop the hinting of all glyphs, whether or not overlaps are removed from them, as
	/// it would look weird if only some glyphs are left (un)hinted (`removeHinting`).
	pub remove_hinting: bool,
	/// Keep the tricky glyphs unchanged (`ignoreErrors`).
	pub ignore_errors: bool,
	/// Remove the unused subroutines of CFF if any glyphs are modified
	/// (`removeUnusedSubroutines`).
	pub remove_unused_subroutines: bool,
}

impl Default for RemoveOverlapsOptions {
	fn default() -> Self {
		RemoveOverlapsOptions {
			glyph_names: None,
			remove_hinting: true,
			ignore_errors: false,
			remove_unused_subroutines: true,
		}
	}
}

#[cfg(feature = "pathops")]
fn pen_error(e: fontoxide_pens::Error) -> Error {
	Error::from(e)
}

/// A pen collecting a path, with the components decomposed (`pathops.Path.getPen`).
#[cfg(feature = "pathops")]
struct PathPen<'a, 'f> {
	path: BezPath,
	glyph_set: &'a GlyphSet<'f>,
	current: Option<Point>,
	open: bool,
}

#[cfg(feature = "pathops")]
impl<'a, 'f> PathPen<'a, 'f> {
	fn new(glyph_set: &'a GlyphSet<'f>) -> Self {
		PathPen {
			path: BezPath::new(),
			glyph_set,
			current: None,
			open: false,
		}
	}

	fn finish(mut self) -> BezPath {
		if self.open {
			self.path.close_path();
		}
		self.path
	}
}

#[cfg(feature = "pathops")]
impl Pen for PathPen<'_, '_> {
	fn move_to(&mut self, pt: Point) -> fontoxide_pens::Result<()> {
		if self.open {
			self.path.close_path();
		}
		self.path.move_to(pt);
		self.current = Some(pt);
		self.open = true;
		Ok(())
	}

	fn line_to(&mut self, pt: Point) -> fontoxide_pens::Result<()> {
		self.path.line_to(pt);
		self.current = Some(pt);
		Ok(())
	}

	fn curve_to(&mut self, points: &[Point]) -> fontoxide_pens::Result<()> {
		for (a, b, c) in decompose_super_bezier_segment(points)? {
			self.path.curve_to(a, b, c);
			self.current = Some(c);
		}
		Ok(())
	}

	fn q_curve_to(
		&mut self,
		off_curves: &[Point],
		on_curve: Option<Point>,
	) -> fontoxide_pens::Result<()> {
		let mut points = off_curves.to_vec();
		match on_curve {
			Some(p) => points.push(p),
			None => {
				// A contour of off-curve points only: it starts and ends halfway between
				// the last and the first.
				let (Some(&last), Some(&first)) = (off_curves.last(), off_curves.first()) else {
					return Ok(());
				};
				let start = ((last.0 + first.0) * 0.5, (last.1 + first.1) * 0.5);
				self.move_to(start)?;
				points.push(start);
			}
		}
		if points.len() == 1 {
			self.line_to(points[0])?;
			return Ok(());
		}
		for (a, b) in decompose_quadratic_segment(&points)? {
			self.path.quad_to(a, b);
			self.current = Some(b);
		}
		Ok(())
	}

	fn close_path(&mut self) -> fontoxide_pens::Result<()> {
		self.path.close_path();
		self.open = false;
		Ok(())
	}

	fn end_path(&mut self) -> fontoxide_pens::Result<()> {
		// The boolean operations need closed contours.
		self.path.close_path();
		self.open = false;
		Ok(())
	}

	fn add_component(
		&mut self,
		glyph_name: &str,
		transformation: Transform,
	) -> fontoxide_pens::Result<()> {
		let glyph_set = self.glyph_set;
		let mut pen = TransformPen::new(self, transformation);
		glyph_set
			.draw(glyph_name, &mut pen)
			.map_err(|e| fontoxide_pens::Error::MissingComponent(e.to_string()))
	}
}

/// `skPathFromGlyph`.
#[cfg(feature = "pathops")]
fn path_from_glyph(name: &str, glyph_set: &GlyphSet<'_>) -> Result<BezPath> {
	let mut pen = PathPen::new(glyph_set);
	glyph_set.draw(name, &mut pen)?;
	Ok(pen.finish())
}

#[cfg(feature = "pathops")]
fn boolean_error(name: &str) -> Error {
	Error::ttlib(format!(
		"RemoveOverlapsError: Failed to remove overlaps from glyph {name:?}"
	))
}

/// `pathops.simplify(path, clockwise=path.clockwise)`: the contours of the union, with the
/// direction of the outer ones as that of the whole path, and alternating when nested.
#[cfg(feature = "pathops")]
fn simplify(path: &BezPath, name: &str) -> Result<Vec<BezPath>> {
	let contours: Contours = binary_op(path, &BezPath::new(), FillRule::NonZero, BinaryOp::Union)
		.map_err(|_| boolean_error(name))?;
	let clockwise = path.area() < 0.0;
	let mut out = Vec::new();
	for group in contours.grouped() {
		for index in group {
			let contour = &contours[index];
			let mut depth = 0;
			let mut parent = contour.parent;
			while let Some(p) = parent {
				depth += 1;
				parent = contours[p].parent;
			}
			let wants_clockwise = clockwise == (depth % 2 == 0);
			let is_clockwise = contour.path.area() < 0.0;
			out.push(if wants_clockwise == is_clockwise {
				contour.path.clone()
			} else {
				contour.path.reverse_subpaths()
			});
		}
	}
	Ok(out)
}

/// The segments of a contour, as lists of points relative to the start of each, with the
/// numbers that compare equal when they are the same point up to rounding errors.
#[cfg(feature = "pathops")]
fn contour_segments(path: &BezPath) -> Vec<Vec<(i64, i64)>> {
	let quantize = |p: kurbo::Point| ((p.x * 1000.0).round() as i64, (p.y * 1000.0).round() as i64);
	let mut segments = Vec::new();
	let mut start = None;
	let mut current = None;
	for el in path.elements() {
		match *el {
			PathEl::MoveTo(p) => {
				start = Some(p);
				current = Some(p);
			}
			PathEl::LineTo(p) => {
				if let Some(c) = current {
					segments.push(vec![quantize(c), quantize(p)]);
				}
				current = Some(p);
			}
			PathEl::QuadTo(a, p) => {
				if let Some(c) = current {
					segments.push(vec![quantize(c), quantize(a), quantize(p)]);
				}
				current = Some(p);
			}
			PathEl::CurveTo(a, b, p) => {
				if let Some(c) = current {
					segments.push(vec![quantize(c), quantize(a), quantize(b), quantize(p)]);
				}
				current = Some(p);
			}
			PathEl::ClosePath => {
				if let (Some(c), Some(s)) = (current, start)
					&& quantize(c) != quantize(s)
				{
					segments.push(vec![quantize(c), quantize(s)]);
				}
			}
		}
	}
	segments
}

/// A form of a contour that doesn't depend on its start and its direction.
#[cfg(feature = "pathops")]
fn canonical_contour(path: &BezPath) -> Vec<Vec<(i64, i64)>> {
	let forward = contour_segments(path);
	let backward: Vec<Vec<(i64, i64)>> = forward
		.iter()
		.rev()
		.map(|s| s.iter().rev().copied().collect())
		.collect();
	let smallest = |segments: &Vec<Vec<(i64, i64)>>| -> Vec<Vec<(i64, i64)>> {
		(0..segments.len().max(1))
			.map(|i| {
				let mut rotated = segments.clone();
				if !rotated.is_empty() {
					rotated.rotate_left(i);
				}
				rotated
			})
			.min()
			.unwrap_or_default()
	};
	smallest(&forward).min(smallest(&backward))
}

/// The separate contours of a path.
#[cfg(feature = "pathops")]
fn split_contours(path: &BezPath) -> Vec<BezPath> {
	let mut out: Vec<BezPath> = Vec::new();
	for el in path.elements() {
		if matches!(el, PathEl::MoveTo(_)) {
			out.push(BezPath::new());
		}
		if let Some(current) = out.last_mut() {
			current.push(*el);
		}
	}
	out
}

/// `_same_path`: whether the contours are the same, ignoring their order. Unlike with
/// Skia's output, their start and direction are ignored, since those aren't kept.
#[cfg(feature = "pathops")]
fn same_path(path: &BezPath, simplified: &[BezPath]) -> bool {
	let contours = split_contours(path);
	if contours.len() != simplified.len() {
		return false;
	}
	let mut a: Vec<_> = contours.iter().map(canonical_contour).collect();
	let mut b: Vec<_> = simplified.iter().map(canonical_contour).collect();
	a.sort();
	b.sort();
	a == b
}

/// `ttfGlyphFromSkPath`, with the coordinates rounded (`TTGlyphPen`).
#[cfg(feature = "pathops")]
fn glyph_from_contours(contours: &[BezPath]) -> Glyph {
	let round = |p: kurbo::Point| {
		(
			fontoxide_misc::round_tools::ot_round_f64(p.x),
			fontoxide_misc::round_tools::ot_round_f64(p.y),
		)
	};
	let mut coordinates: Vec<(f64, f64)> = Vec::new();
	let mut flags: Vec<u8> = Vec::new();
	let mut end_pts = Vec::new();
	for contour in contours {
		let mut points: Vec<((f64, f64), u8)> = Vec::new();
		for el in contour.elements() {
			match *el {
				PathEl::MoveTo(p) | PathEl::LineTo(p) => points.push((round(p), 1)),
				PathEl::QuadTo(a, p) => {
					points.push((round(a), 0));
					points.push((round(p), 1));
				}
				PathEl::CurveTo(a, b, p) => {
					// Curves stay quadratic in `glyf`, up to the rounding of coordinates.
					let start = points.last().map_or(kurbo::Point::ZERO, |e| e.0.into());
					let cubic = kurbo::CubicBez::new(start, a, b, p);
					for (_, _, quad) in cubic.to_quads(0.1) {
						points.push((round(quad.p1), 0));
						points.push((round(quad.p2), 1));
					}
				}
				PathEl::ClosePath => {}
			}
		}
		// The end of a closed contour is its start.
		if points.len() > 1 && points.first() == points.last() {
			points.pop();
		}
		// Implied on-curve points are dropped, as when drawing the path.
		let n = points.len();
		let keep: Vec<bool> = (0..n)
			.map(|i| {
				let (p, on) = points[i];
				if on == 0 || i == 0 {
					return true;
				}
				let (a, a_on) = points[i - 1];
				let (b, b_on) = points[(i + 1) % n];
				!(a_on == 0 && b_on == 0 && a.0 + b.0 == 2.0 * p.0 && a.1 + b.1 == 2.0 * p.1)
			})
			.collect();
		for (&(p, on), &keep) in points.iter().zip(&keep) {
			if keep {
				coordinates.push(p);
				flags.push(on);
			}
		}
		if !coordinates.is_empty() {
			end_pts.push(coordinates.len() as i64 - 1);
		}
	}
	let mut glyph = Glyph {
		number_of_contours: end_pts.len() as i64,
		end_pts_of_contours: end_pts,
		coordinates,
		flags,
		program: Some(Default::default()),
		..Default::default()
	};
	if let Some(&first) = glyph.coordinates.first() {
		let (mut x_min, mut y_min, mut x_max, mut y_max) = (first.0, first.1, first.0, first.1);
		for &(x, y) in &glyph.coordinates {
			x_min = x_min.min(x);
			y_min = y_min.min(y);
			x_max = x_max.max(x);
			y_max = y_max.max(y);
		}
		glyph.x_min = x_min as i64;
		glyph.y_min = y_min as i64;
		glyph.x_max = x_max as i64;
		glyph.y_max = y_max as i64;
	}
	glyph
}

/// `componentsOverlap`, with the base glyphs drawn from the current state of the font.
#[cfg(feature = "pathops")]
fn components_overlap(glyph: &Glyph, glyph_set: &GlyphSet<'_>, name: &str) -> Result<bool> {
	if glyph.components.len() < 2 {
		return Ok(false); // single component, no overlaps
	}
	let mut paths = Vec::with_capacity(glyph.components.len());
	for component in &glyph.components {
		let (gid, t) = Glyph::component_info(component)?;
		let base = glyph_set.glyph_order().name(gid).into_owned();
		let mut path = path_from_glyph(&base, glyph_set)?;
		path.apply_affine(kurbo::Affine::new([t.xx, t.xy, t.yx, t.yy, t.dx, t.dy]));
		paths.push(path);
	}
	for i in 0..paths.len() {
		for j in i + 1..paths.len() {
			let contours = binary_op(
				&paths[i],
				&paths[j],
				FillRule::NonZero,
				BinaryOp::Intersection,
			)
			.map_err(|_| boolean_error(name))?;
			if contours.contours().next().is_some() {
				return Ok(true);
			}
		}
	}
	Ok(false)
}

/// `_remove_glyf_overlaps`.
#[cfg(feature = "pathops")]
fn remove_glyf_overlaps(
	font: &mut Font,
	names: &[String],
	options: &RemoveOverlapsOptions,
) -> Result<()> {
	let order = font.glyph_order()?;
	// Process all simple glyphs first, then composites with increasing component depth, so
	// that by the time component intersections are tested the base glyphs have already
	// been simplified.
	let mut cache = std::collections::HashMap::new();
	let mut sorted = Vec::with_capacity(names.len());
	{
		let glyf = font.require::<Glyf>()?;
		for name in names {
			let gid = order
				.id(name)
				.ok_or_else(|| Error::GlyphNotFound(name.clone()))?;
			let depth = match glyf.glyphs.get(&gid) {
				Some(g) if g.is_composite() => {
					glyf.composite_maxp_values(gid, &order, 1, &mut cache, &mut vec![gid])?
						.2
				}
				_ => 0,
			};
			sorted.push((depth, name.clone(), gid));
		}
	}
	sorted.sort();
	font.require::<Hmtx>()?;

	let extended = font.require::<Glyf>()?.extended;
	let mut modified = 0;
	for (_, name, gid) in sorted {
		let new_glyph = {
			let glyph_set = GlyphSet::new(font)?;
			let glyf = font_glyf(&glyph_set)?;
			let glyph = glyf
				.glyphs
				.get(&gid)
				.ok_or_else(|| Error::GlyphNotFound(name.clone()))?;
			// Decompose composite glyphs only if components overlap each other.
			let attempt = (|| -> Result<Option<Glyph>> {
				if glyph.number_of_contours > 0
					|| (glyph.is_composite() && components_overlap(glyph, &glyph_set, &name)?)
				{
					let path = path_from_glyph(&name, &glyph_set)?;
					let simplified = simplify(&path, &name)?;
					// Replace the glyph if the simplified path is different.
					if !same_path(&path, &simplified) {
						return Ok(Some(glyph_from_contours(&simplified)));
					}
				}
				Ok(None)
			})();
			match attempt {
				Ok(glyph) => glyph,
				Err(e) => {
					if !options.ignore_errors {
						return Err(e);
					}
					log::error!("Failed to remove overlaps for '{name}'");
					// fontTools leaves the glyph as it is, including its hinting.
					continue;
				}
			}
		};
		match new_glyph {
			Some(glyph) => {
				// Also ensure hmtx LSB == glyph.xMin so the glyph origin is at x=0.
				let x_min = glyph.x_min;
				font.require::<Glyf>()?.glyphs.insert(gid, glyph);
				let hmtx = font.require::<Hmtx>()?;
				let metric = hmtx
					.metrics
					.get_mut(&gid)
					.ok_or_else(|| Error::GlyphNotFound(name.clone()))?;
				if i64::from(metric.1) != x_min {
					metric.1 = crate::binary::fit(x_min, "lsb")?;
				}
				modified += 1;
			}
			None => {
				if options.remove_hinting
					&& let Some(glyph) = font.require::<Glyf>()?.glyphs.get_mut(&gid)
				{
					glyph.trim_ext(true, extended)?;
				}
			}
		}
	}
	log::debug!("Removed overlaps for {modified} glyphs");
	Ok(())
}

/// The `glyf` table of a glyph set, which draws from it.
#[cfg(feature = "pathops")]
fn font_glyf<'a>(glyph_set: &GlyphSet<'a>) -> Result<&'a Glyf> {
	glyph_set
		.glyf_table()
		.ok_or(Error::TableNotFound(Glyf::TAG))
}

/// The program of `T2CharStringPen.getCharString`.
#[cfg(feature = "pathops")]
fn char_string_from_contours(contours: &[BezPath], width: Option<f64>) -> Result<Vec<Token>> {
	let round = |p: kurbo::Point| {
		(
			fontoxide_misc::round_tools::ot_round(p.x),
			fontoxide_misc::round_tools::ot_round(p.y),
		)
	};
	let mut commands = Vec::new();
	let mut p0 = (0, 0);
	let mut relative = |p: kurbo::Point, out: &mut Vec<Arg>| {
		let pt = round(p);
		out.push(Arg::Int(pt.0 - p0.0));
		out.push(Arg::Int(pt.1 - p0.1));
		p0 = pt;
	};
	for contour in contours {
		let mut current = kurbo::Point::ZERO;
		for el in contour.elements() {
			let mut args = Vec::new();
			match *el {
				PathEl::MoveTo(p) => {
					relative(p, &mut args);
					commands.push(Command::new("rmoveto", args));
					current = p;
				}
				PathEl::LineTo(p) => {
					relative(p, &mut args);
					commands.push(Command::new("rlineto", args));
					current = p;
				}
				PathEl::QuadTo(a, p) => {
					// `BasePen._qCurveToOne`.
					let c1 = current + (a - current) * (2.0 / 3.0);
					let c2 = p + (a - p) * (2.0 / 3.0);
					relative(c1, &mut args);
					relative(c2, &mut args);
					relative(p, &mut args);
					commands.push(Command::new("rrcurveto", args));
					current = p;
				}
				PathEl::CurveTo(a, b, p) => {
					relative(a, &mut args);
					relative(b, &mut args);
					relative(p, &mut args);
					commands.push(Command::new("rrcurveto", args));
					current = p;
				}
				PathEl::ClosePath => {}
			}
		}
	}
	let commands = specialize_commands(
		&commands,
		&SpecializeOptions {
			generalize_first: false,
			..Default::default()
		},
	)?;
	let mut program = commands_to_program(&commands)?;
	if let Some(width) = width {
		program.insert(0, Token::Int(fontoxide_misc::round_tools::ot_round(width)));
	}
	program.push(Token::Op("endchar"));
	Ok(program)
}

/// `_remove_cff_overlaps`.
#[cfg(feature = "pathops")]
fn remove_cff_overlaps(
	font: &mut Font,
	names: &[String],
	options: &RemoveOverlapsOptions,
) -> Result<()> {
	// What to do is decided on a copy of the outlines, which the glyph set has.
	let mut new_programs = Vec::new();
	{
		let glyph_set = GlyphSet::new(font)?;
		for name in names {
			let attempt = (|| -> Result<Option<Vec<BezPath>>> {
				let path = path_from_glyph(name, &glyph_set)?;
				let simplified = simplify(&path, name)?;
				Ok((!same_path(&path, &simplified)).then_some(simplified))
			})();
			match attempt {
				Ok(Some(contours)) => new_programs.push((name.clone(), contours)),
				Ok(None) => {}
				Err(e) => {
					if !options.ignore_errors {
						return Err(e);
					}
					log::error!("Failed to remove overlaps for '{name}'");
				}
			}
		}
	}
	if new_programs.is_empty() {
		log::debug!("No overlaps found in the specified CFF glyphs");
		return Ok(());
	}
	let cff: &mut CffFontSet = if font.contains(CFF) {
		&mut font.require::<Cff>()?.cff
	} else {
		&mut font.require::<Cff2>()?.cff
	};
	for (name, contours) in &new_programs {
		let gid = cff
			.glyph_index(name)
			.ok_or_else(|| Error::GlyphNotFound(name.clone()))?;
		// `_charString_from_SkPath`: the width stays in the charstring.
		let (width, default, nominal) = cff.char_string_width(gid)?;
		let width = if width == default {
			None
		} else {
			match (width, nominal) {
				(Some(w), Some(n)) => Some(w - n),
				_ => {
					return Err(Error::ttlib(
						"TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'",
					));
				}
			}
		};
		let program = char_string_from_contours(contours, width)?;
		let top = cff
			.top_dicts
			.first_mut()
			.ok_or_else(|| Error::ttlib("IndexError: list index out of range"))?;
		let char_strings = top
			.char_strings
			.as_mut()
			.ok_or_else(|| Error::ttlib("AttributeError: CharStrings"))?;
		char_strings.items[gid] = T2CharString {
			bytecode: None,
			program,
			fd_select_index: char_strings.items[gid].fd_select_index,
		};
	}
	if options.remove_hinting {
		cff.remove_hints()?;
	}
	if options.remove_unused_subroutines {
		cff.remove_unused_subroutines()?;
	}
	log::debug!("Removed overlaps for {} glyphs", new_programs.len());
	Ok(())
}

/// `removeOverlaps`: simplifies the glyphs of a font by merging overlapping contours.
/// Overlapping components are first decomposed to simple contours, then merged.
///
/// Currently this only works for fonts with `glyf`, `CFF ` or `CFF2` tables. Note that
/// removing overlaps invalidates the hinting.
pub fn remove_overlaps(font: &mut Font, options: &RemoveOverlapsOptions) -> Result<()> {
	#[cfg(not(feature = "pathops"))]
	{
		let _ = (font, options);
		Err(Error::Import("No module named 'pathops'".into()))
	}
	#[cfg(feature = "pathops")]
	{
		let has_glyf = font.has::<Glyf>();
		let has_cff = font.contains(CFF) || font.contains(CFF2);
		if !has_glyf && !has_cff {
			return Err(Error::ttlib(
				"NotImplementedError: No outline data found in the font: missing 'glyf', 'GLYF', 'CFF ', or 'CFF2' table",
			));
		}
		let names = match &options.glyph_names {
			Some(names) => names.clone(),
			None => font.glyph_order()?.names().to_vec(),
		};
		if has_glyf && !has_cff {
			remove_glyf_overlaps(font, &names, options)?;
		} else if has_glyf {
			// The glyph set only draws the CFF outlines of a font with both.
			return Err(Error::ttlib(
				"NotImplementedError: removing overlaps of a font with both glyf and CFF",
			));
		}
		if has_cff {
			remove_cff_overlaps(font, &names, options)?;
		}
		let _ = pen_error;
		Ok(())
	}
}

#[cfg(all(test, feature = "pathops"))]
mod tests {
	use super::*;

	fn square(x: f64, y: f64, size: f64) -> BezPath {
		let mut path = BezPath::new();
		path.move_to((x, y));
		path.line_to((x, y + size));
		path.line_to((x + size, y + size));
		path.line_to((x + size, y));
		path.close_path();
		path
	}

	#[test]
	fn merged_squares() -> Result<()> {
		let mut path = square(0.0, 0.0, 100.0);
		path.extend(square(50.0, 0.0, 100.0));
		let simplified = simplify(&path, "a")?;
		assert_eq!(simplified.len(), 1);
		let glyph = glyph_from_contours(&simplified);
		assert_eq!(glyph.number_of_contours, 1);
		assert_eq!(
			(glyph.x_min, glyph.y_min, glyph.x_max, glyph.y_max),
			(0, 0, 150, 100)
		);
		assert!(!same_path(&path, &simplified));
		Ok(())
	}

	#[test]
	fn keeps_what_has_no_overlaps() -> Result<()> {
		// A square with a hole, in opposite directions.
		let mut path = square(0.0, 0.0, 100.0);
		let hole = square(25.0, 25.0, 50.0).reverse_subpaths();
		path.extend(hole);
		let simplified = simplify(&path, "a")?;
		assert_eq!(simplified.len(), 2);
		assert!(same_path(&path, &simplified));
		// Clockwise outside, the other way around for the hole.
		assert!(path.area() < 0.0);
		assert!(simplified[0].area() < 0.0);
		assert!(simplified[1].area() > 0.0);
		Ok(())
	}

	#[test]
	fn all_off_curve_points() {
		let order = crate::GlyphOrder::default();
		let _ = order;
		let mut path = BezPath::new();
		path.move_to((0.0, 0.0));
		path.quad_to((50.0, 100.0), (100.0, 0.0));
		path.close_path();
		let glyph = glyph_from_contours(&[path]);
		assert_eq!(glyph.flags, vec![1, 0, 1]);
	}
}

const HELP: &str = "\
usage: fonttools ttLib.removeOverlaps [-h] [--keep-hinting] [--ignore-errors]
                                      [--keep-unused-subroutines]
                                      INPUT.ttf OUTPUT.ttf [GLYPHS ...]

Simplify TrueType glyphs by merging overlapping contours/components. Requires
https://github.com/fonttools/skia-pathops

positional arguments:
  INPUT.ttf             Input font file
  OUTPUT.ttf            Output font file
  GLYPHS                Optional list of glyph names to remove overlaps from

options:
  -h, --help            show this help message and exit
  --keep-hinting        Keep hinting for unmodified glyphs, default is to drop
                        hinting
  --ignore-errors       ignore errors while removing overlaps, thus keeping
                        the tricky glyphs unchanged
  --keep-unused-subroutines
                        Keep unused subroutines in CFF table after removing
                        overlaps, default is to remove them if any glyphs are
                        modified
";

const COMMAND: Parser = Parser {
	prog: "fonttools ttLib.removeOverlaps",
	module: "ttLib.removeOverlaps",
	help: HELP,
	arguments: &[
		Argument::help(),
		Argument::positional("INPUT.ttf"),
		Argument::positional("OUTPUT.ttf"),
		Argument::positional("GLYPHS").nargs(Nargs::ZeroOrMore),
		Argument::flag(&["--keep-hinting"]),
		Argument::flag(&["--ignore-errors"]),
		Argument::flag(&["--keep-unused-subroutines"]),
	],
	required_groups: &[],
};

/// `fontTools.ttLib.removeOverlaps.main`: removes the overlaps of the glyphs of
/// a font file. Returns the exit code.
///
/// Without the `pathops` feature, it fails with [`Error::Import`] before
/// parsing the arguments, as importing the module does without skia-pathops.
pub fn main(args: &[&str]) -> Result<i32> {
	run(
		args,
		&mut std::io::stdout().lock(),
		&mut std::io::stderr().lock(),
	)
}

/// [`main`], writing to `out` and `err`.
pub fn run(args: &[&str], out: &mut dyn Write, err: &mut dyn Write) -> Result<i32> {
	if cfg!(not(feature = "pathops")) {
		return Err(Error::Import("No module named 'pathops'".into()));
	}
	let options = match COMMAND.parse_args(args, out, err)? {
		Ok(options) => options,
		Err(code) => return Ok(code),
	};
	let input = options.str("INPUT.ttf").unwrap_or_default();
	let output = options.str("OUTPUT.ttf").unwrap_or_default();
	let glyphs = options.list("GLYPHS");
	let mut font = Font::read(std::fs::read(input)?, ReadOptions::default())?;
	remove_overlaps(
		&mut font,
		&RemoveOverlapsOptions {
			glyph_names: (!glyphs.is_empty()).then(|| glyphs.to_vec()),
			remove_hinting: !options.flag("--keep-hinting"),
			ignore_errors: options.flag("--ignore-errors"),
			remove_unused_subroutines: !options.flag("--keep-unused-subroutines"),
		},
	)?;
	std::fs::write(output, font.write(&WriteOptions::default())?)?;
	Ok(0)
}