text.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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},
  25. mesh::MeshBuilder,
  26. prop::{
  27. BatchGuardPtr, PropertyAtomicGuard, PropertyBool, PropertyColor, PropertyFloat32,
  28. 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. render_api: RenderApi,
  40. i18n_fish: I18nBabelFish,
  41. tasks: SyncMutex<Vec<smol::Task<()>>>,
  42. dc_key: u64,
  43. rect: PropertyRect,
  44. z_index: PropertyUint32,
  45. priority: PropertyUint32,
  46. text: PropertyStr,
  47. font_size: PropertyFloat32,
  48. text_color: PropertyColor,
  49. lineheight: PropertyFloat32,
  50. use_i18n: PropertyBool,
  51. debug: PropertyBool,
  52. window_scale: PropertyFloat32,
  53. parent_rect: SyncMutex<Option<Rectangle>>,
  54. }
  55. impl Text {
  56. pub async fn new(
  57. node: SceneNodeWeak,
  58. window_scale: PropertyFloat32,
  59. render_api: RenderApi,
  60. i18n_fish: I18nBabelFish,
  61. ) -> Pimpl {
  62. let node_ref = &node.upgrade().unwrap();
  63. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  64. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  65. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  66. let text = PropertyStr::wrap(node_ref, Role::Internal, "text", 0).unwrap();
  67. let font_size = PropertyFloat32::wrap(node_ref, Role::Internal, "font_size", 0).unwrap();
  68. let text_color = PropertyColor::wrap(node_ref, Role::Internal, "text_color").unwrap();
  69. let lineheight = PropertyFloat32::wrap(node_ref, Role::Internal, "lineheight", 0).unwrap();
  70. let use_i18n = PropertyBool::wrap(node_ref, Role::Internal, "use_i18n", 0).unwrap();
  71. let debug = PropertyBool::wrap(node_ref, Role::Internal, "debug", 0).unwrap();
  72. let self_ = Arc::new(Self {
  73. node,
  74. render_api,
  75. i18n_fish,
  76. tasks: SyncMutex::new(vec![]),
  77. dc_key: OsRng.gen(),
  78. rect,
  79. z_index,
  80. priority,
  81. text,
  82. font_size,
  83. text_color,
  84. lineheight,
  85. use_i18n,
  86. debug,
  87. window_scale,
  88. parent_rect: SyncMutex::new(None),
  89. });
  90. Pimpl::Text(self_)
  91. }
  92. fn regen_mesh(&self) -> Vec<DrawInstruction> {
  93. let text = self.text.get();
  94. let font_size = self.font_size.get();
  95. let lineheight = self.lineheight.get();
  96. let text_color = self.text_color.get();
  97. let window_scale = self.window_scale.get();
  98. let text = if self.use_i18n.get() {
  99. if let Some(trans) = self.i18n_fish.tr(&text) {
  100. //t!("Translate '{text}' to '{trans}'");
  101. trans
  102. } else {
  103. format!("tr err: {}", text)
  104. }
  105. } else {
  106. text
  107. };
  108. let layout =
  109. text::make_layout(&text, text_color, font_size, lineheight, window_scale, None, &[]);
  110. let mut debug_opts = text::DebugRenderOptions::OFF;
  111. if self.debug.get() {
  112. debug_opts |= text::DebugRenderOptions::BASELINE;
  113. }
  114. text::render_layout_with_opts(&layout, debug_opts, &self.render_api, gfxtag!("text"))
  115. }
  116. #[instrument(target = "ui::text")]
  117. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  118. let Some(parent_rect) = self.parent_rect.lock().clone() else { return };
  119. let atom = &mut batch.spawn();
  120. let Some(draw_update) = self.get_draw_calls(atom, parent_rect).await else {
  121. error!(target: "ui::text", "Text failed to draw");
  122. return
  123. };
  124. self.render_api.replace_draw_calls(batch.id, draw_update.draw_calls);
  125. }
  126. async fn get_draw_calls(
  127. &self,
  128. atom: &mut PropertyAtomicGuard,
  129. parent_rect: Rectangle,
  130. ) -> Option<DrawUpdate> {
  131. self.rect.eval(atom, &parent_rect).ok()?;
  132. let rect = self.rect.get();
  133. let mut instrs = vec![DrawInstruction::Move(rect.pos())];
  134. instrs.append(&mut self.regen_mesh());
  135. if self.debug.get() {
  136. let rect = self.rect.get().with_zero_pos();
  137. let mut mesh = MeshBuilder::new(gfxtag!("text_debug-rect"));
  138. mesh.draw_outline(&rect, [0., 1., 0., 0.7], 1.);
  139. let mesh = mesh.alloc(&self.render_api).draw_untextured();
  140. instrs.push(DrawInstruction::Draw(mesh));
  141. }
  142. Some(DrawUpdate {
  143. key: self.dc_key,
  144. draw_calls: vec![(
  145. self.dc_key,
  146. DrawCall::new(instrs, vec![], self.z_index.get(), "text"),
  147. )],
  148. })
  149. }
  150. }
  151. #[async_trait]
  152. impl UIObject for Text {
  153. fn priority(&self) -> u32 {
  154. self.priority.get()
  155. }
  156. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  157. let me = Arc::downgrade(&self);
  158. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  159. on_modify.when_change(self.rect.prop(), Self::redraw);
  160. on_modify.when_change(self.z_index.prop(), Self::redraw);
  161. on_modify.when_change(self.text.prop(), Self::redraw);
  162. on_modify.when_change(self.font_size.prop(), Self::redraw);
  163. on_modify.when_change(self.text_color.prop(), Self::redraw);
  164. on_modify.when_change(self.debug.prop(), Self::redraw);
  165. *self.tasks.lock() = on_modify.tasks;
  166. }
  167. fn stop(&self) {
  168. self.tasks.lock().clear();
  169. *self.parent_rect.lock() = None;
  170. }
  171. #[instrument(target = "ui::text")]
  172. async fn draw(
  173. &self,
  174. parent_rect: Rectangle,
  175. atom: &mut PropertyAtomicGuard,
  176. ) -> Option<DrawUpdate> {
  177. *self.parent_rect.lock() = Some(parent_rect);
  178. self.get_draw_calls(atom, parent_rect).await
  179. }
  180. fn set_i18n(&self, i18n_fish: &I18nBabelFish) {
  181. self.i18n_fish.set(i18n_fish);
  182. }
  183. }
  184. impl Drop for Text {
  185. fn drop(&mut self) {
  186. let atom = self.render_api.make_guard(gfxtag!("Text::drop"));
  187. self.render_api.replace_draw_calls(atom.batch_id, vec![(self.dc_key, Default::default())]);
  188. }
  189. }
  190. impl std::fmt::Debug for Text {
  191. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  192. write!(f, "{:?}", self.node.upgrade().unwrap())
  193. }
  194. }