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 @@
1[package] 1[package]
2name = "iamb" 2name = "iamb"
3version = "0.0.11" 3version = "0.0.11"
4edition = "2018" 4edition = "2024"
5authors = ["Ulyssa <git@ulyssa.dev>"] 5authors = ["Ulyssa <git@ulyssa.dev>"]
6repository = "https://github.com/ulyssa/iamb" 6repository = "https://github.com/ulyssa/iamb"
7homepage = "https://iamb.chat" 7homepage = "https://iamb.chat"
src/base.rs +28 −27
@@ -13,10 +13,10 @@ use std::time::{Duration, Instant};
13 13
14use emojis::Emoji; 14use emojis::Emoji;
15 15
16use matrix_sdk::ruma::OwnedTransactionId;
16use matrix_sdk::ruma::events::receipt::ReceiptThread; 17use matrix_sdk::ruma::events::receipt::ReceiptThread;
17use matrix_sdk::ruma::events::room::MediaSource; 18use matrix_sdk::ruma::events::room::MediaSource;
18use matrix_sdk::ruma::events::sticker::StickerEvent; 19use matrix_sdk::ruma::events::sticker::StickerEvent;
19use matrix_sdk::ruma::OwnedTransactionId;
20use ratatui::{ 20use ratatui::{
21 buffer::Buffer, 21 buffer::Buffer,
22 layout::{Alignment, Rect}, 22 layout::{Alignment, Rect},
@@ -25,21 +25,30 @@ use ratatui::{
25}; 25};
26use ratatui_image::picker::{Picker, ProtocolType}; 26use ratatui_image::picker::{Picker, ProtocolType};
27use serde::{ 27use serde::{
28 de::Error as SerdeError,
29 de::Visitor,
30 Deserialize, 28 Deserialize,
31 Deserializer, 29 Deserializer,
32 Serialize, 30 Serialize,
33 Serializer, 31 Serializer,
32 de::Error as SerdeError,
33 de::Visitor,
34}; 34};
35use tokio::sync::Mutex as AsyncMutex; 35use tokio::sync::Mutex as AsyncMutex;
36use url::Url; 36use url::Url;
37 37
38use matrix_sdk::{ 38use matrix_sdk::{
39 RoomState as MatrixRoomState,
39 encryption::verification::SasVerification, 40 encryption::verification::SasVerification,
40 room::Room as MatrixRoom, 41 room::Room as MatrixRoom,
41 ruma::{ 42 ruma::{
43 EventId,
44 OwnedEventId,
45 OwnedRoomId,
46 OwnedUserId,
47 RoomId,
48 UserId,
42 events::{ 49 events::{
50 AnySyncStateEvent,
51 MessageLikeEvent,
43 reaction::ReactionEvent, 52 reaction::ReactionEvent,
44 relation::{Replacement, Thread}, 53 relation::{Replacement, Thread},
45 room::encrypted::RoomEncryptedEvent, 54 room::encrypted::RoomEncryptedEvent,
@@ -52,18 +61,9 @@ use matrix_sdk::{
52 }, 61 },
53 room::redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent}, 62 room::redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
54 tag::{TagName, Tags}, 63 tag::{TagName, Tags},
55 AnySyncStateEvent,
56 MessageLikeEvent,
57 }, 64 },
58 presence::PresenceState, 65 presence::PresenceState,
59 EventId,
60 OwnedEventId,
61 OwnedRoomId,
62 OwnedUserId,
63 RoomId,
64 UserId,
65 }, 66 },
66 RoomState as MatrixRoomState,
67}; 67};
68 68
69use modalkit::{ 69use modalkit::{
@@ -77,7 +77,7 @@ use modalkit::{
77 ApplicationStore, 77 ApplicationStore,
78 ApplicationWindowId, 78 ApplicationWindowId,
79 }, 79 },
80 completion::{complete_path, Completer, CompletionMap}, 80 completion::{Completer, CompletionMap, complete_path},
81 context::EditContext, 81 context::EditContext,
82 cursor::Cursor, 82 cursor::Cursor,
83 rope::EditRope, 83 rope::EditRope,
@@ -97,7 +97,7 @@ use crate::{
97 config::{ApplicationSettings, ImagePreviewProtocolValues}, 97 config::{ApplicationSettings, ImagePreviewProtocolValues},
98 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages}, 98 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
99 notifications::NotificationHandle, 99 notifications::NotificationHandle,
100 preview::{source_from_event, PreviewManager}, 100 preview::{PreviewManager, source_from_event},
101 worker::Requester, 101 worker::Requester,
102}; 102};
103 103
@@ -1175,11 +1175,11 @@ impl RoomInfo {
1175 } 1175 }
1176 }, 1176 },
1177 Some(EventLocation::Message(Some(root), key)) => { 1177 Some(EventLocation::Message(Some(root), key)) => {
1178 if let Some(thread) = self.threads.get_mut(root) { 1178 if let Some(thread) = self.threads.get_mut(root) &&
1179 if let Some(msg) = thread.get_mut(key) { 1179 let Some(msg) = thread.get_mut(key)
1180 let ev = SyncRoomRedactionEvent::Original(ev); 1180 {
1181 msg.redact(ev); 1181 let ev = SyncRoomRedactionEvent::Original(ev);
1182 } 1182 msg.redact(ev);
1183 } 1183 }
1184 }, 1184 },
1185 Some(EventLocation::Reaction(event_id)) => { 1185 Some(EventLocation::Reaction(event_id)) => {
@@ -1403,13 +1403,12 @@ impl RoomInfo {
1403 let source = source_from_event(&ev); 1403 let source = source_from_event(&ev);
1404 self.insert(ev); 1404 self.insert(ev);
1405 1405
1406 if let Some((event_id, source)) = source { 1406 if let Some((event_id, source)) = source &&
1407 if let (Some(msg), Some(image_preview)) = 1407 let (Some(msg), Some(image_preview)) =
1408 (self.get_event_mut(&event_id), &settings.tunables.image_preview) 1408 (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1409 { 1409 {
1410 msg.image_preview = Some(source.clone()); 1410 msg.image_preview = Some(source.clone());
1411 previews.register_preview(settings, source, image_preview.size, worker) 1411 previews.register_preview(settings, source, image_preview.size, worker)
1412 }
1413 } 1412 }
1414 } 1413 }
1415 1414
@@ -1622,7 +1621,9 @@ fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1622/// Windows cannot guess the right protocol, and always needs type and font_size. 1621/// Windows cannot guess the right protocol, and always needs type and font_size.
1623#[cfg(windows)] 1622#[cfg(windows)]
1624fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> { 1623fn 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 );
1626 None 1627 None
1627} 1628}
1628 1629
@@ -2360,9 +2361,9 @@ pub mod tests {
2360 use crate::config::user_style_from_color; 2361 use crate::config::user_style_from_color;
2361 use crate::tests::*; 2362 use crate::tests::*;
2362 use matrix_sdk::ruma::{ 2363 use matrix_sdk::ruma::{
2364 MilliSecondsSinceUnixEpoch,
2363 events::{reaction::ReactionEventContent, relation::Annotation}, 2365 events::{reaction::ReactionEventContent, relation::Annotation},
2364 owned_event_id, 2366 owned_event_id,
2365 MilliSecondsSinceUnixEpoch,
2366 }; 2367 };
2367 use pretty_assertions::assert_eq; 2368 use pretty_assertions::assert_eq;
2368 use ratatui::style::Color; 2369 use ratatui::style::Color;
src/commands.rs +4 −4
@@ -4,7 +4,7 @@
4//! [modalkit::env::vim::command] for additional Vim commands we pull in. 4//! [modalkit::env::vim::command] for additional Vim commands we pull in.
5use std::{convert::TryFrom, str::FromStr as _}; 5use std::{convert::TryFrom, str::FromStr as _};
6 6
7use matrix_sdk::ruma::{events::tag::TagName, OwnedRoomId, OwnedUserId}; 7use matrix_sdk::ruma::{OwnedRoomId, OwnedUserId, events::tag::TagName};
8 8
9use modalkit::{ 9use modalkit::{
10 commands::{CommandError, CommandResult, CommandStep}, 10 commands::{CommandError, CommandResult, CommandStep},
@@ -550,7 +550,7 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
550 RoomAction::Show(RoomField::CanonicalAlias).into() 550 RoomAction::Show(RoomField::CanonicalAlias).into()
551 }, 551 },
552 ("canonicalalias" | "canon", "show", Some(_)) => { 552 ("canonicalalias" | "canon", "show", Some(_)) => {
553 return Result::Err(CommandError::InvalidArgument) 553 return Result::Err(CommandError::InvalidArgument);
554 }, 554 },
555 555
556 // :room canonicalalias set 556 // :room canonicalalias set
@@ -558,7 +558,7 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
558 RoomAction::Set(RoomField::CanonicalAlias, s).into() 558 RoomAction::Set(RoomField::CanonicalAlias, s).into()
559 }, 559 },
560 ("canonicalalias" | "canon", "set", None) => { 560 ("canonicalalias" | "canon", "set", None) => {
561 return Result::Err(CommandError::InvalidArgument) 561 return Result::Err(CommandError::InvalidArgument);
562 }, 562 },
563 563
564 // :room canonicalalias unset 564 // :room canonicalalias unset
@@ -566,7 +566,7 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
566 RoomAction::Unset(RoomField::CanonicalAlias).into() 566 RoomAction::Unset(RoomField::CanonicalAlias).into()
567 }, 567 },
568 ("canonicalalias" | "canon", "unset", Some(_)) => { 568 ("canonicalalias" | "canon", "unset", Some(_)) => {
569 return Result::Err(CommandError::InvalidArgument) 569 return Result::Err(CommandError::InvalidArgument);
570 }, 570 },
571 571
572 // :room id show 572 // :room id show
src/config.rs +40 −32
@@ -12,14 +12,14 @@ use std::process;
12use std::str::FromStr; 12use std::str::FromStr;
13 13
14use clap::Parser; 14use clap::Parser;
15use matrix_sdk::EncryptionState;
15use matrix_sdk::authentication::matrix::MatrixSession; 16use matrix_sdk::authentication::matrix::MatrixSession;
16use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue}; 17use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
17use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; 18use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
18use matrix_sdk::EncryptionState;
19use ratatui::style::{Color, Modifier as StyleModifier, Style}; 19use ratatui::style::{Color, Modifier as StyleModifier, Style};
20use ratatui::text::Span; 20use ratatui::text::Span;
21use ratatui_image::picker::ProtocolType; 21use 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};
23use url::Url; 23use url::Url;
24 24
25use modalkit::{env::vim::VimMode, key::TerminalKey, keybindings::InputKey}; 25use modalkit::{env::vim::VimMode, key::TerminalKey, keybindings::InputKey};
@@ -428,7 +428,7 @@ impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
428 "title" => location |= EncryptionIndicatorLocation::TITLE, 428 "title" => location |= EncryptionIndicatorLocation::TITLE,
429 "prompt" => location |= EncryptionIndicatorLocation::PROMPT, 429 "prompt" => location |= EncryptionIndicatorLocation::PROMPT,
430 _ => { 430 _ => {
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"));
432 }, 432 },
433 }; 433 };
434 } 434 }
@@ -511,7 +511,7 @@ impl Visitor<'_> for NotifyViaVisitor {
511 }, 511 },
512 #[cfg(not(feature = "desktop"))] 512 #[cfg(not(feature = "desktop"))]
513 "desktop" => { 513 "desktop" => {
514 return Err(E::custom("desktop notification support was compiled out")) 514 return Err(E::custom("desktop notification support was compiled out"));
515 }, 515 },
516 _ => return Err(E::custom("could not parse into a notify destination")), 516 _ => return Err(E::custom("could not parse into a notify destination")),
517 }; 517 };
@@ -1231,10 +1231,10 @@ impl ApplicationSettings {
1231 For more information try '--help'", 1231 For more information try '--help'",
1232 ); 1232 );
1233 } 1233 }
1234 if let Ok(i) = input.trim().parse::<usize>() { 1234 if let Ok(i) = input.trim().parse::<usize>() &&
1235 if i < profiles.len() { 1235 i < profiles.len()
1236 break profiles.into_iter().nth(i).unwrap(); 1236 {
1237 } 1237 break profiles.into_iter().nth(i).unwrap();
1238 } 1238 }
1239 println!("\nInvalid index."); 1239 println!("\nInvalid index.");
1240 } 1240 }
@@ -1749,16 +1749,18 @@ mod tests {
1749 1749
1750 // Always shows in the title: 1750 // Always shows in the title:
1751 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some()); 1751 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_some());
1752 assert!(enc 1752 assert!(
1753 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted) 1753 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1754 .is_some()); 1754 .is_some()
1755 );
1755 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some()); 1756 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1756 1757
1757 // Doesn't show in the prompt: 1758 // Doesn't show in the prompt:
1758 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none()); 1759 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1759 assert!(enc 1760 assert!(
1760 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted) 1761 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1761 .is_none()); 1762 .is_none()
1763 );
1762 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none()); 1764 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1763 } 1765 }
1764 1766
@@ -1773,14 +1775,16 @@ mod tests {
1773 1775
1774 // Never shows in the title or the prompt: 1776 // Never shows in the title or the prompt:
1775 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none()); 1777 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1776 assert!(enc 1778 assert!(
1777 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted) 1779 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1778 .is_none()); 1780 .is_none()
1781 );
1779 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none()); 1782 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1780 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none()); 1783 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Encrypted).is_none());
1781 assert!(enc 1784 assert!(
1782 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted) 1785 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1783 .is_none()); 1786 .is_none()
1787 );
1784 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none()); 1788 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_none());
1785 } 1789 }
1786 1790
@@ -1798,15 +1802,17 @@ mod tests {
1798 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some()); 1802 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1799 1803
1800 // But is hidden when unencrypted: 1804 // But is hidden when unencrypted:
1801 assert!(enc 1805 assert!(
1802 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted) 1806 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1803 .is_none()); 1807 .is_none()
1808 );
1804 1809
1805 // Doesn't show in the title: 1810 // Doesn't show in the title:
1806 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none()); 1811 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Encrypted).is_none());
1807 assert!(enc 1812 assert!(
1808 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted) 1813 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1809 .is_none()); 1814 .is_none()
1815 );
1810 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none()); 1816 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_none());
1811 } 1817 }
1812 #[test] 1818 #[test]
@@ -1819,13 +1825,15 @@ mod tests {
1819 }; 1825 };
1820 1826
1821 // Shows in both the prompt and title when unencrypted or unknown: 1827 // Shows in both the prompt and title when unencrypted or unknown:
1822 assert!(enc 1828 assert!(
1823 .get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted) 1829 enc.get_indicator(EncryptionIndicatorLocation::TITLE, NotEncrypted)
1824 .is_some()); 1830 .is_some()
1831 );
1825 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some()); 1832 assert!(enc.get_indicator(EncryptionIndicatorLocation::TITLE, Unknown).is_some());
1826 assert!(enc 1833 assert!(
1827 .get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted) 1834 enc.get_indicator(EncryptionIndicatorLocation::PROMPT, NotEncrypted)
1828 .is_some()); 1835 .is_some()
1836 );
1829 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some()); 1837 assert!(enc.get_indicator(EncryptionIndicatorLocation::PROMPT, Unknown).is_some());
1830 1838
1831 // But is hidden when encrypted: 1839 // But is hidden when encrypted:
src/keybindings.rs +14 −15
@@ -4,9 +4,9 @@
4//! keys come from [modalkit::env::vim::keybindings]. 4//! keys come from [modalkit::env::vim::keybindings].
5use modalkit::{ 5use modalkit::{
6 actions::{InsertTextAction, MacroAction, WindowAction}, 6 actions::{InsertTextAction, MacroAction, WindowAction},
7 env::vim::keybindings::{InputStep, VimBindings},
8 env::vim::VimMode,
9 env::CommonKeyClass, 7 env::CommonKeyClass,
8 env::vim::VimMode,
9 env::vim::keybindings::{InputStep, VimBindings},
10 key::TerminalKey, 10 key::TerminalKey,
11 keybindings::{EdgeEvent, EdgeRepeat, InputBindings}, 11 keybindings::{EdgeEvent, EdgeRepeat, InputBindings},
12 prelude::*, 12 prelude::*,
@@ -60,12 +60,9 @@ pub fn setup_keybindings() -> Keybindings {
60 ism.add_mapping(VimMode::Visual, &cwcm, &stoggle); 60 ism.add_mapping(VimMode::Visual, &cwcm, &stoggle);
61 61
62 let shift_enter = vec![once(&shift_enter)]; 62 let shift_enter = vec![once(&shift_enter)];
63 let newline = IambStep::new().actions(vec![InsertTextAction::Type( 63 let newline = IambStep::new().actions(vec![
64 Char::Single('\n').into(), 64 InsertTextAction::Type(Char::Single('\n').into(), MoveDir1D::Previous, 1.into()).into(),
65 MoveDir1D::Previous, 65 ]);
66 1.into(),
67 )
68 .into()]);
69 ism.add_mapping(VimMode::Insert, &cwm, &newline); 66 ism.add_mapping(VimMode::Insert, &cwm, &newline);
70 ism.add_mapping(VimMode::Insert, &shift_enter, &newline); 67 ism.add_mapping(VimMode::Insert, &shift_enter, &newline);
71 68
@@ -92,13 +89,15 @@ impl InputBindings<TerminalKey, IambStep> for ApplicationSettings {
92 let ctrl_f = "<C-F>".parse::<TerminalKey>().unwrap(); 89 let ctrl_f = "<C-F>".parse::<TerminalKey>().unwrap();
93 90
94 let vsplit_open = IambStep::new() 91 let vsplit_open = IambStep::new()
95 .actions(vec![WindowAction::Split( 92 .actions(vec![
96 OpenTarget::Cursor(MATRIX_ID_WORD.clone()), 93 WindowAction::Split(
97 Axis::Vertical, 94 OpenTarget::Cursor(MATRIX_ID_WORD.clone()),
98 MoveDir1D::Next, 95 Axis::Vertical,
99 1.into(), 96 MoveDir1D::Next,
100 ) 97 1.into(),
101 .into()]) 98 )
99 .into(),
100 ])
102 .goto(VimMode::Normal); 101 .goto(VimMode::Normal);
103 102
104 let cwf = vec![once(&ctrl_w), once(&key_f)]; 103 let cwf = vec![once(&ctrl_w), once(&key_f)];
src/main.rs +17 −14
@@ -19,21 +19,21 @@
19use std::collections::VecDeque; 19use std::collections::VecDeque;
20use std::convert::TryFrom; 20use std::convert::TryFrom;
21use std::fmt::Display; 21use std::fmt::Display;
22use std::fs::{create_dir_all, File}; 22use std::fs::{File, create_dir_all};
23use std::io::{stdout, BufWriter, Stdout, Write}; 23use std::io::{BufWriter, Stdout, Write, stdout};
24use std::ops::DerefMut; 24use std::ops::DerefMut;
25use std::process; 25use std::process;
26use std::sync::atomic::{AtomicUsize, Ordering};
27use std::sync::Arc; 26use std::sync::Arc;
27use std::sync::atomic::{AtomicUsize, Ordering};
28use std::time::{Duration, Instant}; 28use std::time::{Duration, Instant};
29 29
30use clap::{CommandFactory, Parser}; 30use clap::{CommandFactory, Parser};
31use matrix_sdk::ruma::api::error::ErrorKind;
32use matrix_sdk::ruma::OwnedUserId; 31use matrix_sdk::ruma::OwnedUserId;
32use matrix_sdk::ruma::api::error::ErrorKind;
33use matrix_sdk_crypto::encrypt_room_key_export; 33use matrix_sdk_crypto::encrypt_room_key_export;
34use modalkit::keybindings::InputBindings; 34use modalkit::keybindings::InputBindings;
35use rand::distr::Alphanumeric;
36use rand::RngExt as _; 35use rand::RngExt as _;
36use rand::distr::Alphanumeric;
37use temp_dir::TempDir; 37use temp_dir::TempDir;
38use tokio::sync::Mutex as AsyncMutex; 38use tokio::sync::Mutex as AsyncMutex;
39use tracing::Level; 39use tracing::Level;
@@ -43,8 +43,6 @@ use modalkit::crossterm::{
43 self, 43 self,
44 cursor::{SetCursorStyle, Show as CursorShow}, 44 cursor::{SetCursorStyle, Show as CursorShow},
45 event::{ 45 event::{
46 poll,
47 read,
48 DisableBracketedPaste, 46 DisableBracketedPaste,
49 DisableFocusChange, 47 DisableFocusChange,
50 DisableMouseCapture, 48 DisableMouseCapture,
@@ -57,18 +55,20 @@ use modalkit::crossterm::{
57 MouseEventKind, 55 MouseEventKind,
58 PopKeyboardEnhancementFlags, 56 PopKeyboardEnhancementFlags,
59 PushKeyboardEnhancementFlags, 57 PushKeyboardEnhancementFlags,
58 poll,
59 read,
60 }, 60 },
61 execute, 61 execute,
62 terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle}, 62 terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
63}; 63};
64 64
65use ratatui::{ 65use ratatui::{
66 Terminal,
66 backend::CrosstermBackend, 67 backend::CrosstermBackend,
67 layout::Rect, 68 layout::Rect,
68 style::{Color, Modifier, Style}, 69 style::{Color, Modifier, Style},
69 text::Span, 70 text::Span,
70 widgets::Paragraph, 71 widgets::Paragraph,
71 Terminal,
72}; 72};
73 73
74mod base; 74mod base;
@@ -104,7 +104,7 @@ use crate::{
104 }, 104 },
105 config::{ApplicationSettings, Iamb}, 105 config::{ApplicationSettings, Iamb},
106 windows::IambWindow, 106 windows::IambWindow,
107 worker::{create_room, ClientWorker, LoginStyle, Requester}, 107 worker::{ClientWorker, LoginStyle, Requester, create_room},
108}; 108};
109 109
110use modalkit::{ 110use modalkit::{
@@ -127,20 +127,20 @@ use modalkit::{
127 errors::{EditError, UIError}, 127 errors::{EditError, UIError},
128 key::TerminalKey, 128 key::TerminalKey,
129 keybindings::{ 129 keybindings::{
130 dialog::{Pager, PromptYesNo},
131 BindingMachine, 130 BindingMachine,
131 dialog::{Pager, PromptYesNo},
132 }, 132 },
133 prelude::*, 133 prelude::*,
134 ui::FocusList, 134 ui::FocusList,
135}; 135};
136 136
137use modalkit_ratatui::{ 137use modalkit_ratatui::{
138 cmdbar::CommandBarState,
139 screen::{Screen, ScreenState, TabbedLayoutDescription},
140 windows::{WindowLayoutDescription, WindowLayoutState},
141 TerminalCursor, 138 TerminalCursor,
142 TerminalExtOps, 139 TerminalExtOps,
143 Window, 140 Window,
141 cmdbar::CommandBarState,
142 screen::{Screen, ScreenState, TabbedLayoutDescription},
143 windows::{WindowLayoutDescription, WindowLayoutState},
144}; 144};
145 145
146fn config_tab_to_desc( 146fn config_tab_to_desc(
@@ -1059,7 +1059,10 @@ async fn run(settings: ApplicationSettings) -> IambResult<()> {
1059 match res { 1059 match res {
1060 Err(UIError::Application(IambError::Matrix(e))) => { 1060 Err(UIError::Application(IambError::Matrix(e))) => {
1061 if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() { 1061 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 ))
1063 } else { 1066 } else {
1064 print_exit(e) 1067 print_exit(e)
1065 } 1068 }
src/message/compose.rs +2 −2
@@ -1,12 +1,12 @@
1//! Code for converting composed messages into content to send to the homeserver. 1//! Code for converting composed messages into content to send to the homeserver.
2use comrak::{markdown_to_html, options::Options}; 2use comrak::{markdown_to_html, options::Options};
3use nom::{ 3use nom::{
4 IResult,
5 Parser as _,
4 branch::alt, 6 branch::alt,
5 bytes::complete::tag, 7 bytes::complete::tag,
6 character::complete::space0, 8 character::complete::space0,
7 combinator::value, 9 combinator::value,
8 IResult,
9 Parser as _,
10}; 10};
11 11
12use matrix_sdk::ruma::events::room::message::{ 12use matrix_sdk::ruma::events::room::message::{
src/message/html.rs +1 −1
@@ -20,7 +20,7 @@ use unicode_segmentation::UnicodeSegmentation;
20use url::Url; 20use url::Url;
21 21
22use html5ever::{ 22use html5ever::{
23 driver::{parse_fragment, ParseOpts}, 23 driver::{ParseOpts, parse_fragment},
24 interface::{Attribute, QualName}, 24 interface::{Attribute, QualName},
25 local_name, 25 local_name,
26 ns, 26 ns,
src/message/mod.rs +26 −28
@@ -1,25 +1,32 @@
1//! # Room Messages 1//! # Room Messages
2use std::borrow::Cow; 2use std::borrow::Cow;
3use std::cmp::{Ord, Ordering, PartialOrd}; 3use std::cmp::{Ord, Ordering, PartialOrd};
4use std::collections::hash_map::DefaultHasher;
5use std::collections::BTreeMap; 4use std::collections::BTreeMap;
5use std::collections::hash_map::DefaultHasher;
6use std::convert::{TryFrom, TryInto}; 6use std::convert::{TryFrom, TryInto};
7use std::fmt::{self, Display}; 7use std::fmt::{self, Display};
8use std::hash::{Hash, Hasher}; 8use std::hash::{Hash, Hasher};
9use std::ops::{Deref, DerefMut}; 9use std::ops::{Deref, DerefMut};
10 10
11use chrono::{DateTime, Local as LocalTz}; 11use chrono::{DateTime, Local as LocalTz};
12use humansize::{format_size, DECIMAL}; 12use humansize::{DECIMAL, format_size};
13use matrix_sdk::ruma::OwnedTransactionId;
13use matrix_sdk::ruma::events::receipt::ReceiptThread; 14use matrix_sdk::ruma::events::receipt::ReceiptThread;
14use matrix_sdk::ruma::events::room::MediaSource; 15use matrix_sdk::ruma::events::room::MediaSource;
15use matrix_sdk::ruma::events::sticker::StickerEvent; 16use matrix_sdk::ruma::events::sticker::StickerEvent;
16use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; 17use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent};
17use matrix_sdk::ruma::OwnedTransactionId;
18use matrix_sdk::send_queue::SendHandle; 18use matrix_sdk::send_queue::SendHandle;
19use unicode_width::UnicodeWidthStr; 19use unicode_width::UnicodeWidthStr;
20 20
21use matrix_sdk::ruma::{ 21use matrix_sdk::ruma::{
22 EventId,
23 MilliSecondsSinceUnixEpoch,
24 OwnedEventId,
25 OwnedUserId,
26 UInt,
22 events::{ 27 events::{
28 AnySyncStateEvent,
29 RedactedUnsigned,
23 relation::Thread, 30 relation::Thread,
24 room::{ 31 room::{
25 encrypted::{ 32 encrypted::{
@@ -39,14 +46,7 @@ use matrix_sdk::ruma::{
39 }, 46 },
40 redaction::SyncRoomRedactionEvent, 47 redaction::SyncRoomRedactionEvent,
41 }, 48 },
42 AnySyncStateEvent,
43 RedactedUnsigned,
44 }, 49 },
45 EventId,
46 MilliSecondsSinceUnixEpoch,
47 OwnedEventId,
48 OwnedUserId,
49 UInt,
50}; 50};
51 51
52use ratatui::{ 52use ratatui::{
@@ -64,7 +64,7 @@ use crate::preview::{ImageStatus, PreviewManager};
64use crate::{ 64use crate::{
65 base::RoomInfo, 65 base::RoomInfo,
66 config::ApplicationSettings, 66 config::ApplicationSettings,
67 message::html::{parse_matrix_html, StyleTree}, 67 message::html::{StyleTree, parse_matrix_html},
68 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text}, 68 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
69}; 69};
70 70
@@ -188,13 +188,12 @@ fn placeholder_frame(
188 placeholder.push('\u{230d}'); 188 placeholder.push('\u{230d}');
189 placeholder.push_str(&"\n".repeat((height - 1) / 2)); 189 placeholder.push_str(&"\n".repeat((height - 1) / 2));
190 190
191 if *height > 2 { 191 if *height > 2 &&
192 if let Some(text) = text { 192 let Some(text) = text &&
193 if text.width() <= width - 2 { 193 text.width() <= width - 2
194 placeholder.push(' '); 194 {
195 placeholder.push_str(text); 195 placeholder.push(' ');
196 } 196 placeholder.push_str(text);
197 }
198 } 197 }
199 198
200 placeholder.push_str(&"\n".repeat(height / 2)); 199 placeholder.push_str(&"\n".repeat(height / 2));
@@ -239,7 +238,7 @@ pub struct MessageTimeStamp(pub MilliSecondsSinceUnixEpoch);
239 238
240impl MessageTimeStamp { 239impl MessageTimeStamp {
241 fn as_datetime(self) -> DateTime<LocalTz> { 240 fn as_datetime(self) -> DateTime<LocalTz> {
242 let time = i64::from(self.0 .0) / 1000; 241 let time = i64::from(self.0.0) / 1000;
243 let time = DateTime::from_timestamp(time, 0).unwrap_or_default(); 242 let time = DateTime::from_timestamp(time, 0).unwrap_or_default();
244 time.into() 243 time.into()
245 } 244 }
@@ -275,7 +274,7 @@ impl TryFrom<&MessageTimeStamp> for usize {
275 type Error = TimeStampIntError; 274 type Error = TimeStampIntError;
276 275
277 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> { 276 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))?;
279 278
280 Ok(n) 279 Ok(n)
281 } 280 }
@@ -1154,13 +1153,12 @@ impl Message {
1154 settings: &'a ApplicationSettings, 1153 settings: &'a ApplicationSettings,
1155 width: usize, 1154 width: usize,
1156 ) -> SenderSpan<'a> { 1155 ) -> SenderSpan<'a> {
1157 if let Some(prev) = prev { 1156 if let Some(prev) = prev &&
1158 if self.sender == prev.sender && 1157 self.sender == prev.sender &&
1159 self.timestamp.same_day(prev.timestamp) && 1158 self.timestamp.same_day(prev.timestamp) &&
1160 !self.event.is_emote() 1159 !self.event.is_emote()
1161 { 1160 {
1162 return SenderSpan::None; 1161 return SenderSpan::None;
1163 }
1164 } 1162 }
1165 1163
1166 let Span { content, style } = self.sender_span(info, settings); 1164 let Span { content, style } = self.sender_span(info, settings);
@@ -1266,6 +1264,7 @@ impl Display for Message {
1266#[cfg(test)] 1264#[cfg(test)]
1267pub mod tests { 1265pub mod tests {
1268 use matrix_sdk::ruma::events::room::{ 1266 use matrix_sdk::ruma::events::room::{
1267 ImageInfo,
1269 message::{ 1268 message::{
1270 AudioInfo, 1269 AudioInfo,
1271 AudioMessageEventContent, 1270 AudioMessageEventContent,
@@ -1275,7 +1274,6 @@ pub mod tests {
1275 VideoInfo, 1274 VideoInfo,
1276 VideoMessageEventContent, 1275 VideoMessageEventContent,
1277 }, 1276 },
1278 ImageInfo,
1279 }; 1277 };
1280 1278
1281 use super::*; 1279 use super::*;
src/message/state.rs +3 −3
@@ -3,14 +3,14 @@ use std::borrow::Cow;
3use std::str::FromStr; 3use std::str::FromStr;
4 4
5use matrix_sdk::ruma::{ 5use matrix_sdk::ruma::{
6 OwnedRoomId,
7 UserId,
6 events::{ 8 events::{
7 room::member::MembershipChange,
8 AnyStateEventContentChange, 9 AnyStateEventContentChange,
9 AnySyncStateEvent, 10 AnySyncStateEvent,
10 StateEventContentChange, 11 StateEventContentChange,
12 room::member::MembershipChange,
11 }, 13 },
12 OwnedRoomId,
13 UserId,
14}; 14};
15 15
16use super::html::{StyleTree, StyleTreeNode}; 16use super::html::{StyleTree, StyleTreeNode};
src/notifications.rs +12 −12
@@ -1,18 +1,18 @@
1use std::time::SystemTime; 1use std::time::SystemTime;
2 2
3use matrix_sdk::{ 3use matrix_sdk::{
4 Client,
5 EncryptionState,
4 deserialized_responses::RawAnySyncOrStrippedTimelineEvent, 6 deserialized_responses::RawAnySyncOrStrippedTimelineEvent,
5 notification_settings::{IsEncrypted, IsOneToOne, NotificationSettings, RoomNotificationMode}, 7 notification_settings::{IsEncrypted, IsOneToOne, NotificationSettings, RoomNotificationMode},
6 room::Room as MatrixRoom, 8 room::Room as MatrixRoom,
7 ruma::{ 9 ruma::{
8 events::{room::message::MessageType, AnyMessageLikeEventContent, AnySyncTimelineEvent},
9 serde::Raw,
10 MilliSecondsSinceUnixEpoch, 10 MilliSecondsSinceUnixEpoch,
11 OwnedRoomId, 11 OwnedRoomId,
12 RoomId, 12 RoomId,
13 events::{AnyMessageLikeEventContent, AnySyncTimelineEvent, room::message::MessageType},
14 serde::Raw,
13 }, 15 },
14 Client,
15 EncryptionState,
16}; 16};
17use unicode_segmentation::UnicodeSegmentation; 17use unicode_segmentation::UnicodeSegmentation;
18 18
@@ -208,14 +208,14 @@ async fn global_or_room_mode(
208} 208}
209 209
210fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool { 210fn is_missing_mention(body: &Option<String>, mode: RoomNotificationMode, client: &Client) -> bool {
211 if let Some(body) = body { 211 if let Some(body) = body &&
212 if mode == RoomNotificationMode::MentionsAndKeywordsOnly { 212 mode == RoomNotificationMode::MentionsAndKeywordsOnly
213 let mentioned = match client.user_id() { 213 {
214 Some(user_id) => body.contains(user_id.localpart()), 214 let mentioned = match client.user_id() {
215 _ => false, 215 Some(user_id) => body.contains(user_id.localpart()),
216 }; 216 _ => false,
217 return !mentioned; 217 };
218 } 218 return !mentioned;
219 } 219 }
220 false 220 false
221} 221}
src/preview.rs +9 −9
@@ -1,21 +1,21 @@
1use std::{collections::HashMap, sync::Arc}; 1use std::{collections::HashMap, sync::Arc};
2 2
3use matrix_sdk::{ 3use matrix_sdk::{
4 Media,
4 media::{MediaFormat, MediaRequestParameters, UniqueKey}, 5 media::{MediaFormat, MediaRequestParameters, UniqueKey},
5 ruma::{ 6 ruma::{
7 OwnedEventId,
6 events::{ 8 events::{
9 MessageLikeEvent,
7 room::{ 10 room::{
8 message::{MessageType, RoomMessageEventContent},
9 MediaSource, 11 MediaSource,
12 message::{MessageType, RoomMessageEventContent},
10 }, 13 },
11 MessageLikeEvent,
12 }, 14 },
13 OwnedEventId,
14 }, 15 },
15 Media,
16}; 16};
17use ratatui::layout::Rect; 17use ratatui::layout::Rect;
18use ratatui_image::{picker::Picker, protocol::Protocol, Resize}; 18use ratatui_image::{Resize, picker::Picker, protocol::Protocol};
19use tokio::sync::Semaphore; 19use tokio::sync::Semaphore;
20 20
21use crate::{ 21use crate::{
@@ -110,10 +110,10 @@ impl PreviewManager {
110pub fn source_from_event( 110pub fn source_from_event(
111 ev: &MessageLikeEvent<RoomMessageEventContent>, 111 ev: &MessageLikeEvent<RoomMessageEventContent>,
112) -> Option<(OwnedEventId, MediaSource)> { 112) -> Option<(OwnedEventId, MediaSource)> {
113 if let MessageLikeEvent::Original(ev) = &ev { 113 if let MessageLikeEvent::Original(ev) = &ev &&
114 if let MessageType::Image(c) = &ev.content.msgtype { 114 let MessageType::Image(c) = &ev.content.msgtype
115 return Some((ev.event_id.clone(), c.source.clone())); 115 {
116 } 116 return Some((ev.event_id.clone(), c.source.clone()));
117 } 117 }
118 None 118 None
119} 119}
src/tests.rs +4 −4
@@ -3,16 +3,16 @@ use std::{collections::HashMap, iter::FromIterator as _};
3 3
4use matrix_sdk::ruma::MilliSecondsSinceUnixEpoch; 4use matrix_sdk::ruma::MilliSecondsSinceUnixEpoch;
5use matrix_sdk::ruma::{ 5use matrix_sdk::ruma::{
6 event_id,
7 events::room::message::RoomMessageEventContent,
8 server_name,
9 user_id,
10 EventId, 6 EventId,
11 OwnedEventId, 7 OwnedEventId,
12 OwnedRoomId, 8 OwnedRoomId,
13 OwnedUserId, 9 OwnedUserId,
14 RoomId, 10 RoomId,
15 UInt, 11 UInt,
12 event_id,
13 events::room::message::RoomMessageEventContent,
14 server_name,
15 user_id,
16}; 16};
17 17
18use lazy_static::lazy_static; 18use lazy_static::lazy_static;
src/windows/mod.rs +15 −17
@@ -13,17 +13,17 @@ use std::sync::Arc;
13use std::time::{Duration, Instant}; 13use std::time::{Duration, Instant};
14 14
15use matrix_sdk::{ 15use matrix_sdk::{
16 encryption::verification::{format_emojis, SasVerification}, 16 RoomState as MatrixRoomState,
17 encryption::verification::{SasVerification, format_emojis},
17 room::{Room as MatrixRoom, RoomMember}, 18 room::{Room as MatrixRoom, RoomMember},
18 ruma::{ 19 ruma::{
19 events::room::member::MembershipState,
20 events::tag::{TagName, Tags},
21 OwnedRoomAliasId, 20 OwnedRoomAliasId,
22 OwnedRoomId, 21 OwnedRoomId,
23 RoomAliasId, 22 RoomAliasId,
24 RoomId, 23 RoomId,
24 events::room::member::MembershipState,
25 events::tag::{TagName, Tags},
25 }, 26 },
26 RoomState as MatrixRoomState,
27}; 27};
28 28
29use ratatui::{ 29use ratatui::{
@@ -51,11 +51,11 @@ use modalkit::{
51}; 51};
52 52
53use modalkit_ratatui::{ 53use modalkit_ratatui::{
54 list::{List, ListCursor, ListItem, ListState},
55 TermOffset, 54 TermOffset,
56 TerminalCursor, 55 TerminalCursor,
57 Window, 56 Window,
58 WindowOps, 57 WindowOps,
58 list::{List, ListCursor, ListItem, ListState},
59}; 59};
60 60
61use crate::base::{ 61use crate::base::{
@@ -576,17 +576,15 @@ impl WindowOps<IambInfo> for IambWindow {
576 None => true, 576 None => true,
577 }; 577 };
578 578
579 if need_fetch { 579 if need_fetch && let Ok(mems) = store.application.worker.members(room_id.clone()) {
580 if let Ok(mems) = store.application.worker.members(room_id.clone()) { 580 let mut items = mems
581 let mut items = mems 581 .into_iter()
582 .into_iter() 582 .map(|m| MemberItem::new(m, room_id.clone()))
583 .map(|m| MemberItem::new(m, room_id.clone())) 583 .collect::<Vec<_>>();
584 .collect::<Vec<_>>(); 584 let fields = &store.application.settings.tunables.sort.members;
585 let fields = &store.application.settings.tunables.sort.members; 585 items.sort_by(|a, b| user_fields_cmp(a, b, fields));
586 items.sort_by(|a, b| user_fields_cmp(a, b, fields)); 586 state.set(items);
587 state.set(items); 587 *last_fetch = Some(Instant::now());
588 *last_fetch = Some(Instant::now());
589 }
590 } 588 }
591 589
592 List::new(store) 590 List::new(store)
@@ -1743,7 +1741,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1743#[cfg(test)] 1741#[cfg(test)]
1744mod tests { 1742mod tests {
1745 use super::*; 1743 use super::*;
1746 use matrix_sdk::ruma::{room_alias_id, server_name, MilliSecondsSinceUnixEpoch}; 1744 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, room_alias_id, server_name};
1747 1745
1748 #[derive(Debug, Eq, PartialEq)] 1746 #[derive(Debug, Eq, PartialEq)]
1749 struct TestRoomItem { 1747 struct TestRoomItem {
src/windows/room/chat.rs +18 −14
@@ -5,18 +5,22 @@ use std::fs;
5use std::ops::Deref; 5use std::ops::Deref;
6use std::path::{Path, PathBuf}; 6use std::path::{Path, PathBuf};
7 7
8use edit::edit_with_builder as external_edit;
9use edit::Builder; 8use edit::Builder;
9use edit::edit_with_builder as external_edit;
10use modalkit::editing::store::RegisterError; 10use modalkit::editing::store::RegisterError;
11use std::process::Command; 11use std::process::Command;
12use tokio; 12use tokio;
13use url::Url; 13use url::Url;
14 14
15use matrix_sdk::{ 15use matrix_sdk::{
16 RoomState,
16 attachment::AttachmentConfig, 17 attachment::AttachmentConfig,
17 media::{MediaFormat, MediaRequestParameters}, 18 media::{MediaFormat, MediaRequestParameters},
18 room::Room as MatrixRoom, 19 room::Room as MatrixRoom,
19 ruma::{ 20 ruma::{
21 OwnedEventId,
22 OwnedRoomId,
23 RoomId,
20 events::reaction::ReactionEventContent, 24 events::reaction::ReactionEventContent,
21 events::relation::{Annotation, Replacement}, 25 events::relation::{Annotation, Replacement},
22 events::room::message::{ 26 events::room::message::{
@@ -27,12 +31,8 @@ use matrix_sdk::{
27 Relation, 31 Relation,
28 ReplyWithinThread, 32 ReplyWithinThread,
29 }, 33 },
30 OwnedEventId,
31 OwnedRoomId,
32 RoomId,
33 }, 34 },
34 send_queue::RoomSendQueueError, 35 send_queue::RoomSendQueueError,
35 RoomState,
36}; 36};
37 37
38use ratatui::{ 38use ratatui::{
@@ -45,10 +45,10 @@ use ratatui::{
45use modalkit::keybindings::dialog::{MultiChoice, MultiChoiceItem, PromptYesNo}; 45use modalkit::keybindings::dialog::{MultiChoice, MultiChoiceItem, PromptYesNo};
46 46
47use modalkit_ratatui::{ 47use modalkit_ratatui::{
48 textbox::{TextBox, TextBoxState},
49 PromptActions, 48 PromptActions,
50 TerminalCursor, 49 TerminalCursor,
51 WindowOps, 50 WindowOps,
51 textbox::{TextBox, TextBoxState},
52}; 52};
53 53
54use modalkit::actions::{ 54use modalkit::actions::{
@@ -87,7 +87,7 @@ use crate::base::{
87}; 87};
88 88
89use crate::config::EncryptionIndicatorLocation; 89use crate::config::EncryptionIndicatorLocation;
90use crate::message::{text_to_message, MessageEvent, MessageId, MessageKey, TreeGenState}; 90use crate::message::{MessageEvent, MessageId, MessageKey, TreeGenState, text_to_message};
91use crate::worker::Requester; 91use crate::worker::Requester;
92 92
93use super::scrollback::{Scrollback, ScrollbackState}; 93use super::scrollback::{Scrollback, ScrollbackState};
@@ -373,7 +373,9 @@ impl ChatState {
373 { 373 {
374 emoji.to_string() 374 emoji.to_string()
375 } else { 375 } 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 );
377 let act = IambAction::Message(MessageAction::React(reaction, true)); 379 let act = IambAction::Message(MessageAction::React(reaction, true));
378 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]); 380 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
379 let prompt = Box::new(prompt); 381 let prompt = Box::new(prompt);
@@ -495,7 +497,9 @@ impl ChatState {
495 { 497 {
496 Some(emoji.to_string()) 498 Some(emoji.to_string())
497 } else { 499 } 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 );
499 let act = 503 let act =
500 IambAction::Message(MessageAction::Unreact(Some(reaction), true)); 504 IambAction::Message(MessageAction::Unreact(Some(reaction), true));
501 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]); 505 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
@@ -694,10 +698,10 @@ impl ChatState {
694 // Jump to the end of the scrollback to show the message. 698 // Jump to the end of the scrollback to show the message.
695 self.scrollback.goto_latest(); 699 self.scrollback.goto_latest();
696 700
697 if tunables.read_receipt_trigger.on_message() { 701 if tunables.read_receipt_trigger.on_message() &&
698 if let Some(thread) = self.scrollback.get_thread(info) { 702 let Some(thread) = self.scrollback.get_thread(info)
699 info.fully_read(settings.profile.user_id.clone(), thread.1.clone()); 703 {
700 } 704 info.fully_read(settings.profile.user_id.clone(), thread.1.clone());
701 } 705 }
702 706
703 Ok(None) 707 Ok(None)
@@ -1158,7 +1162,7 @@ mod tests {
1158 1162
1159 use modalkit::actions::{EditAction, InsertTextAction}; 1163 use modalkit::actions::{EditAction, InsertTextAction};
1160 1164
1161 use crate::tests::{mock_store, TEST_ROOM1_ID}; 1165 use crate::tests::{TEST_ROOM1_ID, mock_store};
1162 1166
1163 macro_rules! move_line { 1167 macro_rules! move_line {
1164 ($dir: expr, $count: expr) => { 1168 ($dir: expr, $count: expr) => {
src/windows/room/mod.rs +18 −18
@@ -3,9 +3,15 @@ use std::collections::HashSet;
3 3
4use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind; 4use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind;
5use matrix_sdk::{ 5use matrix_sdk::{
6 RoomDisplayName,
7 RoomState as MatrixRoomState,
6 notification_settings::RoomNotificationMode, 8 notification_settings::RoomNotificationMode,
7 room::Room as MatrixRoom, 9 room::Room as MatrixRoom,
8 ruma::{ 10 ruma::{
11 OwnedEventId,
12 OwnedRoomAliasId,
13 OwnedUserId,
14 RoomId,
9 events::{ 15 events::{
10 room::{ 16 room::{
11 canonical_alias::RoomCanonicalAliasEventContent, 17 canonical_alias::RoomCanonicalAliasEventContent,
@@ -15,13 +21,7 @@ use matrix_sdk::{
15 }, 21 },
16 tag::{TagInfo, Tags}, 22 tag::{TagInfo, Tags},
17 }, 23 },
18 OwnedEventId,
19 OwnedRoomAliasId,
20 OwnedUserId,
21 RoomId,
22 }, 24 },
23 RoomDisplayName,
24 RoomState as MatrixRoomState,
25}; 25};
26 26
27use ratatui::{ 27use ratatui::{
@@ -230,14 +230,14 @@ pub async fn room_command(
230 let user_id = store.application.settings.profile.user_id.clone(); 230 let user_id = store.application.settings.profile.user_id.clone();
231 let info = store.application.get_room_info(id.to_owned()); 231 let info = store.application.get_room_info(id.to_owned());
232 let messages = info.get_thread(None).expect("room main timeline doesn't exist"); 232 let messages = info.get_thread(None).expect("room main timeline doesn't exist");
233 if let Some((key, _)) = messages.last_key_value() { 233 if let Some((key, _)) = messages.last_key_value() &&
234 if let Some(event_id) = key.id.as_origin() { 234 let Some(event_id) = key.id.as_origin()
235 info.set_receipt( 235 {
236 matrix_sdk::ruma::events::receipt::ReceiptThread::Main, 236 info.set_receipt(
237 user_id, 237 matrix_sdk::ruma::events::receipt::ReceiptThread::Main,
238 event_id.to_owned(), 238 user_id,
239 ); 239 event_id.to_owned(),
240 } 240 );
241 } 241 }
242 } 242 }
243 243
@@ -665,10 +665,10 @@ impl RoomState {
665 let style = Style::default().add_modifier(StyleModifier::BOLD); 665 let style = Style::default().add_modifier(StyleModifier::BOLD);
666 let mut spans = vec![]; 666 let mut spans = vec![];
667 667
668 if let RoomState::Chat(chat) = self { 668 if let RoomState::Chat(chat) = self &&
669 if chat.thread().is_some() { 669 chat.thread().is_some()
670 spans.push("Thread in ".into()); 670 {
671 } 671 spans.push("Thread in ".into());
672 } 672 }
673 673
674 spans.push(Span::styled(title, style)); 674 spans.push(Span::styled(title, style));
src/windows/room/space.rs +4 −4
@@ -3,9 +3,9 @@ use std::ops::{Deref, DerefMut};
3use std::str::FromStr; 3use std::str::FromStr;
4use std::time::{Duration, Instant}; 4use std::time::{Duration, Instant};
5 5
6use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
7use matrix_sdk::ruma::events::StateEventType;
8use matrix_sdk::ruma::OwnedSpaceChildOrder; 6use matrix_sdk::ruma::OwnedSpaceChildOrder;
7use matrix_sdk::ruma::events::StateEventType;
8use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
9use matrix_sdk::{ 9use matrix_sdk::{
10 room::Room as MatrixRoom, 10 room::Room as MatrixRoom,
11 ruma::{OwnedRoomId, RoomId}, 11 ruma::{OwnedRoomId, RoomId},
@@ -21,10 +21,10 @@ use ratatui::{
21}; 21};
22 22
23use modalkit_ratatui::{ 23use modalkit_ratatui::{
24 list::{List, ListState},
25 TermOffset, 24 TermOffset,
26 TerminalCursor, 25 TerminalCursor,
27 WindowOps, 26 WindowOps,
27 list::{List, ListState},
28}; 28};
29 29
30use crate::base::{ 30use crate::base::{
@@ -38,7 +38,7 @@ use crate::base::{
38 SpaceAction, 38 SpaceAction,
39}; 39};
40 40
41use crate::windows::{room_fields_cmp, RoomItem, RoomLikeItem}; 41use crate::windows::{RoomItem, RoomLikeItem, room_fields_cmp};
42 42
43const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5); 43const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
44 44
src/windows/welcome.rs +1 −1
@@ -3,7 +3,7 @@ use std::ops::{Deref, DerefMut};
3 3
4use ratatui::{buffer::Buffer, layout::Rect}; 4use ratatui::{buffer::Buffer, layout::Rect};
5 5
6use modalkit_ratatui::{textbox::TextBoxState, TermOffset, TerminalCursor, WindowOps}; 6use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps, textbox::TextBoxState};
7 7
8use modalkit::editing::completion::CompletionList; 8use modalkit::editing::completion::CompletionList;
9use modalkit::prelude::*; 9use modalkit::prelude::*;
src/worker.rs +39 −40
@@ -7,53 +7,71 @@ use std::convert::TryFrom;
7use std::fmt::{Debug, Formatter}; 7use std::fmt::{Debug, Formatter};
8use std::ops::DerefMut; 8use std::ops::DerefMut;
9use std::str::FromStr; 9use std::str::FromStr;
10use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
11use std::sync::Arc; 10use std::sync::Arc;
11use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
12use std::time::{Duration, Instant}; 12use std::time::{Duration, Instant};
13 13
14use futures::{stream::FuturesUnordered, StreamExt}; 14use futures::{StreamExt, stream::FuturesUnordered};
15use gethostname::gethostname; 15use gethostname::gethostname;
16use matrix_sdk::ruma::events::AnyMessageLikeEventContent;
16use matrix_sdk::ruma::events::relation::Thread; 17use matrix_sdk::ruma::events::relation::Thread;
17use matrix_sdk::ruma::events::room::message::Relation;
18use matrix_sdk::ruma::events::room::MediaSource; 18use matrix_sdk::ruma::events::room::MediaSource;
19use matrix_sdk::ruma::events::room::message::Relation;
19use matrix_sdk::ruma::events::sticker::StickerEventContent; 20use matrix_sdk::ruma::events::sticker::StickerEventContent;
20use matrix_sdk::ruma::events::AnyMessageLikeEventContent;
21use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate}; 21use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate};
22use ratatui_image::picker::Picker; 22use ratatui_image::picker::Picker;
23use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
24use tokio::sync::Semaphore; 23use tokio::sync::Semaphore;
24use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
25use tokio::task::JoinHandle; 25use tokio::task::JoinHandle;
26use tracing::{error, warn}; 26use tracing::{error, warn};
27use url::Url; 27use url::Url;
28 28
29use matrix_sdk::{ 29use matrix_sdk::{
30 Client,
31 ClientBuildError,
32 Error as MatrixError,
33 RoomDisplayName,
34 RoomMemberships,
30 authentication::matrix::MatrixSession, 35 authentication::matrix::MatrixSession,
31 config::{RequestConfig, SyncSettings}, 36 config::{RequestConfig, SyncSettings},
32 encryption::{ 37 encryption::{
33 verification::{SasVerification, Verification},
34 BackupDownloadStrategy, 38 BackupDownloadStrategy,
35 EncryptionSettings, 39 EncryptionSettings,
40 verification::{SasVerification, Verification},
36 }, 41 },
37 event_handler::Ctx, 42 event_handler::Ctx,
38 reqwest, 43 reqwest,
39 room::{Messages, MessagesOptions, Room as MatrixRoom, RoomMember}, 44 room::{Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
40 ruma::{ 45 ruma::{
46 EventId,
47 OwnedEventId,
48 OwnedRoomId,
49 OwnedRoomOrAliasId,
50 OwnedUserId,
51 RoomId,
41 api::client::{ 52 api::client::{
42 filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter}, 53 filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
43 room::{ 54 room::{
44 create_room::v3::{CreationContent, Request as CreateRoomRequest},
45 Visibility, 55 Visibility,
56 create_room::v3::{CreationContent, Request as CreateRoomRequest},
46 }, 57 },
47 space::get_hierarchy::v1::Request as SpaceHierarchyRequest, 58 space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
48 }, 59 },
49 assign, 60 assign,
50 events::{ 61 events::{
62 AnyMessageLikeEvent,
63 AnySyncStateEvent,
64 AnyTimelineEvent,
65 InitialStateEvent,
66 SyncEphemeralRoomEvent,
67 SyncMessageLikeEvent,
68 SyncStateEvent,
51 key::verification::{ 69 key::verification::{
70 VerificationMethod,
52 done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent}, 71 done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent},
53 key::{OriginalSyncKeyVerificationKeyEvent, ToDeviceKeyVerificationKeyEvent}, 72 key::{OriginalSyncKeyVerificationKeyEvent, ToDeviceKeyVerificationKeyEvent},
54 request::ToDeviceKeyVerificationRequestEvent, 73 request::ToDeviceKeyVerificationRequestEvent,
55 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent}, 74 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
56 VerificationMethod,
57 }, 75 },
58 presence::PresenceEvent, 76 presence::PresenceEvent,
59 reaction::ReactionEventContent, 77 reaction::ReactionEventContent,
@@ -67,28 +85,10 @@ use matrix_sdk::{
67 }, 85 },
68 tag::Tags, 86 tag::Tags,
69 typing::SyncTypingEvent, 87 typing::SyncTypingEvent,
70 AnyMessageLikeEvent,
71 AnySyncStateEvent,
72 AnyTimelineEvent,
73 InitialStateEvent,
74 SyncEphemeralRoomEvent,
75 SyncMessageLikeEvent,
76 SyncStateEvent,
77 }, 88 },
78 room::RoomType, 89 room::RoomType,
79 serde::Raw, 90 serde::Raw,
80 EventId,
81 OwnedEventId,
82 OwnedRoomId,
83 OwnedRoomOrAliasId,
84 OwnedUserId,
85 RoomId,
86 }, 91 },
87 Client,
88 ClientBuildError,
89 Error as MatrixError,
90 RoomDisplayName,
91 RoomMemberships,
92}; 92};
93 93
94use modalkit::errors::UIError; 94use modalkit::errors::UIError;
@@ -100,6 +100,7 @@ use crate::message::{Message, MessageEvent, MessageId, MessageKey};
100use crate::notifications::register_notifications; 100use crate::notifications::register_notifications;
101use crate::preview::load_image; 101use crate::preview::load_image;
102use crate::{ 102use crate::{
103 ApplicationSettings,
103 base::{ 104 base::{
104 AsyncProgramStore, 105 AsyncProgramStore,
105 ChatStore, 106 ChatStore,
@@ -112,7 +113,6 @@ use crate::{
112 RoomInfo, 113 RoomInfo,
113 VerifyAction, 114 VerifyAction,
114 }, 115 },
115 ApplicationSettings,
116}; 116};
117 117
118const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings { 118const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings {
@@ -510,9 +510,10 @@ async fn send_receipts_forever(client: &Client, store: &AsyncProgramStore) {
510 }; 510 };
511 511
512 if ReceiptThread::Main == thread || ReceiptThread::Unthreaded == thread { 512 if ReceiptThread::Main == thread || ReceiptThread::Unthreaded == thread {
513 if let Err(err) = room.set_unread_flag(false).await { 513 let _ = room
514 tracing::warn!(?room_id, "Failed to clear unread flag: {err}"); 514 .set_unread_flag(false)
515 } 515 .await
516 .inspect_err(|e| tracing::warn!(?room_id, "Failed to clear unread flag: {e}"));
516 } 517 }
517 518
518 match room 519 match room
@@ -1148,16 +1149,14 @@ impl ClientWorker {
1148 async move { 1149 async move {
1149 let room_id = room.room_id(); 1150 let room_id = room.room_id();
1150 1151
1151 if let Some(msg) = ev.as_original() { 1152 if let Some(msg) = ev.as_original() &&
1152 if let MessageType::VerificationRequest(_) = msg.content.msgtype { 1153 let MessageType::VerificationRequest(_) = msg.content.msgtype &&
1153 if let Some(request) = client 1154 let Some(request) = client
1154 .encryption() 1155 .encryption()
1155 .get_verification_request(ev.sender(), ev.event_id()) 1156 .get_verification_request(ev.sender(), ev.event_id())
1156 .await 1157 .await
1157 { 1158 {
1158 request.accept().await.expect("Failed to accept request"); 1159 request.accept().await.expect("Failed to accept request");
1159 }
1160 }
1161 } 1160 }
1162 1161
1163 let mut locked = store.lock().await; 1162 let mut locked = store.lock().await;