text.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_trait::async_trait;
  19. use parking_lot::Mutex as SyncMutex;
  20. use rand::{rngs::OsRng, Rng};
  21. use std::sync::Arc;
  22. use tracing::instrument;
  23. use crate::{
  24. gfx::{gfxtag, DrawCall, DrawInstruction, Rectangle, RenderApi, Renderer},
  25. mesh::{Color, MeshBuilder},
  26. prop::{
  27. BatchGuardPtr, PropertyAtomicGuard, PropertyBool, PropertyColor, PropertyEnum,
  28. PropertyFloat32, PropertyRect, PropertyStr, PropertyUint32, Role,
  29. },
  30. scene::{Pimpl, SceneNodeWeak},
  31. text,
  32. util::i18n::I18nBabelFish,
  33. ExecutorPtr,
  34. };
  35. use super::{DrawUpdate, OnModify, UIObject};
  36. pub type TextPtr = Arc<Text>;
  37. pub struct Text {
  38. node: SceneNodeWeak,
  39. renderer: Renderer,
  40. i18n_fish: I18nBabelFish,
  41. tasks: SyncMutex<Vec<smol::Task<()>>>,
  42. dc_key: u64,
  43. rect: PropertyRect,
  44. height: PropertyFloat32,
  45. z_index: PropertyUint32,
  46. priority: PropertyUint32,
  47. text: PropertyStr,
  48. font_size: PropertyFloat32,
  49. text_color: PropertyColor,
  50. lineheight: PropertyFloat32,
  51. text_align: PropertyEnum,
  52. overflow_wrap: PropertyEnum,
  53. use_i18n: PropertyBool,
  54. debug: PropertyBool,
  55. window_scale: PropertyFloat32,
  56. parent_rect: SyncMutex<Option<Rectangle>>,
  57. }
  58. impl Text {
  59. pub async fn new(
  60. node: SceneNodeWeak,
  61. window_scale: PropertyFloat32,
  62. renderer: Renderer,
  63. i18n_fish: I18nBabelFish,
  64. ) -> Pimpl {
  65. let node_ref = &node.upgrade().unwrap();
  66. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  67. let height = PropertyFloat32::wrap(node_ref, Role::Internal, "height", 0).unwrap();
  68. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  69. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  70. let text = PropertyStr::wrap(node_ref, Role::Internal, "text", 0).unwrap();
  71. let font_size = PropertyFloat32::wrap(node_ref, Role::Internal, "font_size", 0).unwrap();
  72. let text_color = PropertyColor::wrap(node_ref, Role::Internal, "text_color").unwrap();
  73. let lineheight = PropertyFloat32::wrap(node_ref, Role::Internal, "lineheight", 0).unwrap();
  74. let text_align = PropertyEnum::wrap(node_ref, Role::Internal, "text_align", 0).unwrap();
  75. let overflow_wrap =
  76. PropertyEnum::wrap(node_ref, Role::Internal, "overflow_wrap", 0).unwrap();
  77. let use_i18n = PropertyBool::wrap(node_ref, Role::Internal, "use_i18n", 0).unwrap();
  78. let debug = PropertyBool::wrap(node_ref, Role::Internal, "debug", 0).unwrap();
  79. let self_ = Arc::new(Self {
  80. node,
  81. renderer,
  82. i18n_fish,
  83. tasks: SyncMutex::new(vec![]),
  84. dc_key: OsRng.gen(),
  85. rect,
  86. height,
  87. z_index,
  88. priority,
  89. text,
  90. font_size,
  91. text_color,
  92. lineheight,
  93. text_align,
  94. overflow_wrap,
  95. use_i18n,
  96. debug,
  97. window_scale,
  98. parent_rect: SyncMutex::new(None),
  99. });
  100. Pimpl::Text(self_)
  101. }
  102. fn make_layout(&self) -> parley::Layout<Color> {
  103. let text = self.text.get();
  104. let font_size = self.font_size.get();
  105. let lineheight = self.lineheight.get();
  106. let text_color = self.text_color.get();
  107. let window_scale = self.window_scale.get();
  108. let width = self.rect.get_width();
  109. let text_align = self.text_align.get();
  110. let overflow_wrap = self.overflow_wrap.get();
  111. let text = if self.use_i18n.get() {
  112. if let Some(trans) = self.i18n_fish.tr(&text) {
  113. //t!("Translate '{text}' to '{trans}'");
  114. trans
  115. } else {
  116. format!("tr err: {}", text)
  117. }
  118. } else {
  119. text
  120. };
  121. text::make_layout2(
  122. &text,
  123. text_color,
  124. font_size,
  125. lineheight,
  126. window_scale,
  127. Some(width),
  128. &[],
  129. &[],
  130. &text_align,
  131. &overflow_wrap,
  132. )
  133. }
  134. fn regen_mesh(&self, layout: &parley::Layout<Color>) -> Vec<DrawInstruction> {
  135. let mut debug_opts = text::DebugRenderOptions::OFF;
  136. if self.debug.get() {
  137. debug_opts |= text::DebugRenderOptions::BASELINE;
  138. }
  139. text::render_layout_with_opts(layout, debug_opts, &self.renderer, gfxtag!("text"))
  140. }
  141. #[instrument(target = "ui::text")]
  142. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  143. let Some(parent_rect) = self.parent_rect.lock().clone() else {
  144. warn!(target: "ui:text", "Skip draw since parent rect is empty");
  145. return
  146. };
  147. let atom = &mut batch.spawn();
  148. let Some(draw_update) = self.get_draw_calls(atom, parent_rect) else {
  149. error!(target: "ui::text", "Text failed to draw");
  150. return
  151. };
  152. self.renderer.replace_draw_calls(Some(batch.id), draw_update.draw_calls);
  153. }
  154. fn get_draw_calls(
  155. &self,
  156. atom: &mut PropertyAtomicGuard,
  157. parent_rect: Rectangle,
  158. ) -> Option<DrawUpdate> {
  159. self.rect.eval(atom, &parent_rect).ok()?;
  160. let rect = self.rect.get();
  161. let layout = self.make_layout();
  162. self.height.set(atom, layout.height());
  163. let mut instrs = vec![DrawInstruction::Move(rect.pos())];
  164. instrs.append(&mut self.regen_mesh(&layout));
  165. if self.debug.get() {
  166. let rect = self.rect.get().with_zero_pos();
  167. let mut mesh = MeshBuilder::new(gfxtag!("text_debug-rect"));
  168. mesh.draw_outline(&rect, [0., 1., 0., 0.7], 1.);
  169. let mesh = mesh.alloc(&self.renderer).draw_untextured();
  170. instrs.push(DrawInstruction::Draw(mesh));
  171. }
  172. Some(DrawUpdate {
  173. key: self.dc_key,
  174. draw_calls: vec![(
  175. self.dc_key,
  176. DrawCall::new(instrs, vec![], self.z_index.get(), "text"),
  177. )],
  178. })
  179. }
  180. }
  181. #[async_trait]
  182. impl UIObject for Text {
  183. fn priority(&self) -> u32 {
  184. self.priority.get()
  185. }
  186. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  187. let me = Arc::downgrade(&self);
  188. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  189. on_modify.when_change(self.rect.prop(), Self::redraw);
  190. on_modify.when_change(self.z_index.prop(), Self::redraw);
  191. on_modify.when_change(self.text.prop(), Self::redraw);
  192. on_modify.when_change(self.text_align.prop(), Self::redraw);
  193. on_modify.when_change(self.font_size.prop(), Self::redraw);
  194. on_modify.when_change(self.text_color.prop(), Self::redraw);
  195. on_modify.when_change(self.debug.prop(), Self::redraw);
  196. *self.tasks.lock() = on_modify.tasks;
  197. }
  198. fn stop(&self) {
  199. self.tasks.lock().clear();
  200. *self.parent_rect.lock() = None;
  201. }
  202. #[instrument(target = "ui::text")]
  203. async fn draw(
  204. &self,
  205. parent_rect: Rectangle,
  206. atom: &mut PropertyAtomicGuard,
  207. ) -> Option<DrawUpdate> {
  208. *self.parent_rect.lock() = Some(parent_rect);
  209. self.get_draw_calls(atom, parent_rect)
  210. }
  211. fn set_i18n(&self, i18n_fish: &I18nBabelFish) {
  212. self.i18n_fish.set(i18n_fish);
  213. }
  214. }
  215. impl Drop for Text {
  216. fn drop(&mut self) {
  217. let atom = self.renderer.make_guard(gfxtag!("Text::drop"));
  218. self.renderer
  219. .replace_draw_calls(Some(atom.batch_id), vec![(self.dc_key, Default::default())]);
  220. }
  221. }
  222. impl std::fmt::Debug for Text {
  223. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  224. write!(f, "{:?}", self.node.upgrade().unwrap())
  225. }
  226. }