chatview.rs 29 KB

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