chatview.rs 37 KB

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