text.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. 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,
  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. 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. async 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. let mut txt_ctx = TEXT_CTX.get().await;
  110. txt_ctx.make_layout(&text, text_color, font_size, lineheight, window_scale, None, &[])
  111. };
  112. let mut debug_opts = text2::DebugRenderOptions::OFF;
  113. if self.debug.get() {
  114. debug_opts |= text2::DebugRenderOptions::BASELINE;
  115. }
  116. text2::render_layout_with_opts(&layout, debug_opts, &self.render_api, gfxtag!("text"))
  117. }
  118. #[instrument(target = "ui::text")]
  119. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  120. let Some(parent_rect) = self.parent_rect.lock().clone() else { return };
  121. let atom = &mut batch.spawn();
  122. let Some(draw_update) = self.get_draw_calls(atom, parent_rect).await else {
  123. error!(target: "ui::text", "Text failed to draw");
  124. return
  125. };
  126. self.render_api.replace_draw_calls(batch.id, draw_update.draw_calls);
  127. }
  128. async fn get_draw_calls(
  129. &self,
  130. atom: &mut PropertyAtomicGuard,
  131. parent_rect: Rectangle,
  132. ) -> Option<DrawUpdate> {
  133. self.rect.eval(atom, &parent_rect).ok()?;
  134. let rect = self.rect.get();
  135. let mut instrs = vec![DrawInstruction::Move(rect.pos())];
  136. instrs.append(&mut self.regen_mesh().await);
  137. Some(DrawUpdate {
  138. key: self.dc_key,
  139. draw_calls: vec![(
  140. self.dc_key,
  141. DrawCall::new(instrs, vec![], self.z_index.get(), "text"),
  142. )],
  143. })
  144. }
  145. }
  146. #[async_trait]
  147. impl UIObject for Text {
  148. fn priority(&self) -> u32 {
  149. self.priority.get()
  150. }
  151. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  152. let me = Arc::downgrade(&self);
  153. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  154. on_modify.when_change(self.rect.prop(), Self::redraw);
  155. on_modify.when_change(self.z_index.prop(), Self::redraw);
  156. on_modify.when_change(self.text.prop(), Self::redraw);
  157. on_modify.when_change(self.font_size.prop(), Self::redraw);
  158. on_modify.when_change(self.text_color.prop(), Self::redraw);
  159. on_modify.when_change(self.debug.prop(), Self::redraw);
  160. *self.tasks.lock() = on_modify.tasks;
  161. }
  162. fn stop(&self) {
  163. self.tasks.lock().clear();
  164. *self.parent_rect.lock() = None;
  165. }
  166. #[instrument(target = "ui::text")]
  167. async fn draw(
  168. &self,
  169. parent_rect: Rectangle,
  170. atom: &mut PropertyAtomicGuard,
  171. ) -> Option<DrawUpdate> {
  172. *self.parent_rect.lock() = Some(parent_rect);
  173. self.get_draw_calls(atom, parent_rect).await
  174. }
  175. fn set_i18n(&self, i18n_fish: &I18nBabelFish) {
  176. self.i18n_fish.set(i18n_fish);
  177. }
  178. }
  179. impl Drop for Text {
  180. fn drop(&mut self) {
  181. let atom = self.render_api.make_guard(gfxtag!("Text::drop"));
  182. self.render_api.replace_draw_calls(atom.batch_id, vec![(self.dc_key, Default::default())]);
  183. }
  184. }
  185. impl std::fmt::Debug for Text {
  186. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  187. write!(f, "{:?}", self.node.upgrade().unwrap())
  188. }
  189. }