Commit d038da6844

d038da68445b6287389a7efc5d8b66297ca8b575

parent: c744d74e42

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-01-03 21:57 UTC

Support sending and displaying typing notifications (#9)

Layout: unified · split

CONTRIBUTING.md +26
@@ -1 +1,27 @@
11# Contributing to iamb
2
3## Building
4
5You can build `iamb` locally by using `cargo build`.
6
7## Pull Requests
8
9When making changes to `iamb`, please make sure to:
10
11- Add new tests for fixed bugs and new features whenever possible
12- Add new documentation with new features
13
14If you're adding a large amount of new code, please make sure to look at a test
15coverage report and ensure that your tests sufficiently cover your changes.
16
17You can generate an HTML report with [cargo-tarpaulin] by running:
18
19```
20% cargo tarpaulin --avoid-cfg-tarpaulin --out html
21```
22
23## Tests
24
25You can run the unit tests and documentation tests using `cargo test`.
26
27[cargo-tarpaulin]: https://github.com/xd009642/tarpaulin
Cargo.toml +1 −1
@@ -10,7 +10,7 @@ description = "A Matrix chat client that uses Vim keybindings"
1010license = "Apache-2.0"
1111exclude = [".github", "CONTRIBUTING.md"]
1212keywords = ["matrix", "chat", "tui", "vim"]
13rust-version = "1.65"
13rust-version = "1.66"
1414
1515[dependencies]
1616chrono = "0.4"
README.md +2 −2
@@ -24,7 +24,7 @@ You can create a basic configuration in `$CONFIG_DIR/iamb/config.json` that look
2424 "profiles": {
2525 "example.com": {
2626 "url": "https://example.com",
27 "@user:example.com"
27 "user_id": "@user:example.com"
2828 }
2929 }
3030}
@@ -51,7 +51,7 @@ two other TUI clients and Element Web:
5151| Display read markers | :x: ([#11]) | :x: | :x: | :heavy_check_mark: |
5252| Sending Invites | :x: ([#7]) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
5353| Accepting Invites | :x: ([#7]) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
54| Typing Notification | :x: ([#9]) | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
54| Typing Notification | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
5555| E2E | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
5656| Replies | :x: ([#3]) | :heavy_check_mark: | :x: | :heavy_check_mark: |
5757| Attachment uploading | :x: ([#13]) | :x: | :heavy_check_mark: | :heavy_check_mark: |
src/base.rs +151 −2
@@ -8,7 +8,7 @@ use tracing::warn;
88
99use matrix_sdk::{
1010 encryption::verification::SasVerification,
11 ruma::{OwnedRoomId, RoomId},
11 ruma::{OwnedRoomId, OwnedUserId, RoomId},
1212};
1313
1414use modalkit::{
@@ -32,10 +32,16 @@ use modalkit::{
3232 },
3333 input::bindings::SequenceStatus,
3434 input::key::TerminalKey,
35 tui::{
36 buffer::Buffer,
37 layout::{Alignment, Rect},
38 text::{Span, Spans},
39 widgets::{Paragraph, Widget},
40 },
3541};
3642
3743use crate::{
38 message::{Message, Messages},
44 message::{user_style, Message, Messages},
3945 worker::Requester,
4046 ApplicationSettings,
4147};
@@ -167,12 +173,84 @@ pub struct RoomInfo {
167173 pub messages: Messages,
168174 pub fetch_id: RoomFetchStatus,
169175 pub fetch_last: Option<Instant>,
176 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
170177}
171178
172179impl RoomInfo {
173180 fn recently_fetched(&self) -> bool {
174181 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
175182 }
183
184 fn get_typers(&self) -> &[OwnedUserId] {
185 if let Some((t, users)) = &self.users_typing {
186 if t.elapsed() < Duration::from_secs(4) {
187 return users.as_ref();
188 } else {
189 return &[];
190 }
191 } else {
192 return &[];
193 }
194 }
195
196 fn get_typing_spans(&self) -> Spans {
197 let typers = self.get_typers();
198 let n = typers.len();
199
200 match n {
201 0 => Spans(vec![]),
202 1 => {
203 let user = typers[0].as_str();
204 let user = Span::styled(user, user_style(user));
205
206 Spans(vec![user, Span::from(" is typing...")])
207 },
208 2 => {
209 let user1 = typers[0].as_str();
210 let user1 = Span::styled(user1, user_style(user1));
211
212 let user2 = typers[1].as_str();
213 let user2 = Span::styled(user2, user_style(user2));
214
215 Spans(vec![
216 user1,
217 Span::raw(" and "),
218 user2,
219 Span::from(" are typing..."),
220 ])
221 },
222 n if n < 5 => Spans::from("Several people are typing..."),
223 _ => Spans::from("Many people are typing..."),
224 }
225 }
226
227 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
228 self.users_typing = (Instant::now(), user_ids).into();
229 }
230
231 pub fn render_typing(
232 &mut self,
233 area: Rect,
234 buf: &mut Buffer,
235 settings: &ApplicationSettings,
236 ) -> Rect {
237 if area.height <= 2 || area.width <= 20 {
238 return area;
239 }
240
241 if !settings.tunables.typing_notice_display {
242 return area;
243 }
244
245 let top = Rect::new(area.x, area.y, area.width, area.height - 1);
246 let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
247
248 Paragraph::new(self.get_typing_spans())
249 .alignment(Alignment::Center)
250 .render(bar, buf);
251
252 return top;
253 }
176254}
177255
178256pub struct ChatStore {
@@ -326,3 +404,74 @@ impl ApplicationInfo for IambInfo {
326404 type WindowId = IambId;
327405 type ContentId = IambBufferId;
328406}
407
408#[cfg(test)]
409pub mod tests {
410 use super::*;
411 use crate::tests::*;
412
413 #[test]
414 fn test_typing_spans() {
415 let mut info = RoomInfo::default();
416
417 let users0 = vec![];
418 let users1 = vec![TEST_USER1.clone()];
419 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
420 let users4 = vec![
421 TEST_USER1.clone(),
422 TEST_USER2.clone(),
423 TEST_USER3.clone(),
424 TEST_USER4.clone(),
425 ];
426 let users5 = vec![
427 TEST_USER1.clone(),
428 TEST_USER2.clone(),
429 TEST_USER3.clone(),
430 TEST_USER4.clone(),
431 TEST_USER5.clone(),
432 ];
433
434 // Nothing set.
435 assert_eq!(info.users_typing, None);
436 assert_eq!(info.get_typing_spans(), Spans(vec![]));
437
438 // Empty typing list.
439 info.set_typing(users0);
440 assert!(info.users_typing.is_some());
441 assert_eq!(info.get_typing_spans(), Spans(vec![]));
442
443 // Single user typing.
444 info.set_typing(users1);
445 assert!(info.users_typing.is_some());
446 assert_eq!(
447 info.get_typing_spans(),
448 Spans(vec![
449 Span::styled("@user1:example.com", user_style("@user1:example.com")),
450 Span::from(" is typing...")
451 ])
452 );
453
454 // Two users typing.
455 info.set_typing(users2);
456 assert!(info.users_typing.is_some());
457 assert_eq!(
458 info.get_typing_spans(),
459 Spans(vec![
460 Span::styled("@user1:example.com", user_style("@user1:example.com")),
461 Span::raw(" and "),
462 Span::styled("@user2:example.com", user_style("@user2:example.com")),
463 Span::raw(" are typing...")
464 ])
465 );
466
467 // Four users typing.
468 info.set_typing(users4);
469 assert!(info.users_typing.is_some());
470 assert_eq!(info.get_typing_spans(), Spans::from("Several people are typing..."));
471
472 // Five users typing.
473 info.set_typing(users5);
474 assert!(info.users_typing.is_some());
475 assert_eq!(info.get_typing_spans(), Spans::from("Many people are typing..."));
476 }
477}
src/config.rs +75 −11
@@ -69,17 +69,73 @@ pub enum ConfigError {
6969 Invalid(#[from] serde_json::Error),
7070}
7171
72#[derive(Clone)]
73pub struct TunableValues {
74 pub typing_notice: bool,
75 pub typing_notice_display: bool,
76}
77
78#[derive(Clone, Default, Deserialize)]
79pub struct Tunables {
80 pub typing_notice: Option<bool>,
81 pub typing_notice_display: Option<bool>,
82}
83
84impl Tunables {
85 fn merge(self, other: Self) -> Self {
86 Tunables {
87 typing_notice: self.typing_notice.or(other.typing_notice),
88 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
89 }
90 }
91
92 fn values(self) -> TunableValues {
93 TunableValues {
94 typing_notice: self.typing_notice.unwrap_or(true),
95 typing_notice_display: self.typing_notice.unwrap_or(true),
96 }
97 }
98}
99
100#[derive(Clone)]
101pub struct DirectoryValues {
102 pub cache: PathBuf,
103}
104
105#[derive(Clone, Default, Deserialize)]
106pub struct Directories {
107 pub cache: Option<PathBuf>,
108}
109
110impl Directories {
111 fn merge(self, other: Self) -> Self {
112 Directories { cache: self.cache.or(other.cache) }
113 }
114
115 fn values(self) -> DirectoryValues {
116 DirectoryValues {
117 cache: self
118 .cache
119 .or_else(dirs::cache_dir)
120 .expect("no dirs.cache value configured!"),
121 }
122 }
123}
124
72125#[derive(Clone, Deserialize)]
73126pub struct ProfileConfig {
74127 pub user_id: OwnedUserId,
75128 pub url: Url,
129 pub settings: Option<Tunables>,
130 pub dirs: Option<Directories>,
76131}
77132
78133#[derive(Clone, Deserialize)]
79134pub struct IambConfig {
80135 pub profiles: HashMap<String, ProfileConfig>,
81136 pub default_profile: Option<String>,
82 pub cache: Option<PathBuf>,
137 pub settings: Option<Tunables>,
138 pub dirs: Option<Directories>,
83139}
84140
85141impl IambConfig {
@@ -103,10 +159,11 @@ impl IambConfig {
103159#[derive(Clone)]
104160pub struct ApplicationSettings {
105161 pub matrix_dir: PathBuf,
106 pub cache_dir: PathBuf,
107162 pub session_json: PathBuf,
108163 pub profile_name: String,
109164 pub profile: ProfileConfig,
165 pub tunables: TunableValues,
166 pub dirs: DirectoryValues,
110167}
111168
112169impl ApplicationSettings {
@@ -122,12 +179,16 @@ impl ApplicationSettings {
122179 let mut config_json = config_dir.clone();
123180 config_json.push("config.json");
124181
125 let IambConfig { mut profiles, default_profile, cache } =
126 IambConfig::load(config_json.as_path())?;
182 let IambConfig {
183 mut profiles,
184 default_profile,
185 dirs,
186 settings: global,
187 } = IambConfig::load(config_json.as_path())?;
127188
128189 validate_profile_names(&profiles);
129190
130 let (profile_name, profile) = if let Some(profile) = cli.profile.or(default_profile) {
191 let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
131192 profiles.remove_entry(&profile).unwrap_or_else(|| {
132193 usage!(
133194 "No configured profile with the name {:?} in {}",
@@ -146,6 +207,10 @@ impl ApplicationSettings {
146207 );
147208 };
148209
210 let tunables = global.unwrap_or_default();
211 let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
212 let tunables = tunables.values();
213
149214 let mut profile_dir = config_dir.clone();
150215 profile_dir.push("profiles");
151216 profile_dir.push(profile_name.as_str());
@@ -156,18 +221,17 @@ impl ApplicationSettings {
156221 let mut session_json = profile_dir;
157222 session_json.push("session.json");
158223
159 let cache_dir = cache.unwrap_or_else(|| {
160 let mut cache = dirs::cache_dir().expect("no user cache directory");
161 cache.push("iamb");
162 cache
163 });
224 let dirs = dirs.unwrap_or_default();
225 let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
226 let dirs = dirs.values();
164227
165228 let settings = ApplicationSettings {
166229 matrix_dir,
167 cache_dir,
168230 session_json,
169231 profile_name,
170232 profile,
233 tunables,
234 dirs,
171235 };
172236
173237 Ok(settings)
src/main.rs +1 −1
@@ -450,7 +450,7 @@ async fn main() -> IambResult<()> {
450450
451451 // Set up the tracing subscriber so we can log client messages.
452452 let log_prefix = format!("iamb-log-{}", settings.profile_name);
453 let mut log_dir = settings.cache_dir.clone();
453 let mut log_dir = settings.dirs.cache.clone();
454454 log_dir.push("logs");
455455
456456 create_dir_all(settings.matrix_dir.as_path())?;
src/message.rs +14 −8
@@ -66,6 +66,18 @@ const USER_GUTTER_EMPTY_SPAN: Span<'static> = Span {
6666 },
6767};
6868
69pub(crate) fn user_color(user: &str) -> Color {
70 let mut hasher = DefaultHasher::new();
71 user.hash(&mut hasher);
72 let color = hasher.finish() as usize % COLORS.len();
73
74 COLORS[color]
75}
76
77pub(crate) fn user_style(user: &str) -> Style {
78 Style::default().fg(user_color(user)).add_modifier(StyleModifier::BOLD)
79}
80
6981struct WrappedLinesIterator<'a> {
7082 iter: Lines<'a>,
7183 curr: Option<&'a str>,
@@ -446,13 +458,7 @@ impl Message {
446458
447459 fn show_sender(&self, align_right: bool) -> Span {
448460 let sender = self.sender.to_string();
449
450 let mut hasher = DefaultHasher::new();
451 sender.hash(&mut hasher);
452 let color = hasher.finish() as usize % COLORS.len();
453 let color = COLORS[color];
454
455 let bold = Style::default().fg(color).add_modifier(StyleModifier::BOLD);
461 let style = user_style(sender.as_str());
456462
457463 let sender = if align_right {
458464 format!("{: >width$} ", sender, width = 28)
@@ -460,7 +466,7 @@ impl Message {
460466 format!("{: <width$} ", sender, width = 28)
461467 };
462468
463 Span::styled(sender, bold)
469 Span::styled(sender, style)
464470 }
465471}
466472
src/tests.rs +9 −2
@@ -20,7 +20,7 @@ use lazy_static::lazy_static;
2020
2121use crate::{
2222 base::{ChatStore, ProgramStore, RoomFetchStatus, RoomInfo},
23 config::{ApplicationSettings, ProfileConfig},
23 config::{ApplicationSettings, DirectoryValues, ProfileConfig, TunableValues},
2424 message::{
2525 Message,
2626 MessageContent,
@@ -35,6 +35,9 @@ lazy_static! {
3535 pub static ref TEST_ROOM1_ID: OwnedRoomId = RoomId::new(server_name!("example.com")).to_owned();
3636 pub static ref TEST_USER1: OwnedUserId = user_id!("@user1:example.com").to_owned();
3737 pub static ref TEST_USER2: OwnedUserId = user_id!("@user2:example.com").to_owned();
38 pub static ref TEST_USER3: OwnedUserId = user_id!("@user2:example.com").to_owned();
39 pub static ref TEST_USER4: OwnedUserId = user_id!("@user2:example.com").to_owned();
40 pub static ref TEST_USER5: OwnedUserId = user_id!("@user2:example.com").to_owned();
3841 pub static ref MSG1_KEY: MessageKey = (LocalEcho, EventId::new(server_name!("example.com")));
3942 pub static ref MSG2_KEY: MessageKey =
4043 (OriginServer(UInt::new(1).unwrap()), EventId::new(server_name!("example.com")));
@@ -103,19 +106,23 @@ pub fn mock_room() -> RoomInfo {
103106 messages: mock_messages(),
104107 fetch_id: RoomFetchStatus::NotStarted,
105108 fetch_last: None,
109 users_typing: None,
106110 }
107111}
108112
109113pub fn mock_settings() -> ApplicationSettings {
110114 ApplicationSettings {
111115 matrix_dir: PathBuf::new(),
112 cache_dir: PathBuf::new(),
113116 session_json: PathBuf::new(),
114117 profile_name: "test".into(),
115118 profile: ProfileConfig {
116119 user_id: user_id!("@user:example.com").to_owned(),
117120 url: Url::parse("https://example.com").unwrap(),
121 settings: None,
122 dirs: None,
118123 },
124 tunables: TunableValues { typing_notice: true, typing_notice_display: true },
125 dirs: DirectoryValues { cache: PathBuf::new() },
119126 }
120127}
121128
src/windows/room/chat.rs +23
@@ -83,6 +83,27 @@ impl ChatState {
8383 pub fn id(&self) -> &RoomId {
8484 &self.room_id
8585 }
86
87 pub fn typing_notice(
88 &self,
89 act: &EditorAction,
90 ctx: &ProgramContext,
91 store: &mut ProgramStore,
92 ) {
93 if !self.focus.is_msgbar() || act.is_readonly(ctx) {
94 return;
95 }
96
97 if matches!(act, EditorAction::History(_)) {
98 return;
99 }
100
101 if !store.application.settings.tunables.typing_notice {
102 return;
103 }
104
105 store.application.worker.typing_notice(self.room_id.clone());
106 }
86107}
87108
88109macro_rules! delegate {
@@ -148,6 +169,8 @@ impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
148169 ctx: &ProgramContext,
149170 store: &mut ProgramStore,
150171 ) -> EditResult<EditInfo, IambInfo> {
172 self.typing_notice(act, ctx, store);
173
151174 match delegate!(self, w => w.editor_command(act, ctx, store)) {
152175 res @ Ok(_) => res,
153176 Err(EditError::WrongBuffer(IambBufferId::Room(room_id, focus)))
src/windows/room/scrollback.rs +9 −2
@@ -1125,6 +1125,9 @@ impl<'a> StatefulWidget for Scrollback<'a> {
11251125 type State = ScrollbackState;
11261126
11271127 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1128 let info = self.store.application.rooms.entry(state.room_id.clone()).or_default();
1129 let area = info.render_typing(area, buf, &self.store.application.settings);
1130
11281131 state.set_term_info(area);
11291132
11301133 let height = state.viewctx.get_height();
@@ -1137,8 +1140,6 @@ impl<'a> StatefulWidget for Scrollback<'a> {
11371140 state.viewctx.corner = state.cursor.clone();
11381141 }
11391142
1140 let info = self.store.application.get_room_info(state.room_id.clone());
1141
11421143 let cursor = &state.cursor;
11431144 let cursor_key = if let Some(k) = cursor.to_key(info) {
11441145 k
@@ -1297,6 +1298,9 @@ mod tests {
12971298 let prev = MoveDir2D::Up;
12981299 let next = MoveDir2D::Down;
12991300
1301 // Skip rendering typing notices.
1302 store.application.settings.tunables.typing_notice_display = false;
1303
13001304 assert_eq!(scrollback.cursor, MessageCursor::latest());
13011305 assert_eq!(scrollback.viewctx.dimensions, (0, 0));
13021306 assert_eq!(scrollback.viewctx.corner, MessageCursor::latest());
@@ -1425,6 +1429,9 @@ mod tests {
14251429 let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone());
14261430 let ctx = ProgramContext::default();
14271431
1432 // Skip rendering typing notices.
1433 store.application.settings.tunables.typing_notice_display = false;
1434
14281435 // Set a terminal width of 60, and height of 3, rendering in scrollback as:
14291436 //
14301437 // |------------------------------------------------------------|
src/windows/welcome.rs +3 −1
@@ -21,8 +21,10 @@ pub struct WelcomeState {
2121impl WelcomeState {
2222 pub fn new(store: &mut ProgramStore) -> Self {
2323 let buf = store.buffers.load_str(IambBufferId::Welcome, WELCOME_TEXT);
24 let mut tbox = TextBoxState::new(buf);
25 tbox.set_readonly(true);
2426
25 WelcomeState { tbox: TextBoxState::new(buf) }
27 WelcomeState { tbox }
2628 }
2729}
2830
src/worker.rs +34
@@ -32,6 +32,7 @@ use matrix_sdk::{
3232 },
3333 room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent},
3434 room::name::RoomNameEventContent,
35 typing::SyncTypingEvent,
3536 AnyMessageLikeEvent,
3637 AnyTimelineEvent,
3738 SyncMessageLikeEvent,
@@ -104,6 +105,7 @@ pub enum WorkerTask {
104105 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
105106 Spaces(ClientReply<Vec<(MatrixRoom, DisplayName)>>),
106107 SendMessage(OwnedRoomId, String, ClientReply<IambResult<EchoPair>>),
108 TypingNotice(OwnedRoomId),
107109 Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>),
108110 VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>),
109111}
@@ -201,6 +203,10 @@ impl Requester {
201203 return response.recv();
202204 }
203205
206 pub fn typing_notice(&self, room_id: OwnedRoomId) {
207 self.tx.send(WorkerTask::TypingNotice(room_id)).unwrap();
208 }
209
204210 pub fn verify(&self, act: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
205211 let (reply, response) = oneshot();
206212
@@ -333,6 +339,10 @@ impl ClientWorker {
333339 assert!(self.initialized);
334340 reply.send(self.send_message(room_id, msg).await);
335341 },
342 WorkerTask::TypingNotice(room_id) => {
343 assert!(self.initialized);
344 self.typing_notice(room_id).await;
345 },
336346 WorkerTask::Verify(act, sas, reply) => {
337347 assert!(self.initialized);
338348 reply.send(self.verify(act, sas).await);
@@ -347,6 +357,24 @@ impl ClientWorker {
347357 async fn init(&mut self, store: AsyncProgramStore) {
348358 self.client.add_event_handler_context(store);
349359
360 let _ = self.client.add_event_handler(
361 |ev: SyncTypingEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| {
362 async move {
363 let room_id = room.room_id().to_owned();
364 let mut locked = store.lock().await;
365
366 let users = ev
367 .content
368 .user_ids
369 .into_iter()
370 .filter(|u| u != &locked.application.settings.profile.user_id)
371 .collect();
372
373 locked.application.get_room_info(room_id).set_typing(users);
374 }
375 },
376 );
377
350378 let _ = self.client.add_event_handler(
351379 |ev: SyncStateEvent<RoomNameEventContent>,
352380 room: MatrixRoom,
@@ -744,6 +772,12 @@ impl ClientWorker {
744772 return spaces;
745773 }
746774
775 async fn typing_notice(&mut self, room_id: OwnedRoomId) {
776 if let Some(room) = self.client.get_joined_room(room_id.as_ref()) {
777 let _ = room.typing_notice(true).await;
778 }
779 }
780
747781 async fn verify(&self, action: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
748782 match action {
749783 VerifyAction::Accept => {