Commit cda6bf1180

cda6bf11807680d0a6799f398ad70d97ace0b2f9

parent: c39ac5d9d4

Unregistered key

Ulyssa <git@ulyssa.dev> · 2026-08-16 05:22 UTC
committer: <noreply@github.com>

Update to use Rust 2024 Edition (#642)

Layout: unified · split

Cargo.toml +1 −1
@@ -1,7 +1,7 @@
11[package]
22name = "iamb"
33version = "0.0.11"
4edition = "2018"
4edition = "2024"
55authors = ["Ulyssa <git@ulyssa.dev>"]
66repository = "https://github.com/ulyssa/iamb"
77homepage = "https://iamb.chat"
src/base.rs +28 −27
@@ -13,10 +13,10 @@ use std::time::{Duration, Instant};
1313
1414use emojis::Emoji;
1515
16use matrix_sdk::ruma::OwnedTransactionId;
1617use matrix_sdk::ruma::events::receipt::ReceiptThread;
1718use matrix_sdk::ruma::events::room::MediaSource;
1819use matrix_sdk::ruma::events::sticker::StickerEvent;
19use matrix_sdk::ruma::OwnedTransactionId;
2020use ratatui::{
2121 buffer::Buffer,
2222 layout::{Alignment, Rect},
@@ -25,21 +25,30 @@ use ratatui::{
2525};
2626use ratatui_image::picker::{Picker, ProtocolType};
2727use serde::{
28 de::Error as SerdeError,
29 de::Visitor,
3028 Deserialize,
3129 Deserializer,
3230 Serialize,
3331 Serializer,
32 de::Error as SerdeError,
33 de::Visitor,
3434};
3535use tokio::sync::Mutex as AsyncMutex;
3636use url::Url;
3737
3838use matrix_sdk::{
39 RoomState as MatrixRoomState,
3940 encryption::verification::SasVerification,
4041 room::Room as MatrixRoom,
4142 ruma::{
43 EventId,
44 OwnedEventId,
45 OwnedRoomId,
46 OwnedUserId,
47 RoomId,
48 UserId,
4249 events::{
50 AnySyncStateEvent,
51 MessageLikeEvent,
4352 reaction::ReactionEvent,
4453 relation::{Replacement, Thread},
4554 room::encrypted::RoomEncryptedEvent,
@@ -52,18 +61,9 @@ use matrix_sdk::{
5261 },
5362 room::redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
5463 tag::{TagName, Tags},
55 AnySyncStateEvent,
56 MessageLikeEvent,
5764 },
5865 presence::PresenceState,
59 EventId,
60 OwnedEventId,
61 OwnedRoomId,
62 OwnedUserId,
63 RoomId,
64 UserId,
6566 },
66 RoomState as MatrixRoomState,
6767};
6868
6969use modalkit::{
@@ -77,7 +77,7 @@ use modalkit::{
7777 ApplicationStore,
7878 ApplicationWindowId,
7979 },
80 completion::{complete_path, Completer, CompletionMap},
80 completion::{Completer, CompletionMap, complete_path},
8181 context::EditContext,
8282 cursor::Cursor,
8383 rope::EditRope,
@@ -97,7 +97,7 @@ use crate::{
9797 config::{ApplicationSettings, ImagePreviewProtocolValues},
9898 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
9999 notifications::NotificationHandle,
100 preview::{source_from_event, PreviewManager},
100 preview::{PreviewManager, source_from_event},
101101 worker::Requester,
102102};
103103
@@ -1175,11 +1175,11 @@ impl RoomInfo {
11751175 }
11761176 },
11771177 Some(EventLocation::Message(Some(root), key)) => {
1178 if let Some(thread) = self.threads.get_mut(root) {
1179 if let Some(msg) = thread.get_mut(key) {
1180 let ev = SyncRoomRedactionEvent::Original(ev);
1181 msg.redact(ev);
1182 }
1178 if let Some(thread) = self.threads.get_mut(root) &&
1179 let Some(msg) = thread.get_mut(key)
1180 {
1181 let ev = SyncRoomRedactionEvent::Original(ev);
1182 msg.redact(ev);
11831183 }
11841184 },
11851185 Some(EventLocation::Reaction(event_id)) => {
@@ -1403,13 +1403,12 @@ impl RoomInfo {
14031403 let source = source_from_event(&ev);
14041404 self.insert(ev);
14051405
1406 if let Some((event_id, source)) = source {
1407 if let (Some(msg), Some(image_preview)) =
1406 if let Some((event_id, source)) = source &&
1407 let (Some(msg), Some(image_preview)) =
14081408 (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1409 {
1410 msg.image_preview = Some(source.clone());
1411 previews.register_preview(settings, source, image_preview.size, worker)
1412 }
1409 {
1410 msg.image_preview = Some(source.clone());
1411 previews.register_preview(settings, source, image_preview.size, worker)
14131412 }
14141413 }
14151414
@@ -1622,7 +1621,9 @@ fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
16221621/// Windows cannot guess the right protocol, and always needs type and font_size.
16231622#[cfg(windows)]
16241623fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1625 tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1624 tracing::error!(
1625 "\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows."
1626 );
16261627 None
16271628}
16281629
@@ -2360,9 +2361,9 @@ pub mod tests {
23602361 use crate::config::user_style_from_color;
23612362 use crate::tests::*;
23622363 use matrix_sdk::ruma::{
2364 MilliSecondsSinceUnixEpoch,
23632365 events::{reaction::ReactionEventContent, relation::Annotation},
23642366 owned_event_id,
2365 MilliSecondsSinceUnixEpoch,
23662367 };
23672368 use pretty_assertions::assert_eq;
23682369 use ratatui::style::Color;
src/commands.rs +4 −4
@@ -4,7 +4,7 @@
44//! [modalkit::env::vim::command] for additional Vim commands we pull in.
55use std::{convert::TryFrom, str::FromStr as _};
66
7use matrix_sdk::ruma::{events::tag::TagName, OwnedRoomId, OwnedUserId};
7use matrix_sdk::ruma::{OwnedRoomId, OwnedUserId, events::tag::TagName};
88
99use modalkit::{
1010 commands::{CommandError, CommandResult, CommandStep},
@@ -550,7 +550,7 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
550550 RoomAction::Show(RoomField::CanonicalAlias).into()
551551 },
552552 ("canonicalalias" | "canon", "show", Some(_)) => {
553 return Result::Err(CommandError::InvalidArgument)
553 return Result::Err(CommandError::InvalidArgument);
554554 },
555555
556556 // :room canonicalalias set
@@ -558,7 +558,7 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
558558 RoomAction::Set(RoomField::CanonicalAlias, s).into()
559559 },
560560 ("canonicalalias" | "canon", "set", None) => {
561 return Result::Err(CommandError::InvalidArgument)
561 return Result::Err(CommandError::InvalidArgument);
562562 },
563563
564564 // :room canonicalalias unset
@@ -566,7 +566,7 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
566566 RoomAction::Unset(RoomField::CanonicalAlias).into()
567567 },
568568 ("canonicalalias" | "canon", "unset", Some(_)) => {
569 return Result::Err(CommandError::InvalidArgument)
569 return Result::Err(CommandError::InvalidArgument);
570570 },
571571
572572 // :room id show
src/config.rs +40 −32
@@ -12,14 +12,14 @@ use std::process;
1212use std::str::FromStr;
1313
1414use clap::Parser;
15use matrix_sdk::EncryptionState;
1516use matrix_sdk::authentication::matrix::MatrixSession;
1617use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
1718use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
18use matrix_sdk::EncryptionState;
1919use ratatui::style::{Color, Modifier as StyleModifier, Style};
2020use ratatui::text::Span;
2121use ratatui_image::picker::ProtocolType;
22use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer, Serialize};
22use serde::{Deserialize, Deserializer, Serialize, de::Error as SerdeError, de::Visitor};
2323use url::Url;
2424
2525use modalkit::{env::vim::VimMode, key::TerminalKey, keybindings::InputKey};
@@ -428,7 +428,7 @@ impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
428428 "title" => location |= EncryptionIndicatorLocation::TITLE,
429429 "prompt" => location |= EncryptionIndicatorLocation::PROMPT,
430430 _ => {
431 return Err(E::custom("could not parse into an encryption indicator location"))
431 return Err(E::custom("could not parse into an encryption indicator location"));
432432 },
433433 };
434434 }
@@ -511,7 +511,7 @@ impl Visitor<'_> for NotifyViaVisitor {
511511 },
512512 #[cfg(not(feature = "desktop"))]
513513 "desktop" => {
514 return Err(E::custom("desktop notification support was compiled out"))
514 return Err(E::custom("desktop notification support was compiled out"));
515515 },
516516 _ => return Err(E::custom("could not parse into a notify destination")),
517517 };
@@ -1231,10 +1231,10 @@ impl ApplicationSettings {
12311231 For more information try '--help'",
12321232 );
12331233 }
1234 if let Ok(i) = input.trim().parse::<usize>() {
1235 if i < profiles.len() {
1236 break profiles.into_iter().nth(i).unwrap();
1237 }
1234 if let Ok(i) = input.trim().parse::<usize>() &&
1235 i < profiles.len()
1236 {
1237 break profiles.into_iter().nth(i).unwrap();
12381238 }
12391239 println!("\nInvalid index.");
12401240 }
@@ -1749,16 +1749,18 @@ mod tests {
17491749
17501750 // Always shows in the title:
17511751 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
1752 assert!(enc
1753 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1754 .is_some());
1752 assert!(
1753 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1754 .is_some()
1755 );
17551756 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
17561757
17571758 // Doesn't show in the prompt:
17581759 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1759 assert!(enc
1760 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1761 .is_none());
1760 assert!(
1761 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1762 .is_none()
1763 );
17621764 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
17631765 }
17641766
@@ -1773,14 +1775,16 @@ mod tests {
17731775
17741776 // Never shows in the title or the prompt:
17751777 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1776 assert!(enc
1777 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1778 .is_none());
1778 assert!(
1779 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1780 .is_none()
1781 );
17791782 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
17801783 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1781 assert!(enc
1782 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1783 .is_none());
1784 assert!(
1785 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1786 .is_none()
1787 );
17841788 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
17851789 }
17861790
@@ -1798,15 +1802,17 @@ mod tests {
17981802 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
17991803
18001804 // But is hidden when unencrypted:
1801 assert!(enc
1802 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1803 .is_none());
1805 assert!(
1806 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1807 .is_none()
1808 );
18041809
18051810 // Doesn't show in the title:
18061811 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1807 assert!(enc
1808 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1809 .is_none());
1812 assert!(
1813 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1814 .is_none()
1815 );
18101816 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
18111817 }
18121818 #[test]
@@ -1819,13 +1825,15 @@ mod tests {
18191825 };
18201826
18211827 // Shows in both the prompt and title when unencrypted or unknown:
1822 assert!(enc
1823 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1824 .is_some());
1828 assert!(
1829 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1830 .is_some()
1831 );
18251832 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1826 assert!(enc
1827 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1828 .is_some());
1833 assert!(
1834 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1835 .is_some()
1836 );
18291837 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
18301838
18311839 // But is hidden when encrypted:
src/keybindings.rs +14 −15
@@ -4,9 +4,9 @@
44//! keys come from [modalkit::env::vim::keybindings].
55use modalkit::{
66 actions::{InsertTextAction, MacroAction, WindowAction},
7 env::vim::keybindings::{InputStep, VimBindings},
8 env::vim::VimMode,
97 env::CommonKeyClass,
8 env::vim::VimMode,
9 env::vim::keybindings::{InputStep, VimBindings},
1010 key::TerminalKey,
1111 keybindings::{EdgeEvent, EdgeRepeat, InputBindings},
1212 prelude::*,
@@ -60,12 +60,9 @@ pub fn setup_keybindings() -> Keybindings {
6060 ism.add_mapping(VimMode::Visual, &cwcm, &stoggle);
6161
6262 let shift_enter = vec![once(&shift_enter)];
63 let newline = IambStep::new().actions(vec![InsertTextAction::Type(
64 Char::Single('\n').into(),
65 MoveDir1D::Previous,
66 1.into(),
67 )
68 .into()]);
63 let newline = IambStep::new().actions(vec![
64 InsertTextAction::Type(Char::Single('\n').into(), MoveDir1D::Previous, 1.into()).into(),
65 ]);
6966 ism.add_mapping(VimMode::Insert, &cwm, &newline);
7067 ism.add_mapping(VimMode::Insert, &shift_enter, &newline);
7168
@@ -92,13 +89,15 @@ impl InputBindings<TerminalKey, IambStep> for ApplicationSettings {
9289 let ctrl_f = "<C-F>".parse::<TerminalKey>().unwrap();
9390
9491 let vsplit_open = IambStep::new()
95 .actions(vec![WindowAction::Split(
96 OpenTarget::Cursor(MATRIX_ID_WORD.clone()),
97 Axis::Vertical,
98 MoveDir1D::Next,
99 1.into(),
100 )
101 .into()])
92 .actions(vec![
93 WindowAction::Split(
94 OpenTarget::Cursor(MATRIX_ID_WORD.clone()),
95 Axis::Vertical,
96 MoveDir1D::Next,
97 1.into(),
98 )
99 .into(),
100 ])
102101 .goto(VimMode::Normal);
103102
104103 let cwf = vec![once(&ctrl_w), once(&key_f)];
src/main.rs +17 −14
@@ -19,21 +19,21 @@
1919use std::collections::VecDeque;
2020use std::convert::TryFrom;
2121use std::fmt::Display;
22use std::fs::{create_dir_all, File};
23use std::io::{stdout, BufWriter, Stdout, Write};
22use std::fs::{File, create_dir_all};
23use std::io::{BufWriter, Stdout, Write, stdout};
2424use std::ops::DerefMut;
2525use std::process;
26use std::sync::atomic::{AtomicUsize, Ordering};
2726use std::sync::Arc;
27use std::sync::atomic::{AtomicUsize, Ordering};
2828use std::time::{Duration, Instant};
2929
3030use clap::{CommandFactory, Parser};
31use matrix_sdk::ruma::api::error::ErrorKind;
3231use matrix_sdk::ruma::OwnedUserId;
32use matrix_sdk::ruma::api::error::ErrorKind;
3333use matrix_sdk_crypto::encrypt_room_key_export;
3434use modalkit::keybindings::InputBindings;
35use rand::distr::Alphanumeric;
3635use rand::RngExt as _;
36use rand::distr::Alphanumeric;
3737use temp_dir::TempDir;
3838use tokio::sync::Mutex as AsyncMutex;
3939use tracing::Level;
@@ -43,8 +43,6 @@ use modalkit::crossterm::{
4343 self,
4444 cursor::{SetCursorStyle, Show as CursorShow},
4545 event::{
46 poll,
47 read,
4846 DisableBracketedPaste,
4947 DisableFocusChange,
5048 DisableMouseCapture,
@@ -57,18 +55,20 @@ use modalkit::crossterm::{
5755 MouseEventKind,
5856 PopKeyboardEnhancementFlags,
5957 PushKeyboardEnhancementFlags,
58 poll,
59 read,
6060 },
6161 execute,
6262 terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
6363};
6464
6565use ratatui::{
66 Terminal,
6667 backend::CrosstermBackend,
6768 layout::Rect,
6869 style::{Color, Modifier, Style},
6970 text::Span,
7071 widgets::Paragraph,
71 Terminal,
7272};
7373
7474mod base;
@@ -104,7 +104,7 @@ use crate::{
104104 },
105105 config::{ApplicationSettings, Iamb},
106106 windows::IambWindow,
107 worker::{create_room, ClientWorker, LoginStyle, Requester},
107 worker::{ClientWorker, LoginStyle, Requester, create_room},
108108};
109109
110110use modalkit::{
@@ -127,20 +127,20 @@ use modalkit::{
127127 errors::{EditError, UIError},
128128 key::TerminalKey,
129129 keybindings::{
130 dialog::{Pager, PromptYesNo},
131130 BindingMachine,
131 dialog::{Pager, PromptYesNo},
132132 },
133133 prelude::*,
134134 ui::FocusList,
135135};
136136
137137use modalkit_ratatui::{
138 cmdbar::CommandBarState,
139 screen::{Screen, ScreenState, TabbedLayoutDescription},
140 windows::{WindowLayoutDescription, WindowLayoutState},
141138 TerminalCursor,
142139 TerminalExtOps,
143140 Window,
141 cmdbar::CommandBarState,
142 screen::{Screen, ScreenState, TabbedLayoutDescription},
143 windows::{WindowLayoutDescription, WindowLayoutState},
144144};
145145
146146fn config_tab_to_desc(
@@ -1059,7 +1059,10 @@ async fn run(settings: ApplicationSettings) -> IambResult<()> {
10591059 match res {
10601060 Err(UIError::Application(IambError::Matrix(e))) => {
10611061 if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
1062 print_exit(format!("Server did not recognize our API token; did you log out from this session elsewhere?\nTry deleting `{}` to force a clean login.", settings.session_json.display()))
1062 print_exit(format!(
1063 "Server did not recognize our API token; did you log out from this session elsewhere?\nTry deleting `{}` to force a clean login.",
1064 settings.session_json.display()
1065 ))
10631066 } else {
10641067 print_exit(e)
10651068 }
src/message/compose.rs +2 −2
@@ -1,12 +1,12 @@
11//! Code for converting composed messages into content to send to the homeserver.
22use comrak::{markdown_to_html, options::Options};
33use nom::{
4 IResult,
5 Parser as _,
46 branch::alt,
57 bytes::complete::tag,
68 character::complete::space0,
79 combinator::value,
8 IResult,
9 Parser as _,
1010};
1111
1212use matrix_sdk::ruma::events::room::message::{
src/message/html.rs +1 −1
@@ -20,7 +20,7 @@ use unicode_segmentation::UnicodeSegmentation;
2020use url::Url;
2121
2222use html5ever::{
23 driver::{parse_fragment, ParseOpts},
23 driver::{ParseOpts, parse_fragment},
2424 interface::{Attribute, QualName},
2525 local_name,
2626 ns,
src/message/mod.rs +26 −28
@@ -1,25 +1,32 @@
11//! # Room Messages
22use std::borrow::Cow;
33use std::cmp::{Ord, Ordering, PartialOrd};
4use std::collections::hash_map::DefaultHasher;
54use std::collections::BTreeMap;
5use std::collections::hash_map::DefaultHasher;
66use std::convert::{TryFrom, TryInto};
77use std::fmt::{self, Display};
88use std::hash::{Hash, Hasher};
99use std::ops::{Deref, DerefMut};
1010
1111use chrono::{DateTime, Local as LocalTz};
12use humansize::{format_size, DECIMAL};
12use humansize::{DECIMAL, format_size};
13use matrix_sdk::ruma::OwnedTransactionId;
1314use matrix_sdk::ruma::events::receipt::ReceiptThread;
1415use matrix_sdk::ruma::events::room::MediaSource;
1516use matrix_sdk::ruma::events::sticker::StickerEvent;
1617use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent};
17use matrix_sdk::ruma::OwnedTransactionId;
1818use matrix_sdk::send_queue::SendHandle;
1919use unicode_width::UnicodeWidthStr;
2020
2121use matrix_sdk::ruma::{
22 EventId,
23 MilliSecondsSinceUnixEpoch,
24 OwnedEventId,
25 OwnedUserId,
26 UInt,
2227 events::{
28 AnySyncStateEvent,
29 RedactedUnsigned,
2330 relation::Thread,
2431 room::{
2532 encrypted::{
@@ -39,14 +46,7 @@ use matrix_sdk::ruma::{
3946 },
4047 redaction::SyncRoomRedactionEvent,
4148 },
42 AnySyncStateEvent,
43 RedactedUnsigned,
4449 },
45 EventId,
46 MilliSecondsSinceUnixEpoch,
47 OwnedEventId,
48 OwnedUserId,
49 UInt,
5050};
5151
5252use ratatui::{
@@ -64,7 +64,7 @@ use crate::preview::{ImageStatus, PreviewManager};
6464use crate::{
6565 base::RoomInfo,
6666 config::ApplicationSettings,
67 message::html::{parse_matrix_html, StyleTree},
67 message::html::{StyleTree, parse_matrix_html},
6868 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
6969};
7070
@@ -188,13 +188,12 @@ fn placeholder_frame(
188188 placeholder.push('\u{230d}');
189189 placeholder.push_str(&"\n".repeat((height - 1) / 2));
190190
191 if *height > 2 {
192 if let Some(text) = text {
193 if text.width() <= width - 2 {
194 placeholder.push(' ');
195 placeholder.push_str(text);
196 }
197 }
191 if *height > 2 &&
192 let Some(text) = text &&
193 text.width() <= width - 2
194 {
195 placeholder.push(' ');
196 placeholder.push_str(text);
198197 }
199198
200199 placeholder.push_str(&"\n".repeat(height / 2));
@@ -239,7 +238,7 @@ pub struct MessageTimeStamp(pub MilliSecondsSinceUnixEpoch);
239238
240239impl MessageTimeStamp {
241240 fn as_datetime(self) -> DateTime<LocalTz> {
242 let time = i64::from(self.0 .0) / 1000;
241 let time = i64::from(self.0.0) / 1000;
243242 let time = DateTime::from_timestamp(time, 0).unwrap_or_default();
244243 time.into()
245244 }
@@ -275,7 +274,7 @@ impl TryFrom<&MessageTimeStamp> for usize {
275274 type Error = TimeStampIntError;
276275
277276 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
278 let n = usize::try_from(u64::from(ts.0 .0))?;
277 let n = usize::try_from(u64::from(ts.0.0))?;
279278
280279 Ok(n)
281280 }
@@ -1154,13 +1153,12 @@ impl Message {
11541153 settings: &'a ApplicationSettings,
11551154 width: usize,
11561155 ) -> SenderSpan<'a> {
1157 if let Some(prev) = prev {
1158 if self.sender == prev.sender &&
1159 self.timestamp.same_day(prev.timestamp) &&
1160 !self.event.is_emote()
1161 {
1162 return SenderSpan::None;
1163 }
1156 if let Some(prev) = prev &&
1157 self.sender == prev.sender &&
1158 self.timestamp.same_day(prev.timestamp) &&
1159 !self.event.is_emote()
1160 {
1161 return SenderSpan::None;
11641162 }
11651163
11661164 let Span { content, style } = self.sender_span(info, settings);
@@ -1266,6 +1264,7 @@ impl Display for Message {
12661264#[cfg(test)]
12671265pub mod tests {
12681266 use matrix_sdk::ruma::events::room::{
1267 ImageInfo,
12691268 message::{
12701269 AudioInfo,
12711270 AudioMessageEventContent,
@@ -1275,7 +1274,6 @@ pub mod tests {
12751274 VideoInfo,
12761275 VideoMessageEventContent,
12771276 },
1278 ImageInfo,
12791277 };
12801278
12811279 use super::*;
src/message/state.rs +3 −3
@@ -3,14 +3,14 @@ use std::borrow::Cow;
33use std::str::FromStr;
44
55use matrix_sdk::ruma::{
6 OwnedRoomId,
7 UserId,
68 events::{
7 room::member::MembershipChange,
89 AnyStateEventContentChange,
910 AnySyncStateEvent,
1011 StateEventContentChange,
12 room::member::MembershipChange,
1113 },
12 OwnedRoomId,
13 UserId,
1414};
1515
1616use super::html::{StyleTree, StyleTreeNode};
src/notifications.rs +12 −12
@@ -1,18 +1,18 @@
11use std::time::SystemTime;
22
33use matrix_sdk::{
4 Client,
5 EncryptionState,
46 deserialized_responses::RawAnySyncOrStrippedTimelineEvent,
57 notification_settings::{IsEncrypted, IsOneToOne, NotificationSettings, RoomNotificationMode},
68 room::Room as MatrixRoom,
79 ruma::{
8 events::{room::message::MessageType, AnyMessageLikeEventContent, AnySyncTimelineEvent},
9 serde::Raw,
1010 MilliSecondsSinceUnixEpoch,
1111 OwnedRoomId,
1212 RoomId,
13 events::{AnyMessageLikeEventContent, AnySyncTimelineEvent, room::message::MessageType},
14 serde::Raw,
1315 },
14 Client,
15 EncryptionState,
1616};
1717use unicode_segmentation::UnicodeSegmentation;
1818
@@ -208,14 +208,14 @@ async fn global_or_room_mode(
208208}
209209
210210fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
211 if let Some(body) = body {
212 if mode == RoomNotificationMode::MentionsAndKeywordsOnly {
213 let mentioned = match client.user_id() {
214 Some(user_id) => body.contains(user_id.localpart()),
215 _ => false,
216 };
217 return !mentioned;
218 }
211 if let Some(body) = body &&
212 mode == RoomNotificationMode::MentionsAndKeywordsOnly
213 {
214 let mentioned = match client.user_id() {
215 Some(user_id) => body.contains(user_id.localpart()),
216 _ => false,
217 };
218 return !mentioned;
219219 }
220220 false
221221}
src/preview.rs +9 −9
@@ -1,21 +1,21 @@
11use std::{collections::HashMap, sync::Arc};
22
33use matrix_sdk::{
4 Media,
45 media::{MediaFormat, MediaRequestParameters, UniqueKey},
56 ruma::{
7 OwnedEventId,
68 events::{
9 MessageLikeEvent,
710 room::{
8 message::{MessageType, RoomMessageEventContent},
911 MediaSource,
12 message::{MessageType, RoomMessageEventContent},
1013 },
11 MessageLikeEvent,
1214 },
13 OwnedEventId,
1415 },
15 Media,
1616};
1717use ratatui::layout::Rect;
18use ratatui_image::{picker::Picker, protocol::Protocol, Resize};
18use ratatui_image::{Resize, picker::Picker, protocol::Protocol};
1919use tokio::sync::Semaphore;
2020
2121use crate::{
@@ -110,10 +110,10 @@ impl PreviewManager {
110110pub fn source_from_event(
111111 ev: &MessageLikeEvent<RoomMessageEventContent>,
112112) -> Option<(OwnedEventId, MediaSource)> {
113 if let MessageLikeEvent::Original(ev) = &ev {
114 if let MessageType::Image(c) = &ev.content.msgtype {
115 return Some((ev.event_id.clone(), c.source.clone()));
116 }
113 if let MessageLikeEvent::Original(ev) = &ev &&
114 let MessageType::Image(c) = &ev.content.msgtype
115 {
116 return Some((ev.event_id.clone(), c.source.clone()));
117117 }
118118 None
119119}
src/tests.rs +4 −4
@@ -3,16 +3,16 @@ use std::{collections::HashMap, iter::FromIterator as _};
33
44use matrix_sdk::ruma::MilliSecondsSinceUnixEpoch;
55use matrix_sdk::ruma::{
6 event_id,
7 events::room::message::RoomMessageEventContent,
8 server_name,
9 user_id,
106 EventId,
117 OwnedEventId,
128 OwnedRoomId,
139 OwnedUserId,
1410 RoomId,
1511 UInt,
12 event_id,
13 events::room::message::RoomMessageEventContent,
14 server_name,
15 user_id,
1616};
1717
1818use lazy_static::lazy_static;
src/windows/mod.rs +15 −17
@@ -13,17 +13,17 @@ use std::sync::Arc;
1313use std::time::{Duration, Instant};
1414
1515use matrix_sdk::{
16 encryption::verification::{format_emojis, SasVerification},
16 RoomState as MatrixRoomState,
17 encryption::verification::{SasVerification, format_emojis},
1718 room::{Room as MatrixRoom, RoomMember},
1819 ruma::{
19 events::room::member::MembershipState,
20 events::tag::{TagName, Tags},
2120 OwnedRoomAliasId,
2221 OwnedRoomId,
2322 RoomAliasId,
2423 RoomId,
24 events::room::member::MembershipState,
25 events::tag::{TagName, Tags},
2526 },
26 RoomState as MatrixRoomState,
2727};
2828
2929use ratatui::{
@@ -51,11 +51,11 @@ use modalkit::{
5151};
5252
5353use modalkit_ratatui::{
54 list::{List, ListCursor, ListItem, ListState},
5554 TermOffset,
5655 TerminalCursor,
5756 Window,
5857 WindowOps,
58 list::{List, ListCursor, ListItem, ListState},
5959};
6060
6161use crate::base::{
@@ -576,17 +576,15 @@ impl WindowOps<IambInfo> for IambWindow {
576576 None => true,
577577 };
578578
579 if need_fetch {
580 if let Ok(mems) = store.application.worker.members(room_id.clone()) {
581 let mut items = mems
582 .into_iter()
583 .map(|m| MemberItem::new(m, room_id.clone()))
584 .collect::<Vec<_>>();
585 let fields = &store.application.settings.tunables.sort.members;
586 items.sort_by(|a, b| user_fields_cmp(a, b, fields));
587 state.set(items);
588 *last_fetch = Some(Instant::now());
589 }
579 if need_fetch && let Ok(mems) = store.application.worker.members(room_id.clone()) {
580 let mut items = mems
581 .into_iter()
582 .map(|m| MemberItem::new(m, room_id.clone()))
583 .collect::<Vec<_>>();
584 let fields = &store.application.settings.tunables.sort.members;
585 items.sort_by(|a, b| user_fields_cmp(a, b, fields));
586 state.set(items);
587 *last_fetch = Some(Instant::now());
590588 }
591589
592590 List::new(store)
@@ -1743,7 +1741,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
17431741#[cfg(test)]
17441742mod tests {
17451743 use super::*;
1746 use matrix_sdk::ruma::{room_alias_id, server_name, MilliSecondsSinceUnixEpoch};
1744 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, room_alias_id, server_name};
17471745
17481746 #[derive(Debug, Eq, PartialEq)]
17491747 struct TestRoomItem {
src/windows/room/chat.rs +18 −14
@@ -5,18 +5,22 @@ use std::fs;
55use std::ops::Deref;
66use std::path::{Path, PathBuf};
77
8use edit::edit_with_builder as external_edit;
98use edit::Builder;
9use edit::edit_with_builder as external_edit;
1010use modalkit::editing::store::RegisterError;
1111use std::process::Command;
1212use tokio;
1313use url::Url;
1414
1515use matrix_sdk::{
16 RoomState,
1617 attachment::AttachmentConfig,
1718 media::{MediaFormat, MediaRequestParameters},
1819 room::Room as MatrixRoom,
1920 ruma::{
21 OwnedEventId,
22 OwnedRoomId,
23 RoomId,
2024 events::reaction::ReactionEventContent,
2125 events::relation::{Annotation, Replacement},
2226 events::room::message::{
@@ -27,12 +31,8 @@ use matrix_sdk::{
2731 Relation,
2832 ReplyWithinThread,
2933 },
30 OwnedEventId,
31 OwnedRoomId,
32 RoomId,
3334 },
3435 send_queue::RoomSendQueueError,
35 RoomState,
3636};
3737
3838use ratatui::{
@@ -45,10 +45,10 @@ use ratatui::{
4545use modalkit::keybindings::dialog::{MultiChoice, MultiChoiceItem, PromptYesNo};
4646
4747use modalkit_ratatui::{
48 textbox::{TextBox, TextBoxState},
4948 PromptActions,
5049 TerminalCursor,
5150 WindowOps,
51 textbox::{TextBox, TextBoxState},
5252};
5353
5454use modalkit::actions::{
@@ -87,7 +87,7 @@ use crate::base::{
8787};
8888
8989use crate::config::EncryptionIndicatorLocation;
90use crate::message::{text_to_message, MessageEvent, MessageId, MessageKey, TreeGenState};
90use crate::message::{MessageEvent, MessageId, MessageKey, TreeGenState, text_to_message};
9191use crate::worker::Requester;
9292
9393use super::scrollback::{Scrollback, ScrollbackState};
@@ -373,7 +373,9 @@ impl ChatState {
373373 {
374374 emoji.to_string()
375375 } else {
376 let msg = format!("{reaction:?} is not a known Emoji shortcode; do you want to react with exactly {reaction:?}?");
376 let msg = format!(
377 "{reaction:?} is not a known Emoji shortcode; do you want to react with exactly {reaction:?}?"
378 );
377379 let act = IambAction::Message(MessageAction::React(reaction, true));
378380 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
379381 let prompt = Box::new(prompt);
@@ -495,7 +497,9 @@ impl ChatState {
495497 {
496498 Some(emoji.to_string())
497499 } else {
498 let msg = format!("{reaction:?} is not a known Emoji shortcode; do you want to remove exactly {reaction:?}?");
500 let msg = format!(
501 "{reaction:?} is not a known Emoji shortcode; do you want to remove exactly {reaction:?}?"
502 );
499503 let act =
500504 IambAction::Message(MessageAction::Unreact(Some(reaction), true));
501505 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
@@ -694,10 +698,10 @@ impl ChatState {
694698 // Jump to the end of the scrollback to show the message.
695699 self.scrollback.goto_latest();
696700
697 if tunables.read_receipt_trigger.on_message() {
698 if let Some(thread) = self.scrollback.get_thread(info) {
699 info.fully_read(settings.profile.user_id.clone(), thread.1.clone());
700 }
701 if tunables.read_receipt_trigger.on_message() &&
702 let Some(thread) = self.scrollback.get_thread(info)
703 {
704 info.fully_read(settings.profile.user_id.clone(), thread.1.clone());
701705 }
702706
703707 Ok(None)
@@ -1158,7 +1162,7 @@ mod tests {
11581162
11591163 use modalkit::actions::{EditAction, InsertTextAction};
11601164
1161 use crate::tests::{mock_store, TEST_ROOM1_ID};
1165 use crate::tests::{TEST_ROOM1_ID, mock_store};
11621166
11631167 macro_rules! move_line {
11641168 ($dir: expr, $count: expr) => {
src/windows/room/mod.rs +18 −18
@@ -3,9 +3,15 @@ use std::collections::HashSet;
33
44use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind;
55use matrix_sdk::{
6 RoomDisplayName,
7 RoomState as MatrixRoomState,
68 notification_settings::RoomNotificationMode,
79 room::Room as MatrixRoom,
810 ruma::{
11 OwnedEventId,
12 OwnedRoomAliasId,
13 OwnedUserId,
14 RoomId,
915 events::{
1016 room::{
1117 canonical_alias::RoomCanonicalAliasEventContent,
@@ -15,13 +21,7 @@ use matrix_sdk::{
1521 },
1622 tag::{TagInfo, Tags},
1723 },
18 OwnedEventId,
19 OwnedRoomAliasId,
20 OwnedUserId,
21 RoomId,
2224 },
23 RoomDisplayName,
24 RoomState as MatrixRoomState,
2525};
2626
2727use ratatui::{
@@ -230,14 +230,14 @@ pub async fn room_command(
230230 let user_id = store.application.settings.profile.user_id.clone();
231231 let info = store.application.get_room_info(id.to_owned());
232232 let messages = info.get_thread(None).expect("room main timeline doesn't exist");
233 if let Some((key, _)) = messages.last_key_value() {
234 if let Some(event_id) = key.id.as_origin() {
235 info.set_receipt(
236 matrix_sdk::ruma::events::receipt::ReceiptThread::Main,
237 user_id,
238 event_id.to_owned(),
239 );
240 }
233 if let Some((key, _)) = messages.last_key_value() &&
234 let Some(event_id) = key.id.as_origin()
235 {
236 info.set_receipt(
237 matrix_sdk::ruma::events::receipt::ReceiptThread::Main,
238 user_id,
239 event_id.to_owned(),
240 );
241241 }
242242 }
243243
@@ -665,10 +665,10 @@ impl RoomState {
665665 let style = Style::default().add_modifier(StyleModifier::BOLD);
666666 let mut spans = vec![];
667667
668 if let RoomState::Chat(chat) = self {
669 if chat.thread().is_some() {
670 spans.push("Thread in ".into());
671 }
668 if let RoomState::Chat(chat) = self &&
669 chat.thread().is_some()
670 {
671 spans.push("Thread in ".into());
672672 }
673673
674674 spans.push(Span::styled(title, style));
src/windows/room/space.rs +4 −4
@@ -3,9 +3,9 @@ use std::ops::{Deref, DerefMut};
33use std::str::FromStr;
44use std::time::{Duration, Instant};
55
6use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
7use matrix_sdk::ruma::events::StateEventType;
86use matrix_sdk::ruma::OwnedSpaceChildOrder;
7use matrix_sdk::ruma::events::StateEventType;
8use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
99use matrix_sdk::{
1010 room::Room as MatrixRoom,
1111 ruma::{OwnedRoomId, RoomId},
@@ -21,10 +21,10 @@ use ratatui::{
2121};
2222
2323use modalkit_ratatui::{
24 list::{List, ListState},
2524 TermOffset,
2625 TerminalCursor,
2726 WindowOps,
27 list::{List, ListState},
2828};
2929
3030use crate::base::{
@@ -38,7 +38,7 @@ use crate::base::{
3838 SpaceAction,
3939};
4040
41use crate::windows::{room_fields_cmp, RoomItem, RoomLikeItem};
41use crate::windows::{RoomItem, RoomLikeItem, room_fields_cmp};
4242
4343const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
4444
src/windows/welcome.rs +1 −1
@@ -3,7 +3,7 @@ use std::ops::{Deref, DerefMut};
33
44use ratatui::{buffer::Buffer, layout::Rect};
55
6use modalkit_ratatui::{textbox::TextBoxState, TermOffset, TerminalCursor, WindowOps};
6use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps, textbox::TextBoxState};
77
88use modalkit::editing::completion::CompletionList;
99use modalkit::prelude::*;
src/worker.rs +39 −40
@@ -7,53 +7,71 @@ use std::convert::TryFrom;
77use std::fmt::{Debug, Formatter};
88use std::ops::DerefMut;
99use std::str::FromStr;
10use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
1110use std::sync::Arc;
11use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
1212use std::time::{Duration, Instant};
1313
14use futures::{stream::FuturesUnordered, StreamExt};
14use futures::{StreamExt, stream::FuturesUnordered};
1515use gethostname::gethostname;
16use matrix_sdk::ruma::events::AnyMessageLikeEventContent;
1617use matrix_sdk::ruma::events::relation::Thread;
17use matrix_sdk::ruma::events::room::message::Relation;
1818use matrix_sdk::ruma::events::room::MediaSource;
19use matrix_sdk::ruma::events::room::message::Relation;
1920use matrix_sdk::ruma::events::sticker::StickerEventContent;
20use matrix_sdk::ruma::events::AnyMessageLikeEventContent;
2121use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate};
2222use ratatui_image::picker::Picker;
23use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
2423use tokio::sync::Semaphore;
24use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
2525use tokio::task::JoinHandle;
2626use tracing::{error, warn};
2727use url::Url;
2828
2929use matrix_sdk::{
30 Client,
31 ClientBuildError,
32 Error as MatrixError,
33 RoomDisplayName,
34 RoomMemberships,
3035 authentication::matrix::MatrixSession,
3136 config::{RequestConfig, SyncSettings},
3237 encryption::{
33 verification::{SasVerification, Verification},
3438 BackupDownloadStrategy,
3539 EncryptionSettings,
40 verification::{SasVerification, Verification},
3641 },
3742 event_handler::Ctx,
3843 reqwest,
3944 room::{Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
4045 ruma::{
46 EventId,
47 OwnedEventId,
48 OwnedRoomId,
49 OwnedRoomOrAliasId,
50 OwnedUserId,
51 RoomId,
4152 api::client::{
4253 filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
4354 room::{
44 create_room::v3::{CreationContent, Request as CreateRoomRequest},
4555 Visibility,
56 create_room::v3::{CreationContent, Request as CreateRoomRequest},
4657 },
4758 space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
4859 },
4960 assign,
5061 events::{
62 AnyMessageLikeEvent,
63 AnySyncStateEvent,
64 AnyTimelineEvent,
65 InitialStateEvent,
66 SyncEphemeralRoomEvent,
67 SyncMessageLikeEvent,
68 SyncStateEvent,
5169 key::verification::{
70 VerificationMethod,
5271 done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent},
5372 key::{OriginalSyncKeyVerificationKeyEvent, ToDeviceKeyVerificationKeyEvent},
5473 request::ToDeviceKeyVerificationRequestEvent,
5574 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
56 VerificationMethod,
5775 },
5876 presence::PresenceEvent,
5977 reaction::ReactionEventContent,
@@ -67,28 +85,10 @@ use matrix_sdk::{
6785 },
6886 tag::Tags,
6987 typing::SyncTypingEvent,
70 AnyMessageLikeEvent,
71 AnySyncStateEvent,
72 AnyTimelineEvent,
73 InitialStateEvent,
74 SyncEphemeralRoomEvent,
75 SyncMessageLikeEvent,
76 SyncStateEvent,
7788 },
7889 room::RoomType,
7990 serde::Raw,
80 EventId,
81 OwnedEventId,
82 OwnedRoomId,
83 OwnedRoomOrAliasId,
84 OwnedUserId,
85 RoomId,
8691 },
87 Client,
88 ClientBuildError,
89 Error as MatrixError,
90 RoomDisplayName,
91 RoomMemberships,
9292};
9393
9494use modalkit::errors::UIError;
@@ -100,6 +100,7 @@ use crate::message::{Message, MessageEvent, MessageId, MessageKey};
100100use crate::notifications::register_notifications;
101101use crate::preview::load_image;
102102use crate::{
103 ApplicationSettings,
103104 base::{
104105 AsyncProgramStore,
105106 ChatStore,
@@ -112,7 +113,6 @@ use crate::{
112113 RoomInfo,
113114 VerifyAction,
114115 },
115 ApplicationSettings,
116116};
117117
118118const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings {
@@ -510,9 +510,10 @@ async fn send_receipts_forever(client: &Client, store: &AsyncProgramStore) {
510510 };
511511
512512 if ReceiptThread::Main == thread || ReceiptThread::Unthreaded == thread {
513 if let Err(err) = room.set_unread_flag(false).await {
514 tracing::warn!(?room_id, "Failed to clear unread flag: {err}");
515 }
513 let _ = room
514 .set_unread_flag(false)
515 .await
516 .inspect_err(|e| tracing::warn!(?room_id, "Failed to clear unread flag: {e}"));
516517 }
517518
518519 match room
@@ -1148,16 +1149,14 @@ impl ClientWorker {
11481149 async move {
11491150 let room_id = room.room_id();
11501151
1151 if let Some(msg) = ev.as_original() {
1152 if let MessageType::VerificationRequest(_) = msg.content.msgtype {
1153 if let Some(request) = client
1154 .encryption()
1155 .get_verification_request(ev.sender(), ev.event_id())
1156 .await
1157 {
1158 request.accept().await.expect("Failed to accept request");
1159 }
1160 }
1152 if let Some(msg) = ev.as_original() &&
1153 let MessageType::VerificationRequest(_) = msg.content.msgtype &&
1154 let Some(request) = client
1155 .encryption()
1156 .get_verification_request(ev.sender(), ev.event_id())
1157 .await
1158 {
1159 request.accept().await.expect("Failed to accept request");
11611160 }
11621161
11631162 let mut locked = store.lock().await;