mod.rs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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_lock::Mutex as AsyncMutex;
  19. use async_trait::async_trait;
  20. use atomic_float::AtomicF32;
  21. use chrono::{Local, TimeZone};
  22. use darkfi::system::{msleep, CondVar};
  23. use darkfi_serial::{deserialize, Decodable, Encodable, SerialDecodable, SerialEncodable};
  24. use miniquad::{KeyCode, KeyMods, MouseButton, TouchPhase};
  25. use rand::{rngs::OsRng, Rng};
  26. use sled_overlay::sled;
  27. use std::{
  28. collections::VecDeque,
  29. hash::{DefaultHasher, Hash, Hasher},
  30. io::Cursor,
  31. sync::{
  32. atomic::{AtomicBool, Ordering},
  33. Arc, Mutex as SyncMutex, OnceLock, Weak,
  34. },
  35. };
  36. mod page;
  37. use page::MessageBuffer;
  38. use crate::{
  39. gfx::{
  40. GfxDrawCall, GfxDrawInstruction, GfxDrawMesh, GraphicsEventPublisherPtr, Point, Rectangle,
  41. RenderApi,
  42. },
  43. mesh::{Color, MeshBuilder, COLOR_BLUE, COLOR_GREEN},
  44. prop::{
  45. PropertyBool, PropertyColor, PropertyFloat32, PropertyPtr, PropertyRect, PropertyUint32,
  46. Role,
  47. },
  48. pubsub::Subscription,
  49. scene::{MethodCallSub, Pimpl, SceneNodeWeak},
  50. text::{self, Glyph, GlyphPositionIter, TextShaperPtr},
  51. ui::FreedData,
  52. util::{enumerate, is_whitespace},
  53. ExecutorPtr,
  54. };
  55. use super::{DrawUpdate, OnModify, UIObject};
  56. const EPSILON: f32 = 0.001;
  57. const BIG_EPSILON: f32 = 0.05;
  58. // Disable selecting lines for this release.
  59. const ENABLE_SELECT: bool = false;
  60. fn is_zero(x: f32) -> bool {
  61. x.abs() < EPSILON
  62. }
  63. /// std::cmp::max() doesn't work on f32
  64. fn max(a: f32, b: f32) -> f32 {
  65. if a > b {
  66. a
  67. } else {
  68. b
  69. }
  70. }
  71. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  72. pub struct ChatMsg {
  73. pub nick: String,
  74. pub text: String,
  75. }
  76. type Timestamp = u64;
  77. #[derive(Clone, SerialEncodable, SerialDecodable, PartialEq)]
  78. pub struct MessageId(pub [u8; 32]);
  79. impl std::fmt::Display for MessageId {
  80. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  81. for b in &self.0 {
  82. write!(f, "{b:02x}")?
  83. }
  84. Ok(())
  85. }
  86. }
  87. const PRELOAD_PAGES: usize = 1;
  88. #[derive(Clone)]
  89. struct TouchInfo {
  90. start_scroll: f32,
  91. start_y: f32,
  92. start_instant: std::time::Instant,
  93. /// Used for flick scrolling
  94. samples: VecDeque<(std::time::Instant, f32)>,
  95. last_instant: std::time::Instant,
  96. last_y: f32,
  97. /// Selection started?
  98. is_select_mode: Option<bool>,
  99. }
  100. impl TouchInfo {
  101. fn new(start_scroll: f32, y: f32) -> Self {
  102. Self {
  103. start_scroll,
  104. start_y: y,
  105. start_instant: std::time::Instant::now(),
  106. samples: VecDeque::from([(std::time::Instant::now(), y)]),
  107. last_instant: std::time::Instant::now(),
  108. last_y: y,
  109. is_select_mode: None,
  110. }
  111. }
  112. fn push_sample(&mut self, y: f32) {
  113. self.samples.push_back((std::time::Instant::now(), y));
  114. // Now drop all old samples older than 40ms
  115. while let Some((instant, _)) = self.samples.front() {
  116. if instant.elapsed().as_millis_f32() <= 40. {
  117. break
  118. }
  119. self.samples.pop_front().unwrap();
  120. }
  121. }
  122. fn first_sample(&self) -> Option<(f32, f32)> {
  123. self.samples.front().map(|(t, s)| (t.elapsed().as_millis_f32(), *s))
  124. }
  125. }
  126. pub type ChatViewPtr = Arc<ChatView>;
  127. pub struct ChatView {
  128. node: SceneNodeWeak,
  129. tasks: OnceLock<Vec<smol::Task<()>>>,
  130. render_api: RenderApi,
  131. text_shaper: TextShaperPtr,
  132. tree: sled::Tree,
  133. msgbuf: AsyncMutex<MessageBuffer>,
  134. dc_key: u64,
  135. /// Used for detecting when scrolling view
  136. mouse_pos: SyncMutex<Point>,
  137. /// Touch scrolling
  138. touch_info: SyncMutex<Option<TouchInfo>>,
  139. touch_is_active: AtomicBool,
  140. rect: PropertyRect,
  141. scroll: PropertyFloat32,
  142. z_index: PropertyUint32,
  143. scroll_start_accel: PropertyFloat32,
  144. scroll_resist: PropertyFloat32,
  145. select_hold_time: PropertyFloat32,
  146. /// Scroll accel
  147. motion_cv: Arc<CondVar>,
  148. speed: AtomicF32,
  149. mouse_btn_held: AtomicBool,
  150. /// Triggers the background loading task to wake up
  151. bgload_cv: Arc<CondVar>,
  152. /// We use it when we re-eval rect when its changed via property.
  153. parent_rect: SyncMutex<Option<Rectangle>>,
  154. }
  155. impl ChatView {
  156. pub async fn new(
  157. node: SceneNodeWeak,
  158. tree: sled::Tree,
  159. window_scale: PropertyFloat32,
  160. render_api: RenderApi,
  161. text_shaper: TextShaperPtr,
  162. ex: ExecutorPtr,
  163. ) -> Pimpl {
  164. debug!(target: "ui::chatview", "ChatView::new()");
  165. let node_ref = &node.upgrade().unwrap();
  166. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  167. let scroll = PropertyFloat32::wrap(node_ref, Role::Internal, "scroll", 0).unwrap();
  168. let font_size = PropertyFloat32::wrap(node_ref, Role::Internal, "font_size", 0).unwrap();
  169. let timestamp_font_size =
  170. PropertyFloat32::wrap(node_ref, Role::Internal, "timestamp_font_size", 0).unwrap();
  171. let timestamp_width =
  172. PropertyFloat32::wrap(node_ref, Role::Internal, "timestamp_width", 0).unwrap();
  173. let line_height =
  174. PropertyFloat32::wrap(node_ref, Role::Internal, "line_height", 0).unwrap();
  175. let message_spacing =
  176. PropertyFloat32::wrap(node_ref, Role::Internal, "message_spacing", 0).unwrap();
  177. let baseline = PropertyFloat32::wrap(node_ref, Role::Internal, "baseline", 0).unwrap();
  178. let timestamp_color =
  179. PropertyColor::wrap(node_ref, Role::Internal, "timestamp_color").unwrap();
  180. let text_color = PropertyColor::wrap(node_ref, Role::Internal, "text_color").unwrap();
  181. let nick_colors = node_ref.get_property("nick_colors").expect("ChatView::nick_colors");
  182. let hi_bg_color = PropertyColor::wrap(node_ref, Role::Internal, "hi_bg_color").unwrap();
  183. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  184. let debug = PropertyBool::wrap(node_ref, Role::Internal, "debug", 0).unwrap();
  185. let scroll_start_accel =
  186. PropertyFloat32::wrap(node_ref, Role::Internal, "scroll_start_accel", 0).unwrap();
  187. let scroll_resist =
  188. PropertyFloat32::wrap(node_ref, Role::Internal, "scroll_resist", 0).unwrap();
  189. let select_hold_time =
  190. PropertyFloat32::wrap(node_ref, Role::Internal, "select_hold_time", 0).unwrap();
  191. let motion_cv = Arc::new(CondVar::new());
  192. let bgload_cv = Arc::new(CondVar::new());
  193. let self_ = Arc::new(Self {
  194. node: node.clone(),
  195. tasks: OnceLock::new(),
  196. render_api: render_api.clone(),
  197. text_shaper: text_shaper.clone(),
  198. tree,
  199. msgbuf: AsyncMutex::new(MessageBuffer::new(
  200. node,
  201. font_size,
  202. timestamp_font_size,
  203. timestamp_width,
  204. line_height,
  205. message_spacing,
  206. baseline,
  207. timestamp_color,
  208. text_color,
  209. nick_colors,
  210. hi_bg_color,
  211. debug,
  212. window_scale,
  213. render_api,
  214. text_shaper,
  215. )),
  216. dc_key: OsRng.gen(),
  217. mouse_pos: SyncMutex::new(Point::from([0., 0.])),
  218. touch_info: SyncMutex::new(None),
  219. touch_is_active: AtomicBool::new(false),
  220. rect,
  221. scroll,
  222. z_index,
  223. scroll_start_accel,
  224. scroll_resist,
  225. select_hold_time,
  226. motion_cv,
  227. speed: AtomicF32::new(0.),
  228. mouse_btn_held: AtomicBool::new(false),
  229. bgload_cv,
  230. parent_rect: SyncMutex::new(None),
  231. });
  232. Pimpl::ChatView(self_)
  233. }
  234. async fn process_insert_line_method(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  235. let Ok(method_call) = sub.receive().await else {
  236. debug!(target: "ui::chatview", "Event relayer closed");
  237. return false
  238. };
  239. //debug!(target: "ui::chatview", "method called: insert_line({method_call:?})");
  240. assert!(method_call.send_res.is_none());
  241. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, MessageId, String, String)> {
  242. let mut cur = Cursor::new(&data);
  243. let timestamp = Timestamp::decode(&mut cur)?;
  244. let msg_id = MessageId::decode(&mut cur)?;
  245. let nick = String::decode(&mut cur)?;
  246. let text = String::decode(&mut cur)?;
  247. Ok((timestamp, msg_id, nick, text))
  248. }
  249. let Ok((timestamp, msg_id, nick, text)) = decode_data(&method_call.data) else {
  250. error!(target: "ui::chatview", "insert_line() method invalid arg data");
  251. return true
  252. };
  253. let Some(self_) = me.upgrade() else {
  254. // Should not happen
  255. panic!("self destroyed before touch_task was stopped!");
  256. };
  257. self_.handle_insert_line(timestamp, msg_id, nick, text).await;
  258. true
  259. }
  260. async fn process_insert_unconf_line_method(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  261. let Ok(method_call) = sub.receive().await else {
  262. debug!(target: "ui::chatview", "Event relayer closed");
  263. return false
  264. };
  265. //debug!(target: "ui::chatview", "method called: insert_line({method_call:?})");
  266. assert!(method_call.send_res.is_none());
  267. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, MessageId, String, String)> {
  268. let mut cur = Cursor::new(&data);
  269. let timestamp = Timestamp::decode(&mut cur)?;
  270. let msg_id = MessageId::decode(&mut cur)?;
  271. let nick = String::decode(&mut cur)?;
  272. let text = String::decode(&mut cur)?;
  273. Ok((timestamp, msg_id, nick, text))
  274. }
  275. let Ok((timestamp, msg_id, nick, text)) = decode_data(&method_call.data) else {
  276. error!(target: "ui::chatview", "insert_unconf_line() method invalid arg data");
  277. return true
  278. };
  279. let Some(self_) = me.upgrade() else {
  280. // Should not happen
  281. panic!("self destroyed before touch_task was stopped!");
  282. };
  283. self_.handle_insert_unconf_line(timestamp, msg_id, nick, text).await;
  284. true
  285. }
  286. /// Mark line as selected
  287. async fn select_line(&self, mut y: f32) {
  288. // The cursor is inside the rect. We just have to find which line it clicked.
  289. let rect = self.rect.get();
  290. // y coord within widget's screen rect
  291. y -= rect.y;
  292. // The scroll is the position of the bottom of the rect on screen
  293. let scroll = self.scroll.get();
  294. // Now what is its distance from the absolute bottom
  295. y = rect.h - y + scroll;
  296. let mut msgbuf = self.msgbuf.lock().await;
  297. msgbuf.select_line(y).await;
  298. self.redraw_cached(&mut msgbuf).await;
  299. }
  300. fn end_touch_phase(&self, touch_y: f32) {
  301. // Now calculate scroll acceleration
  302. let touch_info = std::mem::replace(&mut *self.touch_info.lock().unwrap(), None);
  303. let Some(touch_info) = &touch_info else { return };
  304. self.touch_is_active.store(false, Ordering::Relaxed);
  305. // No scroll accel with selection mode
  306. if touch_info.is_select_mode.is_some() {
  307. return
  308. }
  309. let Some((time, sample_y)) = touch_info.first_sample() else { return };
  310. let dist = touch_y - sample_y;
  311. // Ignore sub-ms events
  312. if time < 1. {
  313. error!(target: "ui::chatview", "Received a sub-ms touch event!");
  314. return
  315. }
  316. //let speed = dist / time;
  317. //self.speed.fetch_add(speed, Ordering::Relaxed);
  318. //debug!(target: "ui::chatview", "speed = {dist} / {time} = {speed}");
  319. let accel = self.scroll_start_accel.get() * dist / time;
  320. let touch_time = touch_info.start_instant.elapsed();
  321. debug!(target: "ui::chatview", "accel = {dist} / {time} = {accel}, touch = {touch_time:?}");
  322. self.speed.fetch_add(accel, Ordering::Relaxed);
  323. self.motion_cv.notify();
  324. }
  325. async fn add_line_to_db(
  326. &self,
  327. timest: Timestamp,
  328. msg_id: &MessageId,
  329. nick: &str,
  330. text: &str,
  331. ) -> bool {
  332. assert!(timest > 6047051717);
  333. let timest = timest.to_be_bytes();
  334. assert_eq!(timest.len(), 8);
  335. let mut key = [0u8; 8 + 32];
  336. key[..8].clone_from_slice(&timest);
  337. key[8..].clone_from_slice(&msg_id.0);
  338. // When does this return Err?
  339. let contains_key = self.tree.contains_key(&key);
  340. if contains_key.is_err() || contains_key.unwrap() {
  341. // Already exists
  342. return false
  343. }
  344. let msg = ChatMsg { nick: nick.to_string(), text: text.to_string() };
  345. let mut val = vec![];
  346. msg.encode(&mut val).unwrap();
  347. self.tree.insert(&key, val).unwrap();
  348. let _ = self.tree.flush_async().await;
  349. true
  350. }
  351. async fn handle_insert_line(
  352. &self,
  353. timest: Timestamp,
  354. msg_id: MessageId,
  355. nick: String,
  356. text: String,
  357. ) {
  358. debug!(target: "ui::chatview", "handle_insert_line({timest}, {msg_id}, {nick}, {text})");
  359. // Lock message buffer so background loader doesn't load the message as soon as it's
  360. // inserted into the DB.
  361. let mut msgbuf = self.msgbuf.lock().await;
  362. if !self.add_line_to_db(timest, &msg_id, &nick, &text).await {
  363. // Already exists so bail
  364. debug!(target: "ui::chatview", "duplicate msg so bailing");
  365. return
  366. }
  367. // Add message to page
  368. if msgbuf.mark_confirmed(&msg_id) {
  369. // Message already exists. Which means it must be an unconfirmed sent message.
  370. // Mark it as confirmed.
  371. debug!(target: "ui::chatview", "Mark sent message as confirmed");
  372. } else {
  373. // Insert the privmsg since it doesn't already exist
  374. if msgbuf.insert_privmsg(timest, msg_id, nick, text).is_none() {
  375. // Not visible so no need to redraw
  376. return
  377. }
  378. }
  379. self.redraw_cached(&mut msgbuf).await;
  380. self.bgload_cv.notify();
  381. }
  382. async fn handle_insert_unconf_line(
  383. &self,
  384. timest: Timestamp,
  385. msg_id: MessageId,
  386. nick: String,
  387. text: String,
  388. ) {
  389. debug!(target: "ui::chatview", "handle_insert_unconf_line({timest}, {msg_id}, {nick}, {text})");
  390. // We don't add unconfirmed lines to the db. Maybe we should?
  391. // Add message to page
  392. let mut msgbuf = self.msgbuf.lock().await;
  393. let Some(privmsg) = msgbuf.insert_privmsg(timest, msg_id, nick, text) else { return };
  394. privmsg.confirmed = false;
  395. self.redraw_cached(&mut msgbuf).await;
  396. self.bgload_cv.notify();
  397. }
  398. async fn handle_movement(&self) {
  399. // We need to fix this impl because it depends very much on the speed of the device
  400. // that it's running on.
  401. // Look into optimizing scrollview() so scrolling is smooth.
  402. // We could use skiplists to avoid looping from the very bottom.
  403. // So index 1 in the skiplist advances to 100px up... (or however much multiplier)
  404. loop {
  405. msleep(10).await;
  406. if self.touch_is_active.load(Ordering::Relaxed) {
  407. return
  408. }
  409. let mut speed = self.speed.load(Ordering::Relaxed);
  410. // Apply constant decel to speed
  411. speed *= self.scroll_resist.get();
  412. if speed.abs() < BIG_EPSILON {
  413. speed = 0.;
  414. }
  415. self.speed.store(speed, Ordering::Relaxed);
  416. // Finished
  417. if is_zero(speed) {
  418. return
  419. }
  420. let scroll = self.scroll.get() + speed;
  421. let dist = self.scrollview(scroll).await;
  422. // We reached the end so just stop
  423. if is_zero(dist) {
  424. self.speed.store(0., Ordering::Relaxed);
  425. return
  426. }
  427. }
  428. }
  429. async fn handle_bgload(&self) {
  430. //debug!(target: "ui::chatview", "ChatView::handle_bgload()");
  431. // Do we need to load some more?
  432. let scroll = self.scroll.get();
  433. let rect = self.rect.get();
  434. let top = scroll + rect.h;
  435. let preload_height = PRELOAD_PAGES as f32 * rect.h;
  436. let mut msgbuf = self.msgbuf.lock().await;
  437. let total_height = msgbuf.calc_total_height().await;
  438. if total_height > top + preload_height {
  439. // Nothing to do here
  440. //debug!(target: "ui::chatview", "bgloader: buffer is sufficient");
  441. return
  442. }
  443. // Keep loading until this is below 0
  444. let mut remaining_load_height = top + preload_height - total_height;
  445. //debug!(target: "ui::chatview", "bgloader: remaining px = {remaining_load_height}");
  446. let mut remaining_visible = top - total_height;
  447. // Get the current earliest timestamp
  448. let iter = match msgbuf.oldest_timestamp() {
  449. Some(oldest_timest) => {
  450. // iterate from there
  451. //debug!(target: "ui::chatview", "preloading from {oldest_timest}");
  452. let timest = (oldest_timest - 1).to_be_bytes();
  453. let mut key = [0u8; 8 + 32];
  454. key[..8].clone_from_slice(&timest);
  455. let iter = self.tree.range(..key).rev();
  456. iter
  457. }
  458. None => {
  459. //debug!(target: "ui::chatview", "initial load");
  460. self.tree.iter().rev()
  461. }
  462. };
  463. for entry in iter {
  464. let Ok((k, v)) = entry else { break };
  465. assert_eq!(k.len(), 8 + 32);
  466. let timest_bytes: [u8; 8] = k[..8].try_into().unwrap();
  467. let msg_id = MessageId(k[8..].try_into().unwrap());
  468. let timest = Timestamp::from_be_bytes(timest_bytes);
  469. let chatmsg: ChatMsg = deserialize(&v).unwrap();
  470. debug!(target: "ui::chatview", "{timest:?} {chatmsg:?}");
  471. let msg_height = msgbuf.push_privmsg(timest, msg_id, chatmsg.nick, chatmsg.text);
  472. remaining_load_height -= msg_height;
  473. if remaining_load_height <= 0. {
  474. break
  475. }
  476. if remaining_visible > 0. {
  477. self.redraw_cached(&mut msgbuf).await;
  478. }
  479. remaining_visible -= msg_height;
  480. }
  481. }
  482. async fn scrollview(&self, mut scroll: f32) -> f32 {
  483. //debug!(target: "ui::chatview", "scrollview()");
  484. let old_scroll = self.scroll.get();
  485. let rect = self.rect.get();
  486. let mut msgbuf = self.msgbuf.lock().await;
  487. // 1/3 of time spent here ~1.5ms
  488. if let Some(new_scroll) = self.adjust_scroll(&mut msgbuf, scroll, rect.h).await {
  489. scroll = new_scroll;
  490. }
  491. // 2/3 of time spent here ~3.3ms
  492. self.redraw_cached(&mut msgbuf).await;
  493. self.scroll.set(scroll);
  494. self.bgload_cv.notify();
  495. scroll - old_scroll
  496. }
  497. /// Adjusts a proposed scroll value to clamp it within range. It will load pages until we
  498. /// either run out or we have enough, then checks scroll is within range.
  499. /// Returns None if the value is within range.
  500. async fn adjust_scroll(
  501. &self,
  502. msgbuf: &mut MessageBuffer,
  503. mut scroll: f32,
  504. rect_h: f32,
  505. ) -> Option<f32> {
  506. // We still wish to preload pages to fill the screen, so we just adjust it up to 0.
  507. let nonneg_scroll = max(scroll, 0.);
  508. if scroll < 0. {
  509. return Some(0.)
  510. }
  511. let total_height = msgbuf.calc_total_height().await;
  512. let max_allowed_scroll = if total_height > rect_h { total_height - rect_h } else { 0. };
  513. if scroll > max_allowed_scroll {
  514. scroll = max_allowed_scroll;
  515. assert!(scroll >= 0.);
  516. return Some(scroll)
  517. }
  518. // Unchanged
  519. None
  520. }
  521. /// Returns draw calls for drawing
  522. async fn get_meshes(
  523. &self,
  524. msgbuf: &mut MessageBuffer,
  525. rect: &Rectangle,
  526. ) -> (Vec<GfxDrawInstruction>, FreedData) {
  527. let scroll = self.scroll.get();
  528. let total_height = msgbuf.calc_total_height().await;
  529. // Use this to start from the top
  530. //let start_pos = if total_height < rect.h { total_height } else { rect.h };
  531. // We start from the bottom though
  532. let start_pos = rect.h;
  533. let mut instrs = vec![];
  534. //let mut old_drawmesh = vec![];
  535. let meshes = msgbuf.gen_meshes(rect, scroll).await;
  536. for (i, (y_pos, mesh)) in enumerate(meshes) {
  537. // Apply scroll and scissor
  538. // We use the scissor for scrolling
  539. // Because we use the scissor, our actual rect is now rect instead of parent_rect
  540. let off_x = 0.;
  541. // This calc decides whether scroll is in terms of pages or pixels
  542. let off_y = (scroll + start_pos - y_pos);
  543. let pos = Point::from([0., off_y]);
  544. instrs.push(GfxDrawInstruction::Move(pos));
  545. instrs.push(GfxDrawInstruction::Draw(mesh));
  546. }
  547. let freed = std::mem::take(&mut msgbuf.freed);
  548. (instrs, freed)
  549. }
  550. async fn redraw_cached(&self, msgbuf: &mut MessageBuffer) {
  551. let rect = self.rect.get();
  552. let (mut mesh_instrs, freed) = self.get_meshes(msgbuf, &rect).await;
  553. let mut instrs = vec![GfxDrawInstruction::ApplyView(rect)];
  554. instrs.append(&mut mesh_instrs);
  555. let draw_calls =
  556. vec![(self.dc_key, GfxDrawCall { instrs, dcs: vec![], z_index: self.z_index.get() })];
  557. self.render_api.replace_draw_calls(draw_calls);
  558. for buffer_id in freed.buffers {
  559. self.render_api.delete_buffer(buffer_id);
  560. }
  561. }
  562. /// Invalidates cache and redraws everything
  563. async fn redraw_all(&self) {
  564. debug!(target: "ui::chatview", "redraw_all()");
  565. let mut msgbuf = self.msgbuf.lock().await;
  566. msgbuf.adjust_params();
  567. msgbuf.clear_meshes();
  568. self.redraw_cached(&mut msgbuf).await;
  569. }
  570. }
  571. #[async_trait]
  572. impl UIObject for ChatView {
  573. fn z_index(&self) -> u32 {
  574. self.z_index.get()
  575. }
  576. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  577. let me = Arc::downgrade(&self);
  578. let node_ref = &self.node.upgrade().unwrap();
  579. let node_name = node_ref.name.clone();
  580. let node_id = node_ref.id;
  581. let method_sub = node_ref.subscribe_method_call("insert_line").unwrap();
  582. let me2 = me.clone();
  583. let insert_line_method_task =
  584. ex.spawn(
  585. async move { while Self::process_insert_line_method(&me2, &method_sub).await {} },
  586. );
  587. let method_sub = node_ref.subscribe_method_call("insert_unconf_line").unwrap();
  588. let me2 = me.clone();
  589. let insert_unconf_line_method_task = ex.spawn(async move {
  590. while Self::process_insert_unconf_line_method(&me2, &method_sub).await {}
  591. });
  592. let me2 = me.clone();
  593. let cv = self.motion_cv.clone();
  594. let motion_task = ex.spawn(async move {
  595. loop {
  596. cv.wait().await;
  597. let Some(self_) = me2.upgrade() else {
  598. // Should not happen
  599. panic!("self destroyed before motion_task was stopped!");
  600. };
  601. self_.handle_movement().await;
  602. cv.reset();
  603. }
  604. });
  605. let me2 = me.clone();
  606. let cv = self.bgload_cv.clone();
  607. let bgload_task = ex.spawn(async move {
  608. loop {
  609. cv.wait().await;
  610. let Some(self_) = me2.upgrade() else {
  611. // Should not happen
  612. panic!("self destroyed before bgload_task was stopped!");
  613. };
  614. self_.handle_bgload().await;
  615. cv.reset();
  616. }
  617. });
  618. let mut on_modify = OnModify::new(ex, node_name, node_id, me.clone());
  619. async fn reload_view(self_: Arc<ChatView>) {
  620. self_.scrollview(self_.scroll.get()).await;
  621. }
  622. on_modify.when_change(self.scroll.prop(), reload_view);
  623. async fn redraw(self_: Arc<ChatView>) {
  624. self_.redraw_all().await;
  625. }
  626. // These should be inside the class
  627. /*
  628. on_modify.when_change(self.baseline.prop(), redraw);
  629. on_modify.when_change(self.font_size.prop(), redraw);
  630. on_modify.when_change(self.timestamp_font_size.prop(), redraw);
  631. on_modify.when_change(self.timestamp_color.prop(), redraw);
  632. on_modify.when_change(self.timestamp_width.prop(), redraw);
  633. on_modify.when_change(self.line_height.prop(), redraw);
  634. on_modify.when_change(self.message_spacing.prop(), redraw);
  635. on_modify.when_change(self.text_color.prop(), redraw);
  636. on_modify.when_change(self.nick_colors.clone(), redraw);
  637. on_modify.when_change(self.hi_bg_color.prop(), redraw);
  638. on_modify.when_change(self.rect.prop(), redraw);
  639. on_modify.when_change(self.debug.prop(), redraw);
  640. */
  641. let mut tasks =
  642. vec![insert_line_method_task, insert_unconf_line_method_task, motion_task, bgload_task];
  643. tasks.append(&mut on_modify.tasks);
  644. self.tasks.set(tasks);
  645. }
  646. async fn draw(&self, parent_rect: Rectangle) -> Option<DrawUpdate> {
  647. debug!(target: "ui::chatview", "ChatView::draw()");
  648. *self.parent_rect.lock().unwrap() = Some(parent_rect.clone());
  649. self.rect.eval(&parent_rect).ok()?;
  650. let rect = self.rect.get();
  651. let mut msgbuf = self.msgbuf.lock().await;
  652. msgbuf.adjust_window_scale();
  653. msgbuf.adjust_width(rect.w);
  654. msgbuf.clear_meshes();
  655. let mut scroll = self.scroll.get();
  656. if let Some(scroll) = self.adjust_scroll(&mut msgbuf, scroll, rect.h).await {
  657. self.scroll.set(scroll);
  658. }
  659. // We may need to load more messages since the screen size has changed.
  660. // Now we have updated all the values so it's safe to wake up here.
  661. self.bgload_cv.notify();
  662. let (mut mesh_instrs, freed) = self.get_meshes(&mut msgbuf, &rect).await;
  663. drop(msgbuf);
  664. let mut instrs = vec![GfxDrawInstruction::ApplyView(rect)];
  665. instrs.append(&mut mesh_instrs);
  666. Some(DrawUpdate {
  667. key: self.dc_key,
  668. draw_calls: vec![(
  669. self.dc_key,
  670. GfxDrawCall { instrs, dcs: vec![], z_index: self.z_index.get() },
  671. )],
  672. freed_textures: freed.textures,
  673. freed_buffers: freed.buffers,
  674. })
  675. }
  676. async fn handle_key_down(&self, key: KeyCode, mods: KeyMods, repeat: bool) -> bool {
  677. if repeat {
  678. return false
  679. }
  680. match key {
  681. KeyCode::PageUp => {
  682. let scroll = self.scroll.get() + 200.;
  683. self.scrollview(scroll).await;
  684. return true
  685. }
  686. KeyCode::PageDown => {
  687. let scroll = self.scroll.get() - 200.;
  688. self.scrollview(scroll).await;
  689. return true
  690. }
  691. _ => {}
  692. }
  693. false
  694. }
  695. async fn handle_mouse_btn_down(&self, btn: MouseButton, mouse_pos: Point) -> bool {
  696. if btn != MouseButton::Left {
  697. return false
  698. }
  699. let rect = self.rect.get();
  700. if !rect.contains(mouse_pos) {
  701. return false
  702. }
  703. if ENABLE_SELECT {
  704. self.select_line(mouse_pos.y).await;
  705. }
  706. self.mouse_btn_held.store(true, Ordering::Relaxed);
  707. true
  708. }
  709. async fn handle_mouse_btn_up(&self, btn: MouseButton, mouse_pos: Point) -> bool {
  710. if btn != MouseButton::Left {
  711. return false
  712. }
  713. self.mouse_btn_held.store(false, Ordering::Relaxed);
  714. false
  715. }
  716. async fn handle_mouse_move(&self, mouse_pos: Point) -> bool {
  717. //debug!(target: "ui::chatview", "handle_mouse_move({mouse_x}, {mouse_y})");
  718. // We store the mouse pos for use in handle_mouse_wheel()
  719. *self.mouse_pos.lock().unwrap() = mouse_pos.clone();
  720. if !self.mouse_btn_held.load(Ordering::Relaxed) {
  721. return false
  722. }
  723. let rect = self.rect.get();
  724. if !rect.contains(mouse_pos) {
  725. return false
  726. }
  727. if ENABLE_SELECT {
  728. self.select_line(mouse_pos.y).await;
  729. }
  730. false
  731. }
  732. async fn handle_mouse_wheel(&self, wheel_pos: Point) -> bool {
  733. //debug!(target: "ui::chatview", "handle_mouse_wheel({wheel_x}, {wheel_y})");
  734. let rect = self.rect.get();
  735. let mouse_pos = self.mouse_pos.lock().unwrap().clone();
  736. if !rect.contains(mouse_pos) {
  737. //debug!(target: "ui::chatview", "not inside rect");
  738. return false
  739. }
  740. self.speed.fetch_add(wheel_pos.y * self.scroll_start_accel.get(), Ordering::Relaxed);
  741. self.motion_cv.notify();
  742. true
  743. }
  744. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_pos: Point) -> bool {
  745. // Ignore multi-touch
  746. if id != 0 {
  747. return false
  748. }
  749. let rect = self.rect.get();
  750. //debug!(target: "ui::chatview", "handle_touch({phase:?}, {touch_x}, {touch_y})");
  751. let touch_y = touch_pos.y;
  752. if !rect.contains(touch_pos) {
  753. match phase {
  754. TouchPhase::Started => *self.touch_info.lock().unwrap() = None,
  755. _ => self.end_touch_phase(touch_y),
  756. }
  757. return false
  758. }
  759. let select_hold_time = self.select_hold_time.get();
  760. // Simulate mouse events
  761. match phase {
  762. TouchPhase::Started => {
  763. self.touch_is_active.store(true, Ordering::Relaxed);
  764. let mut touch_info = self.touch_info.lock().unwrap();
  765. *touch_info = Some(TouchInfo::new(self.scroll.get(), touch_y));
  766. }
  767. TouchPhase::Moved => {
  768. let (start_scroll, start_y, start_elapsed, do_update, is_select_mode) = {
  769. let mut touch_info = self.touch_info.lock().unwrap();
  770. let Some(touch_info) = &mut *touch_info else { return false };
  771. touch_info.last_y = touch_y;
  772. let start_scroll = touch_info.start_scroll;
  773. let start_y = touch_info.start_y;
  774. let start_elapsed = touch_info.start_instant.elapsed().as_millis_f32();
  775. if start_elapsed > select_hold_time && touch_info.is_select_mode.is_none() {
  776. // Did we move?
  777. if (touch_y - start_y).abs() < BIG_EPSILON {
  778. touch_info.is_select_mode = Some(true);
  779. } else {
  780. touch_info.is_select_mode = Some(false);
  781. }
  782. }
  783. let is_select_mode = touch_info.is_select_mode.clone();
  784. touch_info.push_sample(touch_y);
  785. // Only update screen every 20ms. Avoid wasting cycles.
  786. let last_elapsed = touch_info.last_instant.elapsed().as_millis_f32();
  787. let do_update = last_elapsed > 20.;
  788. if do_update {
  789. touch_info.last_instant = std::time::Instant::now();
  790. }
  791. (start_scroll, start_y, start_elapsed, do_update, is_select_mode)
  792. };
  793. debug!(target: "ui::chatview", "touch phase moved, is_select_mode={is_select_mode:?}");
  794. // When scrolling if we suddenly grab the screen for more than a brief period
  795. // of time then stop the scrolling completely.
  796. if start_elapsed > 200. {
  797. //debug!(target: "ui::chatview", "Stopping scroll accel");
  798. self.speed.store(0., Ordering::Relaxed);
  799. }
  800. // Only update every so often to prevent wasting resources.
  801. if !do_update {
  802. return true
  803. }
  804. // We are in selection mode so don't scroll the screen until touch phase ends.
  805. if let Some(is_select_mode) = is_select_mode &&
  806. is_select_mode
  807. {
  808. if ENABLE_SELECT {
  809. self.select_line(touch_y).await;
  810. }
  811. return true
  812. }
  813. let dist = touch_y - start_y;
  814. // No movement so just return
  815. if dist.abs() < BIG_EPSILON {
  816. return true
  817. }
  818. let scroll = start_scroll + dist;
  819. // Redraws the screen from the cache
  820. self.scrollview(scroll).await;
  821. }
  822. TouchPhase::Ended | TouchPhase::Cancelled => {
  823. self.end_touch_phase(touch_y);
  824. }
  825. }
  826. true
  827. }
  828. }