chatview.rs 37 KB

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