mod.rs 33 KB

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