text.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 rand::{rngs::OsRng, Rng};
  20. use std::sync::{Arc, Mutex as SyncMutex, OnceLock, Weak};
  21. use crate::{
  22. gfx::{
  23. GfxDrawCall, GfxDrawInstruction, GfxDrawMesh, GfxTextureId, ManagedTexturePtr, Rectangle,
  24. RenderApi,
  25. },
  26. mesh::{Color, MeshBuilder, MeshInfo, COLOR_BLUE, COLOR_RED, COLOR_WHITE},
  27. prop::{
  28. PropertyAtomicGuard, PropertyBool, PropertyColor, PropertyFloat32, PropertyPtr,
  29. PropertyRect, PropertyStr, PropertyUint32, Role,
  30. },
  31. scene::{Pimpl, SceneNodePtr, SceneNodeWeak},
  32. text::{self, GlyphPositionIter, TextShaper, TextShaperPtr},
  33. text2,
  34. util::unixtime,
  35. ExecutorPtr,
  36. };
  37. use super::{DrawUpdate, OnModify, UIObject};
  38. macro_rules! d { ($($arg:tt)*) => { debug!(target: "ui::text", $($arg)*); } }
  39. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::text", $($arg)*); } }
  40. pub type TextPtr = Arc<Text>;
  41. #[derive(Clone)]
  42. struct TextRenderInfo {
  43. mesh: MeshInfo,
  44. texture: ManagedTexturePtr,
  45. }
  46. pub struct Text {
  47. node: SceneNodeWeak,
  48. render_api: RenderApi,
  49. text_shaper: TextShaperPtr,
  50. tasks: OnceLock<Vec<smol::Task<()>>>,
  51. dc_key: u64,
  52. rect: PropertyRect,
  53. z_index: PropertyUint32,
  54. priority: PropertyUint32,
  55. text: PropertyStr,
  56. font_size: PropertyFloat32,
  57. text_color: PropertyColor,
  58. baseline: PropertyFloat32,
  59. debug: PropertyBool,
  60. window_scale: PropertyFloat32,
  61. parent_rect: SyncMutex<Option<Rectangle>>,
  62. }
  63. impl Text {
  64. pub async fn new(
  65. node: SceneNodeWeak,
  66. window_scale: PropertyFloat32,
  67. render_api: RenderApi,
  68. text_shaper: TextShaperPtr,
  69. ex: ExecutorPtr,
  70. ) -> Pimpl {
  71. t!("Text::new()");
  72. let node_ref = &node.upgrade().unwrap();
  73. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  74. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  75. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  76. let text = PropertyStr::wrap(node_ref, Role::Internal, "text", 0).unwrap();
  77. let font_size = PropertyFloat32::wrap(node_ref, Role::Internal, "font_size", 0).unwrap();
  78. let text_color = PropertyColor::wrap(node_ref, Role::Internal, "text_color").unwrap();
  79. let baseline = PropertyFloat32::wrap(node_ref, Role::Internal, "baseline", 0).unwrap();
  80. let debug = PropertyBool::wrap(node_ref, Role::Internal, "debug", 0).unwrap();
  81. let node_name = node_ref.name.clone();
  82. let node_id = node_ref.id;
  83. let self_ = Arc::new(Self {
  84. node,
  85. render_api,
  86. text_shaper,
  87. tasks: OnceLock::new(),
  88. dc_key: OsRng.gen(),
  89. rect,
  90. z_index,
  91. priority,
  92. text,
  93. font_size,
  94. text_color,
  95. baseline,
  96. debug,
  97. window_scale,
  98. parent_rect: SyncMutex::new(None),
  99. });
  100. Pimpl::Text(self_)
  101. }
  102. async fn regen_mesh(&self) -> Vec<GfxDrawInstruction> {
  103. let text = self.text.get();
  104. let font_size = self.font_size.get();
  105. let text_color = self.text_color.get();
  106. let window_scale = self.window_scale.get();
  107. let layout = {
  108. let mut txt_ctx = text2::get_ctx().await;
  109. txt_ctx.make_layout(&text, text_color, font_size, 0., window_scale, None)
  110. };
  111. text2::render_layout(&layout, &self.render_api)
  112. }
  113. async fn redraw(self: Arc<Self>) {
  114. let trace_id = rand::random();
  115. let timest = unixtime();
  116. t!("Text::redraw({:?}) [trace_id={trace_id}]", self.node.upgrade().unwrap());
  117. let Some(parent_rect) = self.parent_rect.lock().unwrap().clone() else { return };
  118. let Some(draw_update) = self.get_draw_calls(parent_rect, trace_id).await else {
  119. error!(target: "ui::text", "Text failed to draw [trace_id={trace_id}]");
  120. return;
  121. };
  122. self.render_api.replace_draw_calls(timest, draw_update.draw_calls);
  123. t!("Text::redraw() DONE [trace_id={trace_id}]");
  124. }
  125. async fn get_draw_calls(&self, parent_rect: Rectangle, trace_id: u32) -> Option<DrawUpdate> {
  126. self.rect.eval(&parent_rect).ok()?;
  127. let rect = self.rect.get();
  128. let mut instrs = vec![GfxDrawInstruction::Move(rect.pos())];
  129. instrs.append(&mut self.regen_mesh().await);
  130. Some(DrawUpdate {
  131. key: self.dc_key,
  132. draw_calls: vec![(
  133. self.dc_key,
  134. GfxDrawCall { instrs, dcs: vec![], z_index: self.z_index.get() },
  135. )],
  136. })
  137. }
  138. }
  139. #[async_trait]
  140. impl UIObject for Text {
  141. fn priority(&self) -> u32 {
  142. self.priority.get()
  143. }
  144. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  145. let me = Arc::downgrade(&self);
  146. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  147. on_modify.when_change(self.rect.prop(), Self::redraw);
  148. on_modify.when_change(self.z_index.prop(), Self::redraw);
  149. on_modify.when_change(self.text.prop(), Self::redraw);
  150. on_modify.when_change(self.font_size.prop(), Self::redraw);
  151. on_modify.when_change(self.text_color.prop(), Self::redraw);
  152. on_modify.when_change(self.debug.prop(), Self::redraw);
  153. on_modify.when_change(self.baseline.prop(), Self::redraw);
  154. self.tasks.set(on_modify.tasks);
  155. }
  156. async fn draw(
  157. &self,
  158. parent_rect: Rectangle,
  159. trace_id: u32,
  160. atom: &mut PropertyAtomicGuard,
  161. ) -> Option<DrawUpdate> {
  162. t!("Text::draw({:?}) [trace_id={trace_id}]", self.node.upgrade().unwrap());
  163. *self.parent_rect.lock().unwrap() = Some(parent_rect);
  164. self.get_draw_calls(parent_rect, trace_id).await
  165. }
  166. }
  167. impl Drop for Text {
  168. fn drop(&mut self) {
  169. self.render_api.replace_draw_calls(unixtime(), vec![(self.dc_key, Default::default())]);
  170. }
  171. }