layer.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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, RenderApi, Renderer, RendererSync},
  26. prop::{BatchGuardPtr, 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, UIObject,
  33. };
  34. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui:layer", $($arg)*); } }
  35. pub type LayerPtr = Arc<Layer>;
  36. pub struct Layer {
  37. node: SceneNodeWeak,
  38. renderer: Renderer,
  39. tasks: SyncMutex<Vec<smol::Task<()>>>,
  40. dc_key: u64,
  41. is_visible: PropertyBool,
  42. rect: PropertyRect,
  43. z_index: PropertyUint32,
  44. priority: PropertyUint32,
  45. parent_rect: SyncMutex<Option<Rectangle>>,
  46. }
  47. impl Layer {
  48. pub async fn new(node: SceneNodeWeak, renderer: Renderer) -> 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 self_ = Arc::new(Self {
  55. node,
  56. renderer,
  57. tasks: SyncMutex::new(vec![]),
  58. dc_key: OsRng.gen(),
  59. is_visible,
  60. rect,
  61. z_index,
  62. priority,
  63. parent_rect: SyncMutex::new(None),
  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. #[instrument(target = "ui::layer")]
  72. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  73. let Some(parent_rect) = self.parent_rect.lock().clone() else {
  74. warn!(target: "ui:layer", "Skip draw since parent rect is empty");
  75. return
  76. };
  77. let atom = &mut batch.spawn();
  78. let Some(draw_update) = self.get_draw_calls(parent_rect, atom).await else {
  79. error!(target: "ui:layer", "Layer failed to draw");
  80. return
  81. };
  82. self.renderer.replace_draw_calls(Some(batch.id), draw_update.draw_calls);
  83. }
  84. async fn get_draw_calls(
  85. &self,
  86. parent_rect: Rectangle,
  87. atom: &mut PropertyAtomicGuard,
  88. ) -> Option<DrawUpdate> {
  89. self.rect.eval(atom, &parent_rect).ok()?;
  90. let rect = self.rect.get();
  91. // Apply viewport
  92. let mut draw_calls = vec![];
  93. let mut child_calls = vec![];
  94. // We should return a draw call so that if the layer is made visible, we can just
  95. // recalculate it and update in place.
  96. if self.is_visible.get() {
  97. for child in self.get_children() {
  98. let obj = get_ui_object3(&child);
  99. let Some(mut draw_update) = obj.draw(rect, atom).await else {
  100. //t!("{child:?} draw returned none");
  101. continue
  102. };
  103. draw_calls.append(&mut draw_update.draw_calls);
  104. child_calls.push(draw_update.key);
  105. }
  106. }
  107. let dc = DrawCall::new(
  108. vec![DrawInstruction::ApplyView(rect)],
  109. child_calls,
  110. self.z_index.get(),
  111. "layer",
  112. );
  113. draw_calls.push((self.dc_key, dc));
  114. Some(DrawUpdate { key: self.dc_key, draw_calls })
  115. }
  116. }
  117. #[async_trait]
  118. impl UIObject for Layer {
  119. fn priority(&self) -> u32 {
  120. self.priority.get()
  121. }
  122. fn init(&self) {
  123. for child in self.get_children() {
  124. let obj = get_ui_object3(&child);
  125. obj.init();
  126. }
  127. }
  128. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  129. let me = Arc::downgrade(&self);
  130. let mut on_modify = OnModify::new(ex.clone(), self.node.clone(), me.clone());
  131. on_modify.when_change(self.is_visible.prop(), Self::redraw);
  132. on_modify.when_change(self.rect.prop(), Self::redraw);
  133. on_modify.when_change(self.z_index.prop(), Self::redraw);
  134. *self.tasks.lock() = on_modify.tasks;
  135. for child in self.get_children() {
  136. let obj = get_ui_object_ptr(&child);
  137. obj.start(ex.clone()).await;
  138. }
  139. }
  140. fn stop(&self) {
  141. self.tasks.lock().clear();
  142. *self.parent_rect.lock() = None;
  143. for child in self.get_children() {
  144. let obj = get_ui_object3(&child);
  145. obj.stop();
  146. }
  147. }
  148. #[instrument(target = "ui::layer")]
  149. async fn draw(
  150. &self,
  151. parent_rect: Rectangle,
  152. atom: &mut PropertyAtomicGuard,
  153. ) -> Option<DrawUpdate> {
  154. *self.parent_rect.lock() = Some(parent_rect);
  155. /*
  156. if !parent_rect.dim().contains(&offset_rect) {
  157. error!(
  158. target: "ui::layer",
  159. "layer rect {:?} is not inside parent {:?}",
  160. offset_rect, parent_rect
  161. );
  162. return None
  163. }
  164. */
  165. self.get_draw_calls(parent_rect, atom).await
  166. }
  167. async fn handle_char(&self, key: char, mods: KeyMods, repeat: bool) -> bool {
  168. if !self.is_visible.get() {
  169. return false
  170. }
  171. for child in self.get_children() {
  172. let obj = get_ui_object3(&child);
  173. if obj.handle_char(key, mods, repeat).await {
  174. t!("handle_char({key:?}, {mods:?}, {repeat}) swallowed by {child:?}");
  175. return true
  176. }
  177. }
  178. false
  179. }
  180. async fn handle_key_down(&self, key: KeyCode, 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_key_down(key, mods, repeat).await {
  187. t!("handle_key_down({key:?}, {mods:?}, {repeat}) swallowed by {child:?}");
  188. return true
  189. }
  190. }
  191. false
  192. }
  193. async fn handle_key_up(&self, key: KeyCode, mods: KeyMods) -> 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_up(key, mods).await {
  200. t!("handle_key_up({key:?}, {mods:?}) swallowed by {child:?}");
  201. return true
  202. }
  203. }
  204. false
  205. }
  206. async fn handle_mouse_btn_down(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  207. if !self.is_visible.get() {
  208. return false
  209. }
  210. mouse_pos -= self.rect.get().pos();
  211. for child in self.get_children() {
  212. let obj = get_ui_object3(&child);
  213. if obj.handle_mouse_btn_down(btn, mouse_pos).await {
  214. t!("handle_mouse_btn_down({btn:?}, {mouse_pos:?}) swallowed by {child:?}");
  215. return true
  216. }
  217. }
  218. false
  219. }
  220. async fn handle_mouse_btn_up(&self, btn: MouseButton, mut mouse_pos: Point) -> bool {
  221. if !self.is_visible.get() {
  222. return false
  223. }
  224. mouse_pos -= self.rect.get().pos();
  225. for child in self.get_children() {
  226. let obj = get_ui_object3(&child);
  227. if obj.handle_mouse_btn_up(btn, mouse_pos).await {
  228. t!("handle_mouse_btn_up({btn:?}, {mouse_pos:?}) swallowed by {child:?}");
  229. return true
  230. }
  231. }
  232. false
  233. }
  234. async fn handle_mouse_move(&self, mut mouse_pos: Point) -> bool {
  235. if !self.is_visible.get() {
  236. return false
  237. }
  238. mouse_pos -= self.rect.get().pos();
  239. for child in self.get_children() {
  240. let obj = get_ui_object3(&child);
  241. if obj.handle_mouse_move(mouse_pos).await {
  242. t!("handle_mouse_move({mouse_pos:?}) swallowed by {child:?}");
  243. return true
  244. }
  245. }
  246. false
  247. }
  248. async fn handle_mouse_wheel(&self, mut wheel_pos: Point) -> bool {
  249. if !self.is_visible.get() {
  250. return false
  251. }
  252. wheel_pos -= self.rect.get().pos();
  253. for child in self.get_children() {
  254. let obj = get_ui_object3(&child);
  255. if obj.handle_mouse_wheel(wheel_pos).await {
  256. return true
  257. }
  258. }
  259. false
  260. }
  261. async fn handle_touch(&self, phase: TouchPhase, id: u64, mut touch_pos: Point) -> bool {
  262. if !self.is_visible.get() {
  263. return false
  264. }
  265. touch_pos -= self.rect.get().pos();
  266. for child in self.get_children() {
  267. let obj = get_ui_object3(&child);
  268. if obj.handle_touch(phase, id, touch_pos).await {
  269. return true
  270. }
  271. }
  272. false
  273. }
  274. fn handle_touch_sync(
  275. &self,
  276. renderer: &RendererSync,
  277. phase: TouchPhase,
  278. id: u64,
  279. mut touch_pos: Point,
  280. ) -> bool {
  281. if !self.is_visible.get() {
  282. return false
  283. }
  284. touch_pos -= self.rect.get().pos();
  285. for child in self.get_children() {
  286. let obj = get_ui_object3(&child);
  287. if obj.handle_touch_sync(renderer, phase, id, touch_pos) {
  288. return true
  289. }
  290. }
  291. false
  292. }
  293. fn set_i18n(&self, i18n_fish: &I18nBabelFish) {
  294. for child in self.get_children() {
  295. let obj = get_ui_object3(&child);
  296. obj.set_i18n(i18n_fish);
  297. }
  298. }
  299. }
  300. // TODO: Drop
  301. impl std::fmt::Debug for Layer {
  302. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  303. write!(f, "{:?}", self.node.upgrade().unwrap())
  304. }
  305. }