text.rs 7.0 KB

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