layer.rs 10 KB

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