1use crate::font_features::{
15 FONT_FEATURE_LEN, FONT_FEATURE_TAG_AT, FONT_FEATURE_VALUE_AT, FontFeature, MAX_FONT_FEATURES,
16};
17use crate::fonts::{FONT_REF_LEN, FontRefs};
18use crate::schema::{Paint, TypeRole};
19use std::rc::Rc;
20
21pub const SPAN_LEN: usize = 36;
25
26pub const SPAN_START_AT: usize = 0;
29pub const SPAN_LENGTH_AT: usize = 4;
30pub const SPAN_ROLE_AT: usize = 8;
31pub const SPAN_FLAGS_AT: usize = 10;
32pub const SPAN_COLOR_AT: usize = 12;
33pub const SPAN_BACKGROUND_AT: usize = 20;
34pub const SPAN_HANDLER_AT: usize = 28;
35
36pub const SPAN_FONT_ENTRY_LEN: usize = 12;
42pub const SPAN_FONT_SPAN_AT: usize = 0;
43pub const SPAN_FONT_OFFSET_AT: usize = 4;
44pub const SPAN_FONT_COUNT_AT: usize = 8;
45
46pub const SPAN_FEATURE_ENTRY_LEN: usize = 12;
55pub const SPAN_FEATURE_SPAN_AT: usize = 0;
56pub const SPAN_FEATURE_OFFSET_AT: usize = 4;
57pub const SPAN_FEATURE_COUNT_AT: usize = 8;
58
59pub const FLAG_BOLD: u16 = 1;
60pub const FLAG_ITALIC: u16 = 2;
61pub const FLAG_UNDERLINE: u16 = 4;
62pub const FLAG_STRIKETHROUGH: u16 = 8;
63
64#[derive(Clone, Copy, Debug, Default, PartialEq)]
69pub struct TextSpan {
70 pub start: u32,
71 pub length: u32,
72 pub type_role: Option<TypeRole>,
73 pub color: Option<Paint>,
74 pub background: Option<Paint>,
82 pub bold: bool,
83 pub italic: bool,
84 pub underline: bool,
85 pub strikethrough: bool,
86 pub on_click: Option<u64>,
88}
89
90impl TextSpan {
91 pub const fn new(start: u32, length: u32) -> Self {
93 Self {
94 start,
95 length,
96 type_role: None,
97 color: None,
98 background: None,
99 bold: false,
100 italic: false,
101 underline: false,
102 strikethrough: false,
103 on_click: None,
104 }
105 }
106
107 pub const fn bold(mut self) -> Self {
108 self.bold = true;
109 self
110 }
111
112 pub const fn italic(mut self) -> Self {
113 self.italic = true;
114 self
115 }
116
117 pub const fn underline(mut self) -> Self {
118 self.underline = true;
119 self
120 }
121
122 pub const fn strikethrough(mut self) -> Self {
123 self.strikethrough = true;
124 self
125 }
126
127 pub const fn with_role(mut self, role: TypeRole) -> Self {
128 self.type_role = Some(role);
129 self
130 }
131
132 pub const fn with_color(mut self, color: Paint) -> Self {
133 self.color = Some(color);
134 self
135 }
136
137 pub const fn with_background(mut self, background: Paint) -> Self {
140 self.background = Some(background);
141 self
142 }
143
144 fn flags(&self) -> u16 {
145 let mut flags = 0;
146 if self.bold {
147 flags |= FLAG_BOLD;
148 }
149 if self.italic {
150 flags |= FLAG_ITALIC;
151 }
152 if self.underline {
153 flags |= FLAG_UNDERLINE;
154 }
155 if self.strikethrough {
156 flags |= FLAG_STRIKETHROUGH;
157 }
158 flags
159 }
160
161 fn write_into(&self, out: &mut Vec<u8>) {
162 out.extend_from_slice(&self.start.to_le_bytes());
163 out.extend_from_slice(&self.length.to_le_bytes());
164 out.extend_from_slice(&self.type_role.map_or(0, u16::from).to_le_bytes());
165 out.extend_from_slice(&self.flags().to_le_bytes());
166 let paint = self.color.map_or(0, Paint::to_bits);
169 out.extend_from_slice(&(paint as u32).to_le_bytes());
170 out.extend_from_slice(&((paint >> 32) as u32).to_le_bytes());
171 let background = self.background.map_or(0, Paint::to_bits);
172 out.extend_from_slice(&(background as u32).to_le_bytes());
173 out.extend_from_slice(&((background >> 32) as u32).to_le_bytes());
174 let handler = self.on_click.unwrap_or(0);
175 out.extend_from_slice(&(handler as u32).to_le_bytes());
176 out.extend_from_slice(&((handler >> 32) as u32).to_le_bytes());
177 }
178}
179
180type Marked = (&'static [u8], fn(u32, u32) -> TextSpan);
183
184#[derive(Clone, Default, PartialEq)]
189pub struct TextSpans {
190 bytes: Option<Rc<[u8]>>,
191 fonts: Option<Rc<[u8]>>,
193 features: Option<Rc<[u8]>>,
196}
197
198impl std::fmt::Debug for TextSpans {
199 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 formatter
201 .debug_struct("TextSpans")
202 .field("spans", &(self.as_bytes().len() / SPAN_LEN))
203 .field("fonts", &self.font_entry_count())
204 .field("features", &self.feature_entry_count())
205 .finish()
206 }
207}
208
209impl TextSpans {
210 pub fn new(spans: impl IntoIterator<Item = TextSpan>) -> Self {
211 let mut bytes = Vec::new();
212 for span in spans {
213 span.write_into(&mut bytes);
214 }
215 Self::from_bytes(bytes)
216 }
217
218 pub fn new_with_fonts(spans: impl IntoIterator<Item = (TextSpan, FontRefs)>) -> Self {
223 let mut bytes = Vec::new();
224 let mut named: Vec<(u32, FontRefs)> = Vec::new();
225 for (index, (span, fonts)) in spans.into_iter().enumerate() {
226 span.write_into(&mut bytes);
227 if !fonts.is_empty() {
228 named.push((index as u32, fonts));
229 }
230 }
231 let mut spans = Self::from_bytes(bytes);
232 spans.fonts = encode_font_table(&named);
233 spans
234 }
235
236 pub fn new_with_features(
246 spans: impl IntoIterator<Item = (TextSpan, impl AsRef<[FontFeature]>)>,
247 ) -> Self {
248 let mut bytes = Vec::new();
249 let mut named: Vec<(u32, Vec<FontFeature>)> = Vec::new();
250 for (index, (span, features)) in spans.into_iter().enumerate() {
251 span.write_into(&mut bytes);
252 let slice = features.as_ref();
253 if !slice.is_empty() {
254 named.push((index as u32, slice.to_vec()));
255 }
256 }
257 let mut spans = Self::from_bytes(bytes);
258 spans.features = encode_feature_table(&named);
259 spans
260 }
261
262 pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
264 let bytes = bytes.into();
265 Self {
266 bytes: (!bytes.is_empty()).then_some(bytes),
267 fonts: None,
268 features: None,
269 }
270 }
271
272 pub fn with_font_table(mut self, table: impl Into<Rc<[u8]>>) -> Self {
274 let table = table.into();
275 self.fonts = (!table.is_empty()).then_some(table);
276 self
277 }
278
279 pub fn with_feature_table(mut self, table: impl Into<Rc<[u8]>>) -> Self {
282 let table = table.into();
283 self.features = (!table.is_empty()).then_some(table);
284 self
285 }
286
287 pub fn as_bytes(&self) -> &[u8] {
288 self.bytes.as_deref().unwrap_or(&[])
289 }
290
291 pub fn font_table(&self) -> &[u8] {
294 self.fonts.as_deref().unwrap_or(&[])
295 }
296
297 pub fn feature_table(&self) -> &[u8] {
301 self.features.as_deref().unwrap_or(&[])
302 }
303
304 pub(crate) fn shared_feature_table(&self) -> Option<Rc<[u8]>> {
306 self.features.clone()
307 }
308
309 pub fn is_empty(&self) -> bool {
310 self.bytes.is_none()
311 }
312
313 pub fn font_entry_count(&self) -> usize {
315 let table = self.font_table();
316 if table.len() < 4 {
317 return 0;
318 }
319 u32::from_le_bytes([table[0], table[1], table[2], table[3]]) as usize
320 }
321
322 pub fn span_fonts(&self) -> Vec<(u32, Vec<crate::fonts::FontRef>)> {
324 let table = self.font_table();
325 let word = |at: usize| -> Option<u32> {
326 let slice = table.get(at..at + 4)?;
327 Some(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
328 };
329 (0..self.font_entry_count())
330 .filter_map(|entry| {
331 let at = 4 + entry * SPAN_FONT_ENTRY_LEN;
332 let span = word(at + SPAN_FONT_SPAN_AT)?;
333 let offset = word(at + SPAN_FONT_OFFSET_AT)? as usize;
334 let count = word(at + SPAN_FONT_COUNT_AT)? as usize;
335 let refs = (0..count)
336 .filter_map(|index| {
337 crate::fonts::decode_record(table, offset + index * FONT_REF_LEN)
338 })
339 .collect();
340 Some((span, refs))
341 })
342 .collect()
343 }
344
345 pub fn feature_entry_count(&self) -> usize {
347 let table = self.feature_table();
348 if table.len() < 4 {
349 return 0;
350 }
351 u32::from_le_bytes([table[0], table[1], table[2], table[3]]) as usize
352 }
353
354 pub fn span_features(&self) -> Vec<(u32, Vec<FontFeature>)> {
363 decode_feature_table(self.feature_table()).unwrap_or_default()
364 }
365
366 pub fn spans(&self) -> impl Iterator<Item = TextSpan> + '_ {
368 self.as_bytes().chunks_exact(SPAN_LEN).map(|record| {
369 let word = |at: usize| {
370 u32::from_le_bytes([record[at], record[at + 1], record[at + 2], record[at + 3]])
371 };
372 let half = |at: usize| u16::from_le_bytes([record[at], record[at + 1]]);
373 let flags = half(SPAN_FLAGS_AT);
374 let paint = u64::from(word(SPAN_COLOR_AT)) | (u64::from(word(SPAN_COLOR_AT + 4)) << 32);
375 let background = u64::from(word(SPAN_BACKGROUND_AT))
376 | (u64::from(word(SPAN_BACKGROUND_AT + 4)) << 32);
377 let handler =
378 u64::from(word(SPAN_HANDLER_AT)) | (u64::from(word(SPAN_HANDLER_AT + 4)) << 32);
379 TextSpan {
380 start: word(SPAN_START_AT),
381 length: word(SPAN_LENGTH_AT),
382 type_role: TypeRole::try_from(half(SPAN_ROLE_AT)).ok(),
383 color: Paint::from_bits(paint),
384 background: Paint::from_bits(background),
385 bold: flags & FLAG_BOLD != 0,
386 italic: flags & FLAG_ITALIC != 0,
387 underline: flags & FLAG_UNDERLINE != 0,
388 strikethrough: flags & FLAG_STRIKETHROUGH != 0,
389 on_click: (handler != 0).then_some(handler),
390 }
391 })
392 }
393
394 pub fn from_markdown(source: &str) -> (String, Self) {
403 let mut text = String::with_capacity(source.len());
404 let mut spans = Vec::new();
405 let bytes = source.as_bytes();
406 let mut at = 0;
407 while at < bytes.len() {
408 let (marker, span_of): Marked = if bytes[at..].starts_with(b"**") {
409 (b"**", |start, length| TextSpan::new(start, length).bold())
410 } else if bytes[at] == b'*' {
411 (b"*", |start, length| TextSpan::new(start, length).italic())
412 } else if bytes[at] == b'`' {
413 (b"`", |start, length| {
414 TextSpan::new(start, length).with_role(TypeRole::Mono)
415 })
416 } else {
417 text.push(source[at..].chars().next().expect("a char boundary"));
418 at += source[at..].chars().next().map_or(1, char::len_utf8);
419 continue;
420 };
421 let body = at + marker.len();
422 let Some(end) = find(&bytes[body..], marker).map(|offset| body + offset) else {
423 text.push_str(&source[at..body]);
425 at = body;
426 continue;
427 };
428 let start = text.len() as u32;
429 text.push_str(&source[body..end]);
430 spans.push(span_of(start, text.len() as u32 - start));
431 at = end + marker.len();
432 }
433 (text, Self::new(spans))
434 }
435}
436
437fn encode_font_table(named: &[(u32, FontRefs)]) -> Option<Rc<[u8]>> {
440 if named.is_empty() {
441 return None;
442 }
443 let mut entries = Vec::with_capacity(named.len() * SPAN_FONT_ENTRY_LEN);
444 let mut lists: Vec<u8> = Vec::new();
445 let lists_at = 4 + named.len() * SPAN_FONT_ENTRY_LEN;
446 for (span, fonts) in named {
447 let offset = (lists_at + lists.len()) as u32;
448 let count = fonts.len() as u32;
449 entries.extend_from_slice(&span.to_le_bytes());
450 entries.extend_from_slice(&offset.to_le_bytes());
451 entries.extend_from_slice(&count.to_le_bytes());
452 let names_at = offset + count * FONT_REF_LEN as u32;
453 fonts.write_relocated(&mut lists, names_at);
454 }
455 let mut table = Vec::with_capacity(lists_at + lists.len());
456 table.extend_from_slice(&(named.len() as u32).to_le_bytes());
457 table.extend_from_slice(&entries);
458 table.extend_from_slice(&lists);
459 Some(table.into())
460}
461
462pub fn encode_feature_table(named: &[(u32, Vec<FontFeature>)]) -> Option<Rc<[u8]>> {
471 let entry_count = named
472 .iter()
473 .filter(|(_, features)| !features.is_empty())
474 .count();
475 if entry_count == 0 {
476 return None;
477 }
478 let lists_at = 4 + entry_count * SPAN_FEATURE_ENTRY_LEN;
479 let mut entries = Vec::with_capacity(entry_count * SPAN_FEATURE_ENTRY_LEN);
480 let mut lists: Vec<u8> = Vec::new();
481 for (span, features) in named {
482 if features.is_empty() {
483 continue;
484 }
485 let offset = (lists_at + lists.len()) as u32;
486 let count = features.len() as u32;
487 entries.extend_from_slice(&span.to_le_bytes());
488 entries.extend_from_slice(&offset.to_le_bytes());
489 entries.extend_from_slice(&count.to_le_bytes());
490 for feature in features {
491 lists.extend_from_slice(&feature.to_bytes());
492 }
493 }
494 let mut table = Vec::with_capacity(lists_at + lists.len());
495 table.extend_from_slice(&(entry_count as u32).to_le_bytes());
496 table.extend_from_slice(&entries);
497 table.extend_from_slice(&lists);
498 Some(table.into())
499}
500
501fn decode_feature_table(table: &[u8]) -> Option<Vec<(u32, Vec<FontFeature>)>> {
504 if table.is_empty() {
505 return Some(Vec::new());
506 }
507 let word = |at: usize| -> Option<u32> {
508 let bytes = table.get(at..at.checked_add(4)?)?;
509 Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
510 };
511 let entry_count = word(0)? as usize;
512 let entries_end = entry_count
515 .checked_mul(SPAN_FEATURE_ENTRY_LEN)?
516 .checked_add(4)?;
517 if entries_end > table.len() {
518 return None;
519 }
520 let mut decoded: Vec<(u32, Vec<FontFeature>)> = Vec::with_capacity(entry_count);
521 for entry in 0..entry_count {
522 let at = 4 + entry * SPAN_FEATURE_ENTRY_LEN;
523 let span = word(at + SPAN_FEATURE_SPAN_AT)?;
524 let offset = word(at + SPAN_FEATURE_OFFSET_AT)? as usize;
525 let count = word(at + SPAN_FEATURE_COUNT_AT)? as usize;
526 if count > MAX_FONT_FEATURES || offset % 4 != 0 || offset < entries_end {
527 return None;
528 }
529 let end = offset.checked_add(count * FONT_FEATURE_LEN)?;
530 if end > table.len() || decoded.iter().any(|(seen, _)| *seen == span) {
531 return None;
532 }
533 let features = table[offset..end]
534 .chunks_exact(FONT_FEATURE_LEN)
535 .map(|record| {
536 let tag_at = FONT_FEATURE_TAG_AT;
537 let value_at = FONT_FEATURE_VALUE_AT;
538 FontFeature::new(
539 &[
540 record[tag_at],
541 record[tag_at + 1],
542 record[tag_at + 2],
543 record[tag_at + 3],
544 ],
545 u32::from_le_bytes([
546 record[value_at],
547 record[value_at + 1],
548 record[value_at + 2],
549 record[value_at + 3],
550 ]),
551 )
552 })
553 .collect();
554 decoded.push((span, features));
555 }
556 Some(decoded)
557}
558
559fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
560 haystack
561 .windows(needle.len())
562 .position(|window| window == needle)
563}