mod.rs 34 KB

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