button.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 miniquad::{MouseButton, TouchPhase};
  19. use std::sync::{
  20. atomic::{AtomicBool, Ordering},
  21. Arc, Weak,
  22. };
  23. use crate::{
  24. gfx::{GraphicsEventPublisherPtr, Point, Rectangle},
  25. prop::{PropertyBool, PropertyPtr, Role},
  26. pubsub::Subscription,
  27. scene::{Pimpl, SceneGraphPtr2, SceneNodeId},
  28. ExecutorPtr,
  29. };
  30. use super::{eval_rect, read_rect};
  31. pub type ButtonPtr = Arc<Button>;
  32. pub struct Button {
  33. node_id: SceneNodeId,
  34. #[allow(dead_code)]
  35. tasks: Vec<smol::Task<()>>,
  36. sg: SceneGraphPtr2,
  37. is_active: PropertyBool,
  38. rect: PropertyPtr,
  39. mouse_btn_held: AtomicBool,
  40. }
  41. impl Button {
  42. pub async fn new(
  43. ex: ExecutorPtr,
  44. sg: SceneGraphPtr2,
  45. node_id: SceneNodeId,
  46. event_pub: GraphicsEventPublisherPtr,
  47. ) -> Pimpl {
  48. let scene_graph = sg.lock().await;
  49. let node = scene_graph.get_node(node_id).unwrap();
  50. //let node_name = node.name.clone();
  51. let is_active = PropertyBool::wrap(node, Role::Internal, "is_active", 0).unwrap();
  52. let rect = node.get_property("rect").expect("Button::rect");
  53. //let sig = node.get_signal("click").expect("Button::click");
  54. drop(scene_graph);
  55. let self_ = Arc::new_cyclic(|me: &Weak<Self>| {
  56. let ev_sub = event_pub.subscribe_mouse_btn_down();
  57. let me2 = me.clone();
  58. let mouse_btn_down_task =
  59. ex.spawn(async move { while Self::process_mouse_btn_down(&me2, &ev_sub).await {} });
  60. let ev_sub = event_pub.subscribe_mouse_btn_up();
  61. let me2 = me.clone();
  62. let mouse_btn_up_task =
  63. ex.spawn(async move { while Self::process_mouse_btn_up(&me2, &ev_sub).await {} });
  64. let ev_sub = event_pub.subscribe_touch();
  65. let me2 = me.clone();
  66. let touch_task =
  67. ex.spawn(async move { while Self::process_touch(&me2, &ev_sub).await {} });
  68. let tasks = vec![mouse_btn_down_task, mouse_btn_up_task, touch_task];
  69. Self { node_id, tasks, sg, is_active, rect, mouse_btn_held: AtomicBool::new(false) }
  70. });
  71. Pimpl::Button(self_)
  72. }
  73. async fn process_mouse_btn_down(
  74. me: &Weak<Self>,
  75. ev_sub: &Subscription<(MouseButton, f32, f32)>,
  76. ) -> bool {
  77. let Ok((btn, mouse_x, mouse_y)) = ev_sub.receive().await else {
  78. debug!(target: "ui::button", "Event relayer closed");
  79. return false
  80. };
  81. let Some(self_) = me.upgrade() else {
  82. // Should not happen
  83. panic!("self destroyed before mouse_btn_down_task was stopped!");
  84. };
  85. if !self_.is_active.get() {
  86. return true
  87. }
  88. self_.handle_mouse_btn_down(btn, mouse_x, mouse_y);
  89. true
  90. }
  91. async fn process_mouse_btn_up(
  92. me: &Weak<Self>,
  93. ev_sub: &Subscription<(MouseButton, f32, f32)>,
  94. ) -> bool {
  95. let Ok((btn, mouse_x, mouse_y)) = ev_sub.receive().await else {
  96. debug!(target: "ui::button", "Event relayer closed");
  97. return false
  98. };
  99. let Some(self_) = me.upgrade() else {
  100. // Should not happen
  101. panic!("self destroyed before mouse_btn_up_task was stopped!");
  102. };
  103. if !self_.is_active.get() {
  104. return true
  105. }
  106. self_.handle_mouse_btn_up(btn, mouse_x, mouse_y).await;
  107. true
  108. }
  109. async fn process_touch(
  110. me: &Weak<Self>,
  111. ev_sub: &Subscription<(TouchPhase, u64, f32, f32)>,
  112. ) -> bool {
  113. let Ok((phase, id, touch_x, touch_y)) = ev_sub.receive().await else {
  114. debug!(target: "ui::button", "Event relayer closed");
  115. return false
  116. };
  117. let Some(self_) = me.upgrade() else {
  118. // Should not happen
  119. panic!("self destroyed before touch_task was stopped!");
  120. };
  121. if !self_.is_active.get() {
  122. return true
  123. }
  124. self_.handle_touch(phase, id, touch_x, touch_y).await;
  125. true
  126. }
  127. fn handle_mouse_btn_down(&self, btn: MouseButton, mouse_x: f32, mouse_y: f32) {
  128. if btn != MouseButton::Left {
  129. return
  130. }
  131. let mouse_pos = Point::from([mouse_x, mouse_y]);
  132. let Some(rect) = self.get_cached_rect() else { return };
  133. if !rect.contains(&mouse_pos) {
  134. return
  135. }
  136. self.mouse_btn_held.store(true, Ordering::Relaxed);
  137. }
  138. async fn handle_mouse_btn_up(&self, btn: MouseButton, mouse_x: f32, mouse_y: f32) {
  139. if btn != MouseButton::Left {
  140. return
  141. }
  142. // Did we start the click inside the button?
  143. let btn_held = self.mouse_btn_held.swap(false, Ordering::Relaxed);
  144. if !btn_held {
  145. return
  146. }
  147. let mouse_pos = Point::from([mouse_x, mouse_y]);
  148. // Are we releasing the click inside the button?
  149. let Some(rect) = self.get_cached_rect() else { return };
  150. if !rect.contains(&mouse_pos) {
  151. return
  152. }
  153. debug!(target: "ui::button", "Mouse button clicked!");
  154. let scene_graph = self.sg.lock().await;
  155. let node = scene_graph.get_node(self.node_id).unwrap();
  156. node.trigger("click", vec![]).await.unwrap();
  157. }
  158. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_x: f32, touch_y: f32) {
  159. // Ignore multi-touch
  160. if id != 0 {
  161. return
  162. }
  163. let Some(rect) = self.get_cached_rect() else { return };
  164. let touch_pos = Point { x: touch_x, y: touch_y };
  165. if !rect.contains(&touch_pos) {
  166. //debug!(target: "ui::chatview", "not inside rect");
  167. return
  168. }
  169. // Simulate mouse events
  170. match phase {
  171. TouchPhase::Started => self.handle_mouse_btn_down(MouseButton::Left, touch_x, touch_y),
  172. TouchPhase::Moved => {}
  173. TouchPhase::Ended => {
  174. self.handle_mouse_btn_up(MouseButton::Left, touch_x, touch_y).await
  175. }
  176. TouchPhase::Cancelled => {}
  177. }
  178. }
  179. fn get_cached_rect(&self) -> Option<Rectangle> {
  180. let Ok(rect) = read_rect(self.rect.clone()) else {
  181. error!(target: "ui::button", "cached_rect is None");
  182. return None
  183. };
  184. Some(rect)
  185. }
  186. pub fn set_parent_rect(&self, parent_rect: &Rectangle) {
  187. if let Err(err) = eval_rect(self.rect.clone(), parent_rect) {
  188. panic!("Button bad rect property: {}", err);
  189. }
  190. }
  191. }