layer.rs 10 KB

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