layer.rs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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_recursion::async_recursion;
  19. use async_trait::async_trait;
  20. use atomic_float::AtomicF32;
  21. use miniquad::{KeyCode, KeyMods, MouseButton, TouchPhase};
  22. use rand::{rngs::OsRng, Rng};
  23. use std::sync::{atomic::Ordering, Arc, Mutex as SyncMutex, OnceLock, Weak};
  24. use crate::{
  25. gfx::{GfxDrawCall, GfxDrawInstruction, Point, Rectangle, RenderApi},
  26. prop::{PropertyBool, PropertyFloat32, PropertyPtr, PropertyRect, PropertyUint32, Role},
  27. scene::{Pimpl, SceneNodePtr, SceneNodeWeak},
  28. util::unixtime,
  29. ExecutorPtr,
  30. };
  31. use super::{
  32. get_children_ordered, get_ui_object3, get_ui_object_ptr, DrawUpdate, OnModify, UIObject,
  33. };
  34. pub type LayerPtr = Arc<Layer>;
  35. pub struct Layer {
  36. node: SceneNodeWeak,
  37. render_api: RenderApi,
  38. tasks: OnceLock<Vec<smol::Task<()>>>,
  39. dc_key: u64,
  40. is_visible: PropertyBool,
  41. rect: PropertyRect,
  42. z_index: PropertyUint32,
  43. parent_rect: SyncMutex<Option<Rectangle>>,
  44. }
  45. impl Layer {
  46. pub async fn new(node: SceneNodeWeak, render_api: RenderApi, ex: ExecutorPtr) -> Pimpl {
  47. let node_ref = &node.upgrade().unwrap();
  48. debug!(target: "ui::layer", "Layer::new({node_ref:?})");
  49. let is_visible = PropertyBool::wrap(node_ref, Role::Internal, "is_visible", 0).unwrap();
  50. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  51. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  52. let node_name = node_ref.name.clone();
  53. let node_id = node_ref.id;
  54. let self_ = Arc::new(Self {
  55. node,
  56. render_api,
  57. tasks: OnceLock::new(),
  58. dc_key: OsRng.gen(),
  59. is_visible,
  60. rect,
  61. z_index,
  62. parent_rect: SyncMutex::new(None),
  63. });
  64. Pimpl::Layer(self_)
  65. }
  66. fn get_children(&self) -> Vec<SceneNodePtr> {
  67. let node = self.node.upgrade().unwrap();
  68. get_children_ordered(&node)
  69. }
  70. async fn redraw(self: Arc<Self>) {
  71. let timest = unixtime();
  72. debug!(target: "ui::layer", "Layer::redraw({:?})", self.node.upgrade().unwrap());
  73. let Some(parent_rect) = self.parent_rect.lock().unwrap().clone() else { return };
  74. let Some(draw_update) = self.get_draw_calls(parent_rect).await else {
  75. error!(target: "ui::layer", "Layer failed to draw");
  76. return;
  77. };
  78. self.render_api.replace_draw_calls(timest, draw_update.draw_calls);
  79. debug!(target: "ui::layer", "Layer::redraw({:?}) DONE [timest={timest}]", self.node.upgrade().unwrap());
  80. }
  81. async fn get_draw_calls(&self, parent_rect: Rectangle) -> Option<DrawUpdate> {
  82. self.rect.eval(&parent_rect).ok()?;
  83. let rect = self.rect.get();
  84. debug!(target: "ui::layer", "Layer::get_draw_calls() [rect={rect:?}, dc={}]", self.dc_key);
  85. // Apply viewport
  86. let mut draw_calls = vec![];
  87. let mut child_calls = vec![];
  88. // We should return a draw call so that if the layer is made visible, we can just
  89. // recalculate it and update in place.
  90. if self.is_visible.get() {
  91. for child in self.get_children() {
  92. let obj = get_ui_object3(&child);
  93. let Some(mut draw_update) = obj.draw(rect).await else {
  94. debug!(target: "ui::layer", "Skipped draw for {child:?}");
  95. continue
  96. };
  97. draw_calls.append(&mut draw_update.draw_calls);
  98. child_calls.push(draw_update.key);
  99. }
  100. }
  101. let dc = GfxDrawCall {
  102. instrs: vec![GfxDrawInstruction::ApplyView(rect)],
  103. dcs: child_calls,
  104. z_index: self.z_index(),
  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 z_index(&self) -> u32 {
  113. self.z_index.get()
  114. }
  115. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  116. let me = Arc::downgrade(&self);
  117. let node_ref = &self.node.upgrade().unwrap();
  118. let node_name = node_ref.name.clone();
  119. let node_id = node_ref.id;
  120. let mut on_modify = OnModify::new(ex.clone(), node_name, node_id, me.clone());
  121. on_modify.when_change(self.is_visible.prop(), Self::redraw);
  122. on_modify.when_change(self.rect.prop(), Self::redraw);
  123. on_modify.when_change(self.z_index.prop(), Self::redraw);
  124. self.tasks.set(on_modify.tasks);
  125. for child in self.get_children() {
  126. let obj = get_ui_object_ptr(&child);
  127. obj.start(ex.clone()).await;
  128. }
  129. }
  130. async fn draw(&self, parent_rect: Rectangle) -> Option<DrawUpdate> {
  131. debug!(target: "ui::layer", "Layer::draw({:?})", self.node.upgrade().unwrap());
  132. *self.parent_rect.lock().unwrap() = Some(parent_rect);
  133. /*
  134. if !parent_rect.dim().contains(&offset_rect) {
  135. error!(
  136. target: "ui::layer",
  137. "layer rect {:?} is not inside parent {:?}",
  138. offset_rect, parent_rect
  139. );
  140. return None
  141. }
  142. */
  143. let update = self.get_draw_calls(parent_rect).await;
  144. debug!(target: "ui::layer", "Layer::draw({:?}) DONE", self.node.upgrade().unwrap());
  145. update
  146. }
  147. async fn handle_char(&self, key: char, mods: KeyMods, repeat: bool) -> bool {
  148. if !self.is_visible.get() {
  149. return false
  150. }
  151. for child in self.get_children() {
  152. let obj = get_ui_object3(&child);
  153. if obj.handle_char(key, mods, repeat).await {
  154. return true
  155. }
  156. }
  157. false
  158. }
  159. async fn handle_key_down(&self, key: KeyCode, mods: KeyMods, repeat: bool) -> bool {
  160. if !self.is_visible.get() {
  161. return false
  162. }
  163. for child in self.get_children() {
  164. let obj = get_ui_object3(&child);
  165. if obj.handle_key_down(key, mods, repeat).await {
  166. //debug!(target: "layer", "handle_key_down({key:?}, {mods:?}, {repeat}) swallowed by {child:?}");
  167. return true
  168. }
  169. }
  170. false
  171. }
  172. async fn handle_key_up(&self, key: KeyCode, mods: KeyMods) -> bool {
  173. if !self.is_visible.get() {
  174. return false
  175. }
  176. for child in self.get_children() {
  177. let obj = get_ui_object3(&child);
  178. if obj.handle_key_up(key, mods).await {
  179. return true
  180. }
  181. }
  182. false
  183. }
  184. async fn handle_mouse_btn_down(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  185. if !self.is_visible.get() {
  186. return false
  187. }
  188. mouse_pos -= self.rect.get().pos();
  189. for child in self.get_children() {
  190. let obj = get_ui_object3(&child);
  191. if obj.handle_mouse_btn_down(btn, mouse_pos).await {
  192. return true
  193. }
  194. }
  195. false
  196. }
  197. async fn handle_mouse_btn_up(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  198. if !self.is_visible.get() {
  199. return false
  200. }
  201. mouse_pos -= self.rect.get().pos();
  202. for child in self.get_children() {
  203. let obj = get_ui_object3(&child);
  204. if obj.handle_mouse_btn_up(btn, mouse_pos).await {
  205. return true
  206. }
  207. }
  208. false
  209. }
  210. async fn handle_mouse_move(&self, mut mouse_pos: Point) -> bool {
  211. if !self.is_visible.get() {
  212. return false
  213. }
  214. mouse_pos -= self.rect.get().pos();
  215. for child in self.get_children() {
  216. let obj = get_ui_object3(&child);
  217. if obj.handle_mouse_move(mouse_pos).await {
  218. return true
  219. }
  220. }
  221. false
  222. }
  223. async fn handle_mouse_wheel(&self, mut wheel_pos: Point) -> bool {
  224. if !self.is_visible.get() {
  225. return false
  226. }
  227. wheel_pos -= self.rect.get().pos();
  228. for child in self.get_children() {
  229. let obj = get_ui_object3(&child);
  230. if obj.handle_mouse_wheel(wheel_pos).await {
  231. return true
  232. }
  233. }
  234. false
  235. }
  236. async fn handle_touch(&self, phase: TouchPhase, id: u64, mut touch_pos: Point) -> bool {
  237. if !self.is_visible.get() {
  238. return false
  239. }
  240. touch_pos -= self.rect.get().pos();
  241. for child in self.get_children() {
  242. let obj = get_ui_object3(&child);
  243. if obj.handle_touch(phase, id, touch_pos).await {
  244. return true
  245. }
  246. }
  247. false
  248. }
  249. async fn handle_compose_text(&self, suggest_text: &str, is_commit: bool) -> bool {
  250. if !self.is_visible.get() {
  251. return false
  252. }
  253. for child in self.get_children() {
  254. let obj = get_ui_object3(&child);
  255. if obj.handle_compose_text(suggest_text, is_commit).await {
  256. return true
  257. }
  258. }
  259. false
  260. }
  261. async fn handle_set_compose_region(&self, start: usize, end: usize) -> bool {
  262. if !self.is_visible.get() {
  263. return false
  264. }
  265. for child in self.get_children() {
  266. let obj = get_ui_object3(&child);
  267. if obj.handle_set_compose_region(start, end).await {
  268. return true
  269. }
  270. }
  271. false
  272. }
  273. }