Bladeren bron

wallet: chatview upgrade timestamps to u64 and add a 32 byte message_id to keys

darkfi 2 jaren geleden
bovenliggende
commit
6e128ec095
4 gewijzigde bestanden met toevoegingen van 62 en 45 verwijderingen
  1. 1 0
      bin/darkwallet/Cargo.toml
  2. 22 7
      bin/darkwallet/src/app.rs
  3. 13 4
      bin/darkwallet/src/scene.rs
  4. 26 34
      bin/darkwallet/src/ui/chatview.rs

+ 1 - 0
bin/darkwallet/Cargo.toml

@@ -40,6 +40,7 @@ colored = "2.1.0"
 sled = "0.34"
 url = "2.5"
 semver = "1.0"
+chrono = "0.4"
 
 [patch.crates-io]
 freetype-rs = { git = "https://github.com/narodnik/freetype-rs" }

+ 22 - 7
bin/darkwallet/src/app.rs

@@ -17,6 +17,7 @@
  */
 
 use async_recursion::async_recursion;
+use chrono::{NaiveDate, NaiveDateTime};
 use darkfi_serial::Encodable;
 use futures::{stream::FuturesUnordered, StreamExt};
 use std::{sync::Arc, thread};
@@ -26,7 +27,10 @@ use crate::{
     expr::Op,
     gfx2::{GraphicsEventPublisherPtr, RenderApiPtr, Vertex},
     prop::{Property, PropertySubType, PropertyType, Role},
-    scene::{MethodResponseFn, Pimpl, SceneGraph, SceneGraphPtr2, SceneNodeId, SceneNodeType},
+    scene::{
+        CallArgType, MethodResponseFn, Pimpl, SceneGraph, SceneGraphPtr2, SceneNodeId,
+        SceneNodeType,
+    },
     text2::TextShaperPtr,
     ui::{chatview, Button, ChatView, EditBox, Image, Mesh, RenderLayer, Stoppable, Text, Window},
     ExecutorPtr,
@@ -743,13 +747,23 @@ fn populate_tree(tree: &sled::Tree) {
     for line in chat_txt.lines() {
         let parts: Vec<&str> = line.splitn(3, ' ').collect();
         assert_eq!(parts.len(), 3);
-        let timest = parts[0].replace(':', "").parse::<u32>().unwrap();
+        let time_parts: Vec<&str> = parts[0].splitn(2, ':').collect();
+        let (hour, min) = (time_parts[0], time_parts[1]);
+        let hour = hour.parse::<u32>().unwrap();
+        let min = min.parse::<u32>().unwrap();
+        let dt: NaiveDateTime =
+            NaiveDate::from_ymd_opt(2024, 8, 6).unwrap().and_hms_opt(hour, min, 0).unwrap();
+        let timest = dt.and_utc().timestamp_millis() as u64;
+
+        let message_id = [0u8; 32];
         let nick = parts[1].to_string();
         let text = parts[2].to_string();
 
         // serial order is important here
-        let key = timest.to_be_bytes();
-        //timest.encode(&mut key).unwrap();
+        let timest = timest.to_be_bytes();
+        assert_eq!(timest.len(), 8);
+        let mut key = [0u8; 8 + 32];
+        key[..8].clone_from_slice(&timest);
 
         let msg = chatview::ChatMsg { nick, text };
         let mut val = vec![];
@@ -999,9 +1013,10 @@ fn create_chatview(
     node.add_method(
         "insert_line",
         vec![
-            ("timestamp", "Timestamp", PropertyType::Uint32),
-            ("nick", "Nickname", PropertyType::Str),
-            ("text", "Text", PropertyType::Str),
+            ("timestamp", "Timestamp", CallArgType::Uint64),
+            ("id", "Message ID", CallArgType::Hash),
+            ("nick", "Nickname", CallArgType::Str),
+            ("text", "Text", CallArgType::Str),
         ],
         vec![],
         Box::new(method),

+ 13 - 4
bin/darkwallet/src/scene.rs

@@ -482,7 +482,7 @@ impl SceneNode {
         &mut self,
         name: S,
         desc: S,
-        fmt: Vec<(S, S, PropertyType)>,
+        fmt: Vec<(S, S, CallArgType)>,
     ) -> Result<()> {
         let name = name.into();
         if self.has_signal(&name) {
@@ -551,8 +551,8 @@ impl SceneNode {
     pub fn add_method<S: Into<String>>(
         &mut self,
         name: S,
-        args: Vec<(S, S, PropertyType)>,
-        result: Vec<(S, S, PropertyType)>,
+        args: Vec<(S, S, CallArgType)>,
+        result: Vec<(S, S, CallArgType)>,
         method_fn: MethodRequestFn,
     ) -> Result<()> {
         let name = name.into();
@@ -590,11 +590,20 @@ impl SceneNode {
     }
 }
 
+#[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
+pub enum CallArgType {
+    Uint32,
+    Uint64,
+    Bool,
+    Str,
+    Hash,
+}
+
 #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
 pub struct CallArg {
     pub name: String,
     pub desc: String,
-    pub typ: PropertyType,
+    pub typ: CallArgType,
 }
 
 type SlotFn = Box<dyn Fn(Vec<u8>) + Send>;

+ 26 - 34
bin/darkwallet/src/ui/chatview.rs

@@ -38,7 +38,7 @@ use crate::{
         DrawCall, DrawInstruction, DrawMesh, GraphicsEventPublisherPtr, Point, Rectangle,
         RenderApi, RenderApiPtr, Vertex,
     },
-    mesh::{Color, MeshBuilder, MeshInfo, COLOR_BLUE, COLOR_GREY, COLOR_WHITE},
+    mesh::{Color, MeshBuilder, MeshInfo, COLOR_BLUE, COLOR_GREEN, COLOR_GREY, COLOR_WHITE},
     prop::{
         PropertyBool, PropertyColor, PropertyFloat32, PropertyPtr, PropertyStr, PropertyUint32,
         Role,
@@ -71,11 +71,13 @@ pub struct ChatMsg {
     pub text: String,
 }
 
-type Timestamp = u32;
+type Timestamp = u64;
+type MessageId = [u8; 32];
 
 #[derive(Clone)]
 struct Message {
     timest: Timestamp,
+    id: MessageId,
     chatmsg: ChatMsg,
     glyphs: Vec<Glyph>,
 }
@@ -187,6 +189,8 @@ impl Page2 {
 
         let px_height = wrapped_line_idx as f32 * line_height;
 
+        //mesh.draw_outline(&Rectangle { x: 0., y: 0., w: clip.w, h: -px_height }, COLOR_GREEN, 1.);
+
         let mesh = mesh.alloc(render_api).await.unwrap();
         let mesh = mesh.draw_with_texture(atlas.texture_id);
 
@@ -492,15 +496,16 @@ impl ChatView {
             return false
         };
 
-        fn decode_data(data: &[u8]) -> std::io::Result<(u32, String, String)> {
+        fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, MessageId, String, String)> {
             let mut cur = Cursor::new(&data);
-            let timestamp = u32::decode(&mut cur)?;
+            let timestamp = Timestamp::decode(&mut cur)?;
+            let message_id = MessageId::decode(&mut cur)?;
             let nick = String::decode(&mut cur)?;
             let text = String::decode(&mut cur)?;
-            Ok((timestamp, nick, text))
+            Ok((timestamp, message_id, nick, text))
         }
 
-        let Ok((timestamp, nick, text)) = decode_data(&data) else {
+        let Ok((timestamp, message_id, nick, text)) = decode_data(&data) else {
             error!(target: "ui::chatview", "insert_line() method invalid arg data");
             return true
         };
@@ -510,7 +515,7 @@ impl ChatView {
             panic!("self destroyed before touch_task was stopped!");
         };
 
-        self_.handle_insert_line(timestamp, nick, text).await;
+        self_.handle_insert_line(timestamp, message_id, nick, text).await;
         true
     }
 
@@ -585,8 +590,14 @@ impl ChatView {
         }
     }
 
-    async fn handle_insert_line(&self, timest: u32, nick: String, text: String) {
-        debug!(target: "ui::chatview", "handle_insert_line({timest}, {nick}, {text})");
+    async fn handle_insert_line(
+        &self,
+        timest: Timestamp,
+        message_id: MessageId,
+        nick: String,
+        text: String,
+    ) {
+        debug!(target: "ui::chatview", "handle_insert_line({timest}, {message_id:?}, {nick}, {text})");
 
         let chatmsg = ChatMsg { nick, text };
 
@@ -622,7 +633,7 @@ impl ChatView {
 
         let page = &mut pages[idx];
         let mut msgs = page.msgs.clone();
-        msgs.push(Message { timest, chatmsg, glyphs });
+        msgs.push(Message { timest, id: message_id, chatmsg, glyphs });
         msgs.sort_unstable_by_key(|msg| msg.timest);
         msgs.reverse();
 
@@ -747,9 +758,10 @@ impl ChatView {
 
         for entry in iter {
             let Ok((k, v)) = entry else { break };
-            assert_eq!(k.len(), 4);
-            let key_bytes: [u8; 4] = k.as_ref().try_into().unwrap();
-            let timest = Timestamp::from_be_bytes(key_bytes);
+            assert_eq!(k.len(), 8 + 32);
+            let timest_bytes: [u8; 8] = k[..8].try_into().unwrap();
+            let message_id: MessageId = k[8..].try_into().unwrap();
+            let timest = Timestamp::from_be_bytes(timest_bytes);
             let chatmsg: ChatMsg = deserialize(&v).unwrap();
             debug!(target: "ui::chatview", "{timest:?} {chatmsg:?}");
 
@@ -761,7 +773,7 @@ impl ChatView {
             let text = format!("{} {} {}", timestr, chatmsg.nick, chatmsg.text);
             let glyphs = self.text_shaper.shape(text, self.font_size.get()).await;
 
-            msgs.push(Message { timest, chatmsg, glyphs });
+            msgs.push(Message { timest, id: message_id, chatmsg, glyphs });
 
             if msgs.len() >= LINES_PER_PAGE {
                 let msgs = std::mem::take(&mut msgs);
@@ -1024,26 +1036,6 @@ impl ChatView {
         }
 
         (instrs, old_drawmesh)
-
-        /*
-        if DEBUG_RENDER {
-            let mut debug_mesh = MeshBuilder::new();
-            debug_mesh.draw_outline(
-                &Rectangle { x: 0., y: -clip.h, w: clip.w, h: clip.h },
-                COLOR_BLUE,
-                2.,
-            );
-            let mesh = debug_mesh.alloc(&self.render_api).await.unwrap();
-            draws.push(DrawMesh {
-                vertex_buffer: mesh.vertex_buffer,
-                index_buffer: mesh.index_buffer,
-                texture: None,
-                num_elements: mesh.num_elements,
-            });
-        }
-
-        draws
-        */
     }
 
     fn read_nick_colors(&self) -> Vec<Color> {