text.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. use freetype as ft;
  2. use crate::gfx::{Rectangle, FreetypeFace};
  3. #[derive(Clone)]
  4. pub struct Glyph {
  5. // Substring this glyph corresponds to
  6. pub substr: String,
  7. // The texture
  8. pub bmp: Vec<u8>,
  9. pub bmp_width: u16,
  10. pub bmp_height: u16,
  11. pub pos: Rectangle<f32>,
  12. }
  13. pub struct TextShaper {
  14. pub font_faces: Vec<FreetypeFace>,
  15. }
  16. unsafe impl Send for TextShaper {}
  17. unsafe impl Sync for TextShaper {}
  18. impl TextShaper {
  19. fn split_into_substrs(&self, text: String) -> Vec<(usize, String)> {
  20. let mut current_idx = 0;
  21. let mut current_str = String::new();
  22. let mut substrs = vec![];
  23. 'next_char: for chr in text.chars() {
  24. let idx = 'get_idx: {
  25. for i in 0..self.font_faces.len() {
  26. let ft_face = &self.font_faces[i];
  27. if ft_face.get_char_index(chr as usize).is_some() {
  28. break 'get_idx i
  29. }
  30. }
  31. warn!("no font fallback for char: '{}'", chr);
  32. // Skip this char
  33. continue 'next_char
  34. };
  35. if current_idx != idx {
  36. if !current_str.is_empty() {
  37. // Push
  38. substrs.push((current_idx, current_str.clone()));
  39. }
  40. current_str.clear();
  41. current_idx = idx;
  42. }
  43. current_str.push(chr);
  44. }
  45. if !current_str.is_empty() {
  46. // Push
  47. substrs.push((current_idx, current_str));
  48. }
  49. substrs
  50. }
  51. pub fn shape(&self, text: String, font_size: f32, text_color: [f32; 4]) -> Vec<Glyph> {
  52. let substrs = self.split_into_substrs(text.clone());
  53. let mut glyphs: Vec<Glyph> = vec![];
  54. let mut current_x = 0.;
  55. let mut current_y = 0.;
  56. for (face_idx, text) in substrs {
  57. let face = &self.font_faces[face_idx];
  58. if face.has_fixed_sizes() {
  59. // emojis required a fixed size
  60. //face.set_char_size(109 * 64, 0, 72, 72).unwrap();
  61. face.select_size(0).unwrap();
  62. } else {
  63. face.set_char_size(font_size as isize * 64, 0, 72, 72).unwrap();
  64. }
  65. let hb_font = harfbuzz_rs::Font::from_freetype_face(face.clone());
  66. let buffer = harfbuzz_rs::UnicodeBuffer::new()
  67. .set_cluster_level(harfbuzz_rs::ClusterLevel::MonotoneCharacters)
  68. .add_str(&text);
  69. let output = harfbuzz_rs::shape(&hb_font, buffer, &[]);
  70. let positions = output.get_glyph_positions();
  71. let infos = output.get_glyph_infos();
  72. let mut prev_cluster = 0;
  73. for (i, (position, info)) in positions.iter().zip(infos).enumerate() {
  74. let gid = info.codepoint;
  75. // Index within this substr
  76. let curr_cluster = info.cluster as usize;
  77. // Skip first time
  78. if i != 0 {
  79. let substr = text[prev_cluster..curr_cluster].to_string();
  80. glyphs.last_mut().unwrap().substr = substr;
  81. }
  82. prev_cluster = curr_cluster;
  83. let mut flags = ft::face::LoadFlag::DEFAULT;
  84. if face.has_color() {
  85. flags |= ft::face::LoadFlag::COLOR;
  86. }
  87. face.load_glyph(gid, flags).unwrap();
  88. let glyph = face.glyph();
  89. glyph.render_glyph(ft::RenderMode::Normal).unwrap();
  90. let bmp = glyph.bitmap();
  91. let buffer = bmp.buffer();
  92. let bmp_width = bmp.width() as usize;
  93. let bmp_height = bmp.rows() as usize;
  94. let bearing_x = glyph.bitmap_left() as f32;
  95. let bearing_y = glyph.bitmap_top() as f32;
  96. let pixel_mode = bmp.pixel_mode().unwrap();
  97. let bmp = match pixel_mode {
  98. ft::bitmap::PixelMode::Bgra => {
  99. let mut tdata = vec![];
  100. tdata.resize(4 * bmp_width * bmp_height, 0);
  101. // Convert from BGRA to RGBA
  102. for i in 0..bmp_width*bmp_height {
  103. let idx = i*4;
  104. let b = buffer[idx];
  105. let g = buffer[idx + 1];
  106. let r = buffer[idx + 2];
  107. let a = buffer[idx + 3];
  108. tdata[idx] = r;
  109. tdata[idx + 1] = g;
  110. tdata[idx + 2] = b;
  111. tdata[idx + 3] = a;
  112. }
  113. tdata
  114. }
  115. ft::bitmap::PixelMode::Gray => {
  116. // Convert from greyscale to RGBA8
  117. let tdata: Vec<_> = buffer
  118. .iter()
  119. .flat_map(|coverage| {
  120. let r = (255. * text_color[0]) as u8;
  121. let g = (255. * text_color[1]) as u8;
  122. let b = (255. * text_color[2]) as u8;
  123. let α = ((*coverage as f32) * text_color[3]) as u8;
  124. vec![r, g, b, α]
  125. })
  126. .collect();
  127. tdata
  128. }
  129. _ => panic!("unsupport pixel mode: {:?}", pixel_mode)
  130. };
  131. let pos = if face.has_fixed_sizes() {
  132. // Downscale by height
  133. let w = (bmp_width as f32 * font_size) / bmp_height as f32;
  134. let h = font_size;
  135. let x = current_x;
  136. let y = current_y - h;
  137. current_x += w;
  138. Rectangle {
  139. x, y, w, h
  140. }
  141. } else {
  142. let (w, h) = (bmp_width as f32, bmp_height as f32);
  143. let off_x = position.x_offset as f32 / 64.;
  144. let off_y = position.y_offset as f32 / 64.;
  145. let x = current_x + off_x + bearing_x;
  146. let y = current_y - off_y - bearing_y;
  147. let x_advance = position.x_advance as f32 / 64.;
  148. let y_advance = position.y_advance as f32 / 64.;
  149. current_x += x_advance;
  150. current_y += y_advance;
  151. Rectangle {
  152. x, y, w, h
  153. }
  154. };
  155. let glyph = Glyph {
  156. substr: String::new(),
  157. bmp,
  158. bmp_width: bmp_width as u16,
  159. bmp_height: bmp_height as u16,
  160. pos
  161. };
  162. glyphs.push(glyph);
  163. }
  164. let substr = text[prev_cluster..].to_string();
  165. glyphs.last_mut().unwrap().substr = substr;
  166. }
  167. glyphs
  168. }
  169. }