use own state store

This commit is contained in:
Amanda Graven 2020-12-11 11:43:54 +01:00
parent 3f7c3bd35e
commit a212a0b3a0
Signed by: amanda
GPG key ID: 45C461CDC9286390
2 changed files with 133 additions and 114 deletions

View file

@ -103,7 +103,7 @@ pub async fn login(
homeserver: server.to_owned(), homeserver: server.to_owned(),
}; };
write_session(&session)?; write_session(&session)?;
client.sync_once(SyncSettings::new()).await?; //client.sync_once(SyncSettings::new()).await?;
Ok((client, session)) Ok((client, session))
} }
@ -113,7 +113,7 @@ pub async fn restore_login(session: Session) -> Result<(Client, Session), Error>
let client = client(url)?; let client = client(url)?;
client.restore_login(session.clone().into()).await?; client.restore_login(session.clone().into()).await?;
client.sync_once(SyncSettings::new()).await?; //client.sync_once(SyncSettings::new()).await?;
Ok((client, session)) Ok((client, session))
} }
@ -206,7 +206,7 @@ where
client client
.sync_with_callback( .sync_with_callback(
SyncSettings::new() SyncSettings::new()
.token(client.sync_token().await.unwrap()) //.token(client.sync_token().await.unwrap())
.timeout(Duration::from_secs(90)) .timeout(Duration::from_secs(90))
.full_state(true), .full_state(true),
|response| async { |response| async {

241
src/ui.rs
View file

@ -1,5 +1,5 @@
use std::{ use std::{
collections::{BTreeMap, HashMap, VecDeque}, collections::{BTreeMap, VecDeque},
time::SystemTime, time::SystemTime,
}; };
@ -12,9 +12,8 @@ use iced::{
use matrix_sdk::{ use matrix_sdk::{
events::{ events::{
key::verification::cancel::CancelCode as VerificationCancelCode, key::verification::cancel::CancelCode as VerificationCancelCode,
room::message::MessageEventContent, AnyMessageEventContent, room::message::MessageEventContent, AnyMessageEvent, AnyMessageEventContent,
AnyPossiblyRedactedSyncMessageEvent, AnyRoomEvent, AnyStateEvent, AnySyncMessageEvent, AnyPossiblyRedactedSyncMessageEvent, AnyRoomEvent, AnyStateEvent, AnyToDeviceEvent,
AnyToDeviceEvent,
}, },
identifiers::{RoomAliasId, RoomId, UserId}, identifiers::{RoomAliasId, RoomId, UserId},
}; };
@ -180,8 +179,6 @@ pub struct RoomEntry {
display_name: Option<String>, display_name: Option<String>,
/// Person we're in a direct message with /// Person we're in a direct message with
direct: Option<UserId>, direct: Option<UserId>,
/// Button to select the room
button: iced::button::State,
/// Cache of messages /// Cache of messages
messages: MessageBuffer, messages: MessageBuffer,
} }
@ -228,7 +225,7 @@ impl MessageBuffer {
fn sort(&mut self) { fn sort(&mut self) {
self.messages self.messages
.make_contiguous() .make_contiguous()
.sort_unstable_by(|a, b| a.origin_server_ts().cmp(&b.origin_server_ts()).reverse()) .sort_unstable_by(|a, b| a.origin_server_ts().cmp(&b.origin_server_ts()))
} }
/// Gets the send time of the most recently sent message /// Gets the send time of the most recently sent message
@ -273,7 +270,9 @@ pub struct MainView {
rooms: BTreeMap<RoomId, RoomEntry>, rooms: BTreeMap<RoomId, RoomEntry>,
/// Room list entry/button to select room /// Room list entry/button to select room
buttons: HashMap<RoomId, iced::button::State>, dm_buttons: Vec<iced::button::State>,
///
group_buttons: Vec<iced::button::State>,
/// Room list scrollbar state /// Room list scrollbar state
room_scroll: iced::scrollable::State, room_scroll: iced::scrollable::State,
/// Message view scrollbar state /// Message view scrollbar state
@ -304,7 +303,8 @@ impl MainView {
room_scroll: Default::default(), room_scroll: Default::default(),
message_scroll: Default::default(), message_scroll: Default::default(),
message_input: Default::default(), message_input: Default::default(),
buttons: Default::default(), dm_buttons: Vec::new(),
group_buttons: Vec::new(),
draft: String::new(), draft: String::new(),
send_button: Default::default(), send_button: Default::default(),
sorting: RoomSorting::Alphabetic, sorting: RoomSorting::Alphabetic,
@ -320,85 +320,65 @@ impl MainView {
} }
let mut root_row = Row::new().width(Length::Fill).height(Length::Fill); let mut root_row = Row::new().width(Length::Fill).height(Length::Fill);
// Room list
let joined = self.client.joined_rooms();
let rooms = futures::executor::block_on(async { joined.read().await });
let mut room_scroll = Scrollable::new(&mut self.room_scroll) let mut room_scroll = Scrollable::new(&mut self.room_scroll)
.width(300.into()) .width(300.into())
.height(Length::Fill) .height(Length::Fill)
.scrollbar_width(5); .scrollbar_width(5);
// We have to iterate the buttons map and not the other way around to make the
// borrow checker happy. First we make sure there's a button entry for every room // Group by DM and group conversation
// entry, and clean up button entries from removed rooms. let (mut dm_rooms, mut group_rooms): (
for (id, _) in rooms.iter() { Vec<(&RoomId, &RoomEntry)>,
self.buttons.entry(id.to_owned()).or_default(); Vec<(&RoomId, &RoomEntry)>,
} ) = self
self.buttons.retain(|id, _| rooms.contains_key(id)); .rooms
// Then we make our buttons
let mut buttons: HashMap<RoomId, Button<Message>> = self
.buttons
.iter_mut()
.map(|(id, state)| {
// Get read lock for the room
let room = block_on(async { rooms.get(id).unwrap().read().await });
let button = Button::new(state, Text::new(room.display_name()))
.on_press(Message::SelectRoom(id.to_owned()))
.width(400.into());
(id.clone(), button)
})
.collect();
// List of direct message room ids
let mut dm_rooms: Vec<&RoomId> = rooms
.iter() .iter()
.filter(|(_, room)| { .partition(|(_, room)| room.direct.is_some());
let read = block_on(async { room.read().await }); // Sort
read.direct_target.is_some() for list in [&mut dm_rooms, &mut group_rooms].iter_mut() {
})
.map(|(id, _)| id)
.collect();
// List of non-DM room ids
let mut room_rooms = rooms
.iter()
.filter(|(_, room)| {
let read = block_on(async { room.read().await });
read.direct_target.is_none()
})
.map(|(id, _)| id)
.collect();
for list in [&mut dm_rooms, &mut room_rooms].iter_mut() {
match self.sorting { match self.sorting {
RoomSorting::Recent => list.sort_by_key(|id| { RoomSorting::Alphabetic => list.sort_unstable_by(|(_, a), (_, b)| {
let read = block_on(async { rooms.get(id).unwrap().read().await }); a.name.to_uppercase().cmp(&b.name.to_uppercase())
let time = read
.messages
.iter()
.map(|msg| match msg {
AnyPossiblyRedactedSyncMessageEvent::Regular(m) => m.origin_server_ts(),
AnyPossiblyRedactedSyncMessageEvent::Redacted(m) => {
m.origin_server_ts()
}
})
.min()
.copied();
match time {
Some(time) => time,
None => std::time::SystemTime::now(),
}
}), }),
RoomSorting::Alphabetic => list.sort_by_cached_key(|id| { RoomSorting::Recent => list.sort_unstable_by(|(_, a), (_, b)| {
let read = block_on(async { rooms.get(id).unwrap().read().await }); a.messages.updated.cmp(&b.messages.updated).reverse()
read.display_name().to_uppercase()
}), }),
}; };
} }
self.dm_buttons
// Add buttons to room column .resize_with(dm_rooms.len(), Default::default);
self.group_buttons
.resize_with(group_rooms.len(), Default::default);
// Create buttons
let dm_buttons: Vec<Button<_>> = self
.dm_buttons
.iter_mut()
.enumerate()
.map(|(idx, button)| {
// TODO: highlight selected
let (id, room) = dm_rooms[idx];
Button::new(button, Text::new(&room.name))
.width(300.into())
.on_press(Message::SelectRoom(id.clone().clone()))
})
.collect();
let room_buttons: Vec<Button<_>> = self
.group_buttons
.iter_mut()
.enumerate()
.map(|(idx, button)| {
let (id, room) = group_rooms[idx];
Button::new(button, Text::new(&room.name))
.width(300.into())
.on_press(Message::SelectRoom(id.clone()))
})
.collect();
// Add buttons to container
room_scroll = room_scroll.push(Text::new("Direct messages")); room_scroll = room_scroll.push(Text::new("Direct messages"));
for button in dm_rooms.iter().map(|id| buttons.remove(id).unwrap()) { for button in dm_buttons.into_iter() {
room_scroll = room_scroll.push(button); room_scroll = room_scroll.push(button);
} }
room_scroll = room_scroll.push(Text::new("Rooms")); room_scroll = room_scroll.push(Text::new("Rooms"));
for button in room_rooms.iter().map(|id| buttons.remove(id).unwrap()) { for button in room_buttons.into_iter() {
room_scroll = room_scroll.push(button); room_scroll = room_scroll.push(button);
} }
@ -408,51 +388,84 @@ impl MainView {
.on_press(Message::OpenSettings), .on_press(Message::OpenSettings),
) )
.push(room_scroll); .push(room_scroll);
root_row = root_row.push(room_col); root_row = root_row.push(room_col);
// Messages.
//
// Get selected room.
let mut message_col = Column::new().spacing(5).padding(5); let mut message_col = Column::new().spacing(5).padding(5);
let selected_room = self.selected.as_ref().and_then(|selected| { let selected_room = match self.selected {
futures::executor::block_on(async { Some(ref selected) => self.rooms.get(selected),
match rooms.get(selected) { None => None,
Some(room) => Some(room.read().await), };
None => None,
}
})
});
if let Some(room) = selected_room { if let Some(room) = selected_room {
message_col = message_col message_col = message_col
.push(Text::new(room.display_name()).size(25)) .push(Text::new(&room.name).size(25))
.push(Rule::horizontal(2)); .push(Rule::horizontal(2));
let mut scroll = Scrollable::new(&mut self.message_scroll) let mut scroll = Scrollable::new(&mut self.message_scroll)
.scrollbar_width(2) .scrollbar_width(2)
.height(Length::Fill); .height(Length::Fill);
for message in room.messages.iter() { for event in room.messages.messages.iter() {
if let AnyPossiblyRedactedSyncMessageEvent::Regular(event) = message { match event {
if let AnySyncMessageEvent::RoomMessage(room_message) = event { AnyRoomEvent::Message(AnyMessageEvent::RoomMessage(message)) => {
match &room_message.content { let sender = {
MessageEventContent::Text(text) => { let joined = self.client.joined_rooms();
// Render senders disambiguated name or fallback to mxid let rooms_lock = block_on(async { joined.read().await });
let sender = Text::new( match rooms_lock.get(&message.room_id) {
room.joined_members Some(backend) => {
.get(&room_message.sender) let room_lock = block_on(async { backend.read().await });
.map(|sender| sender.disambiguated_name()) match room_lock.joined_members.get(&message.sender) {
.unwrap_or(room_message.sender.to_string()), Some(member) => member.disambiguated_name(),
) None => message.sender.to_string(),
.color([0.2, 0.2, 1.0]); }
let row = Row::new() }
.spacing(5) None => message.sender.to_string(),
.push(sender)
.push(Text::new(&text.body).width(Length::Fill))
.push(Text::new(format_systime(room_message.origin_server_ts)));
scroll = scroll.push(row);
} }
_ => (), };
} let content: Element<_> = match &message.content {
MessageEventContent::Audio(audio) => {
Text::new(format!("Audio message: {}", audio.body))
.color([0.2, 0.2, 0.2])
.width(Length::Fill)
.into()
}
MessageEventContent::Emote(emote) => {
Text::new(format!("{} {}", sender, emote.body))
.width(Length::Fill)
.into()
}
MessageEventContent::File(file) => {
Text::new(format!("File '{}'", file.body))
.color([0.2, 0.2, 0.2])
.width(Length::Fill)
.into()
}
MessageEventContent::Image(image) => {
Text::new(format!("Image with description: {}", image.body))
.width(Length::Fill)
.into()
}
MessageEventContent::Notice(notice) => {
Text::new(&notice.body).width(Length::Fill).into()
}
MessageEventContent::ServerNotice(notice) => {
Text::new(&notice.body).width(Length::Fill).into()
}
MessageEventContent::Text(text) => {
Text::new(&text.body).width(Length::Fill).into()
}
MessageEventContent::Video(video) => {
Text::new(format!("Video: {}", video.body))
.color([0.2, 0.2, 0.2])
.into()
}
_ => Text::new("Unknown message type").into(),
};
let row = Row::new()
.spacing(5)
.push(Text::new(sender).color([0.0, 0.0, 1.0]))
.push(content)
.push(Text::new(format_systime(message.origin_server_ts)));
scroll = scroll.push(row);
} }
_ => (),
} }
} }
message_col = message_col.push(scroll); message_col = message_col.push(scroll);
@ -469,9 +482,12 @@ impl MainView {
if let Some(ref sas) = self.sas { if let Some(ref sas) = self.sas {
let device = sas.other_device(); let device = sas.other_device();
let sas_row = match sas.emoji() { let sas_row = match sas.emoji() {
_ if sas.is_done() => { _ if sas.is_done() => Row::new()
Row::new().push(Text::new("Verification complete").width(Length::Fill)) .push(Text::new("Verification complete").width(Length::Fill))
} .push(
Button::new(&mut self.sas_accept_button, Text::new("Close"))
.on_press(Message::VerificationClose),
),
Some(emojis) => { Some(emojis) => {
let mut row = Row::new().push(Text::new("Verify emojis match:")); let mut row = Row::new().push(Text::new("Verify emojis match:"));
for (emoji, name) in emojis.iter() { for (emoji, name) in emojis.iter() {
@ -601,6 +617,8 @@ pub enum Message {
VerificationCancel, VerificationCancel,
/// Verification flow cancelled /// Verification flow cancelled
VerificationCancelled(VerificationCancelCode), VerificationCancelled(VerificationCancelCode),
/// Close verification bar
VerificationClose,
/// Matrix event received /// Matrix event received
Sync(matrix::Event), Sync(matrix::Event),
/// Set contents of message compose box /// Set contents of message compose box
@ -983,6 +1001,7 @@ impl Application for Retrix {
return async move { Message::ErrorMessage(code.as_str().to_owned()) } return async move { Message::ErrorMessage(code.as_str().to_owned()) }
.into(); .into();
} }
Message::VerificationClose => view.sas = None,
Message::SetMessage(m) => view.draft = m, Message::SetMessage(m) => view.draft = m,
Message::SendMessage => { Message::SendMessage => {
let selected = match view.selected.clone() { let selected = match view.selected.clone() {