From c7c0041922c162fbe1a9551f1176829929b318fd Mon Sep 17 00:00:00 2001 From: nworbnhoj Date: Fri, 1 Sep 2023 05:41:40 +1000 Subject: [PATCH] Chat readme & comments --- libs/chat/src/README.md | 28 ++++++++ libs/chat/src/api.rs | 14 ++-- libs/chat/src/dialogue.rs | 66 ++++++++++++++--- libs/chat/src/lib.rs | 100 +++++++++++++++++++++++--- libs/chat/src/ui.rs | 145 +++++++++++++++++++++++++++++++------- 5 files changed, 308 insertions(+), 45 deletions(-) create mode 100644 libs/chat/src/README.md diff --git a/libs/chat/src/README.md b/libs/chat/src/README.md new file mode 100644 index 000000000..f96a220fd --- /dev/null +++ b/libs/chat/src/README.md @@ -0,0 +1,28 @@ +# chat lib + +This Chat library provides a generic Chat UI to read a series of Posts in a Dialogue stored in the pddb - and to Author a new Post. + +The idea is to provide a solid common Xous Chat interface, so that Chat Apps can concentrate on the unique protocols of each platform (such as Matrix or Signal). + +This is a work-in-progress accepting all contributions from ideas and discussion, thru to pull-requests. + + +## UI User Interface + +A Dialogue of Posts appears as a cascade of "speech bubbles" with the most recent at the bottom. The user can use the up/down ↑↓ keys to scroll up/down thru the Posts. One Post will be hilited/selected and the right → key will provide options to reply, edit, delete etc. The left ← key will show the Chat App menu to login, logout, change conversation etc. + +A new Post may be authored in the input area at the bottom of the screen. + +The Chat UI can provide read-only access to Dialogues in the pddb when offline. + + +## Integration + +A Chat App will typically call `Chat::new()` to setup a Chat UI server, and a 2 way connection between the Chat App server and the Chat UI server. The Chat UI can raise a menu on behalf of the Chat App, allowing for protocol specific actions. The Chat App can receive messages representing: +* a new outbound user Post +* key UI events, such as F1 click, Left click, Top Post, etc, +* raw keystrokes. + +The Chat App will next typically call `Chat::dialogue_set()` with a pddb dict and key holding a Dialogue of Posts. + +When the Chat App receives a new Post from the Platform, it will call Chat::post_add() to have it saved in the pddb, and displayed. \ No newline at end of file diff --git a/libs/chat/src/api.rs b/libs/chat/src/api.rs index c3583e092..7403c5dd9 100644 --- a/libs/chat/src/api.rs +++ b/libs/chat/src/api.rs @@ -10,22 +10,25 @@ pub const POST_SELECTED_PREV: usize = usize::MAX - 1; #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub enum ChatOp { - // Sve the Dialogue to pddb (ie after PostAdd, PostDelete) + // Save the Dialogue to pddb (ie after PostAdd, PostDelete) DialogueSave = 0, - /// + /// Set the current Dialogue to be displayed DialogueSet, - /// + /// change the Chat UI in/out of focus GamChangeFocus, /// a line of text has arrived GamLine, /// receive rawkeys from gam GamRawkeys, - /// redraw our UI + /// redraw our Chat UI GamRedraw, - Icontray, + /// Add a new MenuItem to the App menu MenuAdd, + /// Add a new Post to the Dialogue PostAdd, + /// Delete a Post from the Dialogue PostDel, + /// Find a Post by timestamp and Author PostFind, PostFlag, UiButton, @@ -65,6 +68,7 @@ pub struct Post { pub attach_url: Option>, } +/// Events are sent to the Chat App when key things occur in the Chat UI #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub enum Event { Focus, diff --git a/libs/chat/src/dialogue.rs b/libs/chat/src/dialogue.rs index 598c9a38d..119d0f796 100644 --- a/libs/chat/src/dialogue.rs +++ b/libs/chat/src/dialogue.rs @@ -15,17 +15,28 @@ use std::io::{Error, ErrorKind}; pub const MAX_BYTES: usize = 4000; +/// A Dialogue is a generic representation of a series of Posts +/// This might represent a room, group, or direct-message conversation #[derive(Archive, Serialize, Deserialize, Debug)] pub struct Dialogue { + /// A title of the Dialogue pub title: String, + /// A time ordered sequence of posts in the Dialogue posts: Vec, + /// An index of unique Author id's (internal) authors: HashMap, + /// A lookup on Author names author_lookup: HashMap, + /// The timestamp on the most recent Post last_timestamp: u64, + /// The id assigned to the most recent new Author last_author_id: u16, } impl Dialogue { + + /// Creates a new Dialogue with a single Author. + /// Author id=0 is assigned to the user of this Chat App. pub fn new(title: &str) -> Self { let first_author_id = 0; let author = Author::new("me"); @@ -41,10 +52,19 @@ impl Dialogue { } } - // add a new post to the dialog - // note: posts are sorted by timestamp, so: - // - add post at beginning or end is fast (middle triggers a binary partition) - // - if adding multiple posts then add oldest/newest last! + /// Add a new Post to the Dialogue + /// + /// note: posts are sorted by timestamp, so: + /// - `post_add` at beginning or end is fast (middle triggers a binary partition) + /// - if adding multiple posts then add oldest/newest last! + /// + /// # Arguments + /// + /// * `author` - the name of the Author of the Post + /// * `timestamp` - the timestamp of the Post + /// * `text` - the text content of the Post + /// * `attach_url` - a url of an attachment (image for example) + /// pub fn post_add( &mut self, author: &str, @@ -72,6 +92,8 @@ impl Dialogue { self.posts.insert(0, new); } else { log::info!("{:?}", new); + // insert a new post in the correct position + // OR replace an existing post with matching timestamp & author let i = self.posts.partition_point(|p| p.timestamp() < new_ts); let last = self.posts.len() - 1; for n in i..last { @@ -96,6 +118,13 @@ impl Dialogue { } } + /// Returns Some(index) of a matching Post by Author and Timestamp, or None + /// + /// # Arguments + /// + /// * `timestamp` - the Post timestamp criteria + /// * `author` - the Post Author criteria + /// pub fn post_find(&self, author: &str, timestamp: u64) -> Option { if let Some(author_id) = self.author_lookup.get(author) { let i = self.posts.partition_point(|p| p.timestamp() < timestamp); @@ -115,12 +144,18 @@ impl Dialogue { None } - // return an arbitrary post in the dialogue by index + /// Return Some by index in the Dialogue, or None. + /// + /// # Arguments + /// + /// * `index` - the index of the required Post + /// pub fn post_get(&self, index: usize) -> Option<&Post> { self.posts.get(index) } - // return the index of the most recent post in the dialogue + /// Return the index of the most recent Post in the Dialogue + /// pub fn post_last(&self) -> Option { if self.posts.len() == 0 { None @@ -129,15 +164,29 @@ impl Dialogue { } } + /// Return an iterator over the Dialogue Posts (oldest first) + /// pub fn posts(&self) -> Iter { return self.posts.iter(); } + /// Return Some by id, or None. + /// + /// # Arguments + /// + /// * `id` - the index of the required Author + /// pub fn author(&self, id: u16) -> Option<&Author> { self.authors.get(&id) } - // get internal author_id for external author str + + /// Return Some by Author name, or None. + /// + /// # Arguments + /// + /// * `author` - the (external) name of the Author + /// pub fn author_id(&mut self, author: &str) -> Option { match self.author_lookup.get(author) { Some(id) => Some(*id), @@ -153,7 +202,8 @@ impl Dialogue { } } - // assign the next available interanl author_id + /// Assign and Return Some, or None + /// fn author_id_next(&mut self) -> Option { if self.last_author_id < u16::max_value() { self.last_author_id += 1; diff --git a/libs/chat/src/lib.rs b/libs/chat/src/lib.rs index ca4fb3abb..d1f2faa7c 100644 --- a/libs/chat/src/lib.rs +++ b/libs/chat/src/lib.rs @@ -19,6 +19,18 @@ pub struct Chat { } impl Chat { + + /// Create a new Chat UI + /// + /// # Arguments + /// + /// * `app_name` - registered with GAM + /// * `app_menu` - with menu items handled by the Chat App rather than the Chat UI + /// * `app_cid` - to accept messages from the Chat UI (see below) + /// * `post_opcode` - to handle a `MemoryMessage` containing a new outbound user Post + /// * `event_opcode` - to handle `ScalarMessage` representing a UI Event, such as F1 click, Left click, Top Post, etc. + /// * `rawkeys_opcode` - to handle a raw-keystroke. + /// pub fn new( app_name: &'static str, app_menu: &'static str, @@ -48,17 +60,34 @@ impl Chat { Chat { cid: chat_cid } } + /// Return the Chat App CID + /// + /// This cid allows the Chat App to contact this Chat UI server + /// pub fn cid(&self) -> CID { self.cid } + /// Create an offline/read-only Chat UI over and existing Dialogue in pddb + /// + /// # Arguments + /// + /// * `pddb_dict` - the pddb dict holding all Dialogues for this Chat App + /// * `pddb_key` - the pddb key holding a Dialogue + /// pub fn read_only(pddb_dict: &str, pddb_key: Option<&str>) -> Self { let chat = Chat::new("_Chat Read_", "unused", None, None, None, None); chat.dialogue_set(pddb_dict, pddb_key).unwrap(); chat } - // set the current Dialogue + /// Set the current Dialogue + /// + /// # Arguments + /// + /// * `pddb_dict` - the pddb dict holding all Dialogues for this Chat App + /// * `pddb_key` - the pddb key holding a Dialogue + /// pub fn dialogue_set(&self, pddb_dict: &str, pddb_key: Option<&str>) -> Result<(), Error> { let dialogue = api::Dialogue { dict: xous_ipc::String::from_str(pddb_dict), @@ -70,6 +99,12 @@ impl Chat { } } + /// Add a new MenuItem to the App menu + /// + /// # Arguments + /// + /// * `item` - an item action not handled by the Chat UI + /// pub fn menu_add(&self, item: MenuItem) -> Result<(), Error> { match Buffer::into_buf(item) { Ok(buf) => buf.send(self.cid, ChatOp::MenuAdd as u32).map(|_| ()), @@ -77,7 +112,19 @@ impl Chat { } } - // add a new Post to the current Dialogue + /// Add a new Post to the current Dialogue + /// + /// note: posts are sorted by timestamp, so: + /// - `post_add` at beginning or end is fast (middle triggers a binary partition) + /// - if adding multiple posts then add oldest/newest last! + /// + /// # Arguments + /// + /// * `author` - the name of the Author of the Post + /// * `timestamp` - the timestamp of the Post + /// * `text` - the text content of the Post + /// * `attach_url` - a url of an attachment (image for example) + /// pub fn post_add( &self, author: &str, @@ -102,13 +149,31 @@ impl Chat { } } - // delete a Post from the current Dialogue - pub fn post_del(&self, _key: u32) -> Result<(), Error> { - log::warn!("not implemented"); - Err(xous::Error::InternalError) + /// Delete a Post from the current Dialogue + /// + /// # Arguments + /// + /// * `index` - the index of the Post to delete. + /// + pub fn post_del(&self, index: usize) -> Result<(), Error> { + xous::send_message( + self.cid, + xous::Message::new_scalar(ChatOp::PostDel as usize, index, 0, 0, 0), + ) + .map(|_| ()) + .expect("failed to delete Pose {index}"); + Ok(()) } - // get a Post from the current Dialogue + /// Returns Some(index) of a matching Post by Author and Timestamp, or None + /// + /// # Arguments + /// + /// * `timestamp` - the Post timestamp criteria + /// * `author` - the Post Author criteria + /// + /// Error if unable to send the msg to the Chat UI server + /// pub fn post_find(&self, author: &str, timestamp: u64) -> Result, Error> { let mut find = Find { author: xous_ipc::String::new(), @@ -128,12 +193,17 @@ impl Chat { } } - // set various status flags on a Post in the current Dialogue + /// Set various status flags on a Post in the current Dialogue + /// + /// TODO: not implemented + /// pub fn post_flag(&self, _key: &str) -> Result<(), Error> { log::warn!("not implemented"); Err(xous::Error::InternalError) } + /// Redraw our Chat UI. + /// pub fn redraw(&self) { xous::send_message( self.cid, @@ -162,6 +232,20 @@ impl Chat { } } + +/// The Chat UI server a manages a Chat UI to read a display and navigate a +/// series of Posts in a Dialogue stored in the pddb - and to Author a new +/// Post. +/// +/// # Arguments +/// +/// * `app_name` - registered with GAM +/// * `app_menu` - with menu items handled by the Chat App rather than the Chat UI +/// * `app_cid` - to accept messages from the Chat UI (see below) +/// * `post_opcode` - to handle a `MemoryMessage` containing a new outbound user Post +/// * `event_opcode` - to handle `ScalarMessage` representing a UI Event, such as F1 click, Left click, Top Post, etc. +/// * `rawkeys_opcode` - to handle a raw-keystroke. +/// pub fn server( sid: SID, app_name: &'static str, diff --git a/libs/chat/src/ui.rs b/libs/chat/src/ui.rs index b01ba73dd..160e5211b 100644 --- a/libs/chat/src/ui.rs +++ b/libs/chat/src/ui.rs @@ -145,6 +145,9 @@ impl Ui { } } + + /// Read the current Dialogue from pddb + /// pub fn dialogue_read(&mut self) -> Result<(), Error> { match (&self.pddb_dict, &self.pddb_key) { (Some(dict), Some(key)) => { @@ -200,6 +203,9 @@ impl Ui { } } + + /// Save the current Dialogue to pddb + /// pub fn dialogue_save(&self) -> Result<(), Error> { match (&self.dialogue, &self.pddb_dict, &self.pddb_key) { (Some(dialogue), Some(dict), Some(key)) => { @@ -246,7 +252,13 @@ impl Ui { } } - // set the current Dialogue + /// Set the current Dialogue + /// + /// # Arguments + /// + /// * `pddb_dict` - the pddb dict holding all Dialogues for this Chat App + /// * `pddb_key` - the pddb key holding a Dialogue + /// pub fn dialogue_set(&mut self, pddb_dict: &str, pddb_key: Option<&str>) { self.pddb_dict = Some(pddb_dict.to_string()); self.pddb_key = pddb_key.map(|key| key.to_string()); @@ -273,6 +285,12 @@ impl Ui { } } + /// Present a Modal to select Dialogue from pddb + /// + /// typically called in offline mode + /// + /// TODO move non-dialogue keys elsewhere + /// pub fn dialogue_modal(&mut self) { if let Some(dict) = &self.pddb_dict { match self.pddb.list_keys(&dict, None) { @@ -297,11 +315,31 @@ impl Ui { } } + /// Add a new MenuItem to the App menu + /// + /// # Arguments + /// + /// * `item` - an item action not handled by the Chat UI + /// pub fn menu_add(&self, item: MenuItem) { self.menu_mgr.add_item(item); } - // add a new Post to the current Dialogue + /// Add a new Post to the current Dialogue + /// + /// TODO posts are truncated to mask a critical error on some posts (long with replies????) + /// + /// note: posts are sorted by timestamp, so: + /// - `post_add` at beginning or end is fast (middle triggers a binary partition) + /// - if adding multiple posts then add oldest/newest last! + /// + /// # Arguments + /// + /// * `author` - the name of the Author of the Post + /// * `timestamp` - the timestamp of the Post + /// * `text` - the text content of the Post + /// * `attach_url` - a url of an attachment (image for example) + /// pub fn post_add( &mut self, author: &str, @@ -320,13 +358,23 @@ impl Ui { Ok(()) } - // delete a Post from the current Dialogue + /// Delete a Post from the current Dialogue pub fn post_del(&self, _key: u32) -> Result<(), Error> { + + /// + /// TODO: implement post_delete() + /// log::warn!("not implemented"); Err(Error::new(ErrorKind::Other, "not implemented")) } - // get a Post from the current Dialogue + /// Returns Some(index) of a matching Post by Author and Timestamp, or None + /// + /// # Arguments + /// + /// * `timestamp` - the Post timestamp criteria + /// * `author` - the Post Author criteria + /// pub fn post_find(&self, author: &str, timestamp: u64) -> Option { match &self.dialogue { Some(dialogue) => dialogue.post_find(author, timestamp), @@ -334,22 +382,33 @@ impl Ui { } } - // get a Post from the current Dialogue - pub fn post_get(&self, key: usize) -> Option<&Post> { + /// Return Some from the current Dialogue, or None + /// + /// # Arguments + /// + /// * `index` - index of the Post to retrieve + /// + pub fn post_get(&self, index: usize) -> Option<&Post> { match &self.dialogue { - Some(dialogue) => dialogue.post_get(key), + Some(dialogue) => dialogue.post_get(index), None => None, } } - // set various status flags on a Post in the current Dialogue + /// Set various status flags on a Post in the current Dialogue + /// + /// TODO: not implemented + /// pub fn post_flag(&self, _key: u32) -> Result<(), Error> { log::warn!("not implemented"); Err(Error::new(ErrorKind::Other, "not implemented")) } - // set the index of the selected post to an arbitrary index - // or select adjacent post with POST_SELECT_NEXT or POST_SELECT_PREV + /// Set the Selected Post to an arbitrary index + /// + /// # Arguments + /// + /// * `index` - POST_SELECT_NEXT or POST_SELECT_PREV or an arbitraty index pub fn post_select(&mut self, index: usize) { self.post_selected = match &self.dialogue { Some(dialogue) => { @@ -404,7 +463,22 @@ impl Ui { self.app_cid } - // send a xous scalar message with an Event to the Chat App cid/opcode + + + + + + + + + /// Send a xous scalar message with an Event to the Chat App cid/opcode + /// + /// # Arguments + /// + /// * `event` - the type of event to send + /// + /// Error when `app_cid` == None or `opcode_event` == None + /// pub fn event(&self, event: Event) { log::info!("Event {:?}", event); match (self.app_cid, self.opcode_event) { @@ -419,12 +493,15 @@ impl Ui { } } - // Create a bubble representing a Dialogue Post - // return: a TextView bubble representing a Post - // post: the post to represent in a TextView bubble - // dialogue: containing the Post for context info - // hilite: hilite this Post on the screen (thicker border) - // anchor_y: the vertical position on screen to draw TextView bubble + /// Return a TextView bubble representing a Dialogue Post + /// + /// # Arguments + /// + /// * `post` - the post to represent in a TextView bubble + /// * `dialogue` - containing the Post for context info + /// * `hilite` - hilite this Post on the screen (thicker border) + /// * `anchor_y` - the vertical position on screen to draw TextView bubble + /// fn bubble(&self, post: &Post, dialogue: &Dialogue, hilite: bool, anchor_y: i16) -> TextView { // set alignment of bubble left/right let mut align_right = false; @@ -466,6 +543,8 @@ impl Ui { bubble_tv } + // Clear the screen area + // fn clear_area(&self) { self.gam .draw_rectangle( @@ -483,15 +562,21 @@ impl Ui { .expect("can't clear canvas area"); } - pub(crate) fn raise_menu(&mut self) { - // self.title_dirty = true; + /// Show the App Menu (← key) + /// + pub(crate) fn raise_app_menu(&mut self) { self.gam .raise_menu(&self.app_menu) .expect("couldn't raise our submenu"); - log::info!("raised menu"); + log::info!("raised app menu"); } - // redraw posts on the screen ensuring the selected post is fully visible + /// Redraw posts on the screen. + /// + /// Up to three attempts are made to layout the Posts: + /// * ensuring the selected post is fully visible, and + /// * best use of the screen is achieved + /// pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> { if self.dialogue.is_some() { let mut attempt = 0; @@ -507,9 +592,21 @@ impl Ui { Ok(()) } - // Layout the post bubbles on the screen from top-down or bottom-up - // return: true if the selected post is fully visible - // error: if Dialogue == None + /// Layout the post bubbles on the screen. + /// + /// The layout proceeds from top-down or bottom-up (starting with the + /// `post_anchor`), drawing a bubble for each Post, until the available space + /// is exhausted. + /// * If the `post_selected` is fully displayed, then `Ok(true)` is Returned. + /// * If the `post_selected` is NOT fully displayed, then the `post_anchor` + /// is set as the `post_anchor`, and `Ok(false)` is Returned - signalling that + /// a re-layout is in order. + /// * If the first/last Post is fully displayed, then the `post_topdown` is + /// toggled, the `post_anchor` is set to the first/last Post, and `Ok(false)` + /// is Returned - signalling that a re-layout is in order. + /// + /// Error if there if Dialogue is None + /// fn layout(&mut self) -> Result { self.clear_area(); match (&self.dialogue, &self.post_anchor ) {