chatview.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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 = 200;
  60. #[derive(Clone)]
  61. struct Page {
  62. msgs: Vec<Message>,
  63. atlas: text2::RenderedAtlas,
  64. }
  65. struct TouchInfo {
  66. start_y: f32,
  67. start_instant: std::time::Instant,
  68. last_y: f32,
  69. }
  70. impl TouchInfo {
  71. fn new() -> Self {
  72. Self { start_y: 0., start_instant: std::time::Instant::now(), last_y: 0. }
  73. }
  74. }
  75. pub type ChatViewPtr = Arc<ChatView>;
  76. pub struct ChatView {
  77. node_id: SceneNodeId,
  78. tasks: Vec<smol::Task<()>>,
  79. sg: SceneGraphPtr2,
  80. render_api: RenderApiPtr,
  81. text_shaper: TextShaperPtr,
  82. tree: sled::Tree,
  83. pages: SyncMutex<Vec<Page>>,
  84. drawcalls: SyncMutex<Vec<DrawMesh>>,
  85. dc_key: u64,
  86. /// Used for detecting when scrolling view
  87. mouse_pos: SyncMutex<Point>,
  88. /// Touch scrolling
  89. touch_info: SyncMutex<TouchInfo>,
  90. rect: PropertyPtr,
  91. scroll: PropertyFloat32,
  92. font_size: PropertyFloat32,
  93. line_height: PropertyFloat32,
  94. baseline: PropertyFloat32,
  95. timestamp_color: PropertyColor,
  96. text_color: PropertyColor,
  97. nick_colors: PropertyPtr,
  98. z_index: PropertyUint32,
  99. }
  100. impl ChatView {
  101. pub async fn new(
  102. ex: Arc<smol::Executor<'static>>,
  103. sg: SceneGraphPtr2,
  104. node_id: SceneNodeId,
  105. render_api: RenderApiPtr,
  106. event_pub: GraphicsEventPublisherPtr,
  107. text_shaper: TextShaperPtr,
  108. tree: sled::Tree,
  109. ) -> Pimpl {
  110. debug!(target: "ui::chatview", "ChatView::new()");
  111. let scene_graph = sg.lock().await;
  112. let node = scene_graph.get_node(node_id).unwrap();
  113. let node_name = node.name.clone();
  114. let rect = node.get_property("rect").expect("ChatView::rect");
  115. let scroll = PropertyFloat32::wrap(node, "scroll", 0).unwrap();
  116. let font_size = PropertyFloat32::wrap(node, "font_size", 0).unwrap();
  117. let line_height = PropertyFloat32::wrap(node, "line_height", 0).unwrap();
  118. let baseline = PropertyFloat32::wrap(node, "baseline", 0).unwrap();
  119. let timestamp_color = PropertyColor::wrap(node, "timestamp_color").unwrap();
  120. let text_color = PropertyColor::wrap(node, "text_color").unwrap();
  121. let nick_colors = node.get_property("nick_colors").expect("ChatView::nick_colors");
  122. let z_index = PropertyUint32::wrap(node, "z_index", 0).unwrap();
  123. drop(scene_graph);
  124. let self_ = Arc::new_cyclic(|me: &Weak<Self>| {
  125. let ev_sub = event_pub.subscribe_mouse_wheel();
  126. let me2 = me.clone();
  127. let mouse_wheel_task = ex.spawn(async move {
  128. loop {
  129. Self::process_mouse_wheel(&me2, &ev_sub).await;
  130. }
  131. });
  132. let ev_sub = event_pub.subscribe_mouse_move();
  133. let me2 = me.clone();
  134. let mouse_move_task = ex.spawn(async move {
  135. loop {
  136. Self::process_mouse_move(&me2, &ev_sub).await;
  137. }
  138. });
  139. let ev_sub = event_pub.subscribe_touch();
  140. let me2 = me.clone();
  141. let touch_task = ex.spawn(async move {
  142. loop {
  143. Self::process_touch(&me2, &ev_sub).await;
  144. }
  145. });
  146. let mut on_modify = OnModify::new(ex, node_name, node_id, me.clone());
  147. //on_modify.when_change(scroll.prop(), Self::scrollview);
  148. async fn redraw(self_: Arc<ChatView>) {
  149. self_.redraw().await;
  150. }
  151. on_modify.when_change(rect.clone(), redraw);
  152. let mut tasks = vec![mouse_wheel_task, mouse_move_task, touch_task];
  153. tasks.append(&mut on_modify.tasks);
  154. Self {
  155. node_id,
  156. tasks,
  157. sg,
  158. render_api,
  159. text_shaper,
  160. tree,
  161. pages: SyncMutex::new(Vec::new()),
  162. drawcalls: SyncMutex::new(Vec::new()),
  163. dc_key: OsRng.gen(),
  164. mouse_pos: SyncMutex::new(Point::from([0., 0.])),
  165. touch_info: SyncMutex::new(TouchInfo::new()),
  166. rect,
  167. scroll,
  168. font_size,
  169. line_height,
  170. baseline,
  171. timestamp_color,
  172. text_color,
  173. nick_colors,
  174. z_index,
  175. }
  176. });
  177. self_.populate().await;
  178. Pimpl::ChatView(self_)
  179. }
  180. async fn process_mouse_wheel(me: &Weak<Self>, ev_sub: &Subscription<(f32, f32)>) {
  181. let Ok((wheel_x, wheel_y)) = ev_sub.receive().await else {
  182. debug!(target: "ui::chatview", "Event relayer closed");
  183. return
  184. };
  185. let Some(self_) = me.upgrade() else {
  186. // Should not happen
  187. panic!("self destroyed before mouse_wheel_task was stopped!");
  188. };
  189. self_.handle_mouse_wheel(wheel_x, wheel_y).await;
  190. }
  191. async fn process_mouse_move(me: &Weak<Self>, ev_sub: &Subscription<(f32, f32)>) {
  192. let Ok((mouse_x, mouse_y)) = ev_sub.receive().await else {
  193. debug!(target: "ui::chatview", "Event relayer closed");
  194. return
  195. };
  196. let Some(self_) = me.upgrade() else {
  197. // Should not happen
  198. panic!("self destroyed before mouse_move_task was stopped!");
  199. };
  200. self_.handle_mouse_move(mouse_x, mouse_y).await;
  201. }
  202. async fn process_touch(me: &Weak<Self>, ev_sub: &Subscription<(TouchPhase, u64, f32, f32)>) {
  203. let Ok((phase, id, touch_x, touch_y)) = ev_sub.receive().await else {
  204. debug!(target: "ui::chatview", "Event relayer closed");
  205. return
  206. };
  207. let Some(self_) = me.upgrade() else {
  208. // Should not happen
  209. panic!("self destroyed before touch_task was stopped!");
  210. };
  211. self_.handle_touch(phase, id, touch_x, touch_y).await;
  212. }
  213. async fn handle_mouse_wheel(&self, wheel_x: f32, wheel_y: f32) {
  214. debug!(target: "ui::chatview", "handle_mouse_wheel({wheel_x}, {wheel_y})");
  215. let Some(rect) = self.get_cached_world_rect().await else { return };
  216. let mouse_pos = self.mouse_pos.lock().unwrap().clone();
  217. if !rect.contains(&mouse_pos) {
  218. debug!(target: "ui::chatview", "not inside rect");
  219. return
  220. }
  221. debug!(target: "ui::chatview", "inside rect");
  222. let scroll = self.scroll.get();
  223. self.scroll.set(scroll + wheel_y * 50.);
  224. self.scrollview().await;
  225. }
  226. async fn handle_mouse_move(&self, mouse_x: f32, mouse_y: f32) {
  227. //debug!(target: "ui::chatview", "handle_mouse_move({mouse_x}, {mouse_y})");
  228. let mut mouse_pos = self.mouse_pos.lock().unwrap();
  229. mouse_pos.x = mouse_x;
  230. mouse_pos.y = mouse_y;
  231. }
  232. async fn handle_touch(&self, phase: TouchPhase, id: u64, touch_x: f32, touch_y: f32) {
  233. // Ignore multi-touch
  234. if id != 0 {
  235. return
  236. }
  237. // Simulate mouse events
  238. match phase {
  239. TouchPhase::Started => {
  240. let mut touch_info = self.touch_info.lock().unwrap();
  241. touch_info.start_y = touch_y;
  242. touch_info.start_instant = std::time::Instant::now();
  243. touch_info.last_y = touch_y;
  244. }
  245. TouchPhase::Moved => {
  246. let start_y = {
  247. let mut touch_info = self.touch_info.lock().unwrap();
  248. touch_info.last_y = touch_y;
  249. touch_info.start_y
  250. };
  251. let dist = touch_y - start_y;
  252. let scroll = self.scroll.get();
  253. // TODO the line selected should be fixed and move exactly that distance
  254. // No use of multipliers
  255. // TODO we are maybe doing too many updates so make a widget to 'slow down'
  256. // how often we move to fixed intervals.
  257. // draw a poly shape and eval each line segment.
  258. self.scroll.set(scroll + dist * 0.05);
  259. self.scrollview().await;
  260. }
  261. TouchPhase::Ended => {
  262. // Now calculate scroll acceleration
  263. }
  264. TouchPhase::Cancelled => {}
  265. }
  266. }
  267. /// Beware of this method. Here be dragons.
  268. /// Possibly racy so we limit it just to mouse stuff (for now).
  269. fn cached_rect(&self) -> Option<Rectangle> {
  270. let Ok(rect) = read_rect(self.rect.clone()) else {
  271. error!(target: "ui::chatview", "cached_rect is None");
  272. return None
  273. };
  274. Some(rect)
  275. }
  276. async fn get_parent_rect(&self) -> Option<Rectangle> {
  277. let sg = self.sg.lock().await;
  278. let node = sg.get_node(self.node_id).unwrap();
  279. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  280. return None;
  281. };
  282. drop(sg);
  283. Some(parent_rect)
  284. }
  285. async fn get_cached_world_rect(&self) -> Option<Rectangle> {
  286. // NBD if it's slightly wrong
  287. let mut rect = self.cached_rect()?;
  288. // If layers can be nested and we use offsets for (x, y)
  289. // then this will be incorrect for nested layers.
  290. // For now we don't allow nesting of layers.
  291. let parent_rect = self.get_parent_rect().await?;
  292. // Offset rect which is now in world coords
  293. rect.x += parent_rect.x;
  294. rect.y += parent_rect.y;
  295. Some(rect)
  296. }
  297. async fn populate(&self) {
  298. let mut pages = vec![];
  299. let mut msgs = vec![];
  300. for entry in self.tree.iter().rev() {
  301. let Ok((k, v)) = entry else { break };
  302. assert_eq!(k.len(), 4);
  303. let key_bytes: [u8; 4] = k.as_ref().try_into().unwrap();
  304. let timest = Timestamp::from_be_bytes(key_bytes);
  305. let chatmsg: ChatMsg = deserialize(&v).unwrap();
  306. //println!("{k:?} {chatmsg:?}");
  307. let timestr = timest.to_string();
  308. // left pad with zeros
  309. let mut timestr = format!("{:0>4}", timestr);
  310. timestr.insert(2, ':');
  311. let text = format!("{} {} {}", timestr, chatmsg.nick, chatmsg.text);
  312. let glyphs = self.text_shaper.shape(text, self.font_size.get()).await;
  313. msgs.push(Message { timest, chatmsg, glyphs });
  314. if msgs.len() >= LINES_PER_PAGE {
  315. let mut atlas = text2::Atlas::new(&self.render_api);
  316. for msg in &msgs {
  317. atlas.push(&msg.glyphs);
  318. }
  319. let Ok(atlas) = atlas.make().await else {
  320. // what else should I do here?
  321. panic!("unable to make atlas!");
  322. };
  323. let page = Page { msgs: std::mem::take(&mut msgs), atlas };
  324. pages.push(page);
  325. if pages.len() >= PRELOAD_PAGES {
  326. break
  327. }
  328. }
  329. }
  330. debug!(target: "ui::chatview", "populated {} pages", pages.len());
  331. *self.pages.lock().unwrap() = pages;
  332. }
  333. /// Basically a version of redraw() where regen_mesh() is never called.
  334. /// Instead we use the cached version.
  335. async fn scrollview(&self) {
  336. debug!(target: "ui::chatview", "scrollview()");
  337. let sg = self.sg.lock().await;
  338. let node = sg.get_node(self.node_id).unwrap();
  339. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  340. return;
  341. };
  342. if let Err(err) = eval_rect(self.rect.clone(), &parent_rect) {
  343. panic!("Node {:?} bad rect property: {}", node, err);
  344. }
  345. let Ok(mut rect) = read_rect(self.rect.clone()) else {
  346. panic!("Node {:?} bad rect property", node);
  347. };
  348. //let mut drawcalls = self.regen_mesh(rect.clone()).await;
  349. debug!(target: "ui::chatview", "chatview rect = {:?}", rect);
  350. // Apply scroll and scissor
  351. // We use the scissor for scrolling
  352. // Because we use the scissor, our actual rect is now rect instead of parent_rect
  353. let off_x = 0.;
  354. // This calc decides whether scroll is in terms of pages or pixels
  355. let off_y = (self.scroll.get() + rect.h) / rect.h;
  356. let scale_x = 1. / rect.w;
  357. let scale_y = 1. / rect.h;
  358. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  359. glam::Mat4::from_scale(glam::Vec3::new(scale_x, scale_y, 1.));
  360. let mut instrs =
  361. vec![DrawInstruction::ApplyViewport(rect), DrawInstruction::ApplyMatrix(model)];
  362. let drawcalls = self.drawcalls.lock().unwrap().clone();
  363. let mut drawcalls: Vec<_> =
  364. drawcalls.into_iter().map(|dc| DrawInstruction::Draw(dc)).collect();
  365. instrs.append(&mut drawcalls);
  366. let draw_calls =
  367. vec![(self.dc_key, DrawCall { instrs, dcs: vec![], z_index: self.z_index.get() })];
  368. self.render_api.replace_draw_calls(draw_calls).await;
  369. debug!(target: "ui::chatview", "scrollview done");
  370. }
  371. async fn redraw(&self) {
  372. debug!(target: "ui::chatview", "redraw()");
  373. let sg = self.sg.lock().await;
  374. let node = sg.get_node(self.node_id).unwrap();
  375. let Some(parent_rect) = get_parent_rect(&sg, node) else {
  376. return;
  377. };
  378. let Some(draw_update) = self.draw(&sg, &parent_rect).await else {
  379. error!(target: "ui::chatview", "ChatView {:?} failed to draw", node);
  380. return;
  381. };
  382. self.render_api.replace_draw_calls(draw_update.draw_calls).await;
  383. debug!(target: "ui::chatview", "replace draw calls done");
  384. for buffer_id in draw_update.freed_buffers {
  385. self.render_api.delete_buffer(buffer_id);
  386. }
  387. for texture_id in draw_update.freed_textures {
  388. self.render_api.delete_texture(texture_id);
  389. }
  390. }
  391. async fn regen_mesh(&self, mut clip: Rectangle) -> Vec<DrawMesh> {
  392. let font_size = self.font_size.get();
  393. let line_height = self.line_height.get();
  394. let baseline = self.baseline.get();
  395. // Draw time and nick, then go over each word. If word crosses end of line
  396. // then apply a line break before the word and continue.
  397. let pages = self.pages.lock().unwrap().clone();
  398. let mut draws = vec![];
  399. let color = COLOR_WHITE;
  400. let timestamp_color = self.timestamp_color.get();
  401. let text_color = self.text_color.get();
  402. let nick_colors = self.read_nick_colors();
  403. // This is a little hack to nudge the bottom line up slightly, otherwise
  404. // chars like p will cross the bottom.
  405. let descent = baseline / 2.;
  406. // Pages start at the bottom.
  407. let mut current_idx = 0;
  408. 'pageloop: for page in pages {
  409. let mut mesh = MeshBuilder::new();
  410. for msg in page.msgs {
  411. let glyphs = msg.glyphs;
  412. let nick_color = self.select_nick_color(&msg.chatmsg.nick, &nick_colors);
  413. // Keep track of the 'section'
  414. // Section 0 is the timestamp
  415. // Section 1 is the nickname (colorized)
  416. // Finally is just the message itself
  417. let mut section = 2;
  418. let mut lines = text2::wrap(clip.w, font_size, &glyphs);
  419. // We are drawing bottom up but line wrap gives us lines in normal order
  420. lines.reverse();
  421. let last_idx = lines.len() - 1;
  422. for (i, line) in lines.into_iter().enumerate() {
  423. let off_y = descent + baseline + current_idx as f32 * line_height;
  424. //if px_height > clip.h {
  425. // break 'pageloop;
  426. //}
  427. if i == last_idx {
  428. section = 0;
  429. }
  430. // Render line
  431. let mut glyph_pos_iter = GlyphPositionIter::new(font_size, &line, baseline);
  432. for (mut glyph_rect, glyph) in glyph_pos_iter.zip(line.iter()) {
  433. let uv_rect =
  434. page.atlas.fetch_uv(glyph.glyph_id).expect("missing glyph UV rect");
  435. glyph_rect.y -= off_y;
  436. let color = match section {
  437. 0 => timestamp_color,
  438. 1 => nick_color,
  439. _ => text_color,
  440. };
  441. mesh.draw_box(&glyph_rect, color, uv_rect);
  442. if section < 2 && is_whitespace(&glyph.substr) {
  443. section += 1;
  444. }
  445. }
  446. current_idx += 1;
  447. }
  448. }
  449. let mesh = mesh.alloc(&self.render_api).await.unwrap();
  450. draws.push(DrawMesh {
  451. vertex_buffer: mesh.vertex_buffer,
  452. index_buffer: mesh.index_buffer,
  453. texture: Some(page.atlas.texture_id),
  454. num_elements: mesh.num_elements,
  455. });
  456. }
  457. if DEBUG_RENDER {
  458. let mut debug_mesh = MeshBuilder::new();
  459. debug_mesh.draw_outline(
  460. &Rectangle { x: 0., y: -clip.h, w: clip.w, h: clip.h },
  461. COLOR_BLUE,
  462. 2.,
  463. );
  464. let mesh = debug_mesh.alloc(&self.render_api).await.unwrap();
  465. draws.push(DrawMesh {
  466. vertex_buffer: mesh.vertex_buffer,
  467. index_buffer: mesh.index_buffer,
  468. texture: None,
  469. num_elements: mesh.num_elements,
  470. });
  471. }
  472. draws
  473. }
  474. fn read_nick_colors(&self) -> Vec<Color> {
  475. let mut colors = vec![];
  476. let mut color = [0f32; 4];
  477. for i in 0..self.nick_colors.get_len() {
  478. color[i % 4] = self.nick_colors.get_f32(i).expect("prop logic err");
  479. if i > 0 && i % 4 == 0 {
  480. let color = std::mem::take(&mut color);
  481. colors.push(color);
  482. }
  483. }
  484. colors
  485. }
  486. fn select_nick_color(&self, nick: &str, nick_colors: &[Color]) -> Color {
  487. let mut hasher = DefaultHasher::new();
  488. nick.hash(&mut hasher);
  489. let i = hasher.finish() as usize;
  490. let color = nick_colors[i % nick_colors.len()];
  491. color
  492. }
  493. pub async fn draw(&self, sg: &SceneGraph, parent_rect: &Rectangle) -> Option<DrawUpdate> {
  494. debug!(target: "ui::chatview", "ChatView::draw()");
  495. // Only used for debug messages
  496. let node = sg.get_node(self.node_id).unwrap();
  497. if let Err(err) = eval_rect(self.rect.clone(), parent_rect) {
  498. panic!("Node {:?} bad rect property: {}", node, err);
  499. }
  500. let Ok(mut rect) = read_rect(self.rect.clone()) else {
  501. panic!("Node {:?} bad rect property", node);
  502. };
  503. // TODO: Do we need this? Because of the viewport clipping
  504. rect.x += parent_rect.x;
  505. rect.y += parent_rect.y;
  506. let drawcalls = self.regen_mesh(rect.clone()).await;
  507. let old_drawcalls =
  508. std::mem::replace(&mut *self.drawcalls.lock().unwrap(), drawcalls.clone());
  509. let mut drawcalls: Vec<_> =
  510. drawcalls.into_iter().map(|dc| DrawInstruction::Draw(dc)).collect();
  511. let mut freed_textures = vec![];
  512. let mut freed_buffers = vec![];
  513. for old_dc in old_drawcalls {
  514. freed_buffers.push(old_dc.vertex_buffer);
  515. freed_buffers.push(old_dc.index_buffer);
  516. if let Some(texture_id) = old_dc.texture {
  517. freed_textures.push(texture_id);
  518. }
  519. }
  520. debug!(target: "ui::chatview", "chatview rect = {:?}", rect);
  521. // Apply scroll and scissor
  522. // We use the scissor for scrolling
  523. // Because we use the scissor, our actual rect is now rect instead of parent_rect
  524. let off_x = 0.;
  525. // This calc decides whether scroll is in terms of pages or pixels
  526. let off_y = (self.scroll.get() + rect.h) / rect.h;
  527. let scale_x = 1. / rect.w;
  528. let scale_y = 1. / rect.h;
  529. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  530. glam::Mat4::from_scale(glam::Vec3::new(scale_x, scale_y, 1.));
  531. let mut instrs =
  532. vec![DrawInstruction::ApplyViewport(rect), DrawInstruction::ApplyMatrix(model)];
  533. //let mut instrs = vec![DrawInstruction::ApplyMatrix(model)];
  534. instrs.append(&mut drawcalls);
  535. Some(DrawUpdate {
  536. key: self.dc_key,
  537. draw_calls: vec![(
  538. self.dc_key,
  539. DrawCall { instrs, dcs: vec![], z_index: self.z_index.get() },
  540. )],
  541. freed_textures,
  542. freed_buffers,
  543. })
  544. }
  545. }