sketch chat UI library

A Chat object provides a generic 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 specialize in the unique aspects of a chat Platform protocol (Matrix, Signal etc).

A Chat App will typically call `Chat::new()` and then `Chat::dialogue_set()` with a pddb dict and key holding a Dialogue of Posts. The Chat object will fire-up the UI and retrieve the Dialogue from the pddb. The user will be able to peruse the stored Posts in the Dialogue - and potentially Author a new Post. A new User Post will be sent to the Chat App in a `MemoryMessage` via the (optional) `CID` and `Opcode` provided by the Chat App. Conversely, when the Chat App receives a new Post from the Platform, it will call Chat::post_add() to have it saved in the pddb.

The Chat UI will also accept (optional) opcodes to forward raw-keystrokes and UI-Events to the Chat App. This allows the Chat App to respond to key UI Events. For example if the User navigates to the `top` of the list of stored Posts, then the Chat App might retrieve older Posts from the Platform to be stored Dialogue with calls to Chat::post_add().
This commit is contained in:
nworbnhoj 2023-07-12 17:23:41 +10:00
parent afc8d96283
commit aab92c2b37
13 changed files with 1048 additions and 0 deletions

View file

@ -89,6 +89,7 @@ members = [
"tools/perflib",
"kernel",
"loader",
"libs/chat",
"libs/userprefs",
"libs/tls"
]

36
libs/chat/Cargo.toml Normal file
View file

@ -0,0 +1,36 @@
[package]
name = "chat"
version = "0.1.0"
authors = ["john <john@nhoj.info>"]
edition = "2018"
description = "Chat UI over pddb records"
# Dependency versions enforced by Cargo.lock.
[dependencies]
log = "0.4.14"
num-derive = {version = "0.3.3", default-features = false}
num-traits = {version = "0.2.14", default-features = false}
xous = "0.9.47"
xous-ipc = "0.9.47"
log-server = { package = "xous-api-log", version = "0.1.43" }
ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.43" }
xous-names = { package = "xous-api-names", version = "0.9.45" }
gam = {path = "../../services/gam" }
graphics-server = {path = "../../services/graphics-server" }
trng = {path = "../../services/trng"}
locales = {path = "../../locales"}
ime-plugin-api = {path = "../../services/ime-plugin-api"}
ime-plugin-shell = {path = "../../services/ime-plugin-shell"}
content-plugin-api = {path = "../../services/content-plugin-api"} # all content canvas providers must provide this API
com = {path = "../../services/com"}
llio = {path = "../../services/llio"}
modals = {path = "../../services/modals"}
codec = {path = "../../services/codec"}
cos_table = {path = "../../libs/cos_table"}
pddb = {path = "../../services/pddb"}
enumset = "1.1.2"
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
[features]
default = []

9
libs/chat/README.md Normal file
View file

@ -0,0 +1,9 @@
# CHAT
A Chat object provides a generic 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 specialize in the unique aspects of a chat Platform protocol (Matrix, Signal etc).
A Chat App will typically call `Chat::new()` and then `Chat::dialogue_set()` with a pddb dict and key holding a Dialogue of Posts. The Chat object will fire-up the UI and retrieve the Dialogue from the pddb. The user will be able to peruse the stored Posts in the Dialogue - and potentially Author a new Post. A new User Post will be sent to the Chat App in a `MemoryMessage` via the (optional) `CID` and `Opcode` provided by the Chat App. Conversely, when the Chat App receives a new Post from the Platform, it will call Chat::post_add() to have it saved in the pddb.
The Chat UI will also accept (optional) opcodes to forward raw-keystrokes and UI-Events to the Chat App. This allows the Chat App to respond to key UI Events. For example if the User navigates to the `top` of the list of stored Posts, then the Chat App might retrieve older Posts from the Platform to be stored Dialogue with calls to Chat::post_add().

View file

@ -0,0 +1,14 @@
{
"chat.cmd": {
"en": "chat <subcommand>",
"en-tts": "chat <subcommand>"
},
"chat.help_cmd": {
"en": "hello",
"en-tts": "hello"
},
"chat.test_cmd": {
"en": "test chat library UI",
"en-tts": "test chat library UI"
}
}

102
libs/chat/src/api.rs Normal file
View file

@ -0,0 +1,102 @@
use enumset::EnumSetType;
use rkyv::{Archive, Deserialize, Serialize};
pub(crate) const SERVER_NAME_CHAT: &str = "Chat UI";
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum ChatOp {
/// change focus
ChangeFocus,
///
DialogueSet,
///
GamChangeFocus,
/// a line of text has arrived
GamLine,
/// receive rawkeys from gam
GamRawKeys,
/// redraw our UI
GamRedraw,
ListenSet,
PostAdd,
PostDel,
PostFind,
PostFlag,
UiButton,
UiMenu,
/// exit the application
Quit,
}
const POST_TEXT_MAX: usize = 3072;
#[derive(Archive, Serialize, Deserialize, Debug)]
pub struct Find {
pub author: xous_ipc::String<128>,
pub timestamp: u32,
pub key: Option<usize>, // the return post key if found.
}
#[derive(Archive, Serialize, Deserialize, Debug)]
pub struct Dialogue {
pub dict: xous_ipc::String<128>,
pub key: xous_ipc::String<128>,
}
#[derive(Archive, Serialize, Deserialize, Debug)]
pub struct Post {
pub author: xous_ipc::String<128>,
pub timestamp: u32,
pub text: xous_ipc::String<POST_TEXT_MAX>,
pub attach_url: Option<xous_ipc::String<128>>,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum Event {
F1, // F1 button click
F2, // F2 button click
F3, // you get the idea
F4, // guess
Up, // Up click
Down, // Down click
Left, // Left click
Right, // Right click
Top, // Top of post list reached
Bottom, // Bottom of post list reached
Key, // keystroke
Post, // new user Post committed
}
#[derive(
Archive,
Serialize,
Deserialize,
Debug,
num_derive::FromPrimitive,
num_derive::ToPrimitive,
EnumSetType,
)]
pub enum PostFlag {
Deleted,
Draft,
Hidden,
}
#[derive(Archive, Serialize, Deserialize, Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, EnumSetType)]
pub enum AuthorFlags {
#[derive(
Archive,
Serialize,
Deserialize,
Debug,
num_derive::FromPrimitive,
num_derive::ToPrimitive,
EnumSetType,
)]
pub enum AuthorFlag {
Bold,
Hidden,
Right,
}

66
libs/chat/src/cmd.rs Normal file
View file

@ -0,0 +1,66 @@
use crate::{now, Chat};
use locales::t;
use std::convert::TryInto;
use std::thread;
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum TestOp {
Post = 0,
Event,
RawKeys,
}
pub fn shellchat<'a>(
mut tokens: impl Iterator<Item = &'a str>,
) -> Result<Option<String>, xous::Error> {
use core::fmt::Write;
let mut ret = String::new();
match tokens.next() {
Some("read") => {
if let Some(dict) = tokens.next() {
if let Some(key) = tokens.next() {
let _chat = Chat::read_only(dict, key);
}
}
}
Some("test") => {
log::info!("starting chat test command");
let xns = xous_names::XousNames::new().unwrap();
let sid = xns
.register_name("Chat test", None)
.expect("can't register server");
log::trace!("registered with NS -- {:?}", sid);
enum TestOp {
Event,
Post,
RawKeys,
}
let chat = Chat::new(
Some(xous::connect(sid).unwrap()),
Some(TestOp::Post as usize),
Some(TestOp::Event as usize),
Some(TestOp::RawKeys as usize),
);
chat.dialogue_set("chat_test", "test");
chat.post_add("system", now(), "chat test commenced", None);
chat.post_add("system", now(), "chat test concluded", None);
log::info!("finished chat test command");
}
// helpful stuff
Some("help") => {
write!(ret, "{}", t!("tls.cmd_help", locales::LANG)).ok();
}
None | _ => {
write!(ret, "{}\n", t!("chat.cmd", locales::LANG)).ok();
write!(ret, "\ttest\t{}\n", t!("tls.test_cmd", locales::LANG)).ok();
write!(ret, "\thelp\n").ok();
}
}
Ok(Some(ret))
}

149
libs/chat/src/dialogue.rs Normal file
View file

@ -0,0 +1,149 @@
pub mod attach;
pub mod author;
pub mod post;
use crate::now;
use author::Author;
use core::slice::Iter;
use post::Post;
//use crate::dialogue::{attach, author, post};
use rkyv::{Archive, Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Error, ErrorKind};
#[derive(Archive, Serialize, Deserialize, Debug)]
pub struct Dialogue {
pub title: String,
posts: Vec<Post>,
authors: HashMap<u16, Author>,
author_lookup: HashMap<String, u16>,
last_timestamp: u32,
last_author_id: u16,
}
impl Dialogue {
pub fn new(title: &str) -> Self {
let first_author_id = 0;
let author = Author::new("me");
let mut authors = HashMap::new();
authors.insert(first_author_id, author);
Self {
title: title.to_string(),
posts: Vec::<Post>::new(),
authors: authors,
author_lookup: HashMap::<String, u16>::new(),
last_timestamp: now(),
last_author_id: first_author_id + 1,
}
}
// 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 sort)
// - if adding multiple posts then add oldest/newest last!
pub fn post_add(
&mut self,
author: &str,
timestamp: u32,
text: &str,
_attach_url: Option<&str>,
) -> Result<(), Error> {
match self.author_id(author) {
Some(author_id) => {
let post = Post::new(
author_id, timestamp, text, None, // TODO implement
);
if self.posts.len() == 0 {
self.posts.push(post);
return Ok(());
}
let post_ts = post.timestamp();
let first_ts = self.posts.first().map_or(0, |post| post.timestamp());
let last_ts = self.posts.last().map_or(0, |post| post.timestamp());
if post_ts >= last_ts {
self.posts.push(post);
} else if post_ts < first_ts {
self.posts.insert(0, post);
} else {
if (last_ts - post_ts) < (post_ts - first_ts) {
self.posts.push(post);
} else {
self.posts.insert(0, post);
}
self.posts.sort_by(|a, b| a.timestamp().cmp(&b.timestamp()));
}
Ok(())
}
None => Err(Error::new(ErrorKind::Other, "max authors exceeeded")),
}
}
pub fn post_find(&self, author: &str, timestamp: u32) -> Option<usize> {
if let Some(author_id) = self.author_lookup.get(author) {
match self
.posts
.binary_search_by(|x| x.timestamp().cmp(&timestamp))
{
Ok(index) => {
// matched timestamp but maybe duplicates by different authors
for (id, post) in self.posts[..index].iter().rev().enumerate() {
if post.timestamp() != timestamp {
break;
}
if post.author_id() == *author_id {
return Some(id);
}
}
for (id, post) in self.posts[index..].iter().enumerate() {
if post.timestamp() != timestamp {
break;
}
if post.author_id() == *author_id {
return Some(id);
}
}
return None;
}
Err(_) => None::<usize>,
};
};
None
}
pub fn posts(&self) -> Iter<Post> {
return self.posts.iter();
}
pub fn author(&self, id: u16) -> Option<&Author> {
self.authors.get(&id)
}
// get internal author_id for external author str
pub fn author_id(&mut self, author: &str) -> Option<u16> {
match self.author_lookup.get(author) {
Some(id) => Some(*id),
None => {
if let Some(id) = self.author_id_next() {
self.authors.insert(id, Author::new(author));
self.author_lookup.insert(author.to_string(), id);
Some(id)
} else {
None
}
}
}
}
// assign the next available interanl author_id
fn author_id_next(&mut self) -> Option<u16> {
if self.last_author_id < u16::max_value() {
self.last_author_id += 1;
Some(self.last_author_id)
} else {
None
}
}
}

View file

@ -0,0 +1,9 @@
use rkyv::{Archive, Deserialize, Serialize};
#[derive(Archive, Serialize, Deserialize, Debug)]
pub enum Attach {
Png(),
Jpg(),
}
impl Attach {}

View file

@ -0,0 +1,34 @@
use crate::api::AuthorFlag;
use enumset;
use enumset::EnumSet;
use rkyv::{Archive, Deserialize, Serialize};
#[derive(Archive, Serialize, Deserialize, Debug)]
pub struct Author {
pub name: String,
pub icon: Option<char>,
pub flags: u16,
}
#[allow(dead_code)]
impl Author {
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
icon: None,
flags: 0,
}
}
pub fn flag_is(&self, flag: AuthorFlag) -> bool {
self.flags_get().contains(flag)
}
pub fn flags_get(&self) -> EnumSet<AuthorFlag> {
EnumSet::<AuthorFlag>::from_u16(self.flags)
}
pub fn flags_set(&mut self, flags: EnumSet<AuthorFlag>) {
self.flags = flags.as_u16();
}
}

View file

@ -0,0 +1,51 @@
use super::attach::Attach;
use crate::PostFlag;
use enumset::EnumSet;
use rkyv::{Archive, Deserialize, Serialize};
#[derive(Archive, Serialize, Deserialize, Debug)]
pub struct Post {
author_id: u16,
timestamp: u32,
text: String,
attach: Option<Attach>,
pub flags: u16,
}
#[allow(dead_code)]
impl Post {
pub fn new(author_id: u16, timestamp: u32, text: &str, attach: Option<Attach>) -> Self {
Self {
author_id: author_id,
timestamp: timestamp,
text: text.to_string(),
attach: attach,
flags: 0,
}
}
pub fn author_id(&self) -> u16 {
self.author_id
}
pub fn flag_is(&self, flag: PostFlag) -> bool {
self.flags_get().contains(flag)
}
pub fn flags_get(&self) -> EnumSet<PostFlag> {
EnumSet::<PostFlag>::from_u16(self.flags)
}
pub fn flags_set(&mut self, flags: EnumSet<PostFlag>) {
self.flags = flags.as_u16();
}
pub fn text(&self) -> &str {
self.text.as_str()
}
pub fn timestamp(&self) -> u32 {
self.timestamp
}
}

273
libs/chat/src/lib.rs Normal file
View file

@ -0,0 +1,273 @@
pub mod api;
pub mod cmd;
pub mod dialogue;
pub mod ui;
pub use api::*;
use num_traits::FromPrimitive;
use std::convert::TryInto;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use xous::{Error, CID, SID};
use xous_ipc::Buffer;
pub struct Chat {
cid: CID,
}
impl Chat {
pub fn new(
app_cid: Option<CID>,
opcode_post: Option<usize>,
opcode_event: Option<usize>,
opcode_rawkeys: Option<usize>,
) -> Self {
let chat_sid = xous::create_server().unwrap();
let chat_cid = xous::connect(chat_sid).unwrap();
log::info!("Starting chat UI server",);
thread::spawn({
move || {
server(chat_sid, app_cid, opcode_post, opcode_event, opcode_rawkeys);
}
});
Chat { cid: chat_cid }
}
pub fn read_only(pddb_dict: &str, pddb_key: &str) -> Self {
let chat = Chat::new(None, None, None, None);
chat.dialogue_set(pddb_dict, pddb_key).unwrap();
chat
}
// set the current Dialogue
pub fn dialogue_set(&self, pddb_dict: &str, pddb_key: &str) -> Result<(), Error> {
let mut dialogue = api::Dialogue {
dict: xous_ipc::String::new(),
key: xous_ipc::String::new(),
};
dialogue.dict.append(pddb_dict).unwrap();
dialogue.key.append(pddb_key).unwrap();
match Buffer::into_buf(dialogue) {
Ok(buf) => buf.send(self.cid, ChatOp::DialogueSet as u32).map(|_| ()),
Err(_) => Err(xous::Error::InternalError),
}
}
// add a new Post to the current Dialogue
pub fn post_add(
&self,
author: &str,
timestamp: u32,
text: &str,
attach_url: Option<&str>,
) -> Result<(), Error> {
let mut post = api::Post {
author: xous_ipc::String::new(),
timestamp: timestamp,
text: xous_ipc::String::new(),
attach_url: match attach_url {
Some(url) => Some(xous_ipc::String::from_str(url)),
None => None,
},
};
post.author.append(author).unwrap();
post.text.append(text).unwrap();
match Buffer::into_buf(post) {
Ok(buf) => buf.send(self.cid, ChatOp::PostAdd as u32).map(|_| ()),
Err(_) => Err(xous::Error::InternalError),
}
}
// delete a Post from the current Dialogue
pub fn post_del(&self, _key: u32) -> Result<(), Error> {
log::warn!("not implemented");
Err(xous::Error::InternalError)
}
// get a Post from the current Dialogue
pub fn post_find(&self, author: &str, timestamp: u32) -> Result<Option<usize>, Error> {
let mut find = Find {
author: xous_ipc::String::new(),
timestamp: timestamp,
key: None,
};
find.author.append(author).unwrap();
match Buffer::into_buf(find) {
Ok(mut buf) => {
buf.lend_mut(self.cid, ChatOp::PostFind as u32).map(|_| ());
find = buf.to_original::<api::Find, _>().unwrap();
Ok(find.key)
}
Err(_) => Err(xous::Error::InternalError),
}
}
// set various status flags on a Post in the current Dialogue
pub fn post_flag(&self, _key: &str) -> Result<(), Error> {
log::warn!("not implemented");
Err(xous::Error::InternalError)
}
// set the text displayed on each of the Precursor Fn buttons
pub fn ui_button(
&self,
_f1: Option<&str>,
_f2: Option<&str>,
_f3: Option<&str>,
_f4: Option<&str>,
) -> Result<(), Error> {
log::warn!("not implemented");
Err(xous::Error::InternalError)
}
// request the Chat object to display a menu with options to the user
pub fn ui_menu(&self, _options: Vec<&str>) -> Result<(), Error> {
log::warn!("not implemented");
Err(xous::Error::InternalError)
}
}
pub fn server(
sid: SID,
app_cid: Option<CID>,
opcode_post: Option<usize>,
opcode_event: Option<usize>,
opcode_rawkeys: Option<usize>,
) -> ! {
//log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info);
log::info!("my PID is {}", xous::process::id());
// let mut app_cid = app_cid;
// let mut opcode_post = opcode_post;
// let mut opcode_event = opcode_event;
// let mut opcode_rawkeys = opcode_rawkeys;
let mut ui = ui::Ui::new(sid, app_cid, opcode_event);
let mut user_post = true;
let mut allow_redraw = false;
loop {
let msg = xous::receive_message(sid).unwrap();
log::debug!("got message {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(ChatOp::DialogueSet) => {
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let dialogue = buffer.to_original::<Dialogue, _>().unwrap();
ui.dialogue_set(
dialogue.dict.as_str().unwrap(),
dialogue.key.as_str().unwrap(),
);
}
Some(ChatOp::GamChangeFocus) => {
xous::msg_scalar_unpack!(msg, new_state_code, _, _, _, {
let new_state = gam::FocusState::convert_focus_change(new_state_code);
match new_state {
gam::FocusState::Background => {
allow_redraw = false;
}
gam::FocusState::Foreground => {
allow_redraw = true;
}
}
})
}
Some(ChatOp::GamLine) => {
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let s = buffer
.to_original::<xous_ipc::String<{ POST_TEXT_MAX }>, _>()
.unwrap();
//log::trace!("ui got input line: {}", s.as_str());
ui.input = Some(s);
user_post = true; // set a flag, instead of calling here, so message can drop and calling server is released
}
Some(ChatOp::GamRawKeys) => {
if let Some(cid) = app_cid {
if let Some(opcode) = opcode_rawkeys {
msg.forward(cid, opcode)
.unwrap_or(log::warn!("failed to forward RawKeys msg"));
}
}
}
Some(ChatOp::GamRedraw) => {
if allow_redraw {
ui.redraw().expect("CHAT couldn't redraw");
}
}
Some(ChatOp::PostAdd) => {
log::info!("ChatOp::PostAdd");
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
match buffer.to_original::<Post, _>() {
Ok(post) => ui
.post_add(
post.author.as_str().unwrap(),
post.timestamp,
post.text.as_str().unwrap(),
None, // TODO implement
)
.unwrap(),
Err(e) => log::warn!("failed to deserialize Post: {:?}", e),
}
}
Some(ChatOp::PostFind) => {
log::info!("ChatOp::PostAdd");
let mut buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
if let Ok(mut find) = buffer.to_original::<Find, _>() {
find.key = ui.post_find(find.author.as_str().unwrap(), find.timestamp);
buffer.replace(find).expect("couldn't serialize return");
} else {
log::warn!("failed to serialize Find");
}
}
Some(ChatOp::PostFlag) => {
log::warn!("ChatOp::PostFlag not implemented");
}
Some(ChatOp::ListenSet) => {
// set listener sid and opcodes to receive UI-event msgs & user posts
// pub fn listen_set(&self, cid: xous::CID, opcode_post: Option<u32>, opcode_event: Option<u32>, opcode_rawkeys: Option<u32>) {
// self.listener = cid;
// self.opcode_post = opcode_post;
// self.opcode_event = opcode_event;
// self.opcode_rawkeys = opcode_rawkeys;
// }
}
Some(ChatOp::UiButton) => {
log::warn!("ChatOp::UiButton not implemented");
}
Some(ChatOp::UiMenu) => {
log::warn!("ChatOp::UiMenu not implemented");
}
Some(ChatOp::Quit) => {
log::error!("got Quit");
break;
}
_ => log::warn!("got unknown message"),
}
if user_post {
log::warn!("TODO relay new user post to Chat App");
user_post = false;
}
log::trace!("reached bottom of main loop");
}
// clean up our program
log::error!("main loop exit, destroying servers");
xous::destroy_server(sid).unwrap();
log::trace!("quitting");
xous::terminate_process(0)
}
pub fn now() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
.try_into()
.unwrap()
}

26
libs/chat/src/main.rs Normal file
View file

@ -0,0 +1,26 @@
#![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)]
mod api;
use crate::server;
use api::*;
use xous::{Error, CID, SID};
pub fn main() -> ! {
let xns = xous_names::XousNames::new().unwrap();
let sid = xns
.register_name("Chat UI", None)
.expect("can't register server");
log::trace!("registered with NS -- {:?}", sid);
let chat_sid = xous::create_server().unwrap();
let chat_cid = xous::connect(chat_sid).unwrap();
log::info!("Starting chat server",);
thread::spawn({
move || {
server(chat_sid, None, None, None, None);
}
});
}

278
libs/chat/src/ui.rs Normal file
View file

@ -0,0 +1,278 @@
use super::*;
//use crate::{ChatOp, Dialogue, Event, Post, CHAT_SERVER_NAME};
use core::fmt::Write;
use dialogue::{author::Author, post::Post, Dialogue};
use gam::UxRegistration;
use graphics_server::api::GlyphStyle;
use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView};
use locales::t;
use modals::Modals;
use std::io::{Error, ErrorKind};
use xous::{MessageEnvelope, CID};
use xous_names::XousNames;
#[allow(dead_code)]
pub(crate) struct Ui {
// optional structures that indicate new input to the Chat loop per iteration
// an input string
pub input: Option<xous_ipc::String<{ POST_TEXT_MAX }>>,
// messages from other servers
msg: Option<MessageEnvelope>,
// Pddb connection
pddb: pddb::Pddb,
pddb_dict: Option<String>,
pddb_key: Option<String>,
dialogue: Option<Dialogue>,
// Callbacks:
// optional SID of the "Owner" Chat App to receive UI-events
app_cid: Option<CID>,
// optional opcode ID to process UI-event msgs
opcode_event: Option<usize>,
canvas: Gid,
gam: gam::Gam,
// variables that define our graphical attributes
screensize: Point,
bubble_width: u16,
margin: Point, // margin to edge of canvas
bubble_margin: Point, // margin of text in bubbles
bubble_radius: u16,
bubble_space: i16, // spacing between text bubbles
// our security token for making changes to our record on the GAM
token: [u32; 4],
}
#[allow(dead_code)]
impl Ui {
pub(crate) fn new(
sid: xous::SID,
app_cid: Option<xous::CID>,
opcode_event: Option<usize>,
) -> Self {
let xns = XousNames::new().unwrap();
let gam = gam::Gam::new(&xns).expect("can't connect to GAM");
let token = gam
.register_ux(UxRegistration {
app_name: xous_ipc::String::<128>::from_str(SERVER_NAME_CHAT),
ux_type: gam::UxType::Chat,
predictor: Some(xous_ipc::String::<64>::from_str(
ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL,
)),
listener: sid.to_array(), // note disclosure of our SID to the GAM -- the secret is now shared with the GAM!
redraw_id: ChatOp::GamRedraw as u32,
gotinput_id: Some(ChatOp::GamLine as u32),
audioframe_id: None,
rawkeys_id: Some(ChatOp::GamRawKeys as u32),
focuschange_id: Some(ChatOp::GamChangeFocus as u32),
})
.expect("couldn't register Ux context for chat");
let canvas = gam
.request_content_canvas(token.unwrap())
.expect("couldn't get content canvas");
let screensize = gam
.get_canvas_bounds(canvas)
.expect("couldn't get dimensions of content canvas");
Ui {
input: None,
msg: None,
pddb: pddb::Pddb::new(),
pddb_dict: None,
pddb_key: None,
dialogue: None,
app_cid,
opcode_event,
canvas,
gam,
screensize,
bubble_width: ((screensize.x / 5) * 4) as u16, // 80% width for the text bubbles
margin: Point::new(4, 4),
bubble_margin: Point::new(4, 4),
bubble_radius: 4,
bubble_space: 4,
token: token.unwrap(),
}
}
// set the current Dialogue
pub fn dialogue_set(&mut self, pddb_dict: &str, pddb_key: &str) {
self.pddb_dict = Some(pddb_dict.to_string());
self.pddb_key = Some(pddb_key.to_string());
}
// set listener sid and opcodes to receive UI-event msgs & user posts
// pub fn listen_set(
// &self,
// cid: xous::CID,
// opcode_post: Option<u32>,
// opcode_event: Option<u32>,
// opcode_rawkeys: Option<u32>,
// ) {
// self.listener = cid;
// self.opcode_post = opcode_post;
// self.opcode_event = opcode_event;
// self.opcode_rawkeys = opcode_rawkeys;
// }
// add a new Post to the current Dialogue
pub fn post_add(
&mut self,
author: &str,
timestamp: u32,
text: &str,
attach_url: Option<&str>,
) -> Result<(), Error> {
match &mut self.dialogue {
Some(ref mut dialogue) => dialogue
.post_add(author, timestamp, text, attach_url)
.unwrap(),
None => log::warn!("no Dialogue available to add Post"),
}
Ok(())
}
// delete a Post from the current Dialogue
pub fn post_del(&self, _key: u32) -> Result<(), Error> {
log::warn!("not implemented");
Err(Error::new(ErrorKind::Other, "not implemented"))
}
// get a Post from the current Dialogue
pub fn post_find(&self, author: &str, timestamp: u32) -> Option<usize> {
match &self.dialogue {
Some(dialogue) => dialogue.post_find(author, timestamp),
None => None,
}
}
// get a Post from the current Dialogue
pub fn post_get(&self, _key: u32) -> Result<Post, Error> {
log::warn!("not implemented");
Err(Error::new(ErrorKind::Other, "not implemented"))
}
// set various status flags on a Post in the current Dialogue
pub fn post_flag(&self, _key: u32) -> Result<(), Error> {
log::warn!("not implemented");
Err(Error::new(ErrorKind::Other, "not implemented"))
}
// set the text displayed on each of the Precursor Fn buttons
pub fn ui_button(
&self,
_f1: Option<&str>,
_f2: Option<&str>,
_f3: Option<&str>,
_f4: Option<&str>,
) -> Result<(), Error> {
log::warn!("not implemented");
Err(Error::new(ErrorKind::Other, "not implemented"))
}
// request the Chat object to display a menu with options to the user
pub fn ui_menu(&self, _options: Vec<&str>) -> Result<Vec<u32>, Error> {
log::warn!("not implemented");
Err(Error::new(ErrorKind::Other, "not implemented"))
}
fn app_cid(&self) -> Option<CID> {
self.app_cid
}
// send a xous scalar message with an Event to the Chat App cid/opcode
fn event(&self, _event: Event) {
log::warn!("not implemented");
// Err(Error::new(ErrorKind::Other, "not implemented"))
}
fn bubble(&self, post: &Post, author: &Author, baseline: i16) -> TextView {
let mut bubble_tv = if author.flag_is(AuthorFlag::Right) {
TextView::new(
self.canvas,
TextBounds::GrowableFromBr(
Point::new(self.screensize.x - self.margin.x, baseline),
self.bubble_width,
),
)
} else {
TextView::new(
self.canvas,
TextBounds::GrowableFromBl(Point::new(self.margin.x, baseline), self.bubble_width),
)
};
bubble_tv.border_width = 1;
bubble_tv.draw_border = true;
bubble_tv.clear_area = true;
bubble_tv.rounded_border = Some(self.bubble_radius);
bubble_tv.style = GlyphStyle::Regular;
bubble_tv.margin = self.bubble_margin;
bubble_tv.ellipsis = false;
bubble_tv.insertion = None;
write!(bubble_tv.text, "{}", post.text()).expect("couldn't write history text to TextView");
bubble_tv
}
fn clear_area(&self) {
self.gam
.draw_rectangle(
self.canvas,
Rectangle::new_with_style(
Point::new(0, 0),
self.screensize,
DrawStyle {
fill_color: Some(PixelColor::Light),
stroke_color: None,
stroke_width: 0,
},
),
)
.expect("can't clear canvas area");
}
pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> {
self.clear_area();
// this defines the bottom border of the text bubbles as they stack up wards
let mut bubble_baseline = self.screensize.y - self.margin.y;
if let Some(dialogue) = &self.dialogue {
for post in dialogue.posts().rev() {
if let Some(author) = dialogue.author(post.author_id()) {
let mut bubble_tv = self.bubble(post, author, bubble_baseline);
self.gam
.post_textview(&mut bubble_tv)
.expect("couldn't render bubble textview");
if let Some(bounds) = bubble_tv.bounds_computed {
// we only subtract 1x of the margin because the bounds were computed from a "bottom right" that already counted
// the margin once.
bubble_baseline -=
(bounds.br.y - bounds.tl.y) + self.bubble_space + self.bubble_margin.y;
if bubble_baseline <= 0 {
// don't draw history that overflows the top of the screen
break;
}
} else {
break; // we get None on the bounds computed if the text view fell off the top of the screen
}
} else {
log::warn!(
"Post missing Author: {:?}:{:?} {:?}",
self.pddb_dict,
self.pddb_key,
post
);
}
}
}
log::trace!("chat app redraw##");
self.gam.redraw().expect("couldn't redraw screen");
Ok(())
}
}