layer.rs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 miniquad::{KeyCode, KeyMods, MouseButton, TouchPhase};
  20. use parking_lot::Mutex as SyncMutex;
  21. use rand::{rngs::OsRng, Rng};
  22. use std::sync::Arc;
  23. use tracing::instrument;
  24. use crate::{
  25. gfx::{DrawCall, DrawInstruction, Point, Rectangle, Renderer},
  26. prop::{PropertyAtomicGuard, PropertyBool, PropertyRect, PropertyUint32, Role},
  27. scene::{Pimpl, SceneNodePtr, SceneNodeWeak},
  28. util::i18n::I18nBabelFish,
  29. ExecutorPtr,
  30. };
  31. use super::{
  32. get_children_ordered, get_ui_object3, get_ui_object_ptr, DrawUpdate, OnModify, RedrawTrigger,
  33. UIObject,
  34. };
  35. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui:layer", $($arg)*); } }
  36. pub type LayerPtr = Arc<Layer>;
  37. pub struct Layer {
  38. node: SceneNodeWeak,
  39. redraw: RedrawTrigger,
  40. tasks: SyncMutex<Vec<smol::Task<()>>>,
  41. dc_key: u64,
  42. is_visible: PropertyBool,
  43. rect: PropertyRect,
  44. z_index: PropertyUint32,
  45. priority: PropertyUint32,
  46. }
  47. impl Layer {
  48. pub async fn new(_node: SceneNodeWeak, renderer: Renderer, redraw: RedrawTrigger) -> Pimpl {
  49. let node_ref = &_node.upgrade().unwrap();
  50. let is_visible = PropertyBool::wrap(node_ref, Role::Internal, "is_visible", 0).unwrap();
  51. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  52. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  53. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  54. let _ = renderer;
  55. let self_ = Arc::new(Self {
  56. node: _node,
  57. redraw,
  58. tasks: SyncMutex::new(vec![]),
  59. dc_key: OsRng.gen(),
  60. is_visible,
  61. rect,
  62. z_index,
  63. priority,
  64. });
  65. Pimpl::Layer(self_)
  66. }
  67. fn get_children(&self) -> Vec<SceneNodePtr> {
  68. let node = self.node.upgrade().unwrap();
  69. get_children_ordered(&node)
  70. }
  71. async fn get_draw_calls(
  72. &self,
  73. parent_rect: Rectangle,
  74. atom: &mut PropertyAtomicGuard,
  75. ) -> Option<DrawUpdate> {
  76. self.rect.eval(atom, &parent_rect).ok()?;
  77. let rect = self.rect.get();
  78. // Apply viewport
  79. let mut draw_calls = vec![];
  80. let mut child_calls = vec![];
  81. // We should return a draw call so that if the layer is made visible, we can just
  82. // recalculate it and update in place.
  83. if self.is_visible.get() {
  84. for child in self.get_children() {
  85. let obj = get_ui_object3(&child);
  86. let Some(mut draw_update) = obj.draw(rect, atom).await else {
  87. //t!("{child:?} draw returned none");
  88. continue
  89. };
  90. draw_calls.append(&mut draw_update.draw_calls);
  91. child_calls.push(draw_update.key);
  92. }
  93. }
  94. let dc = DrawCall::new(
  95. vec![DrawInstruction::ApplyView(rect)],
  96. child_calls,
  97. self.z_index.get(),
  98. "layer",
  99. );
  100. draw_calls.push((self.dc_key, dc));
  101. Some(DrawUpdate { key: self.dc_key, draw_calls })
  102. }
  103. }
  104. #[async_trait]
  105. impl UIObject for Layer {
  106. fn priority(&self) -> u32 {
  107. self.priority.get()
  108. }
  109. fn init(&self) {
  110. for child in self.get_children() {
  111. let obj = get_ui_object3(&child);
  112. obj.init();
  113. }
  114. }
  115. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  116. let me = Arc::downgrade(&self);
  117. let mut on_modify = OnModify::new(ex.clone(), self.node.clone(), me.clone());
  118. // Stateless in the pass: property changes only request a draw pass.
  119. // All layer output is recomputed by the pass itself. Internal-role
  120. // sets are eval echoes of the pass, so only external (App) changes
  121. // trigger — otherwise every pass would queue another, forever.
  122. on_modify.when_change_external(self.is_visible.prop(), |self_, _| async move {
  123. self_.redraw.trigger();
  124. });
  125. on_modify.when_change_external(self.rect.prop(), |self_, _| async move {
  126. self_.redraw.trigger();
  127. });
  128. on_modify.when_change_external(self.z_index.prop(), |self_, _| async move {
  129. self_.redraw.trigger();
  130. });
  131. *self.tasks.lock() = on_modify.tasks;
  132. for child in self.get_children() {
  133. let obj = get_ui_object_ptr(&child);
  134. obj.start(ex.clone()).await;
  135. }
  136. }
  137. fn stop(&self) {
  138. self.tasks.lock().clear();
  139. for child in self.get_children() {
  140. let obj = get_ui_object3(&child);
  141. obj.stop();
  142. }
  143. }
  144. #[instrument(target = "ui::layer")]
  145. async fn draw(
  146. &self,
  147. parent_rect: Rectangle,
  148. atom: &mut PropertyAtomicGuard,
  149. ) -> Option<DrawUpdate> {
  150. self.get_draw_calls(parent_rect, atom).await
  151. }
  152. async fn handle_char(&self, key: char, mods: KeyMods, repeat: bool) -> bool {
  153. if !self.is_visible.get() {
  154. return false
  155. }
  156. for child in self.get_children() {
  157. let obj = get_ui_object3(&child);
  158. if obj.handle_char(key, mods, repeat).await {
  159. t!("handle_char({key:?}, {mods:?}, {repeat}) swallowed by {child:?}");
  160. return true
  161. }
  162. }
  163. false
  164. }
  165. async fn handle_key_down(&self, key: KeyCode, mods: KeyMods, repeat: bool) -> bool {
  166. if !self.is_visible.get() {
  167. return false
  168. }
  169. for child in self.get_children() {
  170. let obj = get_ui_object3(&child);
  171. if obj.handle_key_down(key, mods, repeat).await {
  172. t!("handle_key_down({key:?}, {mods:?}, {repeat}) swallowed by {child:?}");
  173. return true
  174. }
  175. }
  176. false
  177. }
  178. async fn handle_key_up(&self, key: KeyCode, mods: KeyMods) -> bool {
  179. if !self.is_visible.get() {
  180. return false
  181. }
  182. for child in self.get_children() {
  183. let obj = get_ui_object3(&child);
  184. if obj.handle_key_up(key, mods).await {
  185. t!("handle_key_up({key:?}, {mods:?}) swallowed by {child:?}");
  186. return true
  187. }
  188. }
  189. false
  190. }
  191. async fn handle_mouse_btn_down(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  192. if !self.is_visible.get() {
  193. return false
  194. }
  195. mouse_pos -= self.rect.get().pos();
  196. for child in self.get_children() {
  197. let obj = get_ui_object3(&child);
  198. if obj.handle_mouse_btn_down(btn, mouse_pos).await {
  199. t!("handle_mouse_btn_down({btn:?}, {mouse_pos:?}) swallowed by {child:?}");
  200. return true
  201. }
  202. }
  203. false
  204. }
  205. async fn handle_mouse_btn_up(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  206. if !self.is_visible.get() {
  207. return false
  208. }
  209. mouse_pos -= self.rect.get().pos();
  210. for child in self.get_children() {
  211. let obj = get_ui_object3(&child);
  212. if obj.handle_mouse_btn_up(btn, mouse_pos).await {
  213. t!("handle_mouse_btn_up({btn:?}, {mouse_pos:?}) swallowed by {child:?}");
  214. return true
  215. }
  216. }
  217. false
  218. }
  219. async fn handle_mouse_move(&self, mut mouse_pos: Point) -> bool {
  220. if !self.is_visible.get() {
  221. return false
  222. }
  223. mouse_pos -= self.rect.get().pos();
  224. for child in self.get_children() {
  225. let obj = get_ui_object3(&child);
  226. if obj.handle_mouse_move(mouse_pos).await {
  227. t!("handle_mouse_move({mouse_pos:?}) swallowed by {child:?}");
  228. return true
  229. }
  230. }
  231. false
  232. }
  233. async fn handle_mouse_wheel(&self, mut wheel_pos: Point) -> bool {
  234. if !self.is_visible.get() {
  235. return false
  236. }
  237. wheel_pos -= self.rect.get().pos();
  238. for child in self.get_children() {
  239. let obj = get_ui_object3(&child);
  240. if obj.handle_mouse_wheel(wheel_pos).await {
  241. return true
  242. }
  243. }
  244. false
  245. }
  246. async fn handle_touch(&self, phase: TouchPhase, id: u64, mut touch_pos: Point) -> bool {
  247. if !self.is_visible.get() {
  248. return false
  249. }
  250. touch_pos -= self.rect.get().pos();
  251. for child in self.get_children() {
  252. let obj = get_ui_object3(&child);
  253. if obj.handle_touch(phase, id, touch_pos).await {
  254. return true
  255. }
  256. }
  257. false
  258. }
  259. fn handle_touch_sync(&self, phase: TouchPhase, id: u64, mut touch_pos: Point) -> bool {
  260. if !self.is_visible.get() {
  261. return false
  262. }
  263. touch_pos -= self.rect.get().pos();
  264. for child in self.get_children() {
  265. let obj = get_ui_object3(&child);
  266. if obj.handle_touch_sync(phase, id, touch_pos) {
  267. return true
  268. }
  269. }
  270. false
  271. }
  272. fn set_i18n(&self, i18n_fish: &I18nBabelFish) {
  273. for child in self.get_children() {
  274. let obj = get_ui_object3(&child);
  275. obj.set_i18n(i18n_fish);
  276. }
  277. }
  278. }
  279. // TODO: Drop
  280. impl std::fmt::Debug for Layer {
  281. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  282. write!(f, "{:?}", self.node.upgrade().unwrap())
  283. }
  284. }