mod.rs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_lock::Mutex as AsyncMutex;
  19. use async_trait::async_trait;
  20. use atomic_float::AtomicF32;
  21. use darkfi::system::{msleep, CondVar};
  22. use darkfi_serial::{deserialize, Decodable, Encodable, SerialDecodable, SerialEncodable};
  23. use miniquad::{KeyCode, KeyMods, MouseButton, TouchPhase};
  24. use parking_lot::Mutex as SyncMutex;
  25. use rand::{rngs::OsRng, Rng};
  26. use regex::Regex;
  27. use sled_overlay::sled;
  28. use std::{
  29. collections::VecDeque,
  30. io::Cursor,
  31. sync::{
  32. atomic::{AtomicBool, Ordering},
  33. Arc, Weak,
  34. },
  35. };
  36. use tracing::instrument;
  37. use url::Url;
  38. mod page;
  39. use page::{FileMessageStatus, MessageBuffer};
  40. use crate::{
  41. gfx::{gfxtag, DrawCall, DrawInstruction, Point, Rectangle, RenderApi},
  42. prop::{
  43. BatchGuardId, BatchGuardPtr, PropertyAtomicGuard, PropertyBool, PropertyColor,
  44. PropertyFloat32, PropertyRect, PropertyUint32, Role,
  45. },
  46. scene::{MethodCallSub, Pimpl, SceneNodePtr, SceneNodeWeak},
  47. text::TextShaperPtr,
  48. ExecutorPtr,
  49. };
  50. use super::{DrawUpdate, OnModify, UIObject};
  51. macro_rules! d { ($($arg:tt)*) => { debug!(target: "ui::chatview", $($arg)*); } }
  52. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::chatview", $($arg)*); } }
  53. const EPSILON: f32 = 0.001;
  54. const BIG_EPSILON: f32 = 0.05;
  55. // Disable selecting lines for this release.
  56. const ENABLE_SELECT: bool = false;
  57. fn is_zero(x: f32) -> bool {
  58. x.abs() < EPSILON
  59. }
  60. /// std::cmp::max() doesn't work on f32
  61. fn max(a: f32, b: f32) -> f32 {
  62. if a > b {
  63. a
  64. } else {
  65. b
  66. }
  67. }
  68. fn get_file_url(text: &String) -> Option<Url> {
  69. let url_regex = Regex::new(r"fud://[^\s]+").unwrap();
  70. url_regex.find(text).and_then(|match_| Url::parse(match_.as_str()).ok())
  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(Debug, 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_micros() <= 40_000 {
  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_micros() as f32 / 1000., *s))
  125. }
  126. }
  127. pub type ChatViewPtr = Arc<ChatView>;
  128. pub struct ChatView {
  129. node: SceneNodeWeak,
  130. tasks: SyncMutex<Vec<smol::Task<()>>>,
  131. render_api: RenderApi,
  132. sg_root: SceneNodePtr,
  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. /// We use this since there should only ever be a single bg task loading.
  155. bgload_cv: Arc<CondVar>,
  156. /// We use it when we re-eval rect when its changed via property.
  157. parent_rect: SyncMutex<Option<Rectangle>>,
  158. }
  159. impl ChatView {
  160. pub async fn new(
  161. node: SceneNodeWeak,
  162. tree: sled::Tree,
  163. window_scale: PropertyFloat32,
  164. render_api: RenderApi,
  165. text_shaper: TextShaperPtr,
  166. sg_root: SceneNodePtr,
  167. ) -> Pimpl {
  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: SyncMutex::new(vec![]),
  202. render_api: render_api.clone(),
  203. sg_root,
  204. tree,
  205. msgbuf: AsyncMutex::new(MessageBuffer::new(
  206. font_size,
  207. timestamp_font_size,
  208. timestamp_width,
  209. line_height,
  210. message_spacing,
  211. baseline,
  212. timestamp_color,
  213. text_color,
  214. nick_colors,
  215. hi_bg_color,
  216. debug,
  217. window_scale,
  218. render_api,
  219. text_shaper,
  220. )),
  221. dc_key: OsRng.gen(),
  222. mouse_pos: SyncMutex::new(Point::from([0., 0.])),
  223. touch_info: SyncMutex::new(None),
  224. touch_is_active: AtomicBool::new(false),
  225. rect,
  226. scroll,
  227. z_index,
  228. priority,
  229. scroll_start_accel,
  230. scroll_resist,
  231. select_hold_time,
  232. key_scroll_speed,
  233. motion_cv,
  234. speed: AtomicF32::new(0.),
  235. mouse_btn_held: AtomicBool::new(false),
  236. bgload_cv,
  237. parent_rect: SyncMutex::new(None),
  238. });
  239. Pimpl::ChatView(self_)
  240. }
  241. async fn process_insert_line_method(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  242. let Ok(method_call) = sub.receive().await else {
  243. d!("Event relayer closed");
  244. return false
  245. };
  246. t!("method called: insert_line({method_call:?})");
  247. assert!(method_call.send_res.is_none());
  248. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, MessageId, String, String)> {
  249. let mut cur = Cursor::new(&data);
  250. let timestamp = Timestamp::decode(&mut cur)?;
  251. let msg_id = MessageId::decode(&mut cur)?;
  252. let nick = String::decode(&mut cur)?;
  253. let text = String::decode(&mut cur)?;
  254. Ok((timestamp, msg_id, nick, text))
  255. }
  256. let Ok((timestamp, msg_id, nick, text)) = decode_data(&method_call.data) else {
  257. error!(target: "ui::chatview", "insert_line() method invalid arg data");
  258. return true
  259. };
  260. let Some(self_) = me.upgrade() else {
  261. // Should not happen
  262. panic!("self destroyed before insert_line_method_task was stopped!");
  263. };
  264. self_.handle_insert_line(timestamp, msg_id, nick, text).await;
  265. true
  266. }
  267. async fn process_insert_unconf_line_method(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  268. let Ok(method_call) = sub.receive().await else {
  269. d!("Event relayer closed");
  270. return false
  271. };
  272. t!("method called: insert_unconf_line({method_call:?})");
  273. assert!(method_call.send_res.is_none());
  274. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, MessageId, String, String)> {
  275. let mut cur = Cursor::new(&data);
  276. let timestamp = Timestamp::decode(&mut cur)?;
  277. let msg_id = MessageId::decode(&mut cur)?;
  278. let nick = String::decode(&mut cur)?;
  279. let text = String::decode(&mut cur)?;
  280. Ok((timestamp, msg_id, nick, text))
  281. }
  282. let Ok((timestamp, msg_id, nick, text)) = decode_data(&method_call.data) else {
  283. error!(target: "ui::chatview", "insert_unconf_line() method invalid arg data");
  284. return true
  285. };
  286. let Some(self_) = me.upgrade() else {
  287. // Should not happen
  288. panic!("self destroyed before touch_task was stopped!");
  289. };
  290. self_.handle_insert_unconf_line(timestamp, msg_id, nick, text).await;
  291. true
  292. }
  293. /// Mark line as selected
  294. #[instrument(target = "ui::chatview")]
  295. async fn select_line(&self, batch_id: BatchGuardId, 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(batch_id, &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(), 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. #[instrument(target = "ui::chatview")]
  360. pub async fn handle_insert_line(
  361. &self,
  362. timest: Timestamp,
  363. msg_id: MessageId,
  364. nick: String,
  365. text: String,
  366. ) {
  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. let privmsg = msgbuf.insert_privmsg(timest, msg_id.clone(), nick.clone(), text.clone());
  384. if privmsg.is_none() {
  385. // Not visible so no need to redraw
  386. return
  387. }
  388. #[cfg(feature = "enable-plugins")]
  389. if let Some(url) = get_file_url(&text) {
  390. // This is incorrect. Scenegraph paths should not be hardcoded in widgets
  391. // nor should there be dependencies on other widgets.
  392. // Instead use signals and slots through app layer. See how focus is done with
  393. // the edit widgets.
  394. let fud = self.sg_root.lookup_node("/plugin/fud").unwrap();
  395. msgbuf.insert_filemsg(
  396. timest,
  397. msg_id,
  398. FileMessageStatus::Initializing,
  399. nick,
  400. url.clone(),
  401. );
  402. let mut data = vec![];
  403. url.encode(&mut data).unwrap();
  404. fud.call_method("get", data).await.unwrap();
  405. }
  406. }
  407. let atom = self.render_api.make_guard(gfxtag!("ChatView::handle_insert_line"));
  408. self.redraw_cached(atom.batch_id, &mut msgbuf).await;
  409. self.bgload_cv.notify();
  410. }
  411. #[instrument(target = "ui::chatview")]
  412. async fn handle_insert_unconf_line(
  413. &self,
  414. timest: Timestamp,
  415. msg_id: MessageId,
  416. nick: String,
  417. text: String,
  418. ) {
  419. // We don't add unconfirmed lines to the db. Maybe we should?
  420. // Add message to page
  421. let mut msgbuf = self.msgbuf.lock().await;
  422. let Some(privmsg) = msgbuf.insert_privmsg(timest, msg_id, nick, text) else { return };
  423. privmsg.confirmed = false;
  424. let atom = self.render_api.make_guard(gfxtag!("ChatView::handle_insert_unconf_line"));
  425. self.redraw_cached(atom.batch_id, &mut msgbuf).await;
  426. self.bgload_cv.notify();
  427. }
  428. /// Signal to begin scrolling
  429. fn start_scroll(&self, y: f32) {
  430. self.speed.fetch_add(y * self.scroll_start_accel.get(), Ordering::Relaxed);
  431. self.motion_cv.notify();
  432. }
  433. async fn handle_movement(&self) {
  434. // We need to fix this impl because it depends very much on the speed of the device
  435. // that it's running on.
  436. // Look into optimizing scrollview() so scrolling is smooth.
  437. // We could use skiplists to avoid looping from the very bottom.
  438. // So index 1 in the skiplist advances to 100px up... (or however much multiplier)
  439. loop {
  440. msleep(10).await;
  441. if self.touch_is_active.load(Ordering::Relaxed) {
  442. return
  443. }
  444. let mut speed = self.speed.load(Ordering::Relaxed);
  445. // Apply constant decel to speed
  446. speed *= self.scroll_resist.get();
  447. if speed.abs() < BIG_EPSILON {
  448. speed = 0.;
  449. }
  450. self.speed.store(speed, Ordering::Relaxed);
  451. // Finished
  452. if is_zero(speed) {
  453. return
  454. }
  455. let scroll = self.scroll.get() + speed;
  456. let atom = &mut self.render_api.make_guard(gfxtag!("ChatView::motion_task"));
  457. let dist = self.scrollview(scroll, atom).await;
  458. // We reached the end so just stop
  459. if is_zero(dist) {
  460. self.speed.store(0., Ordering::Relaxed);
  461. return
  462. }
  463. }
  464. }
  465. async fn handle_bgload(&self) {
  466. // Do we need to load some more?
  467. let scroll = self.scroll.get();
  468. let rect = self.rect.get();
  469. let top = scroll + rect.h;
  470. let preload_height = PRELOAD_PAGES as f32 * rect.h;
  471. let mut msgbuf = self.msgbuf.lock().await;
  472. let total_height = msgbuf.calc_total_height().await;
  473. if total_height > top + preload_height {
  474. // Nothing to do here
  475. //t!("bgloader: buffer is sufficient [trace_id={trace_id}]");
  476. return
  477. }
  478. // Keep loading until this is below 0
  479. let mut remaining_load_height = top + preload_height - total_height;
  480. let mut remaining_visible = top - total_height;
  481. //t!("bgloader: remaining px = {remaining_load_height}, remaining_visible={remaining_visible} [trace_id={trace_id}]");
  482. // Get the current earliest timestamp
  483. let iter = match msgbuf.oldest_timestamp() {
  484. Some(oldest_timest) => {
  485. // iterate from there
  486. //t!("preloading from {oldest_timest} [trace_id={trace_id}]");
  487. let timest = (oldest_timest - 1).to_be_bytes();
  488. let mut key = [0u8; 8 + 32];
  489. key[..8].clone_from_slice(&timest);
  490. let iter = self.tree.range(..key).rev();
  491. iter
  492. }
  493. None => {
  494. //t!("initial load [trace_id={trace_id}]");
  495. self.tree.iter().rev()
  496. }
  497. };
  498. let mut do_redraw = false;
  499. for entry in iter {
  500. let Ok((k, v)) = entry else { break };
  501. assert_eq!(k.len(), 8 + 32);
  502. let timest_bytes: [u8; 8] = k[..8].try_into().unwrap();
  503. let msg_id = MessageId(k[8..].try_into().unwrap());
  504. let timest = Timestamp::from_be_bytes(timest_bytes);
  505. let chatmsg: ChatMsg = deserialize(&v).unwrap();
  506. //t!("{timest:?} {chatmsg:?} [trace_id={trace_id}]");
  507. let msg_height = msgbuf.push_privmsg(
  508. timest,
  509. msg_id.clone(),
  510. chatmsg.nick.clone(),
  511. chatmsg.text.clone(),
  512. );
  513. // See comment in handle_insert_line()
  514. #[cfg(feature = "enable-plugins")]
  515. if let Some(url) = get_file_url(&chatmsg.text) {
  516. let fud = self.sg_root.lookup_node("/plugin/fud").unwrap();
  517. msgbuf.insert_filemsg(
  518. timest,
  519. msg_id,
  520. FileMessageStatus::Initializing,
  521. chatmsg.nick.clone(),
  522. url.clone(),
  523. );
  524. let mut data = vec![];
  525. url.encode(&mut data).unwrap();
  526. fud.call_method("get", data).await.unwrap();
  527. }
  528. remaining_load_height -= msg_height;
  529. if remaining_load_height <= 0. {
  530. break
  531. }
  532. // Do this once at the end rather than continuously redrawing
  533. if remaining_visible > 0. {
  534. do_redraw = true;
  535. }
  536. remaining_visible -= msg_height;
  537. }
  538. if do_redraw {
  539. let atom = self.render_api.make_guard(gfxtag!("ChatView::handle_bgload"));
  540. self.redraw_cached(atom.batch_id, &mut msgbuf).await;
  541. }
  542. }
  543. async fn scrollview(&self, mut scroll: f32, atom: &mut PropertyAtomicGuard) -> f32 {
  544. let old_scroll = self.scroll.get();
  545. let rect = self.rect.get();
  546. let mut msgbuf = self.msgbuf.lock().await;
  547. // 1/3 of time spent here ~1.5ms
  548. if let Some(new_scroll) = self.adjust_scroll(&mut msgbuf, scroll, rect.h).await {
  549. scroll = new_scroll;
  550. }
  551. // 2/3 of time spent here ~3.3ms
  552. self.redraw_cached(atom.batch_id, &mut msgbuf).await;
  553. self.scroll.set(atom, scroll);
  554. self.bgload_cv.notify();
  555. scroll - old_scroll
  556. }
  557. /// Adjusts a proposed scroll value to clamp it within range. It will load pages until we
  558. /// either run out or we have enough, then checks scroll is within range.
  559. /// Returns None if the value is within range.
  560. async fn adjust_scroll(
  561. &self,
  562. msgbuf: &mut MessageBuffer,
  563. mut scroll: f32,
  564. rect_h: f32,
  565. ) -> Option<f32> {
  566. // We still wish to preload pages to fill the screen, so we just adjust it up to 0.
  567. //let nonneg_scroll = max(scroll, 0.);
  568. if scroll < 0. {
  569. return Some(0.)
  570. }
  571. let total_height = msgbuf.calc_total_height().await;
  572. let max_allowed_scroll = if total_height > rect_h { total_height - rect_h } else { 0. };
  573. if scroll > max_allowed_scroll {
  574. scroll = max_allowed_scroll;
  575. assert!(scroll >= 0.);
  576. return Some(scroll)
  577. }
  578. // Unchanged
  579. None
  580. }
  581. /// Returns draw calls for drawing
  582. async fn get_meshes(
  583. &self,
  584. msgbuf: &mut MessageBuffer,
  585. rect: &Rectangle,
  586. ) -> Vec<DrawInstruction> {
  587. let scroll = self.scroll.get();
  588. //let total_height = msgbuf.calc_total_height().await;
  589. // Use this to start from the top
  590. //let start_pos = if total_height < rect.h { total_height } else { rect.h };
  591. // We start from the bottom though
  592. let start_pos = rect.h;
  593. let mut instrs = vec![];
  594. //let mut old_drawmesh = vec![];
  595. let meshes = msgbuf.gen_meshes(rect, scroll).await;
  596. for (y_pos, mut minstrs) in meshes {
  597. // Apply scroll and scissor
  598. // We use the scissor for scrolling
  599. // Because we use the scissor, our actual rect is now rect instead of parent_rect
  600. let off_x = 0.;
  601. // This calc decides whether scroll is in terms of pages or pixels
  602. let off_y = scroll + start_pos - y_pos;
  603. let pos = Point::from([off_x, off_y]);
  604. instrs.push(DrawInstruction::SetPos(pos));
  605. instrs.append(&mut minstrs);
  606. }
  607. instrs
  608. }
  609. #[instrument(skip(msgbuf), target = "ui::chatview")]
  610. async fn redraw_cached(&self, batch_id: BatchGuardId, msgbuf: &mut MessageBuffer) {
  611. let rect = self.rect.get();
  612. let mut mesh_instrs = self.get_meshes(msgbuf, &rect).await;
  613. let mut instrs = vec![DrawInstruction::ApplyView(rect)];
  614. instrs.append(&mut mesh_instrs);
  615. let draw_calls =
  616. vec![(self.dc_key, DrawCall::new(instrs, vec![], self.z_index.get(), "chatview"))];
  617. self.render_api.replace_draw_calls(batch_id, draw_calls);
  618. }
  619. /// Invalidates cache and redraws everything
  620. #[instrument(target = "ui::chatview")]
  621. async fn redraw_all(&self, atom: &mut PropertyAtomicGuard) {
  622. let parent_rect = self.parent_rect.lock().unwrap().clone();
  623. self.rect.eval(atom, &parent_rect).expect("unable to eval rect");
  624. let mut msgbuf = self.msgbuf.lock().await;
  625. msgbuf.adjust_params();
  626. msgbuf.clear_meshes();
  627. self.redraw_cached(atom.batch_id, &mut msgbuf).await;
  628. }
  629. }
  630. #[async_trait]
  631. impl UIObject for ChatView {
  632. fn priority(&self) -> u32 {
  633. self.priority.get()
  634. }
  635. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  636. let me = Arc::downgrade(&self);
  637. let node_ref = &self.node.upgrade().unwrap();
  638. let method_sub = node_ref.subscribe_method_call("insert_line").unwrap();
  639. let me2 = me.clone();
  640. let insert_line_method_task =
  641. ex.spawn(
  642. async move { while Self::process_insert_line_method(&me2, &method_sub).await {} },
  643. );
  644. let method_sub = node_ref.subscribe_method_call("insert_unconf_line").unwrap();
  645. let me2 = me.clone();
  646. let insert_unconf_line_method_task = ex.spawn(async move {
  647. while Self::process_insert_unconf_line_method(&me2, &method_sub).await {}
  648. });
  649. let me2 = me.clone();
  650. let cv = self.motion_cv.clone();
  651. let motion_task = ex.spawn(async move {
  652. loop {
  653. cv.wait().await;
  654. let Some(self_) = me2.upgrade() else {
  655. // Should not happen
  656. panic!("self destroyed before motion_task was stopped!");
  657. };
  658. self_.handle_movement().await;
  659. cv.reset();
  660. }
  661. });
  662. let me2 = me.clone();
  663. let cv = self.bgload_cv.clone();
  664. let bgload_task = ex.spawn(async move {
  665. loop {
  666. cv.wait().await;
  667. let Some(self_) = me2.upgrade() else {
  668. // Should not happen
  669. panic!("self destroyed before bgload_task was stopped!");
  670. };
  671. self_.handle_bgload().await;
  672. cv.reset();
  673. }
  674. });
  675. let method_sub = node_ref.subscribe_method_call("update_file").unwrap();
  676. let self_ = self.clone();
  677. let update_file_task = ex.spawn(async move {
  678. loop {
  679. let Ok(method_call) = method_sub.receive().await else {
  680. d!("Event relayer closed");
  681. return
  682. };
  683. let mut msgbuf = self_.msgbuf.lock().await;
  684. msgbuf.update_file(&method_call.data).await;
  685. msgbuf.adjust_params();
  686. let atom = self_.render_api.make_guard(gfxtag!("ChatView::update_file_task"));
  687. self_.redraw_cached(atom.batch_id, &mut msgbuf).await;
  688. }
  689. });
  690. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  691. async fn reload_view(self_: Arc<ChatView>, batch: BatchGuardPtr) {
  692. let atom = &mut batch.spawn();
  693. self_.scrollview(self_.scroll.get(), atom).await;
  694. }
  695. on_modify.when_change(self.scroll.prop(), reload_view);
  696. async fn redraw(self_: Arc<ChatView>, batch: BatchGuardPtr) {
  697. if !self_.rect.has_cached() {
  698. return
  699. }
  700. let atom = &mut batch.spawn();
  701. self_.redraw_all(atom).await;
  702. }
  703. //on_modify.when_change(self.baseline.prop(), redraw);
  704. //on_modify.when_change(self.font_size.prop(), redraw);
  705. //on_modify.when_change(self.timestamp_font_size.prop(), redraw);
  706. //on_modify.when_change(self.timestamp_color.prop(), redraw);
  707. //on_modify.when_change(self.timestamp_width.prop(), redraw);
  708. //on_modify.when_change(self.line_height.prop(), redraw);
  709. //on_modify.when_change(self.message_spacing.prop(), redraw);
  710. //on_modify.when_change(self.text_color.prop(), redraw);
  711. //on_modify.when_change(self.nick_colors.clone(), redraw);
  712. //on_modify.when_change(self.hi_bg_color.prop(), redraw);
  713. on_modify.when_change(self.rect.prop(), redraw);
  714. //on_modify.when_change(self.debug.prop(), redraw);
  715. let mut tasks = vec![
  716. insert_line_method_task,
  717. insert_unconf_line_method_task,
  718. motion_task,
  719. bgload_task,
  720. update_file_task,
  721. ];
  722. tasks.append(&mut on_modify.tasks);
  723. *self.tasks.lock() = tasks;
  724. }
  725. fn stop(&self) {
  726. self.tasks.lock().clear();
  727. *self.parent_rect.lock() = None;
  728. // Clear mesh caches
  729. self.msgbuf.lock_blocking().clear();
  730. }
  731. #[instrument(target = "ui::chatview")]
  732. async fn draw(
  733. &self,
  734. parent_rect: Rectangle,
  735. atom: &mut PropertyAtomicGuard,
  736. ) -> Option<DrawUpdate> {
  737. *self.parent_rect.lock() = Some(parent_rect.clone());
  738. self.rect.eval(atom, &parent_rect).ok()?;
  739. let rect = self.rect.get();
  740. let mut msgbuf = self.msgbuf.lock().await;
  741. msgbuf.adjust_window_scale();
  742. msgbuf.adjust_width(rect.w);
  743. msgbuf.clear_meshes();
  744. let scroll = self.scroll.get();
  745. if let Some(scroll) = self.adjust_scroll(&mut msgbuf, scroll, rect.h).await {
  746. self.scroll.set(atom, scroll);
  747. }
  748. // We may need to load more messages since the screen size has changed.
  749. // Now we have updated all the values so it's safe to wake up here.
  750. self.bgload_cv.notify();
  751. let mut mesh_instrs = self.get_meshes(&mut msgbuf, &rect).await;
  752. drop(msgbuf);
  753. let mut instrs = vec![DrawInstruction::ApplyView(rect)];
  754. instrs.append(&mut mesh_instrs);
  755. Some(DrawUpdate {
  756. key: self.dc_key,
  757. draw_calls: vec![(
  758. self.dc_key,
  759. DrawCall::new(instrs, vec![], self.z_index.get(), "chatview"),
  760. )],
  761. })
  762. }
  763. async fn handle_key_down(&self, key: KeyCode, _mods: KeyMods, repeat: bool) -> bool {
  764. if repeat {
  765. return false
  766. }
  767. match key {
  768. KeyCode::PageUp => {
  769. self.start_scroll(1. * self.key_scroll_speed.get());
  770. return true
  771. }
  772. KeyCode::PageDown => {
  773. self.start_scroll(-1. * self.key_scroll_speed.get());
  774. return true
  775. }
  776. _ => {}
  777. }
  778. false
  779. }
  780. async fn handle_mouse_btn_down(&self, btn: MouseButton, mouse_pos: Point) -> bool {
  781. if btn != MouseButton::Left {
  782. return false
  783. }
  784. let rect = self.rect.get();
  785. if !rect.contains(mouse_pos) {
  786. return false
  787. }
  788. let atom = self.render_api.make_guard(gfxtag!("ChatView::handle_mouse_btn_down"));
  789. if ENABLE_SELECT {
  790. self.select_line(atom.batch_id, mouse_pos.y).await;
  791. }
  792. self.mouse_btn_held.store(true, Ordering::Relaxed);
  793. true
  794. }
  795. async fn handle_mouse_btn_up(&self, btn: MouseButton, mouse_pos: Point) -> bool {
  796. t!("handle_mouse_btn_up({btn:?}, {mouse_pos:?})");
  797. if btn != MouseButton::Left {
  798. return false
  799. }
  800. self.mouse_btn_held.store(false, Ordering::Relaxed);
  801. false
  802. }
  803. async fn handle_mouse_move(&self, mouse_pos: Point) -> bool {
  804. //t!("handle_mouse_move({mouse_pos:?})");
  805. // We store the mouse pos for use in handle_mouse_wheel()
  806. *self.mouse_pos.lock() = mouse_pos.clone();
  807. if !self.mouse_btn_held.load(Ordering::Relaxed) {
  808. return false
  809. }
  810. let rect = self.rect.get();
  811. if !rect.contains(mouse_pos) {
  812. return false
  813. }
  814. if ENABLE_SELECT {
  815. let atom = &mut self.render_api.make_guard(gfxtag!("ChatView::handle_mouse_move"));
  816. self.select_line(atom.batch_id, mouse_pos.y).await;
  817. }
  818. false
  819. }
  820. async fn handle_mouse_wheel(&self, wheel_pos: Point) -> bool {
  821. //t!("handle_mouse_wheel({wheel_pos:?})");
  822. let rect = self.rect.get();
  823. let mouse_pos = self.mouse_pos.lock().clone();
  824. if !rect.contains(mouse_pos) {
  825. t!("not inside rect");
  826. return false
  827. }
  828. self.start_scroll(wheel_pos.y);
  829. true
  830. }
  831. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_pos: Point) -> bool {
  832. // Ignore multi-touch
  833. if id != 0 {
  834. return false
  835. }
  836. let rect = self.rect.get();
  837. //t!("handle_touch({phase:?}, {id},{id}, {touch_pos:?})");
  838. let atom = &mut self.render_api.make_guard(gfxtag!("ChatView::handle_touch"));
  839. let touch_y = touch_pos.y;
  840. if !rect.contains(touch_pos) {
  841. match phase {
  842. TouchPhase::Started => *self.touch_info.lock() = None,
  843. _ => self.end_touch_phase(touch_y),
  844. }
  845. return false
  846. }
  847. let select_hold_time = self.select_hold_time.get();
  848. // Simulate mouse events
  849. match phase {
  850. TouchPhase::Started => {
  851. self.touch_is_active.store(true, Ordering::Relaxed);
  852. let mut touch_info = self.touch_info.lock();
  853. *touch_info = Some(TouchInfo::new(self.scroll.get(), touch_y));
  854. }
  855. TouchPhase::Moved => {
  856. let (start_scroll, start_y, start_elapsed, do_update, is_select_mode) = {
  857. let mut touch_info = self.touch_info.lock();
  858. let Some(touch_info) = &mut *touch_info else { return false };
  859. touch_info.last_y = touch_y;
  860. let start_scroll = touch_info.start_scroll;
  861. let start_y = touch_info.start_y;
  862. let start_elapsed =
  863. touch_info.start_instant.elapsed().as_micros() as f32 / 1000.;
  864. if start_elapsed > select_hold_time && touch_info.is_select_mode.is_none() {
  865. // Did we move?
  866. if (touch_y - start_y).abs() < BIG_EPSILON {
  867. touch_info.is_select_mode = Some(true);
  868. } else {
  869. touch_info.is_select_mode = Some(false);
  870. }
  871. }
  872. let is_select_mode = touch_info.is_select_mode.clone();
  873. touch_info.push_sample(touch_y);
  874. // Only update screen every 20ms. Avoid wasting cycles.
  875. let last_elapsed = touch_info.last_instant.elapsed().as_micros();
  876. let do_update = last_elapsed > 20_000;
  877. if do_update {
  878. touch_info.last_instant = std::time::Instant::now();
  879. }
  880. (start_scroll, start_y, start_elapsed, do_update, is_select_mode)
  881. };
  882. t!("touch phase moved, is_select_mode={is_select_mode:?}");
  883. // When scrolling if we suddenly grab the screen for more than a brief period
  884. // of time then stop the scrolling completely.
  885. if start_elapsed > 200. {
  886. t!("Stopping scroll accel");
  887. self.speed.store(0., Ordering::Relaxed);
  888. }
  889. // Only update every so often to prevent wasting resources.
  890. if !do_update {
  891. return true
  892. }
  893. // We are in selection mode so don't scroll the screen until touch phase ends.
  894. if is_select_mode == Some(true) {
  895. if ENABLE_SELECT {
  896. self.select_line(atom.batch_id, touch_y).await;
  897. }
  898. return true
  899. }
  900. let dist = touch_y - start_y;
  901. // No movement so just return
  902. if dist.abs() < BIG_EPSILON {
  903. return true
  904. }
  905. let scroll = start_scroll + dist;
  906. // Redraws the screen from the cache
  907. self.scrollview(scroll, atom).await;
  908. }
  909. TouchPhase::Ended | TouchPhase::Cancelled => {
  910. self.end_touch_phase(touch_y);
  911. }
  912. }
  913. true
  914. }
  915. }
  916. impl Drop for ChatView {
  917. fn drop(&mut self) {
  918. let atom = self.render_api.make_guard(gfxtag!("ChatView::drop"));
  919. self.render_api.replace_draw_calls(atom.batch_id, vec![(self.dc_key, Default::default())]);
  920. }
  921. }
  922. impl std::fmt::Debug for ChatView {
  923. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  924. write!(f, "{:?}", self.node.upgrade().unwrap())
  925. }
  926. }