Commit 8d8af112d7

8d8af112d7a5860e46f16b2a6db44dbafb98bbaa

parent: fa91b75924

Unregistered key

vaw <git@nlih.de> · 2026-09-11 20:36 UTC
committer: <noreply@github.com>

Cleanup imports and create prelude (#681)

Layout: unified · split

.github/workflows/check-imports-format.sh added +89
@@ -0,0 +1,89 @@
1#!/bin/sh
2
3while [ $# -gt 0 ]; do
4 # check that all imports for a `use` statement come from the same module
5 import_error=$(sed -n "
6 # only consider use statements with braces
7 /^ *use .*{/ {
8 # load the import until the first closing brace into the pattern space
9 :find-close
10 /^[^}]*$/ {
11 N
12 b find-close
13 }
14
15 # show error if multiple braces exist
16 /{.*{/ {
17 i\\
18invalid import in '$1' line:
19 =
20 i\\
21containing multiple braces in one import:
22 p
23 b
24 }
25
26 # show error if qualified paths exist inside braces
27 /{.*::/ {
28 i\\
29invalid import in '$1' line:
30 =
31 i\\
32containing a qualified import inside braces:
33 p
34 b
35 }
36 }
37 " "$1")
38 if [ -n "$import_error" ]; then
39 printf "%s\n" "$import_error"
40 exit 1
41 fi
42
43 # check that imports are sorted as `std`, `other imports`, `crate` each seperated by a blank line
44 import_pattern=$(sed -n "
45 # include blank lines
46 /^$/ {
47 p
48 d
49 }
50 # include std imports
51 /^use std::/ {
52 i\\
53use std
54 d
55 }
56 # include crate imports
57 /^use crate::/ {
58 i\\
59use crate
60 d
61 }
62 # include other imports without the target
63 s/^use .*/use/p
64 " "$1" | uniq | tr "\n" "_") # remove duplicates; we only care for the order of the imports; also grep doesn't play nice with line breaks
65
66 # check that the pattern if followed
67 printf "%s" "$import_pattern" | grep -q "^_\?\(use std__\)\?\(use__\)\?\(use crate__\)\?_\?$"
68 if [ $? -ne 0 ]; then
69 printf "imports in '%s' dont follow the pattern:
70\`\`\`
71use std::*;
72
73use *;
74
75use crate::*;
76
77\`\`\`
78
79instead is has the pattern:
80\`\`\`
81%s
82\`\`\`
83" "$1" "$import_pattern" | tr "_" "\n" >&2
84 exit 1
85 fi
86
87
88 shift
89done
.github/workflows/ci.yml +2
@@ -37,6 +37,8 @@ jobs:
37 uses: mozilla-actions/sccache-action@v0.0.9 37 uses: mozilla-actions/sccache-action@v0.0.9
38 - name: Check formatting 38 - name: Check formatting
39 run: cargo +nightly fmt --all -- --check 39 run: cargo +nightly fmt --all -- --check
40 - name: Check imports formatting
41 run: find src -name '*.rs' | xargs ./.github/workflows/check-imports-format.sh
40 - name: Check Clippy 42 - name: Check Clippy
41 if: matrix.platform == 'ubuntu-latest' 43 if: matrix.platform == 'ubuntu-latest'
42 uses: giraffate/clippy-action@v1 44 uses: giraffate/clippy-action@v1
src/base.rs +44 −106
@@ -1,112 +1,50 @@
1//! # Common types and utilities 1//! # Common types and utilities
2//! 2//!
3//! The types defined here get used throughout iamb. 3//! The types defined here get used throughout iamb.
4use std::borrow::Cow; 4
5use std::collections::hash_map::{Entry, IntoIter}; 5use std::collections::hash_map::{Entry, IntoIter};
6use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; 6use std::collections::{BTreeSet, HashSet};
7use std::convert::TryFrom;
8use std::fmt::{self, Display};
9use std::hash::Hash;
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12 7
13use emojis::Emoji; 8use emojis::Emoji;
14
15use matrix_sdk::Client; 9use matrix_sdk::Client;
16use matrix_sdk::encryption::verification::VerificationRequest; 10use matrix_sdk::ruma::events::reaction::ReactionEvent;
17use matrix_sdk::ruma::room::{AllowRule, Restricted}; 11use matrix_sdk::ruma::events::relation::Replacement;
18use ratatui::{ 12use matrix_sdk::ruma::events::room::encrypted::RoomEncryptedEvent;
19 buffer::Buffer, 13use matrix_sdk::ruma::events::room::message::{
20 layout::{Alignment, Rect}, 14 RoomMessageEvent,
21 text::{Line, Span}, 15 RoomMessageEventContentWithoutRelation,
22 widgets::{Paragraph, Widget},
23}; 16};
24use serde::{ 17use matrix_sdk::ruma::events::room::redaction::{
25 Deserialize, 18 OriginalSyncRoomRedactionEvent,
26 Deserializer, 19 SyncRoomRedactionEvent,
27 Serialize,
28 Serializer,
29 de::Error as SerdeError,
30 de::Visitor,
31}; 20};
32use tokio::sync::Mutex as AsyncMutex; 21use matrix_sdk::ruma::events::sticker::{StickerEvent, StickerEventContent};
33use url::Url; 22use matrix_sdk::ruma::events::{MessageLikeEvent, OriginalMessageLikeEvent};
34 23use matrix_sdk::ruma::presence::PresenceState;
35use matrix_sdk::{ 24use matrix_sdk::ruma::room::{AllowRule, Restricted};
36 RoomState as MatrixRoomState, 25use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId};
37 room::Room as MatrixRoom, 26use modalkit::editing::application::{
38 ruma::{ 27 ApplicationAction,
39 EventId, 28 ApplicationContentId,
40 OwnedEventId, 29 ApplicationError,
41 OwnedMxcUri, 30 ApplicationInfo,
42 OwnedRoomAliasId, 31 ApplicationStore,
43 OwnedRoomId, 32 ApplicationWindowId,
44 OwnedRoomOrAliasId,
45 OwnedTransactionId,
46 OwnedUserId,
47 RoomId,
48 RoomVersionId,
49 UserId,
50 events::{
51 AnySyncStateEvent,
52 MessageLikeEvent,
53 OriginalMessageLikeEvent,
54 reaction::ReactionEvent,
55 receipt::ReceiptThread,
56 relation::{Replacement, Thread},
57 room::MediaSource,
58 room::encrypted::RoomEncryptedEvent,
59 room::message::{
60 MessageType,
61 OriginalRoomMessageEvent,
62 Relation,
63 RoomMessageEvent,
64 RoomMessageEventContent,
65 RoomMessageEventContentWithoutRelation,
66 },
67 room::redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
68 sticker::{StickerEvent, StickerEventContent},
69 tag::{TagName, Tags},
70 },
71 presence::PresenceState,
72 profile::{ProfileFieldName, ProfileFieldValue},
73 room::JoinRule,
74 },
75};
76
77use modalkit::{
78 actions::Action,
79 editing::{
80 application::{
81 ApplicationAction,
82 ApplicationContentId,
83 ApplicationError,
84 ApplicationInfo,
85 ApplicationStore,
86 ApplicationWindowId,
87 },
88 completion::CompletionMap,
89 context::EditContext,
90 store::Store,
91 },
92 env::vim::{
93 command::{CommandContext, VimCommand, VimCommandMachine},
94 keybindings::VimMachine,
95 },
96 errors::{UIError, UIResult},
97 key::TerminalKey,
98 keybindings::SequenceStatus,
99 prelude::{CommandType, MoveDir1D, WordStyle},
100}; 33};
34use modalkit::editing::completion::CompletionMap;
35use modalkit::editing::context::EditContext;
36use modalkit::editing::store::Store;
37use modalkit::env::vim::command::{CommandContext, VimCommand, VimCommandMachine};
38use modalkit::env::vim::keybindings::VimMachine;
39use modalkit::errors::UIResult;
40use modalkit::keybindings::SequenceStatus;
41use serde::de::Error as SerdeError;
42use serde::de::Visitor;
43use serde::{Deserialize, Deserializer, Serialize, Serializer};
44use tokio::sync::Mutex as AsyncMutex;
101 45
102use crate::preview::PreviewKind; 46use crate::notifications::NotificationHandle;
103use crate::{ 47use crate::prelude::*;
104 config::ApplicationSettings,
105 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
106 notifications::NotificationHandle,
107 preview::PreviewManager,
108 worker::Requester,
109};
110 48
111/// The set of characters used in different Matrix IDs. 49/// The set of characters used in different Matrix IDs.
112pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char); 50pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
@@ -2307,20 +2245,20 @@ impl ApplicationInfo for IambInfo {
2307 2245
2308#[cfg(test)] 2246#[cfg(test)]
2309pub mod tests { 2247pub mod tests {
2248 use super::*;
2249
2310 use std::iter::FromIterator as _; 2250 use std::iter::FromIterator as _;
2311 2251
2312 use super::*; 2252 use matrix_sdk::ruma::events::reaction::ReactionEventContent;
2313 use crate::config::user_style_from_color; 2253 use matrix_sdk::ruma::events::relation::Annotation;
2314 use crate::tests::*; 2254 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, owned_event_id};
2315 use matrix_sdk::ruma::{
2316 MilliSecondsSinceUnixEpoch,
2317 events::{reaction::ReactionEventContent, relation::Annotation},
2318 owned_event_id,
2319 };
2320 use pretty_assertions::assert_eq; 2255 use pretty_assertions::assert_eq;
2321 use ratatui::style::Color; 2256 use ratatui::style::Color;
2322 use serde_json::{Map, Value}; 2257 use serde_json::{Map, Value};
2323 2258
2259 use crate::config::user_style_from_color;
2260 use crate::tests::*;
2261
2324 fn create_reaction_event( 2262 fn create_reaction_event(
2325 content: &ReactionEventContent, 2263 content: &ReactionEventContent,
2326 event_id: &str, 2264 event_id: &str,
src/commands.rs +5 −21
@@ -2,42 +2,25 @@
2//! 2//!
3//! The command-bar commands are set up here, and iamb-specific commands are defined here. See 3//! The command-bar commands are set up here, and iamb-specific commands are defined here. See
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 _};
6
7use matrix_sdk::ruma::{
8 OwnedMxcUri,
9 OwnedRoomOrAliasId,
10 OwnedUserId,
11 RoomVersionId,
12 events::tag::TagName,
13 profile::{ProfileFieldName, ProfileFieldValue},
14};
15 5
16use modalkit::{ 6use matrix_sdk::ruma::{OwnedMxcUri, RoomVersionId};
17 commands::{CommandError, CommandResult, CommandStep}, 7use modalkit::commands::{CommandError, CommandResult, CommandStep};
18 env::vim::command::{CommandContext, CommandDescription, OptionType}, 8use modalkit::env::vim::command::{CommandContext, CommandDescription, OptionType};
19 prelude::{MoveDir1D, OpenTarget},
20};
21 9
22use crate::base::{ 10use crate::base::{
23 CreateRoomFlags, 11 CreateRoomFlags,
24 CreateRoomType, 12 CreateRoomType,
25 DownloadFlags, 13 DownloadFlags,
26 HomeserverAction, 14 HomeserverAction,
27 IambAction,
28 IambId,
29 IambJoinRule, 15 IambJoinRule,
30 KeysAction, 16 KeysAction,
31 MemberUpdateAction, 17 MemberUpdateAction,
32 MessageAction,
33 ProgramCommand, 18 ProgramCommand,
34 ProgramCommands, 19 ProgramCommands,
35 RoomAction,
36 RoomField, 20 RoomField,
37 SendAction,
38 SpaceAction,
39 VerifyAction, 21 VerifyAction,
40}; 22};
23use crate::prelude::*;
41 24
42type ProgContext = CommandContext; 25type ProgContext = CommandContext;
43type ProgResult = CommandResult<ProgramCommand>; 26type ProgResult = CommandResult<ProgramCommand>;
@@ -1156,6 +1139,7 @@ pub fn setup_commands() -> ProgramCommands {
1156#[cfg(test)] 1139#[cfg(test)]
1157mod tests { 1140mod tests {
1158 use super::*; 1141 use super::*;
1142
1159 use matrix_sdk::ruma::{owned_room_id, user_id}; 1143 use matrix_sdk::ruma::{owned_room_id, user_id};
1160 use modalkit::actions::WindowAction; 1144 use modalkit::actions::WindowAction;
1161 use modalkit::editing::context::EditContext; 1145 use modalkit::editing::context::EditContext;
src/completions.rs +20 −39
@@ -1,39 +1,19 @@
1//! Tab completions for iamb 1//! Tab completions for iamb
2use std::borrow::Cow; 2
3use std::str::FromStr; 3use modalkit::editing::completion::{Completer, complete_path};
4 4use modalkit::editing::cursor::Cursor;
5use modalkit::{ 5use modalkit::env::vim::command::CommandDescription;
6 editing::{ 6
7 completion::{Completer, complete_path}, 7use crate::base::MATRIX_ID_WORD;
8 cursor::Cursor, 8use crate::prelude::*;
9 rope::EditRope,
10 },
11 env::vim::command::CommandDescription,
12 prelude::{
13 CommandType,
14 Count,
15 CursorMovements,
16 CursorMovementsContext,
17 MoveDir1D,
18 MoveType,
19 WordStyle,
20 },
21};
22
23use crate::base::{ChatStore, IambBufferId, IambInfo, MATRIX_ID_WORD, RoomFocus};
24 9
25mod parse { 10mod parse {
26 use nom::{ 11 use nom::branch::alt;
27 IResult, 12 use nom::bytes::complete::{escaped_transform, is_not, tag};
28 Input, 13 use nom::character::complete::{char, space0, space1};
29 OutputMode, 14 use nom::combinator::{cut, eof, opt, value};
30 Parser, 15 use nom::error::{ErrorKind, ParseError};
31 branch::alt, 16 use nom::{IResult, Input, OutputMode, Parser};
32 bytes::complete::{escaped_transform, is_not, tag},
33 character::complete::{char, space0, space1},
34 combinator::{cut, eof, opt, value},
35 error::{ErrorKind, ParseError},
36 };
37 17
38 fn parse_text(input: &str) -> IResult<&str, String> { 18 fn parse_text(input: &str) -> IResult<&str, String> {
39 if input.is_empty() { 19 if input.is_empty() {
@@ -782,14 +762,15 @@ impl Completer<IambInfo> for IambCompleter {
782#[cfg(test)] 762#[cfg(test)]
783pub mod tests { 763pub mod tests {
784 use super::*; 764 use super::*;
785 use crate::{ 765
786 base::{ProgramCommand, ProgramCommands}, 766 use modalkit::commands::CommandResult;
787 commands::add_iamb_commands, 767 use modalkit::env::vim::command::CommandContext;
788 tests::*,
789 };
790 use modalkit::{commands::CommandResult, env::vim::command::CommandContext};
791 use pretty_assertions::assert_eq; 768 use pretty_assertions::assert_eq;
792 769
770 use crate::base::{ProgramCommand, ProgramCommands};
771 use crate::commands::add_iamb_commands;
772 use crate::tests::*;
773
793 #[tokio::test] 774 #[tokio::test]
794 async fn test_complete_msgbar() { 775 async fn test_complete_msgbar() {
795 let store = mock_store().await; 776 let store = mock_store().await;
src/config.rs +13 −27
@@ -1,44 +1,28 @@
1//! # Logic for loading and validating application configuration 1//! # Logic for loading and validating application configuration
2use std::borrow::Cow; 2
3use std::collections::hash_map::DefaultHasher; 3use std::collections::hash_map::DefaultHasher;
4use std::collections::{BTreeMap, HashMap};
5use std::env; 4use std::env;
6use std::fmt;
7use std::fs::File; 5use std::fs::File;
8use std::hash::{Hash, Hasher}; 6use std::hash::{Hash, Hasher};
9use std::io::{BufReader, BufWriter, Write}; 7use std::io::{BufReader, BufWriter, Write as _};
10use std::path::{Path, PathBuf};
11use std::process; 8use std::process;
12use std::str::FromStr;
13 9
14use clap::Parser; 10use clap::Parser;
15use matrix_sdk::EncryptionState; 11use matrix_sdk::EncryptionState;
16use matrix_sdk::authentication::matrix::MatrixSession; 12use matrix_sdk::authentication::matrix::MatrixSession;
17use matrix_sdk::media::MediaRetentionPolicy; 13use matrix_sdk::media::MediaRetentionPolicy;
18use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue}; 14use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
19use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; 15use matrix_sdk::ruma::OwnedDeviceId;
20use ratatui::layout::Size; 16use modalkit::env::vim::VimMode;
21use ratatui::style::{Color, Modifier as StyleModifier, Style}; 17use modalkit::keybindings::InputKey;
22use ratatui::text::Span;
23use ratatui_image::FilterType; 18use ratatui_image::FilterType;
24use ratatui_image::picker::ProtocolType; 19use ratatui_image::picker::ProtocolType;
25use serde::{Deserialize, Deserializer, Serialize, de::Error as SerdeError, de::Visitor}; 20use serde::de::Error as SerdeError;
26use url::Url; 21use serde::de::Visitor;
22use serde::{Deserialize, Deserializer, Serialize};
27 23
28use modalkit::env::vim::VimMode; 24use crate::base::{SortColumn, SortFieldRoom, SortFieldUser, SortOrder};
29use modalkit::key::TerminalKey; 25use crate::prelude::*;
30use modalkit::keybindings::InputKey;
31use modalkit::prelude::Axis;
32
33use super::base::{
34 IambError,
35 IambId,
36 RoomInfo,
37 SortColumn,
38 SortFieldRoom,
39 SortFieldUser,
40 SortOrder,
41};
42 26
43type Macros = HashMap<VimModes, HashMap<Keys, Keys>>; 27type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
44 28
@@ -1426,9 +1410,11 @@ impl ApplicationSettings {
1426#[cfg(test)] 1410#[cfg(test)]
1427mod tests { 1411mod tests {
1428 use super::*; 1412 use super::*;
1429 use matrix_sdk::ruma::user_id; 1413
1430 use std::convert::TryFrom; 1414 use std::convert::TryFrom;
1431 1415
1416 use matrix_sdk::ruma::user_id;
1417
1432 #[test] 1418 #[test]
1433 fn test_profile_name_invalid() { 1419 fn test_profile_name_invalid() {
1434 assert_eq!(validate_profile_name(""), false); 1420 assert_eq!(validate_profile_name(""), false);
src/keybindings.rs +9 −12
@@ -2,18 +2,15 @@
2//! 2//!
3//! The keybindings are set up here. We define some iamb-specific keybindings, but the default Vim 3//! The keybindings are set up here. We define some iamb-specific keybindings, but the default Vim
4//! keys come from [modalkit::env::vim::keybindings]. 4//! keys come from [modalkit::env::vim::keybindings].
5use modalkit::{ 5use modalkit::actions::MacroAction;
6 actions::{InsertTextAction, MacroAction, WindowAction}, 6use modalkit::env::CommonKeyClass;
7 env::CommonKeyClass, 7use modalkit::env::vim::VimMode;
8 env::vim::VimMode, 8use modalkit::env::vim::keybindings::{InputStep, VimBindings};
9 env::vim::keybindings::{InputStep, VimBindings}, 9use modalkit::keybindings::{EdgeEvent, EdgeRepeat, InputBindings};
10 key::TerminalKey, 10
11 keybindings::{EdgeEvent, EdgeRepeat, InputBindings}, 11use crate::base::{Keybindings, MATRIX_ID_WORD};
12 prelude::*, 12use crate::config::{Keys, SplitDirection};
13}; 13use crate::prelude::*;
14
15use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
16use crate::config::{ApplicationSettings, Keys, SplitDirection};
17 14
18pub type IambStep = InputStep<IambInfo>; 15pub type IambStep = InputStep<IambInfo>;
19 16
src/main.rs +45 −102
@@ -16,61 +16,60 @@
16#![allow(clippy::needless_return)] 16#![allow(clippy::needless_return)]
17#![allow(clippy::result_large_err)] 17#![allow(clippy::result_large_err)]
18#![allow(clippy::bool_assert_comparison)] 18#![allow(clippy::bool_assert_comparison)]
19
19use std::collections::VecDeque; 20use std::collections::VecDeque;
20use std::convert::TryFrom;
21use std::fmt::Display;
22use std::fs::{File, create_dir_all}; 21use std::fs::{File, create_dir_all};
23use std::io::{BufWriter, Stdout, Write, stdout}; 22use std::io::{BufWriter, Stdout, Write, stdout};
24use std::ops::DerefMut;
25use std::process; 23use std::process;
26use std::sync::Arc; 24use std::sync::atomic::AtomicUsize;
27use std::sync::atomic::{AtomicUsize, Ordering};
28use std::time::{Duration, Instant};
29 25
30use clap::{CommandFactory, Parser}; 26use clap::{CommandFactory, Parser};
31use matrix_sdk::ruma::UserId;
32use matrix_sdk::ruma::api::error::ErrorKind; 27use matrix_sdk::ruma::api::error::ErrorKind;
33use matrix_sdk::ruma::profile::{ProfileFieldName, ProfileFieldValue};
34use matrix_sdk_crypto::encrypt_room_key_export; 28use matrix_sdk_crypto::encrypt_room_key_export;
35use modalkit::keybindings::InputBindings; 29use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer};
30use modalkit::crossterm::cursor::{SetCursorStyle, Show as CursorShow};
31use modalkit::crossterm::event::{
32 DisableBracketedPaste,
33 DisableFocusChange,
34 DisableMouseCapture,
35 EnableBracketedPaste,
36 EnableFocusChange,
37 EnableMouseCapture,
38 Event,
39 KeyEventKind,
40 KeyboardEnhancementFlags,
41 MouseEventKind,
42 PopKeyboardEnhancementFlags,
43 PushKeyboardEnhancementFlags,
44 poll,
45 read,
46};
47use modalkit::crossterm::terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle};
48use modalkit::crossterm::{self, execute};
49use modalkit::editing::key::KeyManager;
50use modalkit::editing::store::Store;
51use modalkit::keybindings::dialog::Pager;
52use modalkit::keybindings::{BindingMachine, InputBindings};
53use modalkit::ui::FocusList;
54use modalkit_ratatui::cmdbar::CommandBarState;
55use modalkit_ratatui::screen::{Screen, ScreenState, TabbedLayoutDescription};
56use modalkit_ratatui::windows::{WindowLayoutDescription, WindowLayoutState};
57use modalkit_ratatui::{TerminalExtOps, Window};
36use rand::RngExt as _; 58use rand::RngExt as _;
37use rand::distr::Alphanumeric; 59use rand::distr::Alphanumeric;
60use ratatui::Terminal;
61use ratatui::backend::CrosstermBackend;
38use temp_dir::TempDir; 62use temp_dir::TempDir;
39use tokio::sync::Mutex as AsyncMutex; 63use tokio::sync::Mutex as AsyncMutex;
40use tracing::Level; 64use tracing::Level;
41use tracing_subscriber::{EnvFilter, FmtSubscriber}; 65use tracing_subscriber::{EnvFilter, FmtSubscriber};
42 66
43use modalkit::crossterm::{ 67use crate::base::{HomeserverAction, KeysAction};
44 self, 68use crate::completions::IambCompleter;
45 cursor::{SetCursorStyle, Show as CursorShow}, 69use crate::config::Iamb;
46 event::{ 70use crate::prelude::*;
47 DisableBracketedPaste, 71use crate::windows::IambWindow;
48 DisableFocusChange, 72use crate::worker::{ClientWorker, LoginStyle, create_room};
49 DisableMouseCapture,
50 EnableBracketedPaste,
51 EnableFocusChange,
52 EnableMouseCapture,
53 Event,
54 KeyEventKind,
55 KeyboardEnhancementFlags,
56 MouseEventKind,
57 PopKeyboardEnhancementFlags,
58 PushKeyboardEnhancementFlags,
59 poll,
60 read,
61 },
62 execute,
63 terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
64};
65
66use ratatui::{
67 Terminal,
68 backend::CrosstermBackend,
69 layout::Rect,
70 style::{Color, Modifier, Style},
71 text::Span,
72 widgets::Paragraph,
73};
74 73
75mod base; 74mod base;
76mod commands; 75mod commands;
@@ -79,72 +78,16 @@ mod config;
79mod keybindings; 78mod keybindings;
80mod message; 79mod message;
81mod notifications; 80mod notifications;
81mod prelude;
82mod preview; 82mod preview;
83mod sled_export; 83mod sled_export;
84mod util; 84mod util;
85mod verifications;
85mod windows; 86mod windows;
86mod worker; 87mod worker;
87 88
88#[cfg(test)] 89#[cfg(test)]
89mod tests; 90mod tests;
90mod verifications;
91
92use crate::{
93 base::{
94 AsyncProgramStore,
95 ChatStore,
96 HomeserverAction,
97 IambAction,
98 IambError,
99 IambId,
100 IambInfo,
101 IambResult,
102 KeysAction,
103 ProgramAction,
104 ProgramContext,
105 ProgramStore,
106 },
107 completions::IambCompleter,
108 config::{ApplicationSettings, Iamb},
109 windows::IambWindow,
110 worker::{ClientWorker, LoginStyle, Requester, create_room},
111};
112
113use modalkit::{
114 actions::{
115 Action,
116 Commandable,
117 Editable,
118 EditorAction,
119 InsertTextAction,
120 Jumpable,
121 Promptable,
122 Scrollable,
123 TabAction,
124 TabContainer,
125 TabCount,
126 WindowAction,
127 WindowContainer,
128 },
129 editing::{context::Resolve, key::KeyManager, store::Store},
130 errors::{EditError, UIError},
131 key::TerminalKey,
132 keybindings::{
133 BindingMachine,
134 dialog::{Pager, PromptYesNo},
135 },
136 prelude::*,
137 ui::FocusList,
138};
139
140use modalkit_ratatui::{
141 TerminalCursor,
142 TerminalExtOps,
143 Window,
144 cmdbar::CommandBarState,
145 screen::{Screen, ScreenState, TabbedLayoutDescription},
146 windows::{WindowLayoutDescription, WindowLayoutState},
147};
148 91
149fn config_tab_to_desc( 92fn config_tab_to_desc(
150 layout: config::WindowLayout, 93 layout: config::WindowLayout,
@@ -334,9 +277,9 @@ impl Application {
334 .show_dialog(dialogstr) 277 .show_dialog(dialogstr)
335 .show_mode(modestr) 278 .show_mode(modestr)
336 .borders(true) 279 .borders(true)
337 .border_style(Style::default().add_modifier(Modifier::DIM)) 280 .border_style(Style::default().add_modifier(StyleModifier::DIM))
338 .tab_style(Style::default().add_modifier(Modifier::DIM)) 281 .tab_style(Style::default().add_modifier(StyleModifier::DIM))
339 .tab_style_focused(Style::default().remove_modifier(Modifier::DIM)) 282 .tab_style_focused(Style::default().remove_modifier(StyleModifier::DIM))
340 .focus(focused); 283 .focus(focused);
341 f.render_stateful_widget(screen, area, sstate); 284 f.render_stateful_widget(screen, area, sstate);
342 285
@@ -1225,7 +1168,7 @@ fn main() {
1225 .worker_threads(2) 1168 .worker_threads(2)
1226 .thread_name_fn(|| { 1169 .thread_name_fn(|| {
1227 static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0); 1170 static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
1228 let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst); 1171 let id = ATOMIC_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1229 format!("iamb-worker-{id}") 1172 format!("iamb-worker-{id}")
1230 }) 1173 })
1231 .build() 1174 .build()
src/message/compose.rs +10 −16
@@ -1,22 +1,16 @@
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}; 2
3use nom::{ 3use comrak::markdown_to_html;
4 IResult, 4use comrak::options::Options;
5 Parser as _, 5use matrix_sdk::ruma::events::room::message::{EmoteMessageEventContent, TextMessageEventContent};
6 branch::alt, 6use nom::branch::alt;
7 bytes::complete::tag, 7use nom::bytes::complete::tag;
8 character::complete::space0, 8use nom::character::complete::space0;
9 combinator::value, 9use nom::combinator::value;
10}; 10use nom::{IResult, Parser as _};
11
12use matrix_sdk::ruma::events::room::message::{
13 EmoteMessageEventContent,
14 MessageType,
15 RoomMessageEventContent,
16 TextMessageEventContent,
17};
18 11
19use crate::config::MarkupFormat; 12use crate::config::MarkupFormat;
13use crate::prelude::*;
20 14
21#[derive(Clone, Debug, Default)] 15#[derive(Clone, Debug, Default)]
22enum SlashCommand { 16enum SlashCommand {
src/message/html.rs +13 −28
@@ -10,35 +10,18 @@
10//! 10//!
11//! This isn't as important for iamb, since it isn't a browser environment, but we do still map 11//! This isn't as important for iamb, since it isn't a browser environment, but we do still map
12//! input onto an enum of the safe list of tags to keep it easy to understand and process. 12//! input onto an enum of the safe list of tags to keep it easy to understand and process.
13use std::borrow::Cow;
14use std::ops::Deref;
15 13
16use css_color_parser::Color as CssColor; 14use css_color_parser::Color as CssColor;
15use html5ever::driver::{ParseOpts, parse_fragment};
16use html5ever::interface::{Attribute, QualName};
17use html5ever::tendril::{StrTendril, TendrilSink};
18use html5ever::{local_name, ns};
17use markup5ever_rcdom::{Handle, NodeData, RcDom}; 19use markup5ever_rcdom::{Handle, NodeData, RcDom};
18use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId}; 20use ratatui::symbols::line;
19use unicode_segmentation::UnicodeSegmentation; 21
20use url::Url; 22use crate::message::printer::TextPrinter;
21 23use crate::prelude::*;
22use html5ever::{ 24use crate::util::{join_cell_text, space_text};
23 driver::{ParseOpts, parse_fragment},
24 interface::{Attribute, QualName},
25 local_name,
26 ns,
27 tendril::{StrTendril, TendrilSink},
28};
29
30use ratatui::{
31 layout::Alignment,
32 style::{Color, Modifier as StyleModifier, Style},
33 symbols::line,
34 text::{Line, Span, Text},
35};
36
37use crate::{
38 config::ApplicationSettings,
39 message::printer::TextPrinter,
40 util::{join_cell_text, space_text},
41};
42 25
43const QUOTE_COLOR: Color = Color::Indexed(236); 26const QUOTE_COLOR: Color = Color::Indexed(236);
44 27
@@ -844,11 +827,13 @@ pub fn parse_matrix_html(s: &str) -> StyleTree {
844#[cfg(test)] 827#[cfg(test)]
845pub mod tests { 828pub mod tests {
846 use super::*; 829 use super::*;
847 use crate::tests::mock_settings; 830
848 use crate::util::space_span;
849 use pretty_assertions::assert_eq; 831 use pretty_assertions::assert_eq;
850 use unicode_width::UnicodeWidthStr; 832 use unicode_width::UnicodeWidthStr;
851 833
834 use crate::tests::mock_settings;
835 use crate::util::space_span;
836
852 #[test] 837 #[test]
853 fn test_header() { 838 fn test_header() {
854 let settings = mock_settings(); 839 let settings = mock_settings();
src/message/mod.rs +36 −72
@@ -1,75 +1,41 @@
1//! # Room Messages 1//! # Room Messages
2use std::borrow::Cow; 2
3use std::cmp::{Ord, Ordering, PartialOrd}; 3use std::cmp::{Ord, PartialOrd};
4use std::collections::BTreeMap;
5use std::collections::hash_map::DefaultHasher; 4use std::collections::hash_map::DefaultHasher;
6use std::convert::{TryFrom, TryInto}; 5use std::convert::TryInto;
7use std::fmt::{self, Display};
8use std::hash::{Hash, Hasher}; 6use std::hash::{Hash, Hasher};
9use std::ops::{Deref, DerefMut};
10 7
11use chrono::{DateTime, Local as LocalTz}; 8use chrono::{DateTime, Local as LocalTz};
12use humansize::{DECIMAL, format_size}; 9use humansize::{DECIMAL, format_size};
13use matrix_sdk::ruma::OwnedTransactionId; 10use matrix_sdk::ruma::OwnedTransactionId;
14use matrix_sdk::ruma::events::receipt::ReceiptThread; 11use matrix_sdk::ruma::UInt;
15use matrix_sdk::ruma::events::room::MediaSource; 12use matrix_sdk::ruma::events::RedactedUnsigned;
13use matrix_sdk::ruma::events::room::encrypted::{
14 OriginalRoomEncryptedEvent,
15 RedactedRoomEncryptedEvent,
16 RoomEncryptedEvent,
17};
16use matrix_sdk::ruma::events::room::message::RoomMessageEventContentWithoutRelation; 18use matrix_sdk::ruma::events::room::message::RoomMessageEventContentWithoutRelation;
19use matrix_sdk::ruma::events::room::message::{
20 FormattedBody,
21 MessageFormat,
22 RedactedRoomMessageEvent,
23 RoomMessageEvent,
24};
25use matrix_sdk::ruma::events::room::redaction::SyncRoomRedactionEvent;
17use matrix_sdk::ruma::events::sticker::{OriginalStickerEvent, RedactedStickerEvent, StickerEvent}; 26use matrix_sdk::ruma::events::sticker::{OriginalStickerEvent, RedactedStickerEvent, StickerEvent};
18use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; 27use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent};
19use matrix_sdk::send_queue::SendHandle; 28use matrix_sdk::send_queue::SendHandle;
20use ratatui::layout::Size;
21use ratatui::style::Color;
22use ratatui_image::sliced::SlicedProtocol;
23use unicode_width::UnicodeWidthStr;
24
25use matrix_sdk::ruma::{
26 EventId,
27 MilliSecondsSinceUnixEpoch,
28 OwnedEventId,
29 OwnedUserId,
30 UInt,
31 events::{
32 AnySyncStateEvent,
33 RedactedUnsigned,
34 relation::Thread,
35 room::{
36 encrypted::{
37 OriginalRoomEncryptedEvent,
38 RedactedRoomEncryptedEvent,
39 RoomEncryptedEvent,
40 },
41 message::{
42 FormattedBody,
43 MessageFormat,
44 MessageType,
45 OriginalRoomMessageEvent,
46 RedactedRoomMessageEvent,
47 Relation,
48 RoomMessageEvent,
49 RoomMessageEventContent,
50 },
51 redaction::SyncRoomRedactionEvent,
52 },
53 },
54};
55
56use ratatui::{
57 style::{Modifier as StyleModifier, Style},
58 symbols::line::THICK_VERTICAL,
59 text::{Line, Span, Text},
60};
61
62use modalkit::editing::cursor::Cursor; 29use modalkit::editing::cursor::Cursor;
63use modalkit::prelude::*; 30use ratatui::symbols::line::THICK_VERTICAL;
31use ratatui_image::sliced::SlicedProtocol;
64 32
65use crate::base::MessageEdits; 33use crate::base::MessageEdits;
66use crate::preview::{ImageStatus, PreviewKind, PreviewManager}; 34use crate::message::html::{StyleTree, parse_matrix_html};
67use crate::{ 35use crate::message::state::{body_cow_state, html_state};
68 base::RoomInfo, 36use crate::prelude::*;
69 config::ApplicationSettings, 37use crate::preview::ImageStatus;
70 message::html::{StyleTree, parse_matrix_html}, 38use crate::util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text};
71 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
72};
73 39
74mod compose; 40mod compose;
75mod html; 41mod html;
@@ -77,8 +43,7 @@ mod printer;
77mod state; 43mod state;
78 44
79pub use self::compose::{text_to_message, text_to_text_message_event_content}; 45pub use self::compose::{text_to_message, text_to_text_message_event_content};
80use self::state::{body_cow_state, html_state}; 46pub use self::html::TreeGenState;
81pub use html::TreeGenState;
82 47
83type ProtocolPreview<'a> = (&'a SlicedProtocol, u16, u16); 48type ProtocolPreview<'a> = (&'a SlicedProtocol, u16, u16);
84 49
@@ -1473,20 +1438,19 @@ impl Display for Message {
1473 1438
1474#[cfg(test)] 1439#[cfg(test)]
1475pub mod tests { 1440pub mod tests {
1476 use matrix_sdk::ruma::events::room::{ 1441 use super::*;
1477 ImageInfo, 1442
1478 message::{ 1443 use matrix_sdk::ruma::events::room::ImageInfo;
1479 AudioInfo, 1444 use matrix_sdk::ruma::events::room::message::{
1480 AudioMessageEventContent, 1445 AudioInfo,
1481 FileInfo, 1446 AudioMessageEventContent,
1482 FileMessageEventContent, 1447 FileInfo,
1483 ImageMessageEventContent, 1448 FileMessageEventContent,
1484 VideoInfo, 1449 ImageMessageEventContent,
1485 VideoMessageEventContent, 1450 VideoInfo,
1486 }, 1451 VideoMessageEventContent,
1487 }; 1452 };
1488 1453
1489 use super::*;
1490 use crate::tests::*; 1454 use crate::tests::*;
1491 1455
1492 #[test] 1456 #[test]
src/message/printer.rs +3 −8
@@ -3,15 +3,9 @@
3//! The [TextPrinter] handles wrapping stylized text and inserting spaces for padding at the end of 3//! The [TextPrinter] handles wrapping stylized text and inserting spaces for padding at the end of
4//! lines to make concatenation work right (e.g., combining table cells after wrapping their 4//! lines to make concatenation work right (e.g., combining table cells after wrapping their
5//! contents). 5//! contents).
6use std::borrow::Cow;
7 6
8use ratatui::layout::Alignment; 7use crate::config::TunableValues;
9use ratatui::style::Style; 8use crate::prelude::*;
10use ratatui::text::{Line, Span, Text};
11use unicode_segmentation::UnicodeSegmentation;
12use unicode_width::UnicodeWidthStr;
13
14use crate::config::{ApplicationSettings, TunableValues};
15use crate::util::{ 9use crate::util::{
16 replace_emojis_in_line, 10 replace_emojis_in_line,
17 replace_emojis_in_span, 11 replace_emojis_in_span,
@@ -295,6 +289,7 @@ impl<'a> TextPrinter<'a> {
295#[cfg(test)] 289#[cfg(test)]
296pub mod tests { 290pub mod tests {
297 use super::*; 291 use super::*;
292
298 use crate::tests::mock_settings; 293 use crate::tests::mock_settings;
299 294
300 #[test] 295 #[test]
src/message/state.rs +6 −16
@@ -1,20 +1,10 @@
1//! Code for displaying state events. 1//! Code for displaying state events.
2use std::borrow::Cow; 2
3use std::str::FromStr; 3use matrix_sdk::ruma::events::room::member::MembershipChange;
4 4use matrix_sdk::ruma::events::{AnyStateEventContentChange, StateEventContentChange};
5use matrix_sdk::ruma::{ 5
6 OwnedRoomId, 6use crate::message::html::{StyleTree, StyleTreeNode};
7 UserId, 7use crate::prelude::*;
8 events::{
9 AnyStateEventContentChange,
10 AnySyncStateEvent,
11 StateEventContentChange,
12 room::member::MembershipChange,
13 },
14};
15
16use super::html::{StyleTree, StyleTreeNode};
17use ratatui::style::{Modifier as StyleModifier, Style};
18 8
19fn bold(s: impl Into<Cow<'static, str>>) -> StyleTreeNode { 9fn bold(s: impl Into<Cow<'static, str>>) -> StyleTreeNode {
20 let bold = Style::default().add_modifier(StyleModifier::BOLD); 10 let bold = Style::default().add_modifier(StyleModifier::BOLD);
src/notifications.rs +11 −18
@@ -1,25 +1,18 @@
1use std::time::SystemTime; 1use std::time::SystemTime;
2 2
3use matrix_sdk::{ 3use matrix_sdk::EncryptionState;
4 Client, 4use matrix_sdk::deserialized_responses::RawAnySyncOrStrippedTimelineEvent;
5 EncryptionState, 5use matrix_sdk::notification_settings::{
6 deserialized_responses::RawAnySyncOrStrippedTimelineEvent, 6 IsEncrypted,
7 notification_settings::{IsEncrypted, IsOneToOne, NotificationSettings, RoomNotificationMode}, 7 IsOneToOne,
8 room::Room as MatrixRoom, 8 NotificationSettings,
9 ruma::{ 9 RoomNotificationMode,
10 MilliSecondsSinceUnixEpoch,
11 OwnedRoomId,
12 RoomId,
13 events::{AnyMessageLikeEventContent, AnySyncTimelineEvent, room::message::MessageType},
14 serde::Raw,
15 },
16}; 10};
17use unicode_segmentation::UnicodeSegmentation; 11use matrix_sdk::ruma::events::{AnyMessageLikeEventContent, AnySyncTimelineEvent};
12use matrix_sdk::ruma::serde::Raw;
18 13
19use crate::{ 14use crate::config::NotifyVia;
20 base::{AsyncProgramStore, IambError, IambResult, ProgramStore}, 15use crate::prelude::*;
21 config::{ApplicationSettings, NotifyVia},
22};
23 16
24const IAMB_XDG_NAME: &str = match option_env!("IAMB_XDG_NAME") { 17const IAMB_XDG_NAME: &str = match option_env!("IAMB_XDG_NAME") {
25 None => "iamb", 18 None => "iamb",
src/prelude.rs added +90
@@ -0,0 +1,90 @@
1pub use std::borrow::Cow;
2pub use std::cmp::Ordering;
3pub use std::collections::{BTreeMap, HashMap};
4pub use std::convert::TryFrom;
5pub use std::fmt::{self, Display};
6pub use std::ops::{Deref, DerefMut};
7pub use std::path::{Path, PathBuf};
8pub use std::str::FromStr;
9pub use std::sync::Arc;
10pub use std::time::{Duration, Instant};
11
12pub use matrix_sdk::ruma::events::AnySyncStateEvent;
13pub use matrix_sdk::ruma::events::receipt::ReceiptThread;
14pub use matrix_sdk::ruma::events::relation::Thread;
15pub use matrix_sdk::ruma::events::room::MediaSource;
16pub use matrix_sdk::ruma::events::room::message::{
17 MessageType,
18 OriginalRoomMessageEvent,
19 Relation,
20 RoomMessageEventContent,
21};
22pub use matrix_sdk::ruma::events::tag::{TagName, Tags};
23pub use matrix_sdk::ruma::{
24 EventId,
25 MilliSecondsSinceUnixEpoch,
26 OwnedEventId,
27 OwnedRoomAliasId,
28 OwnedRoomId,
29 OwnedRoomOrAliasId,
30 OwnedUserId,
31 RoomId,
32 UserId,
33 profile::{ProfileFieldName, ProfileFieldValue},
34 room::JoinRule,
35};
36pub use matrix_sdk::{
37 Client,
38 RoomState as MatrixRoomState,
39 encryption::verification::VerificationRequest,
40 room::Room as MatrixRoom,
41};
42pub use modalkit::actions::{
43 Action,
44 Editable,
45 EditorAction,
46 InsertTextAction,
47 Jumpable,
48 PromptAction,
49 Promptable,
50 Scrollable,
51 WindowAction,
52};
53pub use modalkit::editing::{completion::CompletionList, context::Resolve, rope::EditRope};
54pub use modalkit::errors::{EditError, EditResult, UIError};
55pub use modalkit::key::TerminalKey;
56pub use modalkit::keybindings::dialog::PromptYesNo;
57pub use modalkit::prelude::*;
58pub use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
59pub use ratatui::buffer::Buffer;
60pub use ratatui::layout::{Alignment, Rect, Size};
61pub use ratatui::style::{Color, Modifier as StyleModifier, Style};
62pub use ratatui::text::{Line, Span, Text};
63pub use ratatui::widgets::{Paragraph, StatefulWidget, Widget};
64pub use unicode_segmentation::UnicodeSegmentation;
65pub use unicode_width::UnicodeWidthStr;
66pub use url::Url;
67
68pub use crate::base::{
69 AsyncProgramStore,
70 ChatStore,
71 IambAction,
72 IambBufferId,
73 IambError,
74 IambId,
75 IambInfo,
76 IambResult,
77 MessageAction,
78 ProgramAction,
79 ProgramContext,
80 ProgramStore,
81 RoomAction,
82 RoomFocus,
83 RoomInfo,
84 SendAction,
85 SpaceAction,
86};
87pub use crate::config::ApplicationSettings;
88pub use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages};
89pub use crate::preview::{PreviewKind, PreviewManager};
90pub use crate::worker::Requester;
src/preview.rs +6 −14
@@ -1,20 +1,12 @@
1use std::{collections::HashMap, sync::Arc}; 1use matrix_sdk::Media;
2 2use matrix_sdk::media::{MediaFormat, MediaRequestParameters, UniqueKey};
3use matrix_sdk::{ 3use ratatui_image::picker::Picker;
4 Media,
5 media::{MediaFormat, MediaRequestParameters, UniqueKey},
6 ruma::events::room::MediaSource,
7};
8use ratatui::layout::Size;
9use ratatui_image::sliced::SlicedProtocol; 4use ratatui_image::sliced::SlicedProtocol;
10use ratatui_image::{FilterType, Resize, picker::Picker}; 5use ratatui_image::{FilterType, Resize};
11use tokio::sync::Semaphore; 6use tokio::sync::Semaphore;
12 7
13use crate::{ 8use crate::config::ImagePreviewValues;
14 base::{AsyncProgramStore, IambError}, 9use crate::prelude::*;
15 config::{ApplicationSettings, ImagePreviewValues},
16 worker::Requester,
17};
18 10
19pub enum ImageStatus { 11pub enum ImageStatus {
20 Queued(Size), 12 Queued(Size),
src/sled_export.rs +3 −3
@@ -10,11 +10,11 @@
10//! time to upgrade off of pre-0.0.9 versions. 10//! time to upgrade off of pre-0.0.9 versions.
11//! 11//!
12//! [sled]: https://docs.rs/sled/0.34.7/sled/index.html 12//! [sled]: https://docs.rs/sled/0.34.7/sled/index.html
13use sled::{Config, IVec};
14use std::path::Path;
15 13
16use crate::base::IambError;
17use matrix_sdk_crypto::olm::{ExportedRoomKey, InboundGroupSession, PickledInboundGroupSession}; 14use matrix_sdk_crypto::olm::{ExportedRoomKey, InboundGroupSession, PickledInboundGroupSession};
15use sled::{Config, IVec};
16
17use crate::prelude::*;
18 18
19#[derive(Debug, thiserror::Error)] 19#[derive(Debug, thiserror::Error)]
20pub enum SledMigrationError { 20pub enum SledMigrationError {
src/tests.rs +6 −24
@@ -1,32 +1,14 @@
1use std::path::PathBuf; 1use std::iter::FromIterator as _;
2use std::{collections::HashMap, iter::FromIterator as _};
3
4use matrix_sdk::ruma::{
5 EventId,
6 OwnedEventId,
7 OwnedRoomId,
8 OwnedUserId,
9 RoomId,
10 UInt,
11 event_id,
12 events::room::message::RoomMessageEventContent,
13 server_name,
14 user_id,
15};
16use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, assign};
17 2
18use lazy_static::lazy_static; 3use lazy_static::lazy_static;
19use ratatui::style::{Color, Style}; 4use matrix_sdk::ruma::assign;
5use matrix_sdk::ruma::{UInt, event_id, server_name, user_id};
20use serde_json::{Map, Value}; 6use serde_json::{Map, Value};
21use tokio::sync::mpsc::unbounded_channel; 7use tokio::sync::mpsc::unbounded_channel;
22 8
23use crate::message::MessageTimeStamp; 9use crate::base::EventLocation;
24use crate::{ 10use crate::config::*;
25 base::{ChatStore, EventLocation, ProgramStore, RoomInfo}, 11use crate::prelude::*;
26 config::*,
27 message::{Message, MessageEvent, MessageKey, Messages},
28 worker::Requester,
29};
30 12
31const TEST_ROOM1_ALIAS: &str = "#room1:example.com"; 13const TEST_ROOM1_ALIAS: &str = "#room1:example.com";
32 14
src/util.rs +1 −5
@@ -1,12 +1,8 @@
1//! # Utility functions 1//! # Utility functions
2use std::borrow::Cow;
3 2
4use regex::{Regex, RegexBuilder}; 3use regex::{Regex, RegexBuilder};
5use unicode_segmentation::UnicodeSegmentation;
6use unicode_width::UnicodeWidthStr;
7 4
8use ratatui::style::Style; 5use crate::prelude::*;
9use ratatui::text::{Line, Span, Text};
10 6
11pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) { 7pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) {
12 match cow { 8 match cow {
src/verifications.rs +4 −10
@@ -1,15 +1,9 @@
1use matrix_sdk::Client; 1use matrix_sdk::encryption::verification::{Verification, VerificationRequestState};
2use matrix_sdk::encryption::verification::{ 2use matrix_sdk::ruma::OwnedDeviceId;
3 Verification,
4 VerificationRequest,
5 VerificationRequestState,
6};
7use matrix_sdk::ruma::events::key::verification::VerificationMethod; 3use matrix_sdk::ruma::events::key::verification::VerificationMethod;
8use matrix_sdk::ruma::{OwnedDeviceId, OwnedUserId, UserId};
9use modalkit::errors::UIError;
10use modalkit::prelude::{EditInfo, InfoMessage};
11 4
12use crate::base::{AsyncProgramStore, IambError, IambResult, ProgramStore, VerifyAction}; 5use crate::base::VerifyAction;
6use crate::prelude::*;
13 7
14const SUPPORTED_METHODS: [VerificationMethod; 3] = [ 8const SUPPORTED_METHODS: [VerificationMethod; 3] = [
15 // Emoji verification 9 // Emoji verification
src/windows/mod.rs +16 −77
@@ -6,84 +6,22 @@
6//! Additionally, some of the iamb commands delegate behaviour to the current UI element. For 6//! Additionally, some of the iamb commands delegate behaviour to the current UI element. For
7//! example, [sending messages][crate::base::SendAction] delegate to the [room window][RoomState], 7//! example, [sending messages][crate::base::SendAction] delegate to the [room window][RoomState],
8//! where we have the message bar and room ID easily accessible and resettable. 8//! where we have the message bar and room ID easily accessible and resettable.
9use std::cmp::{Ord, Ordering}; 9
10use std::fmt::{self, Display}; 10use std::cmp::Ord;
11use std::ops::Deref; 11use std::fmt::{self};
12use std::sync::Arc; 12
13use std::time::{Duration, Instant};
14
15use matrix_sdk::{
16 RoomState as MatrixRoomState,
17 room::{Room as MatrixRoom, RoomMember},
18 ruma::{
19 OwnedRoomAliasId,
20 OwnedRoomId,
21 RoomAliasId,
22 RoomId,
23 events::room::member::MembershipState,
24 events::tag::{TagName, Tags},
25 },
26};
27
28use ratatui::{
29 buffer::Buffer,
30 layout::{Alignment, Rect},
31 style::{Color, Modifier as StyleModifier, Style},
32 text::{Line, Span, Text},
33 widgets::StatefulWidget,
34};
35
36use modalkit::{
37 actions::{
38 Action,
39 Editable,
40 EditorAction,
41 Jumpable,
42 PromptAction,
43 Promptable,
44 Scrollable,
45 WindowAction,
46 },
47 editing::completion::CompletionList,
48 errors::{EditError, EditResult, UIError},
49 prelude::*,
50};
51
52use modalkit_ratatui::{
53 TermOffset,
54 TerminalCursor,
55 Window,
56 WindowOps,
57 list::{List, ListCursor, ListItem, ListState},
58};
59
60use crate::base::{
61 ChatStore,
62 IambBufferId,
63 IambError,
64 IambId,
65 IambInfo,
66 IambResult,
67 MessageAction,
68 ProgramAction,
69 ProgramContext,
70 ProgramStore,
71 RoomAction,
72 SendAction,
73 SortColumn,
74 SortFieldRoom,
75 SortFieldUser,
76 SortOrder,
77 SpaceAction,
78 UnreadInfo,
79};
80use crate::windows::room::room_command;
81
82use self::room::RoomState;
83use self::verify::VerifyItem;
84use self::welcome::WelcomeState;
85use crate::message::MessageTimeStamp;
86use feruca::Collator; 13use feruca::Collator;
14use matrix_sdk::room::RoomMember;
15use matrix_sdk::ruma::RoomAliasId;
16use matrix_sdk::ruma::events::room::member::MembershipState;
17use modalkit_ratatui::Window;
18use modalkit_ratatui::list::{List, ListCursor, ListItem, ListState};
19
20use crate::base::{SortColumn, SortFieldRoom, SortFieldUser, SortOrder, UnreadInfo};
21use crate::prelude::*;
22use crate::windows::room::{RoomState, room_command};
23use crate::windows::verify::VerifyItem;
24use crate::windows::welcome::WelcomeState;
87 25
88pub mod room; 26pub mod room;
89pub mod verify; 27pub mod verify;
@@ -1587,6 +1525,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1587#[cfg(test)] 1525#[cfg(test)]
1588mod tests { 1526mod tests {
1589 use super::*; 1527 use super::*;
1528
1590 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, room_alias_id, server_name}; 1529 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, room_alias_id, server_name};
1591 1530
1592 #[derive(Debug, Eq, PartialEq)] 1531 #[derive(Debug, Eq, PartialEq)]
src/windows/room/chat.rs +18 −87
@@ -1,106 +1,37 @@
1//! Window for Matrix rooms 1//! Window for Matrix rooms
2use std::borrow::Cow;
3use std::convert::TryInto; 2use std::convert::TryInto;
4use std::ffi::{OsStr, OsString}; 3use std::ffi::{OsStr, OsString};
5use std::fs; 4use std::fs;
6use std::path::{Path, PathBuf}; 5use std::process::Command;
7 6
8use edit::Builder; 7use edit::Builder;
9use edit::edit_with_builder as external_edit; 8use edit::edit_with_builder as external_edit;
9use matrix_sdk::RoomState as MatrixRoomState;
10use matrix_sdk::attachment::AttachmentConfig;
10use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo}; 11use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
12use matrix_sdk::media::{MediaFormat, MediaRequestParameters};
11use matrix_sdk::room::reply::{EnforceThread, Reply}; 13use matrix_sdk::room::reply::{EnforceThread, Reply};
14use matrix_sdk::ruma::events::reaction::ReactionEventContent;
15use matrix_sdk::ruma::events::relation::{Annotation, Replacement};
16use matrix_sdk::ruma::events::room::message::{AddMentions, ForwardThread, ReplyWithinThread};
17use matrix_sdk::send_queue::RoomSendQueueError;
18use modalkit::editing::history::{self, HistoryList};
12use modalkit::editing::store::RegisterError; 19use modalkit::editing::store::RegisterError;
13use std::process::Command; 20use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem};
14use tokio; 21use modalkit_ratatui::PromptActions;
15use url::Url; 22use modalkit_ratatui::textbox::{TextBox, TextBoxState};
16 23use ratatui::prelude::Stylize;
17use matrix_sdk::{
18 RoomState,
19 attachment::AttachmentConfig,
20 media::{MediaFormat, MediaRequestParameters},
21 room::Room as MatrixRoom,
22 ruma::{
23 OwnedEventId,
24 OwnedRoomId,
25 RoomId,
26 events::reaction::ReactionEventContent,
27 events::relation::{Annotation, Replacement},
28 events::room::message::{
29 AddMentions,
30 ForwardThread,
31 MessageType,
32 OriginalRoomMessageEvent,
33 Relation,
34 ReplyWithinThread,
35 },
36 },
37 send_queue::RoomSendQueueError,
38};
39
40use ratatui::{
41 buffer::Buffer,
42 layout::Rect,
43 prelude::Stylize,
44 text::{Line, Span},
45 widgets::{Paragraph, StatefulWidget, Widget},
46};
47
48use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem, PromptYesNo};
49 24
50use modalkit_ratatui::{ 25use crate::base::{DownloadFlags, EchoLocation};
51 PromptActions, 26use crate::config::EncryptionIndicatorLocation;
52 TerminalCursor,
53 WindowOps,
54 textbox::{TextBox, TextBoxState},
55};
56
57use modalkit::actions::{
58 Action,
59 Editable,
60 EditorAction,
61 Jumpable,
62 PromptAction,
63 Promptable,
64 Scrollable,
65};
66use modalkit::editing::{
67 completion::CompletionList,
68 context::Resolve,
69 history::{self, HistoryList},
70 rope::EditRope,
71};
72use modalkit::errors::{EditError, EditResult, UIError};
73use modalkit::prelude::*;
74
75use crate::base::{
76 DownloadFlags,
77 EchoLocation,
78 IambAction,
79 IambBufferId,
80 IambError,
81 IambInfo,
82 IambResult,
83 MessageAction,
84 ProgramAction,
85 ProgramContext,
86 ProgramStore,
87 RoomFocus,
88 RoomInfo,
89 SendAction,
90};
91
92use crate::config::{ApplicationSettings, EncryptionIndicatorLocation};
93use crate::message::{ 27use crate::message::{
94 MessageEvent,
95 MessageId, 28 MessageId,
96 MessageKey,
97 TreeGenState, 29 TreeGenState,
98 text_to_message, 30 text_to_message,
99 text_to_text_message_event_content, 31 text_to_text_message_event_content,
100}; 32};
101use crate::worker::Requester; 33use crate::prelude::*;
102 34use crate::windows::room::scrollback::{Scrollback, ScrollbackState};
103use super::scrollback::{Scrollback, ScrollbackState};
104 35
105/// State needed for rendering [Chat]. 36/// State needed for rendering [Chat].
106pub struct ChatState { 37pub struct ChatState {
@@ -151,7 +82,7 @@ impl ChatState {
151 return Err(IambError::NotJoined); 82 return Err(IambError::NotJoined);
152 }; 83 };
153 84
154 if room.state() == RoomState::Joined { 85 if room.state() == MatrixRoomState::Joined {
155 Ok(room) 86 Ok(room)
156 } else { 87 } else {
157 Err(IambError::NotJoined) 88 Err(IambError::NotJoined)
src/windows/room/mod.rs +16 −69
@@ -1,78 +1,25 @@
1//! # Windows for Matrix rooms and spaces 1//! # Windows for Matrix rooms and spaces
2use std::collections::HashSet; 2use std::collections::HashSet;
3 3
4use matrix_sdk::{ 4use matrix_sdk::RoomDisplayName;
5 RoomDisplayName, 5use matrix_sdk::notification_settings::RoomNotificationMode;
6 RoomState as MatrixRoomState, 6use matrix_sdk::ruma::api::client::room::upgrade_room::v3::Request as UpgradeRoomRequest;
7 notification_settings::RoomNotificationMode, 7use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind;
8 room::Room as MatrixRoom, 8use matrix_sdk::ruma::events::room::canonical_alias::RoomCanonicalAliasEventContent;
9 ruma::{ 9use matrix_sdk::ruma::events::room::history_visibility::{
10 OwnedEventId, 10 HistoryVisibility,
11 OwnedRoomAliasId, 11 RoomHistoryVisibilityEventContent,
12 OwnedUserId,
13 RoomId,
14 api::{
15 client::room::upgrade_room::v3::Request as UpgradeRoomRequest,
16 error::ErrorKind as ClientApiErrorKind,
17 },
18 events::{
19 room::{
20 canonical_alias::RoomCanonicalAliasEventContent,
21 history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
22 name::RoomNameEventContent,
23 topic::RoomTopicEventContent,
24 },
25 tag::{TagInfo, Tags},
26 },
27 room::{AllowRule, JoinRule, Restricted as JoinRestrictions},
28 },
29};
30
31use ratatui::{
32 buffer::Buffer,
33 layout::{Alignment, Rect},
34 style::{Modifier as StyleModifier, Style},
35 text::{Line, Span, Text},
36 widgets::{Paragraph, StatefulWidget, Widget},
37}; 12};
13use matrix_sdk::ruma::events::room::name::RoomNameEventContent;
14use matrix_sdk::ruma::events::room::topic::RoomTopicEventContent;
15use matrix_sdk::ruma::events::tag::TagInfo;
16use matrix_sdk::ruma::room::{AllowRule, Restricted as JoinRestrictions};
38 17
39use modalkit::actions::{ 18use crate::base::{MemberUpdateAction, RoomField};
40 Action,
41 Editable,
42 EditorAction,
43 Jumpable,
44 PromptAction,
45 Promptable,
46 Scrollable,
47 WindowAction,
48};
49use modalkit::errors::{EditResult, UIError};
50use modalkit::prelude::*;
51use modalkit::{editing::completion::CompletionList, keybindings::dialog::PromptYesNo};
52use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
53
54use crate::base::{
55 IambAction,
56 IambError,
57 IambId,
58 IambInfo,
59 IambResult,
60 MemberUpdateAction,
61 MessageAction,
62 ProgramAction,
63 ProgramContext,
64 ProgramStore,
65 RoomAction,
66 RoomField,
67 SendAction,
68 SpaceAction,
69};
70
71use self::chat::ChatState;
72use self::space::{Space, SpaceState};
73use crate::config::EncryptionIndicatorLocation; 19use crate::config::EncryptionIndicatorLocation;
74 20use crate::prelude::*;
75use std::convert::TryFrom; 21use crate::windows::room::chat::ChatState;
22use crate::windows::room::space::{Space, SpaceState};
76 23
77mod chat; 24mod chat;
78mod scrollback; 25mod scrollback;
src/windows/room/scrollback.rs +14 −51
@@ -1,62 +1,23 @@
1//! Message scrollback 1//! Message scrollback
2use ratatui_image::sliced::{SignedPosition, SlicedImage};
3use regex::Regex;
4
5use matrix_sdk::ruma::{OwnedEventId, OwnedRoomId};
6
7use modalkit_ratatui::{ScrollActions, TerminalCursor, WindowOps};
8use ratatui::{
9 buffer::Buffer,
10 layout::{Alignment, Rect},
11 style::{Modifier as StyleModifier, Style},
12 text::{Line, Span},
13 widgets::{Paragraph, StatefulWidget, Widget},
14};
15
16use modalkit::actions::{ 2use modalkit::actions::{
17 Action,
18 CursorAction, 3 CursorAction,
19 EditAction, 4 EditAction,
20 Editable,
21 EditorAction,
22 EditorActions, 5 EditorActions,
23 HistoryAction, 6 HistoryAction,
24 InsertTextAction,
25 Jumpable,
26 PromptAction,
27 Promptable,
28 Scrollable,
29 Searchable, 7 Searchable,
30 SelectionAction, 8 SelectionAction,
31 WindowAction,
32};
33use modalkit::editing::{
34 completion::CompletionList,
35 context::Resolve,
36 cursor::{CursorGroup, CursorState},
37 history::HistoryList,
38 rope::EditRope,
39 store::{RegisterCell, RegisterPutFlags},
40};
41use modalkit::errors::{EditError, EditResult, UIError, UIResult};
42use modalkit::prelude::*;
43
44use crate::{
45 base::{
46 IambBufferId,
47 IambId,
48 IambInfo,
49 IambResult,
50 ProgramContext,
51 ProgramStore,
52 RoomFetchStatus,
53 RoomFocus,
54 RoomInfo,
55 },
56 config::ApplicationSettings,
57 message::{Message, MessageCursor, MessageKey, Messages},
58 preview::{PreviewKind, PreviewManager},
59}; 9};
10use modalkit::editing::cursor::{CursorGroup, CursorState};
11use modalkit::editing::history::HistoryList;
12use modalkit::editing::store::{RegisterCell, RegisterPutFlags};
13use modalkit::errors::UIResult;
14use modalkit_ratatui::ScrollActions;
15use ratatui_image::sliced::{SignedPosition, SlicedImage};
16use regex::Regex;
17
18use crate::base::RoomFetchStatus;
19use crate::message::MessageCursor;
20use crate::prelude::*;
60 21
61fn no_msgs() -> EditError<IambInfo> { 22fn no_msgs() -> EditError<IambInfo> {
62 let msg = "No messages to select."; 23 let msg = "No messages to select.";
@@ -1535,7 +1496,9 @@ impl StatefulWidget for Scrollback<'_> {
1535#[cfg(test)] 1496#[cfg(test)]
1536mod tests { 1497mod tests {
1537 use super::*; 1498 use super::*;
1538 use crate::{base::Need, tests::*}; 1499
1500 use crate::base::Need;
1501 use crate::tests::*;
1539 1502
1540 #[tokio::test] 1503 #[tokio::test]
1541 async fn test_search_messages() { 1504 async fn test_search_messages() {
src/windows/room/space.rs +2 −34
@@ -1,43 +1,11 @@
1//! Window for Matrix spaces 1//! Window for Matrix spaces
2use std::ops::{Deref, DerefMut};
3use std::str::FromStr;
4use std::time::{Duration, Instant};
5 2
6use matrix_sdk::ruma::OwnedSpaceChildOrder; 3use matrix_sdk::ruma::OwnedSpaceChildOrder;
7use matrix_sdk::ruma::events::StateEventType; 4use matrix_sdk::ruma::events::StateEventType;
8use matrix_sdk::ruma::events::space::child::SpaceChildEventContent; 5use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
9use matrix_sdk::{ 6use modalkit_ratatui::list::{List, ListState};
10 room::Room as MatrixRoom,
11 ruma::{OwnedRoomId, RoomId},
12};
13
14use modalkit::prelude::{EditInfo, InfoMessage};
15use ratatui::{
16 buffer::Buffer,
17 layout::Rect,
18 style::{Color, Style},
19 text::{Line, Span, Text},
20 widgets::StatefulWidget,
21};
22
23use modalkit_ratatui::{
24 TermOffset,
25 TerminalCursor,
26 WindowOps,
27 list::{List, ListState},
28};
29
30use crate::base::{
31 IambBufferId,
32 IambError,
33 IambInfo,
34 IambResult,
35 ProgramContext,
36 ProgramStore,
37 RoomFocus,
38 SpaceAction,
39};
40 7
8use crate::prelude::*;
41use crate::windows::{RoomItem, RoomLikeItem, room_fields_cmp}; 9use crate::windows::{RoomItem, RoomLikeItem, room_fields_cmp};
42 10
43const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5); 11const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
src/windows/verify.rs +2 −15
@@ -1,23 +1,10 @@
1use std::cmp::Ordering; 1use matrix_sdk::encryption::verification::{Verification, VerificationRequestState};
2use std::fmt;
3
4use matrix_sdk::encryption::verification::{
5 Verification,
6 VerificationRequest,
7 VerificationRequestState,
8};
9use matrix_sdk::ruma::events::key::verification::VerificationMethod; 2use matrix_sdk::ruma::events::key::verification::VerificationMethod;
10use matrix_sdk_crypto::matrix_sdk_qrcode::qrcode::render::unicode::Dense1x2; 3use matrix_sdk_crypto::matrix_sdk_qrcode::qrcode::render::unicode::Dense1x2;
11use matrix_sdk_crypto::{QrVerificationState, SasState, format_emojis}; 4use matrix_sdk_crypto::{QrVerificationState, SasState, format_emojis};
12
13use modalkit::actions::{PromptAction, Promptable};
14use modalkit::errors::{EditError, EditResult};
15use modalkit::prelude::ViewportContext;
16use modalkit_ratatui::list::{ListCursor, ListItem}; 5use modalkit_ratatui::list::{ListCursor, ListItem};
17use ratatui::style::{Color, Modifier as StyleModifier, Style};
18use ratatui::text::{Line, Span, Text};
19 6
20use crate::base::{IambInfo, ProgramAction, ProgramContext, ProgramStore}; 7use crate::prelude::*;
21 8
22const BLACK_ON_WHITE: Style = Style::new().fg(Color::Black).bg(Color::White); 9const BLACK_ON_WHITE: Style = Style::new().fg(Color::Black).bg(Color::White);
23 10
src/windows/welcome.rs +2 −8
@@ -1,14 +1,8 @@
1//! Welcome Window 1//! Welcome Window
2use std::ops::{Deref, DerefMut};
3 2
4use ratatui::{buffer::Buffer, layout::Rect}; 3use modalkit_ratatui::textbox::TextBoxState;
5 4
6use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps, textbox::TextBoxState}; 5use crate::prelude::*;
7
8use modalkit::editing::completion::CompletionList;
9use modalkit::prelude::*;
10
11use crate::base::{IambBufferId, IambInfo, IambResult, ProgramStore};
12 6
13const WELCOME_TEXT: &str = include_str!("welcome.md"); 7const WELCOME_TEXT: &str = include_str!("welcome.md");
14 8
src/worker.rs +58 −92
@@ -2,116 +2,81 @@
2//! 2//!
3//! The worker thread handles asynchronous work, and can receive messages from the main thread that 3//! The worker thread handles asynchronous work, and can receive messages from the main thread that
4//! block on a reply from the async worker. 4//! block on a reply from the async worker.
5use std::collections::HashMap; 5
6use std::convert::TryFrom;
7use std::fmt::{Debug, Formatter}; 6use std::fmt::{Debug, Formatter};
8use std::ops::DerefMut;
9use std::str::FromStr;
10use std::sync::Arc;
11use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; 7use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
12use std::time::{Duration, Instant};
13 8
14use futures::{StreamExt, stream::FuturesUnordered}; 9use futures::StreamExt;
10use futures::stream::FuturesUnordered;
15use gethostname::gethostname; 11use gethostname::gethostname;
12use matrix_sdk::authentication::matrix::MatrixSession;
13use matrix_sdk::config::{RequestConfig, SyncSettings};
14use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings};
15use matrix_sdk::event_handler::Ctx;
16use matrix_sdk::room::{Messages as MatrixMessages, MessagesOptions, RoomMember};
17use matrix_sdk::ruma::api::client::filter::{
18 FilterDefinition,
19 LazyLoadOptions,
20 RoomEventFilter,
21 RoomFilter,
22};
23use matrix_sdk::ruma::api::client::room::Visibility;
24use matrix_sdk::ruma::api::client::room::create_room::v3::{
25 CreationContent,
26 Request as CreateRoomRequest,
27};
28use matrix_sdk::ruma::api::client::space::get_hierarchy::v1::Request as SpaceHierarchyRequest;
29use matrix_sdk::ruma::assign;
16use matrix_sdk::ruma::events::key::verification::ready::{ 30use matrix_sdk::ruma::events::key::verification::ready::{
17 OriginalSyncKeyVerificationReadyEvent, 31 OriginalSyncKeyVerificationReadyEvent,
18 ToDeviceKeyVerificationReadyEvent, 32 ToDeviceKeyVerificationReadyEvent,
19}; 33};
20use matrix_sdk_base::RoomStateFilter; 34use matrix_sdk::ruma::events::key::verification::request::ToDeviceKeyVerificationRequestEvent;
21use ratatui::layout::Size; 35use matrix_sdk::ruma::events::key::verification::start::{
22use ratatui_image::picker::Picker; 36 OriginalSyncKeyVerificationStartEvent,
23use tokio::sync::Semaphore; 37 ToDeviceKeyVerificationStartEvent,
24use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; 38};
25use tokio::task::JoinHandle; 39use matrix_sdk::ruma::events::presence::PresenceEvent;
26use tracing::{Instrument as _, error, warn}; 40use matrix_sdk::ruma::events::reaction::ReactionEventContent;
27use url::Url; 41use matrix_sdk::ruma::events::receipt::{ReceiptEventContent, ReceiptType};
28 42use matrix_sdk::ruma::events::room::encryption::RoomEncryptionEventContent;
43use matrix_sdk::ruma::events::room::member::OriginalSyncRoomMemberEvent;
44use matrix_sdk::ruma::events::room::name::RoomNameEventContent;
45use matrix_sdk::ruma::events::room::redaction::OriginalSyncRoomRedactionEvent;
46use matrix_sdk::ruma::events::sticker::StickerEventContent;
47use matrix_sdk::ruma::events::typing::SyncTypingEvent;
48use matrix_sdk::ruma::events::{
49 AnyMessageLikeEvent,
50 AnyMessageLikeEventContent,
51 AnyTimelineEvent,
52 InitialStateEvent,
53 SyncEphemeralRoomEvent,
54 SyncMessageLikeEvent,
55 SyncStateEvent,
56};
57use matrix_sdk::ruma::room::RoomType;
58use matrix_sdk::ruma::serde::Raw;
59use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate};
29use matrix_sdk::{ 60use matrix_sdk::{
30 Client,
31 ClientBuildError, 61 ClientBuildError,
32 Error as MatrixError, 62 Error as MatrixError,
33 RoomDisplayName, 63 RoomDisplayName,
34 RoomMemberships, 64 RoomMemberships,
35 authentication::matrix::MatrixSession,
36 config::{RequestConfig, SyncSettings},
37 encryption::{BackupDownloadStrategy, EncryptionSettings},
38 event_handler::Ctx,
39 reqwest, 65 reqwest,
40 room::{Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
41 ruma::{
42 EventId,
43 OwnedEventId,
44 OwnedRoomId,
45 OwnedRoomOrAliasId,
46 OwnedUserId,
47 RoomId,
48 api::client::{
49 filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
50 room::{
51 Visibility,
52 create_room::v3::{CreationContent, Request as CreateRoomRequest},
53 },
54 space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
55 },
56 assign,
57 events::{
58 AnyMessageLikeEvent,
59 AnyMessageLikeEventContent,
60 AnySyncStateEvent,
61 AnyTimelineEvent,
62 InitialStateEvent,
63 SyncEphemeralRoomEvent,
64 SyncMessageLikeEvent,
65 SyncStateEvent,
66 key::verification::{
67 request::ToDeviceKeyVerificationRequestEvent,
68 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
69 },
70 presence::PresenceEvent,
71 reaction::ReactionEventContent,
72 receipt::{ReceiptEventContent, ReceiptThread, ReceiptType},
73 relation::Thread,
74 room::{
75 MediaSource,
76 encryption::RoomEncryptionEventContent,
77 member::OriginalSyncRoomMemberEvent,
78 message::{MessageType, Relation, RoomMessageEventContent},
79 name::RoomNameEventContent,
80 redaction::OriginalSyncRoomRedactionEvent,
81 },
82 sticker::StickerEventContent,
83 tag::Tags,
84 typing::SyncTypingEvent,
85 },
86 room::RoomType,
87 serde::Raw,
88 },
89 send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate},
90}; 66};
67use matrix_sdk_base::RoomStateFilter;
68use ratatui_image::picker::Picker;
69use tokio::sync::Semaphore;
70use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
71use tokio::task::JoinHandle;
72use tracing::{Instrument as _, error, warn};
91 73
92use modalkit::errors::UIError; 74use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed, RoomFetchStatus};
93use modalkit::prelude::{EditInfo, InfoMessage};
94
95use crate::base::{EchoLocation, MessageNeed};
96use crate::config::ProxyUrl; 75use crate::config::ProxyUrl;
97use crate::message::{Message, MessageEvent, MessageId, MessageKey}; 76use crate::message::MessageId;
98use crate::notifications::register_notifications; 77use crate::notifications::register_notifications;
99use crate::preview::PreviewKind; 78use crate::prelude::*;
100use crate::verifications; 79use crate::verifications;
101use crate::{
102 ApplicationSettings,
103 base::{
104 AsyncProgramStore,
105 ChatStore,
106 CreateRoomFlags,
107 CreateRoomType,
108 IambError,
109 IambResult,
110 ProgramStore,
111 RoomFetchStatus,
112 RoomInfo,
113 },
114};
115 80
116const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings { 81const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings {
117 auto_enable_cross_signing: true, 82 auto_enable_cross_signing: true,
@@ -265,7 +230,8 @@ async fn load_older_one(
265 }; 230 };
266 opts.limit = limit.into(); 231 opts.limit = limit.into();
267 232
268 let Messages { end, chunk, .. } = room.messages(opts).await.map_err(IambError::from)?; 233 let MatrixMessages { end, chunk, .. } =
234 room.messages(opts).await.map_err(IambError::from)?;
269 235
270 let mut msgs = vec![]; 236 let mut msgs = vec![];
271 237