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
use crate::{
	ImtError, ImtErrorSrc, ImtErrorTy, ImtLang, ImtParsedGlyph, ImtParser, ImtPosition,
	ImtScript,
};
use allsorts::gpos::Placement;
use std::sync::Arc;

#[derive(Clone, Debug, PartialEq)]
pub enum ImtVertAlign {
	Top,
	Bottom,
	Center,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ImtHoriAlign {
	Left,
	Right,
	Center,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ImtTextWrap {
	Shift,
	NewLine,
	None,
	NoneDotted,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ImtShapeOpts {
	pub body_width: f32,
	pub body_height: f32,
	pub text_height: f32,
	pub line_spacing: f32,
	pub text_wrap: ImtTextWrap,
	pub vert_align: ImtVertAlign,
	pub hori_align: ImtHoriAlign,
	pub align_whole_pixels: bool,
}

impl Default for ImtShapeOpts {
	fn default() -> Self {
		ImtShapeOpts {
			body_width: 0.0,
			body_height: 0.0,
			text_height: 36.0,
			line_spacing: 0.0,
			text_wrap: ImtTextWrap::None,
			vert_align: ImtVertAlign::Top,
			hori_align: ImtHoriAlign::Left,
			align_whole_pixels: true,
		}
	}
}

#[derive(Clone, Debug)]
pub struct ImtGlyphInfo {
	pub font_family: String,
	pub text_height: f32,
	pub word_index: usize,
	pub line_index: usize,
	pub pos_from_l: Option<f32>,
	pub pos_from_r: Option<f32>,
	pub pos_from_t: Option<f32>,
	pub pos_from_b: Option<f32>,
}

pub struct ImtShapedGlyph {
	pub parsed: Arc<ImtParsedGlyph>,
	pub position: ImtPosition,
	pub x_overflow: f32,
	pub y_overflow: f32,
}

pub struct ImtShaper {}

impl ImtShaper {
	pub fn new() -> Result<Self, ImtError> {
		Ok(ImtShaper {})
	}

	pub fn shape_parsed_glyphs(
		&self,
		parser: &ImtParser,
		script: ImtScript,
		lang: ImtLang,
		opts: ImtShapeOpts,
		glyphs: Vec<Arc<ImtParsedGlyph>>,
	) -> Result<Vec<ImtShapedGlyph>, ImtError> {
		let font_props = parser.font_props();
		let mut imt_shaped_glyphs: Vec<ImtShapedGlyph> = Vec::new();
		let mut raw_glyphs = Vec::new();

		for parsed_glyph in glyphs {
			raw_glyphs.push(parsed_glyph.inner.clone());

			imt_shaped_glyphs.push(ImtShapedGlyph {
				parsed: parsed_glyph,
				position: ImtPosition {
					x: 0.0,
					y: 0.0,
				},
				y_overflow: 0.0,
				x_overflow: 0.0,
			});
		}

		let mut shape_from = 0;
		let mut y = 0.0;
		let line_spacing = ((opts.text_height / 18.0).floor() + opts.line_spacing)
			/ (font_props.scaler * opts.text_height);
		let mut vert_adv = font_props.line_gap + font_props.ascender + line_spacing;

		if opts.align_whole_pixels {
			vert_adv = vert_adv.ceil();
		}

		let mut lines: Vec<(usize, usize, f32)> = Vec::new();

		'line: loop {
			let infos =
				parser.retreive_info(raw_glyphs[shape_from..].to_vec(), script, lang)?;

			let mut x: f32 = 0.0;
			let mut x_offset = 0.0;
			let mut line_max_x = 0.0;
			let infos_len = infos.len();

			for (i, info) in infos.into_iter().enumerate() {
				if *info.glyph.unicodes.first().unwrap() == '\n' {
					if shape_from + i >= raw_glyphs.len() {
						break 'line;
					} else {
						if i == 0 {
							lines.push((shape_from, shape_from, line_max_x));
						} else {
							lines.push((shape_from, shape_from + i, line_max_x));
						}

						y += vert_adv;
						shape_from = shape_from + i + 1;
						continue 'line;
					}
				}

				if x == 0.0 {
					x_offset = imt_shaped_glyphs[i].parsed.min_x;
				}

				let (glyph_x, glyph_y) = match info.placement {
					Placement::Distance(dist_x, dist_y) => {
						let dist_x = dist_x as f32;
						let dist_y = dist_y as f32;
						(x + dist_x, y + dist_y)
					},
					Placement::Anchor(..) | Placement::None => (x, y),
				};

				let lmaxx = glyph_x + x_offset + imt_shaped_glyphs[i + shape_from].parsed.max_x;

				if let &ImtTextWrap::NewLine = &opts.text_wrap {
					if lmaxx * font_props.scaler * opts.text_height > opts.body_width {
						if x == 0.0 {
							return Err(ImtError::src_and_ty(
								ImtErrorSrc::Shaper,
								ImtErrorTy::Other(format!("Body width too small.")),
							));
						}

						lines.push((shape_from, i + shape_from, line_max_x));
						shape_from += i;
						y += vert_adv;
						continue 'line;
					}
				}

				line_max_x = lmaxx;

				imt_shaped_glyphs[shape_from + i].position = if opts.align_whole_pixels {
					ImtPosition {
						x: (glyph_x + x_offset).ceil(),
						y: glyph_y.ceil(),
					}
				} else {
					ImtPosition {
						x: glyph_x + x_offset,
						y: glyph_y,
					}
				};

				x += if opts.align_whole_pixels {
					imt_shaped_glyphs[shape_from + i].parsed.hori_adv.ceil()
				} else {
					imt_shaped_glyphs[shape_from + i].parsed.hori_adv
				};
			}

			lines.push((shape_from, shape_from + infos_len, line_max_x));
			break 'line;
		}

		// -- Shift Wrapping -- //

		if let &ImtTextWrap::Shift = &opts.text_wrap {
			let mut remove_glyphs = Vec::new();
			let mut i_adjust = 0;

			for (start, end, width) in &mut lines {
				if start != end {
					let shift =
						(opts.body_width / (font_props.scaler * opts.text_height)) - *width;
					let mut new_start = None;

					for i in *start..*end {
						if new_start.is_none() {
							if imt_shaped_glyphs[i].position.x > shift {
								new_start = Some(i);
								imt_shaped_glyphs[i].position.x -= shift;
							} else {
								remove_glyphs.push(i);
							}
						} else {
							imt_shaped_glyphs[i].position.x -= shift;
						}
					}

					if let Some(new_start) = new_start {
						let start_diff = new_start - *start;
						*start = new_start - i_adjust;
						*end = *end - i_adjust;
						*width -= shift;
						i_adjust += start_diff;
					}
				}
			}

			for (i, g) in imt_shaped_glyphs.split_off(0).into_iter().enumerate() {
				if !remove_glyphs.contains(&i) {
					imt_shaped_glyphs.push(g);
				}
			}
		}

		// -- Calculate Overflows -- //
		// TODO: Adjust line width?

		{
			let mut remove_glyphs = Vec::new();
			let mut i_adjust = 0;
			let body_width_fu = opts.body_width / (opts.text_height * font_props.scaler);
			let body_height_fu = opts.body_height / (opts.text_height * font_props.scaler);

			for (start, end, _width) in &mut lines {
				if start != end {
					let mut removed = 0;
					let mut new_start = None;
					let mut len = 0;

					for i in *start..*end {
						let glyph = &mut imt_shaped_glyphs[i];
						let mut remove = false;
						let width = glyph.parsed.max_x - glyph.parsed.min_x;
						let min_x = glyph.position.x + glyph.parsed.min_x;
						let max_x = min_x + width;

						if max_x > body_width_fu {
							if min_x > body_width_fu {
								remove = true;
								removed += 1;
							} else {
								glyph.x_overflow = max_x - body_width_fu;
							}
						}

						let height = glyph.parsed.max_y - glyph.parsed.min_y;
						let bearing_y = font_props.ascender - glyph.parsed.max_y;
						let min_y = glyph.position.y + bearing_y;
						let max_y = min_y + height;

						if max_y > body_height_fu {
							if min_y > body_height_fu {
								remove = true;
								removed += 1;
							} else {
								glyph.y_overflow = max_y - body_height_fu;
							}
						}

						if remove {
							remove_glyphs.push(i);
						} else {
							if new_start.is_none() {
								new_start = Some(i);
							}

							len += 1;
						}
					}

					if let Some(new_start) = new_start {
						*start = new_start - i_adjust;
					}

					*end = *start + len;
					i_adjust += removed;
				}
			}

			for (i, g) in imt_shaped_glyphs.split_off(0).into_iter().enumerate() {
				if !remove_glyphs.contains(&i) {
					imt_shaped_glyphs.push(g);
				}
			}
		}

		// -- Horizontal Alignment -- //

		let hori_align_scaler = match &opts.hori_align {
			&ImtHoriAlign::Left => 0.0,
			&ImtHoriAlign::Right => 1.0,
			&ImtHoriAlign::Center => 0.5,
		};

		if hori_align_scaler != 0.0 {
			for (start, end, width) in &lines {
				if start != end {
					let space_px =
						opts.body_width - (*width * font_props.scaler * opts.text_height);
					let space_font_units = space_px / (font_props.scaler * opts.text_height);
					let shift = space_font_units * hori_align_scaler;

					for i in *start..*end {
						imt_shaped_glyphs[i].position.x += shift;
					}
				}
			}
		}

		// Remove New Line Characters
		imt_shaped_glyphs.retain(|g| g.parsed.inner.unicodes[0] != '\n');
		Ok(imt_shaped_glyphs)
	}
}