Commit 504b520fe1

504b520fe1eb362b194f444955295a07959986e5

parent: 739aab1534

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-01-07 00:56 UTC

Support configuring a user's color and name (#19)

Layout: unified · split

Cargo.lock +1 −1
@@ -1128,7 +1128,7 @@ dependencies = [
11281128
11291129[[package]]
11301130name = "iamb"
1131version = "0.0.1"
1131version = "0.0.2"
11321132dependencies = [
11331133 "chrono",
11341134 "clap",
README.md +4
@@ -1,5 +1,9 @@
11# iamb
22
3[![Build Status](https://github.com/ulyssa/iamb/workflows/CI/badge.svg)](https://github.com/ulyssa/iamb/actions?query=workflow%3ACI+)
4[![License: Apache 2.0](https://img.shields.io/crates/l/iamb.svg?logo=apache)](https://crates.io/crates/iamb)
5[![Latest Version](https://img.shields.io/crates/v/iamb.svg?logo=rust)](https://crates.io/crates/iamb)
6
37## About
48
59`iamb` is a Matrix client for the terminal that uses Vim keybindings.
src/base.rs +26 −16
@@ -41,7 +41,7 @@ use modalkit::{
4141};
4242
4343use crate::{
44 message::{user_style, Message, Messages},
44 message::{Message, Messages},
4545 worker::Requester,
4646 ApplicationSettings,
4747};
@@ -222,24 +222,20 @@ impl RoomInfo {
222222 }
223223 }
224224
225 fn get_typing_spans(&self) -> Spans {
225 fn get_typing_spans(&self, settings: &ApplicationSettings) -> Spans {
226226 let typers = self.get_typers();
227227 let n = typers.len();
228228
229229 match n {
230230 0 => Spans(vec![]),
231231 1 => {
232 let user = typers[0].as_str();
233 let user = Span::styled(user, user_style(user));
232 let user = settings.get_user_span(typers[0].as_ref());
234233
235234 Spans(vec![user, Span::from(" is typing...")])
236235 },
237236 2 => {
238 let user1 = typers[0].as_str();
239 let user1 = Span::styled(user1, user_style(user1));
240
241 let user2 = typers[1].as_str();
242 let user2 = Span::styled(user2, user_style(user2));
237 let user1 = settings.get_user_span(typers[0].as_ref());
238 let user2 = settings.get_user_span(typers[1].as_ref());
243239
244240 Spans(vec![
245241 user1,
@@ -274,7 +270,7 @@ impl RoomInfo {
274270 let top = Rect::new(area.x, area.y, area.width, area.height - 1);
275271 let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
276272
277 Paragraph::new(self.get_typing_spans())
273 Paragraph::new(self.get_typing_spans(settings))
278274 .alignment(Alignment::Center)
279275 .render(bar, buf);
280276
@@ -448,11 +444,14 @@ impl ApplicationInfo for IambInfo {
448444#[cfg(test)]
449445pub mod tests {
450446 use super::*;
447 use crate::config::{user_style, user_style_from_color};
451448 use crate::tests::*;
449 use modalkit::tui::style::Color;
452450
453451 #[test]
454452 fn test_typing_spans() {
455453 let mut info = RoomInfo::default();
454 let settings = mock_settings();
456455
457456 let users0 = vec![];
458457 let users1 = vec![TEST_USER1.clone()];
@@ -473,18 +472,18 @@ pub mod tests {
473472
474473 // Nothing set.
475474 assert_eq!(info.users_typing, None);
476 assert_eq!(info.get_typing_spans(), Spans(vec![]));
475 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
477476
478477 // Empty typing list.
479478 info.set_typing(users0);
480479 assert!(info.users_typing.is_some());
481 assert_eq!(info.get_typing_spans(), Spans(vec![]));
480 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
482481
483482 // Single user typing.
484483 info.set_typing(users1);
485484 assert!(info.users_typing.is_some());
486485 assert_eq!(
487 info.get_typing_spans(),
486 info.get_typing_spans(&settings),
488487 Spans(vec![
489488 Span::styled("@user1:example.com", user_style("@user1:example.com")),
490489 Span::from(" is typing...")
@@ -495,7 +494,7 @@ pub mod tests {
495494 info.set_typing(users2);
496495 assert!(info.users_typing.is_some());
497496 assert_eq!(
498 info.get_typing_spans(),
497 info.get_typing_spans(&settings),
499498 Spans(vec![
500499 Span::styled("@user1:example.com", user_style("@user1:example.com")),
501500 Span::raw(" and "),
@@ -507,11 +506,22 @@ pub mod tests {
507506 // Four users typing.
508507 info.set_typing(users4);
509508 assert!(info.users_typing.is_some());
510 assert_eq!(info.get_typing_spans(), Spans::from("Several people are typing..."));
509 assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
511510
512511 // Five users typing.
513512 info.set_typing(users5);
514513 assert!(info.users_typing.is_some());
515 assert_eq!(info.get_typing_spans(), Spans::from("Many people are typing..."));
514 assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
515
516 // Test that USER5 gets rendered using the configured color and name.
517 info.set_typing(vec![TEST_USER5.clone()]);
518 assert!(info.users_typing.is_some());
519 assert_eq!(
520 info.get_typing_spans(&settings),
521 Spans(vec![
522 Span::styled("USER 5", user_style_from_color(Color::Black)),
523 Span::from(" is typing...")
524 ])
525 );
516526 }
517527}
src/config.rs +207 −2
@@ -1,14 +1,22 @@
1use std::collections::hash_map::DefaultHasher;
12use std::collections::HashMap;
3use std::fmt;
24use std::fs::File;
5use std::hash::{Hash, Hasher};
36use std::io::BufReader;
47use std::path::{Path, PathBuf};
58use std::process;
69
710use clap::Parser;
8use matrix_sdk::ruma::OwnedUserId;
9use serde::Deserialize;
11use matrix_sdk::ruma::{OwnedUserId, UserId};
12use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
1013use url::Url;
1114
15use modalkit::tui::{
16 style::{Color, Modifier as StyleModifier, Style},
17 text::Span,
18};
19
1220macro_rules! usage {
1321 ( $($args: tt)* ) => {
1422 println!($($args)*);
@@ -16,6 +24,38 @@ macro_rules! usage {
1624 }
1725}
1826
27const COLORS: [Color; 13] = [
28 Color::Blue,
29 Color::Cyan,
30 Color::Green,
31 Color::LightBlue,
32 Color::LightGreen,
33 Color::LightCyan,
34 Color::LightMagenta,
35 Color::LightRed,
36 Color::LightYellow,
37 Color::Magenta,
38 Color::Red,
39 Color::Reset,
40 Color::Yellow,
41];
42
43pub fn user_color(user: &str) -> Color {
44 let mut hasher = DefaultHasher::new();
45 user.hash(&mut hasher);
46 let color = hasher.finish() as usize % COLORS.len();
47
48 COLORS[color]
49}
50
51pub fn user_style_from_color(color: Color) -> Style {
52 Style::default().fg(color).add_modifier(StyleModifier::BOLD)
53}
54
55pub fn user_style(user: &str) -> Style {
56 user_style_from_color(user_color(user))
57}
58
1959fn is_profile_char(c: char) -> bool {
2060 c.is_ascii_alphanumeric() || c == '.' || c == '-'
2161}
@@ -69,16 +109,88 @@ pub enum ConfigError {
69109 Invalid(#[from] serde_json::Error),
70110}
71111
112#[derive(Clone, Debug, Eq, PartialEq)]
113pub struct UserColor(pub Color);
114pub struct UserColorVisitor;
115
116impl<'de> Visitor<'de> for UserColorVisitor {
117 type Value = UserColor;
118
119 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
120 formatter.write_str("a valid color")
121 }
122
123 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
124 where
125 E: SerdeError,
126 {
127 match value {
128 "none" => Ok(UserColor(Color::Reset)),
129 "red" => Ok(UserColor(Color::Red)),
130 "black" => Ok(UserColor(Color::Black)),
131 "green" => Ok(UserColor(Color::Green)),
132 "yellow" => Ok(UserColor(Color::Yellow)),
133 "blue" => Ok(UserColor(Color::Blue)),
134 "magenta" => Ok(UserColor(Color::Magenta)),
135 "cyan" => Ok(UserColor(Color::Cyan)),
136 "gray" => Ok(UserColor(Color::Gray)),
137 "dark-gray" => Ok(UserColor(Color::DarkGray)),
138 "light-red" => Ok(UserColor(Color::LightRed)),
139 "light-green" => Ok(UserColor(Color::LightGreen)),
140 "light-yellow" => Ok(UserColor(Color::LightYellow)),
141 "light-blue" => Ok(UserColor(Color::LightBlue)),
142 "light-magenta" => Ok(UserColor(Color::LightMagenta)),
143 "light-cyan" => Ok(UserColor(Color::LightCyan)),
144 "white" => Ok(UserColor(Color::White)),
145 _ => Err(E::custom("Could not parse color")),
146 }
147 }
148}
149
150impl<'de> Deserialize<'de> for UserColor {
151 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
152 where
153 D: Deserializer<'de>,
154 {
155 deserializer.deserialize_str(UserColorVisitor)
156 }
157}
158
159#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
160pub struct UserDisplayTunables {
161 pub color: Option<UserColor>,
162 pub name: Option<String>,
163}
164
165pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
166
167fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
168 match (a, b) {
169 (Some(a), None) => Some(a),
170 (None, Some(b)) => Some(b),
171 (Some(mut a), Some(b)) => {
172 for (k, v) in b {
173 a.insert(k, v);
174 }
175
176 Some(a)
177 },
178 (None, None) => None,
179 }
180}
181
72182#[derive(Clone)]
73183pub struct TunableValues {
74184 pub typing_notice: bool,
75185 pub typing_notice_display: bool,
186 pub users: UserOverrides,
76187}
77188
78189#[derive(Clone, Default, Deserialize)]
79190pub struct Tunables {
80191 pub typing_notice: Option<bool>,
81192 pub typing_notice_display: Option<bool>,
193 pub users: Option<UserOverrides>,
82194}
83195
84196impl Tunables {
@@ -86,6 +198,7 @@ impl Tunables {
86198 Tunables {
87199 typing_notice: self.typing_notice.or(other.typing_notice),
88200 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
201 users: merge_users(self.users, other.users),
89202 }
90203 }
91204
@@ -93,6 +206,7 @@ impl Tunables {
93206 TunableValues {
94207 typing_notice: self.typing_notice.unwrap_or(true),
95208 typing_notice_display: self.typing_notice.unwrap_or(true),
209 users: self.users.unwrap_or_default(),
96210 }
97211 }
98212}
@@ -255,11 +369,32 @@ impl ApplicationSettings {
255369
256370 Ok(settings)
257371 }
372
373 pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
374 if let Some(user) = self.tunables.users.get(user_id) {
375 let color = if let Some(UserColor(c)) = user.color {
376 c
377 } else {
378 user_color(user_id.as_str())
379 };
380
381 let style = user_style_from_color(color);
382
383 if let Some(name) = &user.name {
384 Span::styled(name.clone(), style)
385 } else {
386 Span::styled(user_id.as_str(), style)
387 }
388 } else {
389 Span::styled(user_id.as_str(), user_style(user_id.as_str()))
390 }
391 }
258392}
259393
260394#[cfg(test)]
261395mod tests {
262396 use super::*;
397 use matrix_sdk::ruma::user_id;
263398
264399 #[test]
265400 fn test_profile_name_invalid() {
@@ -283,4 +418,74 @@ mod tests {
283418 assert_eq!(validate_profile_name("a.b-c"), true);
284419 assert_eq!(validate_profile_name("a.B-c"), true);
285420 }
421
422 #[test]
423 fn test_merge_users() {
424 let a = None;
425 let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
426 color: Some(UserColor(Color::Red)),
427 name: Some("Hello".into()),
428 })]
429 .into_iter()
430 .collect::<HashMap<_, _>>();
431 let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
432 color: Some(UserColor(Color::Green)),
433 name: Some("World".into()),
434 })]
435 .into_iter()
436 .collect::<HashMap<_, _>>();
437
438 let res = merge_users(a.clone(), a.clone());
439 assert_eq!(res, None);
440
441 let res = merge_users(a.clone(), Some(b.clone()));
442 assert_eq!(res, Some(b.clone()));
443
444 let res = merge_users(Some(b.clone()), a.clone());
445 assert_eq!(res, Some(b.clone()));
446
447 let res = merge_users(Some(b.clone()), Some(b.clone()));
448 assert_eq!(res, Some(b.clone()));
449
450 let res = merge_users(Some(b.clone()), Some(c.clone()));
451 assert_eq!(res, Some(c.clone()));
452
453 let res = merge_users(Some(c.clone()), Some(b.clone()));
454 assert_eq!(res, Some(b.clone()));
455 }
456
457 #[test]
458 fn test_parse_tunables() {
459 let res: Tunables = serde_json::from_str("{}").unwrap();
460 assert_eq!(res.typing_notice, None);
461 assert_eq!(res.typing_notice_display, None);
462 assert_eq!(res.users, None);
463
464 let res: Tunables = serde_json::from_str("{\"typing_notice\": true}").unwrap();
465 assert_eq!(res.typing_notice, Some(true));
466 assert_eq!(res.typing_notice_display, None);
467 assert_eq!(res.users, None);
468
469 let res: Tunables = serde_json::from_str("{\"typing_notice\": false}").unwrap();
470 assert_eq!(res.typing_notice, Some(false));
471 assert_eq!(res.typing_notice_display, None);
472 assert_eq!(res.users, None);
473
474 let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
475 assert_eq!(res.typing_notice, None);
476 assert_eq!(res.typing_notice_display, None);
477 assert_eq!(res.users, Some(HashMap::new()));
478
479 let res: Tunables = serde_json::from_str(
480 "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
481 )
482 .unwrap();
483 assert_eq!(res.typing_notice, None);
484 assert_eq!(res.typing_notice_display, None);
485 let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
486 color: Some(UserColor(Color::Black)),
487 name: Some("Tim".into()),
488 })];
489 assert_eq!(res.users, Some(users.into_iter().collect()));
490 }
286491}
src/message.rs +32 −39
@@ -22,35 +22,22 @@ use matrix_sdk::ruma::{
2222};
2323
2424use modalkit::tui::{
25 style::{Color, Modifier as StyleModifier, Style},
25 style::{Modifier as StyleModifier, Style},
2626 text::{Span, Spans, Text},
2727};
2828
2929use modalkit::editing::{base::ViewportContext, cursor::Cursor};
3030
31use crate::base::{IambResult, RoomInfo};
31use crate::{
32 base::{IambResult, RoomInfo},
33 config::ApplicationSettings,
34};
3235
3336pub type MessageEvent = MessageLikeEvent<RoomMessageEventContent>;
3437pub type MessageFetchResult = IambResult<(Option<String>, Vec<MessageEvent>)>;
3538pub type MessageKey = (MessageTimeStamp, OwnedEventId);
3639pub type Messages = BTreeMap<MessageKey, Message>;
3740
38const COLORS: [Color; 13] = [
39 Color::Blue,
40 Color::Cyan,
41 Color::Green,
42 Color::LightBlue,
43 Color::LightGreen,
44 Color::LightCyan,
45 Color::LightMagenta,
46 Color::LightRed,
47 Color::LightYellow,
48 Color::Magenta,
49 Color::Red,
50 Color::Reset,
51 Color::Yellow,
52];
53
5441const USER_GUTTER: usize = 30;
5542const TIME_GUTTER: usize = 12;
5643const MIN_MSG_LEN: usize = 30;
@@ -66,18 +53,6 @@ const USER_GUTTER_EMPTY_SPAN: Span<'static> = Span {
6653 },
6754};
6855
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
8156struct WrappedLinesIterator<'a> {
8257 iter: Lines<'a>,
8358 curr: Option<&'a str>,
@@ -390,7 +365,13 @@ impl Message {
390365 Message { content, sender, timestamp }
391366 }
392367
393 pub fn show(&self, selected: bool, vwctx: &ViewportContext<MessageCursor>) -> Text {
368 pub fn show(
369 &self,
370 prev: Option<&Message>,
371 selected: bool,
372 vwctx: &ViewportContext<MessageCursor>,
373 settings: &ApplicationSettings,
374 ) -> Text {
394375 let width = vwctx.get_width();
395376 let msg = self.as_ref();
396377
@@ -414,7 +395,7 @@ impl Message {
414395 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
415396
416397 if i == 0 {
417 let user = self.show_sender(true);
398 let user = self.show_sender(prev, true, settings);
418399
419400 if let Some(time) = self.timestamp.show() {
420401 lines.push(Spans(vec![user, line, trailing, time]))
@@ -435,7 +416,7 @@ impl Message {
435416 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
436417
437418 let prefix = if i == 0 {
438 self.show_sender(true)
419 self.show_sender(prev, true, settings)
439420 } else {
440421 USER_GUTTER_EMPTY_SPAN
441422 };
@@ -443,7 +424,7 @@ impl Message {
443424 lines.push(Spans(vec![prefix, line, trailing]))
444425 }
445426 } else {
446 lines.push(Spans::from(self.show_sender(false)));
427 lines.push(Spans::from(self.show_sender(prev, false, settings)));
447428
448429 for (line, _) in wrap(msg, width.saturating_sub(2)) {
449430 let line = format!(" {}", line);
@@ -456,14 +437,26 @@ impl Message {
456437 return Text { lines };
457438 }
458439
459 fn show_sender(&self, align_right: bool) -> Span {
460 let sender = self.sender.to_string();
461 let style = user_style(sender.as_str());
440 fn show_sender(
441 &self,
442 prev: Option<&Message>,
443 align_right: bool,
444 settings: &ApplicationSettings,
445 ) -> Span {
446 let user = if matches!(prev, Some(prev) if self.sender == prev.sender) {
447 USER_GUTTER_EMPTY_SPAN
448 } else {
449 settings.get_user_span(self.sender.as_ref())
450 };
451
452 let Span { content, style } = user;
453 let stop = content.len().min(28);
454 let s = &content[..stop];
462455
463456 let sender = if align_right {
464 format!("{: >width$} ", sender, width = 28)
457 format!("{: >width$} ", s, width = 28)
465458 } else {
466 format!("{: <width$} ", sender, width = 28)
459 format!("{: <width$} ", s, width = 28)
467460 };
468461
469462 Span::styled(sender, style)
src/tests.rs +30 −10
@@ -1,4 +1,6 @@
1use std::collections::BTreeMap;
1use std::collections::{BTreeMap, HashMap};
2use std::path::PathBuf;
3use std::sync::mpsc::sync_channel;
24
35use matrix_sdk::ruma::{
46 event_id,
@@ -12,15 +14,20 @@ use matrix_sdk::ruma::{
1214 UInt,
1315};
1416
15use std::path::PathBuf;
16use std::sync::mpsc::sync_channel;
17use url::Url;
18
1917use lazy_static::lazy_static;
18use modalkit::tui::style::Color;
19use url::Url;
2020
2121use crate::{
2222 base::{ChatStore, ProgramStore, RoomFetchStatus, RoomInfo},
23 config::{ApplicationSettings, DirectoryValues, ProfileConfig, TunableValues},
23 config::{
24 ApplicationSettings,
25 DirectoryValues,
26 ProfileConfig,
27 TunableValues,
28 UserColor,
29 UserDisplayTunables,
30 },
2431 message::{
2532 Message,
2633 MessageContent,
@@ -35,9 +42,9 @@ lazy_static! {
3542 pub static ref TEST_ROOM1_ID: OwnedRoomId = RoomId::new(server_name!("example.com")).to_owned();
3643 pub static ref TEST_USER1: OwnedUserId = user_id!("@user1:example.com").to_owned();
3744 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();
45 pub static ref TEST_USER3: OwnedUserId = user_id!("@user3:example.com").to_owned();
46 pub static ref TEST_USER4: OwnedUserId = user_id!("@user4:example.com").to_owned();
47 pub static ref TEST_USER5: OwnedUserId = user_id!("@user5:example.com").to_owned();
4148 pub static ref MSG1_KEY: MessageKey = (LocalEcho, EventId::new(server_name!("example.com")));
4249 pub static ref MSG2_KEY: MessageKey =
4350 (OriginServer(UInt::new(1).unwrap()), EventId::new(server_name!("example.com")));
@@ -118,6 +125,19 @@ pub fn mock_dirs() -> DirectoryValues {
118125 }
119126}
120127
128pub fn mock_tunables() -> TunableValues {
129 TunableValues {
130 typing_notice: true,
131 typing_notice_display: true,
132 users: vec![(TEST_USER5.clone(), UserDisplayTunables {
133 color: Some(UserColor(Color::Black)),
134 name: Some("USER 5".into()),
135 })]
136 .into_iter()
137 .collect::<HashMap<_, _>>(),
138 }
139}
140
121141pub fn mock_settings() -> ApplicationSettings {
122142 ApplicationSettings {
123143 matrix_dir: PathBuf::new(),
@@ -129,7 +149,7 @@ pub fn mock_settings() -> ApplicationSettings {
129149 settings: None,
130150 dirs: None,
131151 },
132 tunables: TunableValues { typing_notice: true, typing_notice_display: true },
152 tunables: mock_tunables(),
133153 dirs: mock_dirs(),
134154 }
135155}
src/windows/mod.rs +18 −18
@@ -51,19 +51,16 @@ use modalkit::{
5151 },
5252};
5353
54use crate::{
55 base::{
56 ChatStore,
57 IambBufferId,
58 IambId,
59 IambInfo,
60 IambResult,
61 ProgramAction,
62 ProgramContext,
63 ProgramStore,
64 RoomAction,
65 },
66 message::user_style,
54use crate::base::{
55 ChatStore,
56 IambBufferId,
57 IambId,
58 IambInfo,
59 IambResult,
60 ProgramAction,
61 ProgramContext,
62 ProgramStore,
63 RoomAction,
6764};
6865
6966use self::{room::RoomState, welcome::WelcomeState};
@@ -845,15 +842,18 @@ impl ToString for MemberItem {
845842}
846843
847844impl ListItem<IambInfo> for MemberItem {
848 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
849 let mut style = user_style(self.member.user_id().as_str());
845 fn show(
846 &self,
847 selected: bool,
848 _: &ViewportContext<ListCursor>,
849 store: &mut ProgramStore,
850 ) -> Text {
851 let mut user = store.application.settings.get_user_span(self.member.user_id());
850852
851853 if selected {
852 style = style.add_modifier(StyleModifier::REVERSED);
854 user.style = user.style.add_modifier(StyleModifier::REVERSED);
853855 }
854856
855 let user = Span::styled(self.to_string(), style);
856
857857 let state = match self.member.membership() {
858858 MembershipState::Ban => Span::raw(" (banned)").into(),
859859 MembershipState::Invite => Span::raw(" (invited)").into(),
src/windows/room/scrollback.rs +25 −12
@@ -61,6 +61,7 @@ use modalkit::editing::{
6161
6262use crate::{
6363 base::{IambBufferId, IambInfo, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
64 config::ApplicationSettings,
6465 message::{Message, MessageCursor, MessageKey},
6566};
6667
@@ -148,7 +149,13 @@ impl ScrollbackState {
148149 }
149150 }
150151
151 fn scrollview(&mut self, idx: MessageKey, pos: MovePosition, info: &RoomInfo) {
152 fn scrollview(
153 &mut self,
154 idx: MessageKey,
155 pos: MovePosition,
156 info: &RoomInfo,
157 settings: &ApplicationSettings,
158 ) {
152159 let selidx = if let Some(key) = self.cursor.to_key(info) {
153160 key
154161 } else {
@@ -165,7 +172,7 @@ impl ScrollbackState {
165172
166173 for (key, item) in info.messages.range(..=&idx).rev() {
167174 let sel = selidx == key;
168 let len = item.show(sel, &self.viewctx).lines.len();
175 let len = item.show(None, sel, &self.viewctx, settings).lines.len();
169176
170177 if key == &idx {
171178 lines += len / 2;
@@ -187,7 +194,7 @@ impl ScrollbackState {
187194
188195 for (key, item) in info.messages.range(..=&idx).rev() {
189196 let sel = key == selidx;
190 let len = item.show(sel, &self.viewctx).lines.len();
197 let len = item.show(None, sel, &self.viewctx, settings).lines.len();
191198
192199 lines += len;
193200
@@ -202,7 +209,7 @@ impl ScrollbackState {
202209 }
203210 }
204211
205 fn shift_cursor(&mut self, info: &RoomInfo) {
212 fn shift_cursor(&mut self, info: &RoomInfo, settings: &ApplicationSettings) {
206213 let last_key = if let Some(k) = info.messages.last_key_value() {
207214 k.0
208215 } else {
@@ -227,7 +234,7 @@ impl ScrollbackState {
227234 break;
228235 }
229236
230 lines += item.show(false, &self.viewctx).height().max(1);
237 lines += item.show(None, false, &self.viewctx, settings).height().max(1);
231238
232239 if lines >= self.viewctx.get_height() {
233240 // We've reached the end of the viewport; move cursor into it.
@@ -930,7 +937,8 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
930937 ctx: &ProgramContext,
931938 store: &mut ProgramStore,
932939 ) -> EditResult<EditInfo, IambInfo> {
933 let info = store.application.get_room_info(self.room_id.clone());
940 let info = store.application.rooms.entry(self.room_id.clone()).or_default();
941 let settings = &store.application.settings;
934942 let mut corner = self.viewctx.corner.clone();
935943
936944 let last_key = if let Some(k) = info.messages.last_key_value() {
@@ -956,7 +964,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
956964
957965 for (key, item) in info.messages.range(..=&corner_key).rev() {
958966 let sel = key == cursor_key;
959 let txt = item.show(sel, &self.viewctx);
967 let txt = item.show(None, sel, &self.viewctx, settings);
960968 let len = txt.height().max(1);
961969 let max = len.saturating_sub(1);
962970
@@ -982,7 +990,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
982990 MoveDir2D::Down => {
983991 for (key, item) in info.messages.range(&corner_key..) {
984992 let sel = key == cursor_key;
985 let txt = item.show(sel, &self.viewctx);
993 let txt = item.show(None, sel, &self.viewctx, settings);
986994 let len = txt.height().max(1);
987995 let max = len.saturating_sub(1);
988996
@@ -1018,7 +1026,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
10181026 }
10191027
10201028 self.viewctx.corner = corner;
1021 self.shift_cursor(info);
1029 self.shift_cursor(info, settings);
10221030
10231031 Ok(None)
10241032 }
@@ -1038,10 +1046,11 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
10381046 Err(err)
10391047 },
10401048 Axis::Vertical => {
1041 let info = store.application.get_room_info(self.room_id.clone());
1049 let info = store.application.rooms.entry(self.room_id.clone()).or_default();
1050 let settings = &store.application.settings;
10421051
10431052 if let Some(key) = self.cursor.to_key(info).cloned() {
1044 self.scrollview(key, pos, info);
1053 self.scrollview(key, pos, info, settings);
10451054 }
10461055
10471056 Ok(None)
@@ -1126,6 +1135,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
11261135
11271136 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
11281137 let info = self.store.application.rooms.entry(state.room_id.clone()).or_default();
1138 let settings = &self.store.application.settings;
11291139 let area = info.render_typing(area, buf, &self.store.application.settings);
11301140
11311141 state.set_term_info(area);
@@ -1157,10 +1167,13 @@ impl<'a> StatefulWidget for Scrollback<'a> {
11571167
11581168 let mut lines = vec![];
11591169 let mut sawit = false;
1170 let mut prev = None;
11601171
11611172 for (key, item) in info.messages.range(&corner_key..) {
11621173 let sel = key == cursor_key;
1163 let txt = item.show(self.focused && sel, &state.viewctx);
1174 let txt = item.show(prev, self.focused && sel, &state.viewctx, settings);
1175
1176 prev = Some(item);
11641177
11651178 for (row, line) in txt.lines.into_iter().enumerate() {
11661179 if sawit && lines.len() >= height {