text.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 crate::{
  23. gfx::{gfxtag, DrawCall, DrawInstruction, Rectangle, RenderApi},
  24. prop::{
  25. BatchGuardPtr, PropertyAtomicGuard, PropertyBool, PropertyColor, PropertyFloat32,
  26. PropertyRect, PropertyStr, PropertyUint32, Role,
  27. },
  28. scene::{Pimpl, SceneNodeWeak},
  29. text2::{self, TEXT_CTX},
  30. util::{i18n::I18nBabelFish, unixtime},
  31. ExecutorPtr,
  32. };
  33. use super::{DrawTrace, DrawUpdate, OnModify, UIObject};
  34. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::text", $($arg)*); } }
  35. pub type TextPtr = Arc<Text>;
  36. pub struct Text {
  37. node: SceneNodeWeak,
  38. render_api: RenderApi,
  39. i18n_fish: I18nBabelFish,
  40. tasks: SyncMutex<Vec<smol::Task<()>>>,
  41. dc_key: u64,
  42. rect: PropertyRect,
  43. z_index: PropertyUint32,
  44. priority: PropertyUint32,
  45. text: PropertyStr,
  46. font_size: PropertyFloat32,
  47. text_color: PropertyColor,
  48. lineheight: PropertyFloat32,
  49. use_i18n: PropertyBool,
  50. debug: PropertyBool,
  51. window_scale: PropertyFloat32,
  52. parent_rect: SyncMutex<Option<Rectangle>>,
  53. }
  54. impl Text {
  55. pub async fn new(
  56. node: SceneNodeWeak,
  57. window_scale: PropertyFloat32,
  58. render_api: RenderApi,
  59. i18n_fish: I18nBabelFish,
  60. ) -> Pimpl {
  61. t!("Text::new()");
  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. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  119. let trace: DrawTrace = rand::random();
  120. let timest = unixtime();
  121. t!("Text::redraw({:?}) [trace={trace}]", self.node.upgrade().unwrap());
  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 [trace={trace}]");
  126. return
  127. };
  128. self.render_api.replace_draw_calls(batch.id, timest, draw_update.draw_calls);
  129. t!("Text::redraw() DONE [trace={trace}]");
  130. }
  131. async fn get_draw_calls(
  132. &self,
  133. atom: &mut PropertyAtomicGuard,
  134. parent_rect: Rectangle,
  135. ) -> Option<DrawUpdate> {
  136. self.rect.eval(atom, &parent_rect).ok()?;
  137. let rect = self.rect.get();
  138. let mut instrs = vec![DrawInstruction::Move(rect.pos())];
  139. instrs.append(&mut self.regen_mesh().await);
  140. Some(DrawUpdate {
  141. key: self.dc_key,
  142. draw_calls: vec![(
  143. self.dc_key,
  144. DrawCall::new(instrs, vec![], self.z_index.get(), "text"),
  145. )],
  146. })
  147. }
  148. }
  149. #[async_trait]
  150. impl UIObject for Text {
  151. fn priority(&self) -> u32 {
  152. self.priority.get()
  153. }
  154. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  155. let me = Arc::downgrade(&self);
  156. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  157. on_modify.when_change(self.rect.prop(), Self::redraw);
  158. on_modify.when_change(self.z_index.prop(), Self::redraw);
  159. on_modify.when_change(self.text.prop(), Self::redraw);
  160. on_modify.when_change(self.font_size.prop(), Self::redraw);
  161. on_modify.when_change(self.text_color.prop(), Self::redraw);
  162. on_modify.when_change(self.debug.prop(), Self::redraw);
  163. *self.tasks.lock() = on_modify.tasks;
  164. }
  165. fn stop(&self) {
  166. self.tasks.lock().clear();
  167. *self.parent_rect.lock() = None;
  168. }
  169. async fn draw(
  170. &self,
  171. parent_rect: Rectangle,
  172. trace: DrawTrace,
  173. atom: &mut PropertyAtomicGuard,
  174. ) -> Option<DrawUpdate> {
  175. t!("Text::draw({:?}) [trace={trace}]", self.node.upgrade().unwrap());
  176. *self.parent_rect.lock() = Some(parent_rect);
  177. self.get_draw_calls(atom, parent_rect).await
  178. }
  179. fn set_i18n(&self, i18n_fish: &I18nBabelFish) {
  180. self.i18n_fish.set(i18n_fish);
  181. }
  182. }
  183. impl Drop for Text {
  184. fn drop(&mut self) {
  185. let atom = self.render_api.make_guard(gfxtag!("Text::drop"));
  186. self.render_api.replace_draw_calls(
  187. atom.batch_id,
  188. unixtime(),
  189. vec![(self.dc_key, Default::default())],
  190. );
  191. }
  192. }