mod.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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_buffers: freed.buffers,
  673. })
  674. }
  675. async fn handle_key_down(&self, key: KeyCode, mods: KeyMods, repeat: bool) -> bool {
  676. if repeat {
  677. return false
  678. }
  679. match key {
  680. KeyCode::PageUp => {
  681. let scroll = self.scroll.get() + 200.;
  682. self.scrollview(scroll).await;
  683. return true
  684. }
  685. KeyCode::PageDown => {
  686. let scroll = self.scroll.get() - 200.;
  687. self.scrollview(scroll).await;
  688. return true
  689. }
  690. _ => {}
  691. }
  692. false
  693. }
  694. async fn handle_mouse_btn_down(&self, btn: MouseButton, mouse_pos: Point) -> bool {
  695. if btn != MouseButton::Left {
  696. return false
  697. }
  698. let rect = self.rect.get();
  699. if !rect.contains(mouse_pos) {
  700. return false
  701. }
  702. if ENABLE_SELECT {
  703. self.select_line(mouse_pos.y).await;
  704. }
  705. self.mouse_btn_held.store(true, Ordering::Relaxed);
  706. true
  707. }
  708. async fn handle_mouse_btn_up(&self, btn: MouseButton, mouse_pos: Point) -> bool {
  709. if btn != MouseButton::Left {
  710. return false
  711. }
  712. self.mouse_btn_held.store(false, Ordering::Relaxed);
  713. false
  714. }
  715. async fn handle_mouse_move(&self, mouse_pos: Point) -> bool {
  716. //debug!(target: "ui::chatview", "handle_mouse_move({mouse_x}, {mouse_y})");
  717. // We store the mouse pos for use in handle_mouse_wheel()
  718. *self.mouse_pos.lock().unwrap() = mouse_pos.clone();
  719. if !self.mouse_btn_held.load(Ordering::Relaxed) {
  720. return false
  721. }
  722. let rect = self.rect.get();
  723. if !rect.contains(mouse_pos) {
  724. return false
  725. }
  726. if ENABLE_SELECT {
  727. self.select_line(mouse_pos.y).await;
  728. }
  729. false
  730. }
  731. async fn handle_mouse_wheel(&self, wheel_pos: Point) -> bool {
  732. //debug!(target: "ui::chatview", "handle_mouse_wheel({wheel_x}, {wheel_y})");
  733. let rect = self.rect.get();
  734. let mouse_pos = self.mouse_pos.lock().unwrap().clone();
  735. if !rect.contains(mouse_pos) {
  736. //debug!(target: "ui::chatview", "not inside rect");
  737. return false
  738. }
  739. self.speed.fetch_add(wheel_pos.y * self.scroll_start_accel.get(), Ordering::Relaxed);
  740. self.motion_cv.notify();
  741. true
  742. }
  743. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_pos: Point) -> bool {
  744. // Ignore multi-touch
  745. if id != 0 {
  746. return false
  747. }
  748. let rect = self.rect.get();
  749. //debug!(target: "ui::chatview", "handle_touch({phase:?}, {touch_x}, {touch_y})");
  750. let touch_y = touch_pos.y;
  751. if !rect.contains(touch_pos) {
  752. match phase {
  753. TouchPhase::Started => *self.touch_info.lock().unwrap() = None,
  754. _ => self.end_touch_phase(touch_y),
  755. }
  756. return false
  757. }
  758. let select_hold_time = self.select_hold_time.get();
  759. // Simulate mouse events
  760. match phase {
  761. TouchPhase::Started => {
  762. self.touch_is_active.store(true, Ordering::Relaxed);
  763. let mut touch_info = self.touch_info.lock().unwrap();
  764. *touch_info = Some(TouchInfo::new(self.scroll.get(), touch_y));
  765. }
  766. TouchPhase::Moved => {
  767. let (start_scroll, start_y, start_elapsed, do_update, is_select_mode) = {
  768. let mut touch_info = self.touch_info.lock().unwrap();
  769. let Some(touch_info) = &mut *touch_info else { return false };
  770. touch_info.last_y = touch_y;
  771. let start_scroll = touch_info.start_scroll;
  772. let start_y = touch_info.start_y;
  773. let start_elapsed = touch_info.start_instant.elapsed().as_millis_f32();
  774. if start_elapsed > select_hold_time && touch_info.is_select_mode.is_none() {
  775. // Did we move?
  776. if (touch_y - start_y).abs() < BIG_EPSILON {
  777. touch_info.is_select_mode = Some(true);
  778. } else {
  779. touch_info.is_select_mode = Some(false);
  780. }
  781. }
  782. let is_select_mode = touch_info.is_select_mode.clone();
  783. touch_info.push_sample(touch_y);
  784. // Only update screen every 20ms. Avoid wasting cycles.
  785. let last_elapsed = touch_info.last_instant.elapsed().as_millis_f32();
  786. let do_update = last_elapsed > 20.;
  787. if do_update {
  788. touch_info.last_instant = std::time::Instant::now();
  789. }
  790. (start_scroll, start_y, start_elapsed, do_update, is_select_mode)
  791. };
  792. debug!(target: "ui::chatview", "touch phase moved, is_select_mode={is_select_mode:?}");
  793. // When scrolling if we suddenly grab the screen for more than a brief period
  794. // of time then stop the scrolling completely.
  795. if start_elapsed > 200. {
  796. //debug!(target: "ui::chatview", "Stopping scroll accel");
  797. self.speed.store(0., Ordering::Relaxed);
  798. }
  799. // Only update every so often to prevent wasting resources.
  800. if !do_update {
  801. return true
  802. }
  803. // We are in selection mode so don't scroll the screen until touch phase ends.
  804. if let Some(is_select_mode) = is_select_mode &&
  805. is_select_mode
  806. {
  807. if ENABLE_SELECT {
  808. self.select_line(touch_y).await;
  809. }
  810. return true
  811. }
  812. let dist = touch_y - start_y;
  813. // No movement so just return
  814. if dist.abs() < BIG_EPSILON {
  815. return true
  816. }
  817. let scroll = start_scroll + dist;
  818. // Redraws the screen from the cache
  819. self.scrollview(scroll).await;
  820. }
  821. TouchPhase::Ended | TouchPhase::Cancelled => {
  822. self.end_touch_phase(touch_y);
  823. }
  824. }
  825. true
  826. }
  827. }