text.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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. prop::{
  26. BatchGuardPtr, PropertyAtomicGuard, PropertyBool, PropertyColor, PropertyFloat32,
  27. PropertyRect, PropertyStr, PropertyUint32, Role,
  28. },
  29. scene::{Pimpl, SceneNodeWeak},
  30. text2::{self, TEXT_CTX},
  31. util::{i18n::I18nBabelFish, unixtime},
  32. ExecutorPtr,
  33. };
  34. use super::{DrawUpdate, OnModify, UIObject};
  35. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::text", $($arg)*); } }
  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. t!("Text::new()");
  63. let node_ref = &node.upgrade().unwrap();
  64. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  65. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  66. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  67. let text = PropertyStr::wrap(node_ref, Role::Internal, "text", 0).unwrap();
  68. let font_size = PropertyFloat32::wrap(node_ref, Role::Internal, "font_size", 0).unwrap();
  69. let text_color = PropertyColor::wrap(node_ref, Role::Internal, "text_color").unwrap();
  70. let lineheight = PropertyFloat32::wrap(node_ref, Role::Internal, "lineheight", 0).unwrap();
  71. let use_i18n = PropertyBool::wrap(node_ref, Role::Internal, "use_i18n", 0).unwrap();
  72. let debug = PropertyBool::wrap(node_ref, Role::Internal, "debug", 0).unwrap();
  73. let self_ = Arc::new(Self {
  74. node,
  75. render_api,
  76. i18n_fish,
  77. tasks: SyncMutex::new(vec![]),
  78. dc_key: OsRng.gen(),
  79. rect,
  80. z_index,
  81. priority,
  82. text,
  83. font_size,
  84. text_color,
  85. lineheight,
  86. use_i18n,
  87. debug,
  88. window_scale,
  89. parent_rect: SyncMutex::new(None),
  90. });
  91. Pimpl::Text(self_)
  92. }
  93. async fn regen_mesh(&self) -> Vec<DrawInstruction> {
  94. let text = self.text.get();
  95. let font_size = self.font_size.get();
  96. let lineheight = self.lineheight.get();
  97. let text_color = self.text_color.get();
  98. let window_scale = self.window_scale.get();
  99. let text = if self.use_i18n.get() {
  100. if let Some(trans) = self.i18n_fish.tr(&text) {
  101. //t!("Translate '{text}' to '{trans}'");
  102. trans
  103. } else {
  104. format!("tr err: {}", text)
  105. }
  106. } else {
  107. text
  108. };
  109. let layout = {
  110. let mut txt_ctx = TEXT_CTX.get().await;
  111. txt_ctx.make_layout(&text, text_color, font_size, lineheight, window_scale, None, &[])
  112. };
  113. let mut debug_opts = text2::DebugRenderOptions::OFF;
  114. if self.debug.get() {
  115. debug_opts |= text2::DebugRenderOptions::BASELINE;
  116. }
  117. text2::render_layout_with_opts(&layout, debug_opts, &self.render_api, gfxtag!("text"))
  118. }
  119. #[instrument(target = "ui::text")]
  120. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  121. let timest = unixtime();
  122. let Some(parent_rect) = self.parent_rect.lock().clone() else { return };
  123. let atom = &mut batch.spawn();
  124. let Some(draw_update) = self.get_draw_calls(atom, parent_rect).await else {
  125. error!(target: "ui::text", "Text failed to draw");
  126. return
  127. };
  128. self.render_api.replace_draw_calls(batch.id, timest, draw_update.draw_calls);
  129. }
  130. async fn get_draw_calls(
  131. &self,
  132. atom: &mut PropertyAtomicGuard,
  133. parent_rect: Rectangle,
  134. ) -> Option<DrawUpdate> {
  135. self.rect.eval(atom, &parent_rect).ok()?;
  136. let rect = self.rect.get();
  137. let mut instrs = vec![DrawInstruction::Move(rect.pos())];
  138. instrs.append(&mut self.regen_mesh().await);
  139. Some(DrawUpdate {
  140. key: self.dc_key,
  141. draw_calls: vec![(
  142. self.dc_key,
  143. DrawCall::new(instrs, vec![], self.z_index.get(), "text"),
  144. )],
  145. })
  146. }
  147. }
  148. #[async_trait]
  149. impl UIObject for Text {
  150. fn priority(&self) -> u32 {
  151. self.priority.get()
  152. }
  153. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  154. let me = Arc::downgrade(&self);
  155. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  156. on_modify.when_change(self.rect.prop(), Self::redraw);
  157. on_modify.when_change(self.z_index.prop(), Self::redraw);
  158. on_modify.when_change(self.text.prop(), Self::redraw);
  159. on_modify.when_change(self.font_size.prop(), Self::redraw);
  160. on_modify.when_change(self.text_color.prop(), Self::redraw);
  161. on_modify.when_change(self.debug.prop(), Self::redraw);
  162. *self.tasks.lock() = on_modify.tasks;
  163. }
  164. fn stop(&self) {
  165. self.tasks.lock().clear();
  166. *self.parent_rect.lock() = None;
  167. }
  168. #[instrument(target = "ui::text")]
  169. async fn draw(
  170. &self,
  171. parent_rect: Rectangle,
  172. atom: &mut PropertyAtomicGuard,
  173. ) -> Option<DrawUpdate> {
  174. *self.parent_rect.lock() = Some(parent_rect);
  175. self.get_draw_calls(atom, parent_rect).await
  176. }
  177. fn set_i18n(&self, i18n_fish: &I18nBabelFish) {
  178. self.i18n_fish.set(i18n_fish);
  179. }
  180. }
  181. impl Drop for Text {
  182. fn drop(&mut self) {
  183. let atom = self.render_api.make_guard(gfxtag!("Text::drop"));
  184. self.render_api.replace_draw_calls(
  185. atom.batch_id,
  186. unixtime(),
  187. vec![(self.dc_key, Default::default())],
  188. );
  189. }
  190. }
  191. impl std::fmt::Debug for Text {
  192. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  193. write!(f, "{:?}", self.node.upgrade().unwrap())
  194. }
  195. }