mod.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 darkfi_serial::Encodable;
  20. use miniquad::{MouseButton, TouchPhase};
  21. use parking_lot::Mutex as SyncMutex;
  22. use rand::{rngs::OsRng, Rng};
  23. use std::sync::{
  24. atomic::{AtomicBool, Ordering},
  25. Arc,
  26. };
  27. use crate::{
  28. gfx::{
  29. gfxtag, Dimension, DrawCall, DrawInstruction, EpochCache, Point, Rectangle, RenderApi,
  30. Renderer,
  31. },
  32. prop::{PropertyAtomicGuard, PropertyFloat32, PropertyPtr, PropertyRect, PropertyUint32, Role},
  33. scene::{Pimpl, SceneNodeWeak},
  34. ExecutorPtr,
  35. };
  36. use super::{DrawUpdate, OnModify, RedrawTrigger, UIObject};
  37. mod default;
  38. use default::DEFAULT_EMOJI_LIST;
  39. mod emoji;
  40. pub use emoji::{EmojiMeshes, EmojiMeshesPtr};
  41. macro_rules! d { ($($arg:tt)*) => { debug!(target: "ui::emoji_picker", $($arg)*) } }
  42. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::emoji_picker", $($arg)*) } }
  43. #[derive(Clone)]
  44. struct TouchInfo {
  45. start_pos: Point,
  46. start_scroll: f32,
  47. is_scroll: bool,
  48. }
  49. pub type EmojiPickerPtr = Arc<EmojiPicker>;
  50. pub struct EmojiPicker {
  51. node: SceneNodeWeak,
  52. renderer: Renderer,
  53. tasks: SyncMutex<Vec<smol::Task<()>>>,
  54. dc_key: u64,
  55. emoji_meshes: EmojiMeshesPtr,
  56. rect: PropertyRect,
  57. z_index: PropertyUint32,
  58. priority: PropertyUint32,
  59. scroll: PropertyFloat32,
  60. emoji_size: PropertyFloat32,
  61. /// `[x, y]` padding around each emoji icon
  62. emoji_margin: PropertyPtr,
  63. mouse_scroll_speed: PropertyFloat32,
  64. redraw: RedrawTrigger,
  65. /// Cached emoji grid instructions. Empty means stale (rect, scroll or
  66. /// z_index changed). Scroll is set with an internal role, so scroll
  67. /// mutation sites invalidate explicitly. Entries from a dead UI epoch
  68. /// are evicted automatically.
  69. draw_cache: EpochCache<Vec<DrawInstruction>>,
  70. is_mouse_hover: AtomicBool,
  71. touch_info: SyncMutex<Option<TouchInfo>>,
  72. }
  73. impl EmojiPicker {
  74. pub async fn new(
  75. node: SceneNodeWeak,
  76. renderer: Renderer,
  77. emoji_meshes: EmojiMeshesPtr,
  78. redraw: RedrawTrigger,
  79. ) -> Pimpl {
  80. let node_ref = &node.upgrade().unwrap();
  81. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  82. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  83. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  84. let scroll = PropertyFloat32::wrap(node_ref, Role::Internal, "scroll", 0).unwrap();
  85. let emoji_size = PropertyFloat32::wrap(node_ref, Role::Internal, "emoji_size", 0).unwrap();
  86. let emoji_margin = node_ref.get_property("emoji_margin").unwrap();
  87. let mouse_scroll_speed =
  88. PropertyFloat32::wrap(node_ref, Role::Internal, "mouse_scroll_speed", 0).unwrap();
  89. let draw_cache = EpochCache::new(&renderer);
  90. let self_ = Arc::new(Self {
  91. node,
  92. renderer,
  93. tasks: SyncMutex::new(vec![]),
  94. dc_key: OsRng.gen(),
  95. emoji_meshes,
  96. rect,
  97. z_index,
  98. priority,
  99. scroll,
  100. emoji_size,
  101. emoji_margin,
  102. mouse_scroll_speed,
  103. redraw,
  104. draw_cache,
  105. is_mouse_hover: AtomicBool::new(false),
  106. touch_info: SyncMutex::new(None),
  107. });
  108. Pimpl::EmojiPicker(self_)
  109. }
  110. /// Size of a grid cell, i.e. the emoji icon plus its surrounding margin
  111. fn cell(&self) -> Dimension {
  112. Dimension {
  113. w: self.emoji_size.get() + self.emoji_margin.get_f32(0).unwrap(),
  114. h: self.emoji_size.get() + self.emoji_margin.get_f32(1).unwrap(),
  115. }
  116. }
  117. /// Number of emoji cells that fit in a row (at least 1)
  118. fn emojis_per_line(&self) -> usize {
  119. let cell = self.cell();
  120. let rect_w = self.rect.get().w;
  121. ((rect_w / cell.w).floor() as usize).max(1)
  122. }
  123. /// Horizontal pitch between cells. The row is spread evenly across the
  124. /// full width, so leftover space is distributed into the gaps.
  125. fn calc_off_x(&self) -> f32 {
  126. let cell = self.cell();
  127. let rect_w = self.rect.get().w;
  128. let n = self.emojis_per_line();
  129. if n <= 1 {
  130. return 0.
  131. }
  132. (rect_w - cell.w) / (n as f32 - 1.)
  133. }
  134. fn max_scroll(&self) -> f32 {
  135. let emojis_len = DEFAULT_EMOJI_LIST.len() as f32;
  136. let cell = self.cell();
  137. let cols = self.emojis_per_line() as f32;
  138. let rows = (emojis_len / cols).ceil();
  139. let rect_h = self.rect.get().h;
  140. let height = rows * cell.h;
  141. if height < rect_h {
  142. return 0.
  143. }
  144. height - rect_h
  145. }
  146. async fn click_emoji(&self, pos: Point) {
  147. let n_cols = self.emojis_per_line();
  148. let cell = self.cell();
  149. let off_x = self.calc_off_x();
  150. let scroll = self.scroll.get();
  151. // Icons are spread with pitch `off_x` and width `cell.w`. The gap
  152. // between two neighboring cells is `off_x - cell.w`, and the
  153. // boundary between them sits in the middle of that gap.
  154. let col = if off_x > 0. {
  155. let gap = off_x - cell.w;
  156. let shifted_x = pos.x - gap / 2.;
  157. (shifted_x / off_x).floor()
  158. } else {
  159. 0.
  160. };
  161. let y = pos.y + scroll;
  162. let row = (y / cell.h).floor();
  163. let idx = (col + row * n_cols as f32).round() as usize;
  164. let emoji_selected = {
  165. if idx < DEFAULT_EMOJI_LIST.len() {
  166. let emoji = DEFAULT_EMOJI_LIST[idx].to_string();
  167. Some(emoji)
  168. } else {
  169. None
  170. }
  171. };
  172. match emoji_selected {
  173. Some(emoji) => {
  174. d!("Selected emoji: {emoji}");
  175. let mut param_data = vec![];
  176. emoji.encode(&mut param_data).unwrap();
  177. let node = self.node.upgrade().unwrap();
  178. node.trigger("emoji_select", param_data).await.unwrap();
  179. }
  180. None => d!("Index out of bounds: {idx}"),
  181. }
  182. }
  183. fn get_draw_calls(
  184. &self,
  185. parent_rect: Rectangle,
  186. atom: &mut PropertyAtomicGuard,
  187. ) -> Option<DrawUpdate> {
  188. // Rect property is its own memo: compare before/after eval.
  189. let prev_rect = self.rect.get();
  190. if let Err(e) = self.rect.eval(atom, &parent_rect) {
  191. warn!(target: "ui:emoji_picker", "Rect eval failed: {e}");
  192. return None
  193. }
  194. let rect = self.rect.get();
  195. let rect_changed = rect != prev_rect;
  196. // Clamp scroll if needed due to window size change
  197. let max_scroll = self.max_scroll();
  198. if self.scroll.get() > max_scroll {
  199. self.scroll.set(atom, max_scroll);
  200. self.draw_cache.clear();
  201. }
  202. // The grid depends on rect and scroll. Compute under the cache
  203. // lock so concurrent invalidations land before or after, never
  204. // between.
  205. if rect_changed {
  206. self.draw_cache.clear();
  207. }
  208. if !self.emoji_meshes.clone().start_make() {
  209. // Skip the draw while the atlas is unbuilt so an empty grid
  210. // never lands in the cache; the pass retries once built.
  211. return None
  212. }
  213. let instrs = self.draw_cache.get_or_insert_with(|| {
  214. let mut instrs = vec![DrawInstruction::ApplyView(rect)];
  215. let off_x = self.calc_off_x();
  216. let cell = self.cell();
  217. let n_cols = self.emojis_per_line();
  218. let scroll = self.scroll.get();
  219. for i in 0..DEFAULT_EMOJI_LIST.len() {
  220. let col = (i % n_cols) as f32;
  221. let row = (i / n_cols) as f32;
  222. let x = col * off_x;
  223. let y = row * cell.h - scroll;
  224. if y > rect.h + cell.h {
  225. break
  226. }
  227. let Some((mesh, ink)) = self.emoji_meshes.get(i) else { break };
  228. // Center the emoji's ink inside its cell so the margin pads
  229. // it evenly on all sides. The ink origin sits above the
  230. // mesh origin (text baseline), hence the -ink.x/-ink.y.
  231. let pos = Point::new(
  232. x + (cell.w - ink.w) / 2. - ink.x,
  233. y + (cell.h - ink.h) / 2. - ink.y,
  234. );
  235. instrs.extend_from_slice(&[
  236. DrawInstruction::SetPos(pos),
  237. DrawInstruction::Draw(mesh),
  238. ]);
  239. }
  240. instrs
  241. });
  242. Some(DrawUpdate {
  243. key: self.dc_key,
  244. draw_calls: vec![(
  245. self.dc_key,
  246. DrawCall::new(instrs, vec![], self.z_index.get(), "emoji"),
  247. )],
  248. })
  249. }
  250. }
  251. #[async_trait]
  252. impl UIObject for EmojiPicker {
  253. fn priority(&self) -> u32 {
  254. self.priority.get()
  255. }
  256. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  257. let me = Arc::downgrade(&self);
  258. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  259. // Invalidate the cache, then request a pass. Internal-role echoes
  260. // (the pass's own evals) are skipped.
  261. on_modify.when_change_external(self.rect.prop(), |self_, _| async move {
  262. self_.draw_cache.clear();
  263. self_.redraw.trigger();
  264. });
  265. on_modify.when_change_external(self.z_index.prop(), |self_, _| async move {
  266. self_.draw_cache.clear();
  267. self_.redraw.trigger();
  268. });
  269. on_modify.when_change_external(self.emoji_size.prop(), |self_, _| async move {
  270. let emoji_size = self_.emoji_size.get();
  271. self_.emoji_meshes.set_size(emoji_size);
  272. self_.draw_cache.clear();
  273. self_.redraw.trigger();
  274. });
  275. on_modify.when_change_external(self.emoji_margin.clone(), |self_, _| async move {
  276. self_.draw_cache.clear();
  277. self_.redraw.trigger();
  278. });
  279. *self.tasks.lock() = on_modify.tasks;
  280. }
  281. fn stop(&self) {
  282. self.tasks.lock().clear();
  283. self.draw_cache.clear();
  284. self.emoji_meshes.clear();
  285. }
  286. #[instrument(target = "ui::emoji_picker")]
  287. async fn draw(
  288. &self,
  289. parent_rect: Rectangle,
  290. atom: &mut PropertyAtomicGuard,
  291. ) -> Option<DrawUpdate> {
  292. self.get_draw_calls(parent_rect, atom)
  293. }
  294. async fn handle_mouse_move(&self, mouse_pos: Point) -> bool {
  295. let rect = self.rect.get();
  296. self.is_mouse_hover.store(rect.contains(mouse_pos), Ordering::Relaxed);
  297. false
  298. }
  299. async fn handle_mouse_wheel(&self, wheel_pos: Point) -> bool {
  300. if !self.is_mouse_hover.load(Ordering::Relaxed) {
  301. return false
  302. }
  303. t!("handle_mouse_wheel()");
  304. let atom = &mut self.redraw.make_guard(gfxtag!("EmojiPicker::handle_mouse_wheel"));
  305. let mut scroll = self.scroll.get();
  306. scroll -= self.mouse_scroll_speed.get() * wheel_pos.y;
  307. scroll = scroll.clamp(0., self.max_scroll());
  308. self.scroll.set(atom, scroll);
  309. self.draw_cache.clear();
  310. true
  311. }
  312. async fn handle_mouse_btn_up(&self, _btn: MouseButton, mut mouse_pos: Point) -> bool {
  313. let rect = self.rect.get();
  314. if !rect.contains(mouse_pos) {
  315. return false
  316. }
  317. mouse_pos.x -= rect.x;
  318. mouse_pos.y -= rect.y;
  319. self.click_emoji(mouse_pos).await;
  320. true
  321. }
  322. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_pos: Point) -> bool {
  323. // Ignore multi-touch
  324. if id != 0 {
  325. return false
  326. }
  327. let atom = &mut self.redraw.make_guard(gfxtag!("EmojiPicker::handle_touch"));
  328. let rect = self.rect.get();
  329. let pos = touch_pos - Point::new(rect.x, rect.y);
  330. // We need this cos you cannot hold mutex and call async fn
  331. // todo: clean this up
  332. let mut emoji_is_clicked = false;
  333. {
  334. match phase {
  335. TouchPhase::Started => {
  336. let mut touch_info = self.touch_info.lock();
  337. if !rect.contains(touch_pos) {
  338. return false
  339. }
  340. *touch_info = Some(TouchInfo {
  341. start_pos: pos,
  342. start_scroll: self.scroll.get(),
  343. is_scroll: false,
  344. });
  345. }
  346. TouchPhase::Moved => {
  347. let (touch_info, y_diff) = {
  348. let mut touch_info = self.touch_info.lock();
  349. let Some(touch_info) = touch_info.as_mut() else {
  350. return false;
  351. };
  352. let y_diff = touch_info.start_pos.y - pos.y;
  353. if y_diff.abs() > 0.5 {
  354. touch_info.is_scroll = true;
  355. }
  356. (touch_info.clone(), y_diff)
  357. };
  358. if touch_info.is_scroll {
  359. let mut scroll = touch_info.start_scroll + y_diff;
  360. scroll = scroll.clamp(0., self.max_scroll());
  361. self.scroll.set(atom, scroll);
  362. self.draw_cache.clear();
  363. }
  364. }
  365. TouchPhase::Ended | TouchPhase::Cancelled => {
  366. let touch_info = std::mem::take(&mut *self.touch_info.lock());
  367. let Some(touch_info) = touch_info else { return false };
  368. if !touch_info.is_scroll {
  369. emoji_is_clicked = true;
  370. }
  371. }
  372. }
  373. }
  374. if emoji_is_clicked {
  375. self.click_emoji(pos).await;
  376. }
  377. true
  378. }
  379. }
  380. impl Drop for EmojiPicker {
  381. fn drop(&mut self) {
  382. self.renderer.replace_draw_calls(vec![(self.dc_key, Default::default())]);
  383. }
  384. }
  385. impl std::fmt::Debug for EmojiPicker {
  386. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  387. write!(f, "{:?}", self.node.upgrade().unwrap())
  388. }
  389. }