chatview.rs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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 atomic_float::AtomicF32;
  20. use chrono::{Local, TimeZone};
  21. use darkfi::system::{msleep, CondVar};
  22. use darkfi_serial::{
  23. async_trait, deserialize, Decodable, Encodable, FutAsyncWriteExt, ReadExt, SerialDecodable,
  24. SerialEncodable, VarInt,
  25. };
  26. use miniquad::{KeyCode, KeyMods, TouchPhase};
  27. use rand::{rngs::OsRng, Rng};
  28. use std::{
  29. collections::BTreeMap,
  30. hash::{DefaultHasher, Hash, Hasher},
  31. io::Cursor,
  32. sync::{atomic::Ordering, Arc, Mutex as SyncMutex, Weak},
  33. };
  34. use crate::{
  35. error::Result,
  36. gfx2::{
  37. DrawCall, DrawInstruction, DrawMesh, GraphicsEventPublisherPtr, Point, Rectangle,
  38. RenderApi, RenderApiPtr, Vertex,
  39. },
  40. mesh::{Color, MeshBuilder, MeshInfo, COLOR_BLUE, COLOR_GREEN, COLOR_GREY, COLOR_WHITE},
  41. prop::{
  42. PropertyBool, PropertyColor, PropertyFloat32, PropertyPtr, PropertyStr, PropertyUint32,
  43. Role,
  44. },
  45. pubsub::Subscription,
  46. scene::{Pimpl, SceneGraph, SceneGraphPtr2, SceneNodeId},
  47. text2::{self, Glyph, GlyphPositionIter, SpritePtr, TextShaper, TextShaperPtr},
  48. util::zip3,
  49. ExecutorPtr,
  50. };
  51. use super::{eval_rect, get_parent_rect, read_rect, DrawUpdate, OnModify, Stoppable};
  52. const DEBUG_RENDER: bool = false;
  53. const EPSILON: f32 = 0.001;
  54. const BIG_EPSILON: f32 = 0.05;
  55. fn is_whitespace(s: &str) -> bool {
  56. s.chars().all(char::is_whitespace)
  57. }
  58. fn is_zero(x: f32) -> bool {
  59. x.abs() < EPSILON
  60. }
  61. // Replace vec item with N items
  62. fn replace_vec_item<T>(vec: &mut Vec<T>, idx: usize, mut items: Vec<T>) {
  63. assert!(idx < vec.len());
  64. if items.len() == 1 {
  65. let item = items.remove(0);
  66. std::mem::replace(&mut vec[idx], item);
  67. return
  68. }
  69. let mut drain_iter = vec.drain(idx..);
  70. // Drop the item at idx which will be replaced
  71. drain_iter.next().unwrap();
  72. let mut tail: Vec<_> = drain_iter.collect();
  73. vec.append(&mut items);
  74. vec.append(&mut tail);
  75. }
  76. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  77. pub struct ChatMsg {
  78. pub nick: String,
  79. pub text: String,
  80. }
  81. type Timestamp = u64;
  82. type MessageId = [u8; 32];
  83. #[derive(Clone)]
  84. struct Message {
  85. timest: Timestamp,
  86. id: MessageId,
  87. chatmsg: ChatMsg,
  88. glyphs: Vec<Glyph>,
  89. }
  90. const PAGE_SIZE: usize = 10;
  91. const PRELOAD_PAGES: usize = 10;
  92. #[derive(Clone)]
  93. struct Page {
  94. msgs: Vec<Message>,
  95. atlas: text2::RenderedAtlas,
  96. }
  97. #[derive(Clone)]
  98. struct PageMeshInfo {
  99. px_height: f32,
  100. mesh: DrawMesh,
  101. }
  102. type Page2Ptr = Arc<Page2>;
  103. struct Page2 {
  104. msgs: Vec<Message>,
  105. atlas: SyncMutex<text2::RenderedAtlas>,
  106. // One draw call per page.
  107. // Resizing the canvas means we recalc wrapping and the mesh changes
  108. mesh_inf: SyncMutex<Option<PageMeshInfo>>,
  109. }
  110. impl Page2 {
  111. async fn new(msgs: Vec<Message>, render_api: &RenderApi) -> Arc<Self> {
  112. let mut atlas = text2::Atlas::new(render_api);
  113. for msg in &msgs {
  114. atlas.push(&msg.glyphs);
  115. }
  116. let Ok(atlas) = atlas.make().await else {
  117. // what else should I do here?
  118. panic!("unable to make atlas!");
  119. };
  120. Arc::new(Self { msgs, atlas: SyncMutex::new(atlas), mesh_inf: SyncMutex::new(None) })
  121. }
  122. /// Regenerates the mesh, returning the old mesh which should be freed
  123. async fn regen_mesh(
  124. &self,
  125. clip: &Rectangle,
  126. render_api: &RenderApi,
  127. font_size: f32,
  128. line_height: f32,
  129. baseline: f32,
  130. nick_colors: &[Color],
  131. timestamp_color: Color,
  132. text_color: Color,
  133. ) -> (PageMeshInfo, Option<DrawMesh>) {
  134. let mut wrapped_line_idx = 0;
  135. let mut mesh = MeshBuilder::new();
  136. let atlas = self.atlas.lock().unwrap().clone();
  137. for msg in &self.msgs {
  138. let glyphs = &msg.glyphs;
  139. let nick_color = select_nick_color(&msg.chatmsg.nick, nick_colors);
  140. // Keep track of the 'section'
  141. // Section 0 is the timestamp
  142. // Section 1 is the nickname (colorized)
  143. // Finally is just the message itself
  144. let mut section = 2;
  145. let mut lines = text2::wrap(clip.w, font_size, glyphs);
  146. // We are drawing bottom up but line wrap gives us lines in normal order
  147. lines.reverse();
  148. let last_idx = lines.len() - 1;
  149. for (i, line) in lines.into_iter().enumerate() {
  150. let off_y = (wrapped_line_idx + 1) as f32 * line_height;
  151. if i == last_idx {
  152. section = 0;
  153. }
  154. // debug draw baseline
  155. //let y = baseline - off_y;
  156. //mesh.draw_filled_box(&Rectangle { x: 0., y: y - 1., w: clip.w, h: 1. }, COLOR_BLUE);
  157. // Render line
  158. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &line, baseline);
  159. for (mut glyph_rect, glyph) in glyph_pos_iter.zip(line.iter()) {
  160. let uv_rect = atlas.fetch_uv(glyph.glyph_id).expect("missing glyph UV rect");
  161. glyph_rect.y -= off_y;
  162. let color = match section {
  163. 0 => timestamp_color,
  164. 1 => nick_color,
  165. _ => text_color,
  166. };
  167. //mesh.draw_outline(&glyph_rect, COLOR_BLUE, 2.);
  168. mesh.draw_box(&glyph_rect, color, uv_rect);
  169. if section < 2 && is_whitespace(&glyph.substr) {
  170. section += 1;
  171. }
  172. }
  173. wrapped_line_idx += 1;
  174. }
  175. }
  176. let px_height = wrapped_line_idx as f32 * line_height;
  177. mesh.draw_outline(&Rectangle { x: 0., y: 0., w: clip.w, h: -px_height }, COLOR_GREEN, 1.);
  178. let mesh = mesh.alloc(render_api).await.unwrap();
  179. let mesh = mesh.draw_with_texture(atlas.texture_id);
  180. let mesh_inf = PageMeshInfo { px_height, mesh };
  181. let old = std::mem::replace(&mut *self.mesh_inf.lock().unwrap(), Some(mesh_inf.clone()));
  182. let old = old.map(|v| v.mesh);
  183. (mesh_inf, old)
  184. }
  185. }
  186. fn select_nick_color(nick: &str, nick_colors: &[Color]) -> Color {
  187. let mut hasher = DefaultHasher::new();
  188. nick.hash(&mut hasher);
  189. let i = hasher.finish() as usize;
  190. let color = nick_colors[i % nick_colors.len()];
  191. color
  192. }
  193. #[derive(Clone)]
  194. struct TouchInfo {
  195. start_scroll: f32,
  196. start_y: f32,
  197. start_instant: std::time::Instant,
  198. last_y: f32,
  199. }
  200. impl TouchInfo {
  201. fn new() -> Self {
  202. Self { start_scroll: 0., start_y: 0., start_instant: std::time::Instant::now(), last_y: 0. }
  203. }
  204. }
  205. pub type ChatViewPtr = Arc<ChatView>;
  206. pub struct ChatView {
  207. node_id: SceneNodeId,
  208. tasks: Vec<smol::Task<()>>,
  209. sg: SceneGraphPtr2,
  210. render_api: RenderApiPtr,
  211. text_shaper: TextShaperPtr,
  212. tree: sled::Tree,
  213. pages: SyncMutex<Vec<Page>>,
  214. pages2: AsyncMutex<Vec<Page2Ptr>>,
  215. drawcalls: SyncMutex<Vec<DrawMesh>>,
  216. dc_key: u64,
  217. /// Used for detecting when scrolling view
  218. mouse_pos: SyncMutex<Point>,
  219. /// Touch scrolling
  220. touch_info: SyncMutex<TouchInfo>,
  221. rect: PropertyPtr,
  222. scroll: PropertyFloat32,
  223. font_size: PropertyFloat32,
  224. line_height: PropertyFloat32,
  225. baseline: PropertyFloat32,
  226. timestamp_color: PropertyColor,
  227. text_color: PropertyColor,
  228. nick_colors: PropertyPtr,
  229. z_index: PropertyUint32,
  230. mouse_scroll_start_accel: PropertyFloat32,
  231. mouse_scroll_decel: PropertyFloat32,
  232. mouse_scroll_resist: PropertyFloat32,
  233. // Scroll accel
  234. motion_cv: Arc<CondVar>,
  235. accel: AtomicF32,
  236. speed: AtomicF32,
  237. }
  238. impl ChatView {
  239. pub async fn new(
  240. ex: ExecutorPtr,
  241. sg: SceneGraphPtr2,
  242. node_id: SceneNodeId,
  243. render_api: RenderApiPtr,
  244. event_pub: GraphicsEventPublisherPtr,
  245. text_shaper: TextShaperPtr,
  246. tree: sled::Tree,
  247. recvr: async_channel::Receiver<Vec<u8>>,
  248. ) -> Pimpl {
  249. debug!(target: "ui::chatview", "ChatView::new()");
  250. let scene_graph = sg.lock().await;
  251. let node = scene_graph.get_node(node_id).unwrap();
  252. let node_name = node.name.clone();
  253. let rect = node.get_property("rect").expect("ChatView::rect");
  254. let scroll = PropertyFloat32::wrap(node, Role::Internal, "scroll", 0).unwrap();
  255. let font_size = PropertyFloat32::wrap(node, Role::Internal, "font_size", 0).unwrap();
  256. let line_height = PropertyFloat32::wrap(node, Role::Internal, "line_height", 0).unwrap();
  257. let baseline = PropertyFloat32::wrap(node, Role::Internal, "baseline", 0).unwrap();
  258. let timestamp_color = PropertyColor::wrap(node, Role::Internal, "timestamp_color").unwrap();
  259. let text_color = PropertyColor::wrap(node, Role::Internal, "text_color").unwrap();
  260. let nick_colors = node.get_property("nick_colors").expect("ChatView::nick_colors");
  261. let z_index = PropertyUint32::wrap(node, Role::Internal, "z_index", 0).unwrap();
  262. let mouse_scroll_start_accel =
  263. PropertyFloat32::wrap(node, Role::Internal, "mouse_scroll_start_accel", 0).unwrap();
  264. let mouse_scroll_decel =
  265. PropertyFloat32::wrap(node, Role::Internal, "mouse_scroll_decel", 0).unwrap();
  266. let mouse_scroll_resist =
  267. PropertyFloat32::wrap(node, Role::Internal, "mouse_scroll_resist", 0).unwrap();
  268. drop(scene_graph);
  269. let self_ = Arc::new_cyclic(|me: &Weak<Self>| {
  270. let ev_sub = event_pub.subscribe_mouse_wheel();
  271. let me2 = me.clone();
  272. let mouse_wheel_task =
  273. ex.spawn(async move { while Self::process_mouse_wheel(&me2, &ev_sub).await {} });
  274. let ev_sub = event_pub.subscribe_mouse_move();
  275. let me2 = me.clone();
  276. let mouse_move_task =
  277. ex.spawn(async move { while Self::process_mouse_move(&me2, &ev_sub).await {} });
  278. let ev_sub = event_pub.subscribe_touch();
  279. let me2 = me.clone();
  280. let touch_task =
  281. ex.spawn(async move { while Self::process_touch(&me2, &ev_sub).await {} });
  282. let ev_sub = event_pub.subscribe_key_down();
  283. let me2 = me.clone();
  284. let key_down_task =
  285. ex.spawn(async move { while Self::process_key_down(&me2, &ev_sub).await {} });
  286. let me2 = me.clone();
  287. let insert_line_method_task =
  288. ex.spawn(
  289. async move { while Self::process_insert_line_method(&me2, &recvr).await {} },
  290. );
  291. let me2 = me.clone();
  292. let motion_cv = Arc::new(CondVar::new());
  293. let cv = motion_cv.clone();
  294. let motion_task = ex.spawn(async move {
  295. loop {
  296. cv.wait().await;
  297. let Some(self_) = me2.upgrade() else {
  298. // Should not happen
  299. panic!("self destroyed before motion_task was stopped!");
  300. };
  301. self_.handle_movement().await;
  302. cv.reset();
  303. }
  304. });
  305. let mut on_modify = OnModify::new(ex, node_name, node_id, me.clone());
  306. async fn reload_view(self_: Arc<ChatView>) {
  307. self_.scrollview(self_.scroll.get()).await;
  308. }
  309. on_modify.when_change(scroll.prop(), reload_view);
  310. async fn redraw(self_: Arc<ChatView>) {
  311. self_.redraw().await;
  312. }
  313. on_modify.when_change(rect.clone(), redraw);
  314. let mut tasks = vec![
  315. mouse_wheel_task,
  316. mouse_move_task,
  317. touch_task,
  318. key_down_task,
  319. insert_line_method_task,
  320. motion_task,
  321. ];
  322. tasks.append(&mut on_modify.tasks);
  323. Self {
  324. node_id,
  325. tasks,
  326. sg,
  327. render_api,
  328. text_shaper,
  329. tree,
  330. pages: SyncMutex::new(Vec::new()),
  331. pages2: AsyncMutex::new(Vec::new()),
  332. drawcalls: SyncMutex::new(Vec::new()),
  333. dc_key: OsRng.gen(),
  334. mouse_pos: SyncMutex::new(Point::from([0., 0.])),
  335. touch_info: SyncMutex::new(TouchInfo::new()),
  336. rect,
  337. scroll,
  338. font_size,
  339. line_height,
  340. baseline,
  341. timestamp_color,
  342. text_color,
  343. nick_colors,
  344. z_index,
  345. mouse_scroll_start_accel,
  346. mouse_scroll_decel,
  347. mouse_scroll_resist,
  348. motion_cv,
  349. accel: AtomicF32::new(0.),
  350. speed: AtomicF32::new(0.),
  351. }
  352. });
  353. let timer = std::time::Instant::now();
  354. self_.populate().await;
  355. debug!(target: "ui::chatview", "populate() took {:?}", timer.elapsed());
  356. Pimpl::ChatView(self_)
  357. }
  358. async fn process_mouse_wheel(me: &Weak<Self>, ev_sub: &Subscription<(f32, f32)>) -> bool {
  359. let Ok((wheel_x, wheel_y)) = ev_sub.receive().await else {
  360. debug!(target: "ui::chatview", "Event relayer closed");
  361. return false
  362. };
  363. let Some(self_) = me.upgrade() else {
  364. // Should not happen
  365. panic!("self destroyed before mouse_wheel_task was stopped!");
  366. };
  367. self_.handle_mouse_wheel(wheel_x, wheel_y).await;
  368. true
  369. }
  370. async fn process_mouse_move(me: &Weak<Self>, ev_sub: &Subscription<(f32, f32)>) -> bool {
  371. let Ok((mouse_x, mouse_y)) = ev_sub.receive().await else {
  372. debug!(target: "ui::chatview", "Event relayer closed");
  373. return false
  374. };
  375. let Some(self_) = me.upgrade() else {
  376. // Should not happen
  377. panic!("self destroyed before mouse_move_task was stopped!");
  378. };
  379. self_.handle_mouse_move(mouse_x, mouse_y).await;
  380. true
  381. }
  382. async fn process_touch(
  383. me: &Weak<Self>,
  384. ev_sub: &Subscription<(TouchPhase, u64, f32, f32)>,
  385. ) -> bool {
  386. let Ok((phase, id, touch_x, touch_y)) = ev_sub.receive().await else {
  387. debug!(target: "ui::chatview", "Event relayer closed");
  388. return false
  389. };
  390. let Some(self_) = me.upgrade() else {
  391. // Should not happen
  392. panic!("self destroyed before touch_task was stopped!");
  393. };
  394. self_.handle_touch(phase, id, touch_x, touch_y).await;
  395. true
  396. }
  397. async fn process_key_down(
  398. me: &Weak<Self>,
  399. ev_sub: &Subscription<(KeyCode, KeyMods, bool)>,
  400. ) -> bool {
  401. let Ok((key, mods, repeat)) = ev_sub.receive().await else {
  402. debug!(target: "ui::editbox", "Event relayer closed");
  403. return false
  404. };
  405. if repeat {
  406. return true
  407. }
  408. let Some(self_) = me.upgrade() else {
  409. // Should not happen
  410. panic!("self destroyed before char_task was stopped!");
  411. };
  412. match key {
  413. KeyCode::PageUp => {
  414. let scroll = self_.scroll.get() + 200.;
  415. self_.scrollview(scroll).await;
  416. }
  417. KeyCode::PageDown => {
  418. let scroll = self_.scroll.get() - 200.;
  419. self_.scrollview(scroll).await;
  420. }
  421. _ => {}
  422. }
  423. true
  424. }
  425. async fn process_insert_line_method(
  426. me: &Weak<Self>,
  427. recvr: &async_channel::Receiver<Vec<u8>>,
  428. ) -> bool {
  429. let Ok(data) = recvr.recv().await else {
  430. debug!(target: "ui::chatview", "Event relayer closed");
  431. return false
  432. };
  433. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, MessageId, String, String)> {
  434. let mut cur = Cursor::new(&data);
  435. let timestamp = Timestamp::decode(&mut cur)?;
  436. let message_id = MessageId::decode(&mut cur)?;
  437. let nick = String::decode(&mut cur)?;
  438. let text = String::decode(&mut cur)?;
  439. Ok((timestamp, message_id, nick, text))
  440. }
  441. let Ok((timestamp, message_id, nick, text)) = decode_data(&data) else {
  442. error!(target: "ui::chatview", "insert_line() method invalid arg data");
  443. return true
  444. };
  445. let Some(self_) = me.upgrade() else {
  446. // Should not happen
  447. panic!("self destroyed before touch_task was stopped!");
  448. };
  449. self_.handle_insert_line(timestamp, message_id, nick, text).await;
  450. true
  451. }
  452. async fn handle_mouse_wheel(&self, wheel_x: f32, wheel_y: f32) {
  453. debug!(target: "ui::chatview", "handle_mouse_wheel({wheel_x}, {wheel_y})");
  454. let Some(rect) = self.get_cached_world_rect().await else { return };
  455. let mouse_pos = self.mouse_pos.lock().unwrap().clone();
  456. if !rect.contains(&mouse_pos) {
  457. //debug!(target: "ui::chatview", "not inside rect");
  458. return
  459. }
  460. //debug!(target: "ui::chatview", "inside rect");
  461. //let scroll = self.scroll.get() + wheel_y * 50.;
  462. //self.scrollview(scroll).await;
  463. self.accel.fetch_add(wheel_y * self.mouse_scroll_start_accel.get(), Ordering::Relaxed);
  464. self.motion_cv.notify();
  465. }
  466. async fn handle_mouse_move(&self, mouse_x: f32, mouse_y: f32) {
  467. //debug!(target: "ui::chatview", "handle_mouse_move({mouse_x}, {mouse_y})");
  468. let mut mouse_pos = self.mouse_pos.lock().unwrap();
  469. mouse_pos.x = mouse_x;
  470. mouse_pos.y = mouse_y;
  471. }
  472. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_x: f32, touch_y: f32) {
  473. // Ignore multi-touch
  474. if id != 0 {
  475. return
  476. }
  477. // Simulate mouse events
  478. match phase {
  479. TouchPhase::Started => {
  480. let mut touch_info = self.touch_info.lock().unwrap();
  481. touch_info.start_scroll = self.scroll.get();
  482. touch_info.start_y = touch_y;
  483. touch_info.start_instant = std::time::Instant::now();
  484. touch_info.last_y = touch_y;
  485. }
  486. TouchPhase::Moved => {
  487. let (start_scroll, start_y) = {
  488. let mut touch_info = self.touch_info.lock().unwrap();
  489. touch_info.last_y = touch_y;
  490. (touch_info.start_scroll, touch_info.start_y)
  491. };
  492. let dist = touch_y - start_y;
  493. // TODO the line selected should be fixed and move exactly that distance
  494. // No use of multipliers
  495. // TODO we are maybe doing too many updates so make a widget to 'slow down'
  496. // how often we move to fixed intervals.
  497. // draw a poly shape and eval each line segment.
  498. let scroll = start_scroll + dist;
  499. self.scrollview(scroll).await;
  500. }
  501. TouchPhase::Ended => {
  502. // Now calculate scroll acceleration
  503. let touch_info = self.touch_info.lock().unwrap().clone();
  504. let time = touch_info.start_instant.elapsed().as_millis_f32();
  505. let dist = touch_y - touch_info.start_y;
  506. let accel = self.mouse_scroll_start_accel.get() * dist / time;
  507. self.accel.fetch_add(accel, Ordering::Relaxed);
  508. self.motion_cv.notify();
  509. }
  510. TouchPhase::Cancelled => {}
  511. }
  512. }
  513. async fn handle_insert_line(
  514. &self,
  515. timest: Timestamp,
  516. message_id: MessageId,
  517. nick: String,
  518. text: String,
  519. ) {
  520. debug!(target: "ui::chatview", "handle_insert_line({timest}, {message_id:?}, {nick}, {text})");
  521. let chatmsg = ChatMsg { nick, text };
  522. let dt = Local.timestamp_millis_opt(timest as i64).unwrap();
  523. let timestr = dt.format("%H:%M").to_string();
  524. let text = format!("{} {} {}", timestr, chatmsg.nick, chatmsg.text);
  525. let glyphs = self.text_shaper.shape(text, self.font_size.get()).await;
  526. // Now add message to page
  527. let mut pages = self.pages2.lock().await;
  528. let mut idx = None;
  529. for (i, page) in pages.iter_mut().enumerate() {
  530. let first_timest = page.msgs.last().unwrap().timest;
  531. let last_timest = page.msgs.first().unwrap().timest;
  532. //debug!(target: "ui::chatview", "page {i} [{first_timest}, {last_timest}]");
  533. if first_timest <= timest && timest <= last_timest {
  534. //debug!(target: "ui::chatview", "found page {i} [{first_timest}, {last_timest}]");
  535. idx = Some(i);
  536. break
  537. }
  538. }
  539. let idx = match idx {
  540. Some(idx) => idx,
  541. None => {
  542. //debug!(target: "ui::chatview", "no page found");
  543. 0
  544. }
  545. };
  546. let page = &mut pages[idx];
  547. let mut msgs = page.msgs.clone();
  548. msgs.push(Message { timest, id: message_id, chatmsg, glyphs });
  549. msgs.sort_unstable_by_key(|msg| msg.timest);
  550. msgs.reverse();
  551. let chunk_size = if msgs.len() > PAGE_SIZE {
  552. // Round up so we don't get a weird page with a single item
  553. msgs.len() / 2 + 1
  554. } else {
  555. PAGE_SIZE
  556. };
  557. // Replace single page with N pages each with chunk_size messages
  558. let mut new_pages = vec![];
  559. for page_msgs in msgs.chunks(chunk_size).map(|m| m.to_vec()) {
  560. debug!(target: "ui::chatview", "PAGE ==========================");
  561. for msg in &page_msgs {
  562. debug!(target: "ui::chatview", "{} {:?}", msg.timest, msg.chatmsg);
  563. }
  564. debug!(target: "ui::chatview", "===============================");
  565. let new_page = Page2::new(page_msgs, &self.render_api).await;
  566. new_pages.push(new_page);
  567. }
  568. replace_vec_item(&mut pages, idx, new_pages);
  569. drop(pages);
  570. // This will refresh the view, so we just use this
  571. let mut scroll = self.scroll.get();
  572. self.scrollview(scroll).await;
  573. }
  574. async fn handle_movement(&self) {
  575. loop {
  576. msleep(20).await;
  577. let mut accel = self.accel.load(Ordering::Relaxed);
  578. let mut speed = self.speed.fetch_add(accel, Ordering::Relaxed) + accel;
  579. accel *= self.mouse_scroll_decel.get();
  580. if accel.abs() < 0.05 {
  581. accel = 0.;
  582. }
  583. self.accel.store(accel, Ordering::Relaxed);
  584. // Apply constant decel to speed
  585. if is_zero(accel) {
  586. speed *= self.mouse_scroll_resist.get();
  587. if speed.abs() < BIG_EPSILON {
  588. speed = 0.;
  589. }
  590. self.speed.store(speed, Ordering::Relaxed);
  591. }
  592. // Finished
  593. if is_zero(accel) && is_zero(speed) {
  594. return
  595. }
  596. if is_zero(speed) {
  597. self.accel.store(0., Ordering::Relaxed);
  598. self.speed.store(0., Ordering::Relaxed);
  599. return
  600. }
  601. let scroll = self.scroll.get() + speed;
  602. let dist = self.scrollview(scroll).await;
  603. if is_zero(dist) {
  604. self.accel.store(0., Ordering::Relaxed);
  605. self.speed.store(0., Ordering::Relaxed);
  606. return
  607. }
  608. }
  609. }
  610. /// Descent = line height - baseline
  611. fn descent(&self) -> f32 {
  612. self.line_height.get() - self.baseline.get()
  613. }
  614. /// Beware of this method. Here be dragons.
  615. /// Possibly racy so we limit it just to mouse stuff (for now).
  616. fn cached_rect(&self) -> Option<Rectangle> {
  617. let Ok(rect) = read_rect(self.rect.clone()) else {
  618. error!(target: "ui::chatview", "cached_rect is None");
  619. return None
  620. };
  621. Some(rect)
  622. }
  623. async fn get_parent_rect(&self) -> Option<Rectangle> {
  624. let sg = self.sg.lock().await;
  625. let node = sg.get_node(self.node_id).unwrap();
  626. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  627. return None;
  628. };
  629. drop(sg);
  630. Some(parent_rect)
  631. }
  632. async fn get_cached_world_rect(&self) -> Option<Rectangle> {
  633. // NBD if it's slightly wrong
  634. let mut rect = self.cached_rect()?;
  635. // If layers can be nested and we use offsets for (x, y)
  636. // then this will be incorrect for nested layers.
  637. // For now we don't allow nesting of layers.
  638. let parent_rect = self.get_parent_rect().await?;
  639. // Offset rect which is now in world coords
  640. rect.x += parent_rect.x;
  641. rect.y += parent_rect.y;
  642. Some(rect)
  643. }
  644. async fn populate(&self) {
  645. let iter = self.tree.iter().rev();
  646. self.load_n_pages(iter, PRELOAD_PAGES).await;
  647. }
  648. /// Load extra pages
  649. async fn preload_pages(&self) -> usize {
  650. // Get last page
  651. let last_page = self.pages2.lock().await.last().unwrap().clone();
  652. // get the current earliest timestamp
  653. let last_timest = last_page.msgs.last().unwrap().timest;
  654. // iterate from there
  655. let key = last_timest.to_be_bytes();
  656. debug!(target: "ui::chatview", "preloading from {key:?}");
  657. let iter = self.tree.range(..key).rev();
  658. self.load_n_pages(iter, PRELOAD_PAGES).await
  659. }
  660. async fn load_n_pages<I: Iterator<Item = sled::Result<(sled::IVec, sled::IVec)>>>(
  661. &self,
  662. iter: I,
  663. n: usize,
  664. ) -> usize {
  665. let mut pages_len = 0;
  666. let mut msgs = vec![];
  667. for entry in iter {
  668. let Ok((k, v)) = entry else { break };
  669. assert_eq!(k.len(), 8 + 32);
  670. let timest_bytes: [u8; 8] = k[..8].try_into().unwrap();
  671. let message_id: MessageId = k[8..].try_into().unwrap();
  672. let timest = Timestamp::from_be_bytes(timest_bytes);
  673. let chatmsg: ChatMsg = deserialize(&v).unwrap();
  674. debug!(target: "ui::chatview", "{timest:?} {chatmsg:?}");
  675. let dt = Local.timestamp_millis_opt(timest as i64).unwrap();
  676. let timestr = dt.format("%H:%M").to_string();
  677. let text = format!("{} {} {}", timestr, chatmsg.nick, chatmsg.text);
  678. let glyphs = self.text_shaper.shape(text, self.font_size.get()).await;
  679. msgs.push(Message { timest, id: message_id, chatmsg, glyphs });
  680. if msgs.len() >= PAGE_SIZE {
  681. let msgs = std::mem::take(&mut msgs);
  682. let page = Page2::new(msgs, &self.render_api).await;
  683. self.pages2.lock().await.push(page);
  684. pages_len += 1;
  685. if pages_len >= n {
  686. break
  687. }
  688. }
  689. }
  690. // Any remaining messages added to a short page
  691. if !msgs.is_empty() {
  692. let page = Page2::new(msgs, &self.render_api).await;
  693. self.pages2.lock().await.push(page);
  694. pages_len += 1;
  695. }
  696. debug!(target: "ui::chatview", "populated {} pages", pages_len);
  697. pages_len
  698. }
  699. async fn get_total_height(&self, rect: &Rectangle, pages: &Vec<Page2Ptr>) -> f32 {
  700. let font_size = self.font_size.get();
  701. let line_height = self.line_height.get();
  702. let baseline = self.baseline.get();
  703. let timest_color = self.timestamp_color.get();
  704. let text_color = self.text_color.get();
  705. let nick_colors = self.read_nick_colors();
  706. // Nudge the bottom line up slightly, otherwise chars like p will cross the bottom.
  707. let mut current_height = self.descent();
  708. for page in pages {
  709. let mesh_inf = page.mesh_inf.lock().unwrap().clone();
  710. let mesh_inf = match mesh_inf {
  711. Some(mesh_inf) => mesh_inf,
  712. None => {
  713. let (mesh_inf, old_drawmesh) = page
  714. .regen_mesh(
  715. &rect,
  716. &self.render_api,
  717. font_size,
  718. line_height,
  719. baseline,
  720. &nick_colors,
  721. timest_color.clone(),
  722. text_color.clone(),
  723. )
  724. .await;
  725. assert!(old_drawmesh.is_none());
  726. mesh_inf
  727. }
  728. };
  729. current_height += mesh_inf.px_height;
  730. }
  731. current_height
  732. }
  733. async fn draw_cached(&self, mut rect: Rectangle, scroll: &mut f32) -> Vec<DrawInstruction> {
  734. let mut instrs = vec![];
  735. if *scroll < 0. {
  736. *scroll = 0.;
  737. }
  738. // Make sure we have enough pages loaded.
  739. // If there's no more to load then adjust the scroll.
  740. let mut pages = self.pages2.lock().await.clone();
  741. while self.get_total_height(&rect, &pages).await < *scroll + rect.h {
  742. debug!(target: "ui::chatview", "draw_cached() loading more pages");
  743. if self.preload_pages().await == 0 {
  744. // No more pages available to load
  745. pages = self.pages2.lock().await.clone();
  746. let new_height = self.get_total_height(&rect, &pages).await;
  747. *scroll = new_height - rect.h;
  748. break
  749. }
  750. }
  751. let descent = self.descent();
  752. let mut current_height = 0.;
  753. for page in pages {
  754. if current_height > *scroll + rect.h {
  755. break
  756. }
  757. let mesh_inf = page.mesh_inf.lock().unwrap().clone();
  758. let mesh_inf = mesh_inf.expect("preload above should've regen_mesh()");
  759. // Apply scroll and scissor
  760. // We use the scissor for scrolling
  761. // Because we use the scissor, our actual rect is now rect instead of parent_rect
  762. let off_x = 0.;
  763. // This calc decides whether scroll is in terms of pages or pixels
  764. let off_y = (*scroll - current_height + rect.h) / rect.h;
  765. let scale_x = 1. / rect.w;
  766. let scale_y = 1. / rect.h;
  767. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  768. glam::Mat4::from_scale(glam::Vec3::new(scale_x, scale_y, 1.));
  769. instrs.push(DrawInstruction::ApplyMatrix(model));
  770. instrs.push(DrawInstruction::Draw(mesh_inf.mesh));
  771. current_height += mesh_inf.px_height;
  772. }
  773. instrs
  774. }
  775. /// Basically a version of redraw() where regen_mesh() is never called.
  776. /// Instead we use the cached version.
  777. async fn scrollview(&self, mut scroll: f32) -> f32 {
  778. //debug!(target: "ui::chatview", "scrollview()");
  779. let old_scroll = self.scroll.get();
  780. let sg = self.sg.lock().await;
  781. let node = sg.get_node(self.node_id).unwrap();
  782. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  783. return 0.;
  784. };
  785. if let Err(err) = eval_rect(self.rect.clone(), &parent_rect) {
  786. panic!("Node {:?} bad rect property: {}", node, err);
  787. }
  788. let Ok(mut rect) = read_rect(self.rect.clone()) else {
  789. panic!("Node {:?} bad rect property", node);
  790. };
  791. let mut mesh_instrs = self.draw_cached(rect.clone(), &mut scroll).await;
  792. let mut instrs = vec![DrawInstruction::ApplyViewport(rect)];
  793. instrs.append(&mut mesh_instrs);
  794. let draw_calls =
  795. vec![(self.dc_key, DrawCall { instrs, dcs: vec![], z_index: self.z_index.get() })];
  796. self.render_api.replace_draw_calls(draw_calls).await;
  797. self.scroll.set(scroll);
  798. scroll - old_scroll
  799. }
  800. async fn redraw(&self) {
  801. debug!(target: "ui::chatview", "redraw()");
  802. let sg = self.sg.lock().await;
  803. let node = sg.get_node(self.node_id).unwrap();
  804. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  805. return;
  806. };
  807. let Some(draw_update) = self.draw(&sg, &parent_rect).await else {
  808. error!(target: "ui::chatview", "ChatView {:?} failed to draw", node);
  809. return;
  810. };
  811. self.render_api.replace_draw_calls(draw_update.draw_calls).await;
  812. debug!(target: "ui::chatview", "replace draw calls done");
  813. for buffer_id in draw_update.freed_buffers {
  814. self.render_api.delete_buffer(buffer_id);
  815. }
  816. for texture_id in draw_update.freed_textures {
  817. self.render_api.delete_texture(texture_id);
  818. }
  819. }
  820. async fn regen_mesh(&self, mut rect: Rectangle) -> (Vec<DrawInstruction>, Vec<DrawMesh>) {
  821. let font_size = self.font_size.get();
  822. let line_height = self.line_height.get();
  823. let baseline = self.baseline.get();
  824. let descent = self.descent();
  825. let mut instrs = vec![];
  826. let mut old_drawmesh = vec![];
  827. let timest_color = self.timestamp_color.get();
  828. let text_color = self.text_color.get();
  829. let nick_colors = self.read_nick_colors();
  830. let pages = self.pages2.lock().await.clone();
  831. let mut mesh_infs = vec![];
  832. // First pass is to measure the height and generate the meshes
  833. let mut current_height = 0.;
  834. for page in pages {
  835. // We should be able to count lines and perform wrapping without having to
  836. // generate the mesh and alloc buffers.
  837. // We need to separate both these ops.
  838. let (mesh_inf, old) = page
  839. .regen_mesh(
  840. &rect,
  841. &self.render_api,
  842. font_size,
  843. line_height,
  844. baseline,
  845. &nick_colors,
  846. timest_color.clone(),
  847. text_color.clone(),
  848. )
  849. .await;
  850. current_height += mesh_inf.px_height;
  851. if let Some(old) = old {
  852. old_drawmesh.push(old);
  853. }
  854. mesh_infs.push(mesh_inf);
  855. }
  856. let total_height = current_height + descent;
  857. // If lines aren't enough to fill the available buffer then start from the top
  858. let start_pos = if total_height < rect.h { total_height } else { rect.h };
  859. let mut scroll = self.scroll.get();
  860. assert!(scroll >= 0.);
  861. // For when we resize the window and scroll is no longer valid
  862. let max_allowed_scroll = total_height - rect.h;
  863. debug!(
  864. "max_allowed_scroll = {max_allowed_scroll} = total_height={total_height} - rect.h={}",
  865. rect.h
  866. );
  867. if scroll > max_allowed_scroll {
  868. scroll = max_allowed_scroll;
  869. self.scroll.set(scroll);
  870. }
  871. let mut current_height = 0.;
  872. for mesh_inf in mesh_infs {
  873. if current_height > scroll + rect.h {
  874. break
  875. }
  876. // Apply scroll and scissor
  877. // We use the scissor for scrolling
  878. // Because we use the scissor, our actual rect is now rect instead of parent_rect
  879. let off_x = 0.;
  880. // This calc decides whether scroll is in terms of pages or pixels
  881. let off_y = (scroll + start_pos - current_height) / rect.h;
  882. let scale_x = 1. / rect.w;
  883. let scale_y = 1. / rect.h;
  884. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  885. glam::Mat4::from_scale(glam::Vec3::new(scale_x, scale_y, 1.));
  886. instrs.push(DrawInstruction::ApplyMatrix(model));
  887. instrs.push(DrawInstruction::Draw(mesh_inf.mesh));
  888. current_height += mesh_inf.px_height;
  889. }
  890. (instrs, old_drawmesh)
  891. }
  892. fn read_nick_colors(&self) -> Vec<Color> {
  893. let mut colors = vec![];
  894. let mut color = [0f32; 4];
  895. for i in 0..self.nick_colors.get_len() {
  896. color[i % 4] = self.nick_colors.get_f32(i).expect("prop logic err");
  897. if i > 0 && i % 4 == 0 {
  898. let color = std::mem::take(&mut color);
  899. colors.push(color);
  900. }
  901. }
  902. colors
  903. }
  904. fn select_nick_color(&self, nick: &str, nick_colors: &[Color]) -> Color {
  905. let mut hasher = DefaultHasher::new();
  906. nick.hash(&mut hasher);
  907. let i = hasher.finish() as usize;
  908. let color = nick_colors[i % nick_colors.len()];
  909. color
  910. }
  911. pub async fn draw(&self, sg: &SceneGraph, parent_rect: &Rectangle) -> Option<DrawUpdate> {
  912. debug!(target: "ui::chatview", "ChatView::draw()");
  913. // Only used for debug messages
  914. let node = sg.get_node(self.node_id).unwrap();
  915. if let Err(err) = eval_rect(self.rect.clone(), parent_rect) {
  916. panic!("Node {:?} bad rect property: {}", node, err);
  917. }
  918. let Ok(mut rect) = read_rect(self.rect.clone()) else {
  919. panic!("Node {:?} bad rect property", node);
  920. };
  921. let timer = std::time::Instant::now();
  922. let (mut mesh_instrs, mut old_drawmesh) = self.regen_mesh(rect.clone()).await;
  923. debug!(target: "ui::chatview", "regen_mesh() took {:?}", timer.elapsed());
  924. let mut freed_textures = vec![];
  925. let mut freed_buffers = vec![];
  926. for old_mesh in old_drawmesh {
  927. freed_buffers.push(old_mesh.vertex_buffer);
  928. freed_buffers.push(old_mesh.index_buffer);
  929. //if let Some(texture_id) = old_dc.texture {
  930. // freed_textures.push(texture_id);
  931. //}
  932. }
  933. debug!(target: "ui::chatview", "chatview rect = {:?}", rect);
  934. let mut instrs = vec![DrawInstruction::ApplyViewport(rect)];
  935. instrs.append(&mut mesh_instrs);
  936. Some(DrawUpdate {
  937. key: self.dc_key,
  938. draw_calls: vec![(
  939. self.dc_key,
  940. DrawCall { instrs, dcs: vec![], z_index: self.z_index.get() },
  941. )],
  942. freed_textures,
  943. freed_buffers,
  944. })
  945. }
  946. }