layer.rs 9.7 KB

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