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:
3737 uses: mozilla-actions/sccache-action@v0.0.9
3838 - name: Check formatting
3939 run: cargo +nightly fmt --all -- --check
40 - name: Check imports formatting
41 run: find src -name '*.rs' | xargs ./.github/workflows/check-imports-format.sh
4042 - name: Check Clippy
4143 if: matrix.platform == 'ubuntu-latest'
4244 uses: giraffate/clippy-action@v1
src/base.rs +44 −106
@@ -1,112 +1,50 @@
11//! # Common types and utilities
22//!
33//! The types defined here get used throughout iamb.
4use std::borrow::Cow;
4
55use std::collections::hash_map::{Entry, IntoIter};
6use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
7use std::convert::TryFrom;
8use std::fmt::{self, Display};
9use std::hash::Hash;
10use std::sync::Arc;
11use std::time::{Duration, Instant};
6use std::collections::{BTreeSet, HashSet};
127
138use emojis::Emoji;
14
159use matrix_sdk::Client;
16use matrix_sdk::encryption::verification::VerificationRequest;
17use matrix_sdk::ruma::room::{AllowRule, Restricted};
18use ratatui::{
19 buffer::Buffer,
20 layout::{Alignment, Rect},
21 text::{Line, Span},
22 widgets::{Paragraph, Widget},
10use matrix_sdk::ruma::events::reaction::ReactionEvent;
11use matrix_sdk::ruma::events::relation::Replacement;
12use matrix_sdk::ruma::events::room::encrypted::RoomEncryptedEvent;
13use matrix_sdk::ruma::events::room::message::{
14 RoomMessageEvent,
15 RoomMessageEventContentWithoutRelation,
2316};
24use serde::{
25 Deserialize,
26 Deserializer,
27 Serialize,
28 Serializer,
29 de::Error as SerdeError,
30 de::Visitor,
17use matrix_sdk::ruma::events::room::redaction::{
18 OriginalSyncRoomRedactionEvent,
19 SyncRoomRedactionEvent,
3120};
32use tokio::sync::Mutex as AsyncMutex;
33use url::Url;
34
35use matrix_sdk::{
36 RoomState as MatrixRoomState,
37 room::Room as MatrixRoom,
38 ruma::{
39 EventId,
40 OwnedEventId,
41 OwnedMxcUri,
42 OwnedRoomAliasId,
43 OwnedRoomId,
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},
21use matrix_sdk::ruma::events::sticker::{StickerEvent, StickerEventContent};
22use matrix_sdk::ruma::events::{MessageLikeEvent, OriginalMessageLikeEvent};
23use matrix_sdk::ruma::presence::PresenceState;
24use matrix_sdk::ruma::room::{AllowRule, Restricted};
25use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId};
26use modalkit::editing::application::{
27 ApplicationAction,
28 ApplicationContentId,
29 ApplicationError,
30 ApplicationInfo,
31 ApplicationStore,
32 ApplicationWindowId,
10033};
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;
10145
102use crate::preview::PreviewKind;
103use crate::{
104 config::ApplicationSettings,
105 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
106 notifications::NotificationHandle,
107 preview::PreviewManager,
108 worker::Requester,
109};
46use crate::notifications::NotificationHandle;
47use crate::prelude::*;
11048
11149/// The set of characters used in different Matrix IDs.
11250pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
@@ -2307,20 +2245,20 @@ impl ApplicationInfo for IambInfo {
23072245
23082246#[cfg(test)]
23092247pub mod tests {
2248 use super::*;
2249
23102250 use std::iter::FromIterator as _;
23112251
2312 use super::*;
2313 use crate::config::user_style_from_color;
2314 use crate::tests::*;
2315 use matrix_sdk::ruma::{
2316 MilliSecondsSinceUnixEpoch,
2317 events::{reaction::ReactionEventContent, relation::Annotation},
2318 owned_event_id,
2319 };
2252 use matrix_sdk::ruma::events::reaction::ReactionEventContent;
2253 use matrix_sdk::ruma::events::relation::Annotation;
2254 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, owned_event_id};
23202255 use pretty_assertions::assert_eq;
23212256 use ratatui::style::Color;
23222257 use serde_json::{Map, Value};
23232258
2259 use crate::config::user_style_from_color;
2260 use crate::tests::*;
2261
23242262 fn create_reaction_event(
23252263 content: &ReactionEventContent,
23262264 event_id: &str,
src/commands.rs +5 −21
@@ -2,42 +2,25 @@
22//!
33//! The command-bar commands are set up here, and iamb-specific commands are defined here. See
44//! [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};
155
16use modalkit::{
17 commands::{CommandError, CommandResult, CommandStep},
18 env::vim::command::{CommandContext, CommandDescription, OptionType},
19 prelude::{MoveDir1D, OpenTarget},
20};
6use matrix_sdk::ruma::{OwnedMxcUri, RoomVersionId};
7use modalkit::commands::{CommandError, CommandResult, CommandStep};
8use modalkit::env::vim::command::{CommandContext, CommandDescription, OptionType};
219
2210use crate::base::{
2311 CreateRoomFlags,
2412 CreateRoomType,
2513 DownloadFlags,
2614 HomeserverAction,
27 IambAction,
28 IambId,
2915 IambJoinRule,
3016 KeysAction,
3117 MemberUpdateAction,
32 MessageAction,
3318 ProgramCommand,
3419 ProgramCommands,
35 RoomAction,
3620 RoomField,
37 SendAction,
38 SpaceAction,
3921 VerifyAction,
4022};
23use crate::prelude::*;
4124
4225type ProgContext = CommandContext;
4326type ProgResult = CommandResult<ProgramCommand>;
@@ -1156,6 +1139,7 @@ pub fn setup_commands() -> ProgramCommands {
11561139#[cfg(test)]
11571140mod tests {
11581141 use super::*;
1142
11591143 use matrix_sdk::ruma::{owned_room_id, user_id};
11601144 use modalkit::actions::WindowAction;
11611145 use modalkit::editing::context::EditContext;
src/completions.rs +20 −39
@@ -1,39 +1,19 @@
11//! Tab completions for iamb
2use std::borrow::Cow;
3use std::str::FromStr;
4
5use modalkit::{
6 editing::{
7 completion::{Completer, complete_path},
8 cursor::Cursor,
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};
2
3use modalkit::editing::completion::{Completer, complete_path};
4use modalkit::editing::cursor::Cursor;
5use modalkit::env::vim::command::CommandDescription;
6
7use crate::base::MATRIX_ID_WORD;
8use crate::prelude::*;
249
2510mod parse {
26 use nom::{
27 IResult,
28 Input,
29 OutputMode,
30 Parser,
31 branch::alt,
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 };
11 use nom::branch::alt;
12 use nom::bytes::complete::{escaped_transform, is_not, tag};
13 use nom::character::complete::{char, space0, space1};
14 use nom::combinator::{cut, eof, opt, value};
15 use nom::error::{ErrorKind, ParseError};
16 use nom::{IResult, Input, OutputMode, Parser};
3717
3818 fn parse_text(input: &str) -> IResult<&str, String> {
3919 if input.is_empty() {
@@ -782,14 +762,15 @@ impl Completer<IambInfo> for IambCompleter {
782762#[cfg(test)]
783763pub mod tests {
784764 use super::*;
785 use crate::{
786 base::{ProgramCommand, ProgramCommands},
787 commands::add_iamb_commands,
788 tests::*,
789 };
790 use modalkit::{commands::CommandResult, env::vim::command::CommandContext};
765
766 use modalkit::commands::CommandResult;
767 use modalkit::env::vim::command::CommandContext;
791768 use pretty_assertions::assert_eq;
792769
770 use crate::base::{ProgramCommand, ProgramCommands};
771 use crate::commands::add_iamb_commands;
772 use crate::tests::*;
773
793774 #[tokio::test]
794775 async fn test_complete_msgbar() {
795776 let store = mock_store().await;
src/config.rs +13 −27
@@ -1,44 +1,28 @@
11//! # Logic for loading and validating application configuration
2use std::borrow::Cow;
2
33use std::collections::hash_map::DefaultHasher;
4use std::collections::{BTreeMap, HashMap};
54use std::env;
6use std::fmt;
75use std::fs::File;
86use std::hash::{Hash, Hasher};
9use std::io::{BufReader, BufWriter, Write};
10use std::path::{Path, PathBuf};
7use std::io::{BufReader, BufWriter, Write as _};
118use std::process;
12use std::str::FromStr;
139
1410use clap::Parser;
1511use matrix_sdk::EncryptionState;
1612use matrix_sdk::authentication::matrix::MatrixSession;
1713use matrix_sdk::media::MediaRetentionPolicy;
1814use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
19use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
20use ratatui::layout::Size;
21use ratatui::style::{Color, Modifier as StyleModifier, Style};
22use ratatui::text::Span;
15use matrix_sdk::ruma::OwnedDeviceId;
16use modalkit::env::vim::VimMode;
17use modalkit::keybindings::InputKey;
2318use ratatui_image::FilterType;
2419use ratatui_image::picker::ProtocolType;
25use serde::{Deserialize, Deserializer, Serialize, de::Error as SerdeError, de::Visitor};
26use url::Url;
20use serde::de::Error as SerdeError;
21use serde::de::Visitor;
22use serde::{Deserialize, Deserializer, Serialize};
2723
28use modalkit::env::vim::VimMode;
29use modalkit::key::TerminalKey;
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};
24use crate::base::{SortColumn, SortFieldRoom, SortFieldUser, SortOrder};
25use crate::prelude::*;
4226
4327type Macros = HashMap<VimModes, HashMap<Keys, Keys>>;
4428
@@ -1426,9 +1410,11 @@ impl ApplicationSettings {
14261410#[cfg(test)]
14271411mod tests {
14281412 use super::*;
1429 use matrix_sdk::ruma::user_id;
1413
14301414 use std::convert::TryFrom;
14311415
1416 use matrix_sdk::ruma::user_id;
1417
14321418 #[test]
14331419 fn test_profile_name_invalid() {
14341420 assert_eq!(validate_profile_name(""), false);
src/keybindings.rs +9 −12
@@ -2,18 +2,15 @@
22//!
33//! The keybindings are set up here. We define some iamb-specific keybindings, but the default Vim
44//! keys come from [modalkit::env::vim::keybindings].
5use modalkit::{
6 actions::{InsertTextAction, MacroAction, WindowAction},
7 env::CommonKeyClass,
8 env::vim::VimMode,
9 env::vim::keybindings::{InputStep, VimBindings},
10 key::TerminalKey,
11 keybindings::{EdgeEvent, EdgeRepeat, InputBindings},
12 prelude::*,
13};
14
15use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
16use crate::config::{ApplicationSettings, Keys, SplitDirection};
5use modalkit::actions::MacroAction;
6use modalkit::env::CommonKeyClass;
7use modalkit::env::vim::VimMode;
8use modalkit::env::vim::keybindings::{InputStep, VimBindings};
9use modalkit::keybindings::{EdgeEvent, EdgeRepeat, InputBindings};
10
11use crate::base::{Keybindings, MATRIX_ID_WORD};
12use crate::config::{Keys, SplitDirection};
13use crate::prelude::*;
1714
1815pub type IambStep = InputStep<IambInfo>;
1916
src/main.rs +45 −102
@@ -16,61 +16,60 @@
1616#![allow(clippy::needless_return)]
1717#![allow(clippy::result_large_err)]
1818#![allow(clippy::bool_assert_comparison)]
19
1920use std::collections::VecDeque;
20use std::convert::TryFrom;
21use std::fmt::Display;
2221use std::fs::{File, create_dir_all};
2322use std::io::{BufWriter, Stdout, Write, stdout};
24use std::ops::DerefMut;
2523use std::process;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicUsize, Ordering};
28use std::time::{Duration, Instant};
24use std::sync::atomic::AtomicUsize;
2925
3026use clap::{CommandFactory, Parser};
31use matrix_sdk::ruma::UserId;
3227use matrix_sdk::ruma::api::error::ErrorKind;
33use matrix_sdk::ruma::profile::{ProfileFieldName, ProfileFieldValue};
3428use 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};
3658use rand::RngExt as _;
3759use rand::distr::Alphanumeric;
60use ratatui::Terminal;
61use ratatui::backend::CrosstermBackend;
3862use temp_dir::TempDir;
3963use tokio::sync::Mutex as AsyncMutex;
4064use tracing::Level;
4165use tracing_subscriber::{EnvFilter, FmtSubscriber};
4266
43use modalkit::crossterm::{
44 self,
45 cursor::{SetCursorStyle, Show as CursorShow},
46 event::{
47 DisableBracketedPaste,
48 DisableFocusChange,
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};
67use crate::base::{HomeserverAction, KeysAction};
68use crate::completions::IambCompleter;
69use crate::config::Iamb;
70use crate::prelude::*;
71use crate::windows::IambWindow;
72use crate::worker::{ClientWorker, LoginStyle, create_room};
7473
7574mod base;
7675mod commands;
@@ -79,72 +78,16 @@ mod config;
7978mod keybindings;
8079mod message;
8180mod notifications;
81mod prelude;
8282mod preview;
8383mod sled_export;
8484mod util;
85mod verifications;
8586mod windows;
8687mod worker;
8788
8889#[cfg(test)]
8990mod 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};
14891
14992fn config_tab_to_desc(
15093 layout: config::WindowLayout,
@@ -334,9 +277,9 @@ impl Application {
334277 .show_dialog(dialogstr)
335278 .show_mode(modestr)
336279 .borders(true)
337 .border_style(Style::default().add_modifier(Modifier::DIM))
338 .tab_style(Style::default().add_modifier(Modifier::DIM))
339 .tab_style_focused(Style::default().remove_modifier(Modifier::DIM))
280 .border_style(Style::default().add_modifier(StyleModifier::DIM))
281 .tab_style(Style::default().add_modifier(StyleModifier::DIM))
282 .tab_style_focused(Style::default().remove_modifier(StyleModifier::DIM))
340283 .focus(focused);
341284 f.render_stateful_widget(screen, area, sstate);
342285
@@ -1225,7 +1168,7 @@ fn main() {
12251168 .worker_threads(2)
12261169 .thread_name_fn(|| {
12271170 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);
12291172 format!("iamb-worker-{id}")
12301173 })
12311174 .build()
src/message/compose.rs +10 −16
@@ -1,22 +1,16 @@
11//! Code for converting composed messages into content to send to the homeserver.
2use comrak::{markdown_to_html, options::Options};
3use nom::{
4 IResult,
5 Parser as _,
6 branch::alt,
7 bytes::complete::tag,
8 character::complete::space0,
9 combinator::value,
10};
11
12use matrix_sdk::ruma::events::room::message::{
13 EmoteMessageEventContent,
14 MessageType,
15 RoomMessageEventContent,
16 TextMessageEventContent,
17};
2
3use comrak::markdown_to_html;
4use comrak::options::Options;
5use matrix_sdk::ruma::events::room::message::{EmoteMessageEventContent, TextMessageEventContent};
6use nom::branch::alt;
7use nom::bytes::complete::tag;
8use nom::character::complete::space0;
9use nom::combinator::value;
10use nom::{IResult, Parser as _};
1811
1912use crate::config::MarkupFormat;
13use crate::prelude::*;
2014
2115#[derive(Clone, Debug, Default)]
2216enum SlashCommand {
src/message/html.rs +13 −28
@@ -10,35 +10,18 @@
1010//!
1111//! This isn't as important for iamb, since it isn't a browser environment, but we do still map
1212//! 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;
1513
1614use 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};
1719use markup5ever_rcdom::{Handle, NodeData, RcDom};
18use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId};
19use unicode_segmentation::UnicodeSegmentation;
20use url::Url;
21
22use html5ever::{
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};
20use ratatui::symbols::line;
21
22use crate::message::printer::TextPrinter;
23use crate::prelude::*;
24use crate::util::{join_cell_text, space_text};
4225
4326const QUOTE_COLOR: Color = Color::Indexed(236);
4427
@@ -844,11 +827,13 @@ pub fn parse_matrix_html(s: &str) -> StyleTree {
844827#[cfg(test)]
845828pub mod tests {
846829 use super::*;
847 use crate::tests::mock_settings;
848 use crate::util::space_span;
830
849831 use pretty_assertions::assert_eq;
850832 use unicode_width::UnicodeWidthStr;
851833
834 use crate::tests::mock_settings;
835 use crate::util::space_span;
836
852837 #[test]
853838 fn test_header() {
854839 let settings = mock_settings();
src/message/mod.rs +36 −72
@@ -1,75 +1,41 @@
11//! # Room Messages
2use std::borrow::Cow;
3use std::cmp::{Ord, Ordering, PartialOrd};
4use std::collections::BTreeMap;
2
3use std::cmp::{Ord, PartialOrd};
54use std::collections::hash_map::DefaultHasher;
6use std::convert::{TryFrom, TryInto};
7use std::fmt::{self, Display};
5use std::convert::TryInto;
86use std::hash::{Hash, Hasher};
9use std::ops::{Deref, DerefMut};
107
118use chrono::{DateTime, Local as LocalTz};
129use humansize::{DECIMAL, format_size};
1310use matrix_sdk::ruma::OwnedTransactionId;
14use matrix_sdk::ruma::events::receipt::ReceiptThread;
15use matrix_sdk::ruma::events::room::MediaSource;
11use matrix_sdk::ruma::UInt;
12use matrix_sdk::ruma::events::RedactedUnsigned;
13use matrix_sdk::ruma::events::room::encrypted::{
14 OriginalRoomEncryptedEvent,
15 RedactedRoomEncryptedEvent,
16 RoomEncryptedEvent,
17};
1618use 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;
1726use matrix_sdk::ruma::events::sticker::{OriginalStickerEvent, RedactedStickerEvent, StickerEvent};
1827use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent};
1928use 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
6229use modalkit::editing::cursor::Cursor;
63use modalkit::prelude::*;
30use ratatui::symbols::line::THICK_VERTICAL;
31use ratatui_image::sliced::SlicedProtocol;
6432
6533use crate::base::MessageEdits;
66use crate::preview::{ImageStatus, PreviewKind, PreviewManager};
67use crate::{
68 base::RoomInfo,
69 config::ApplicationSettings,
70 message::html::{StyleTree, parse_matrix_html},
71 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
72};
34use crate::message::html::{StyleTree, parse_matrix_html};
35use crate::message::state::{body_cow_state, html_state};
36use crate::prelude::*;
37use crate::preview::ImageStatus;
38use crate::util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text};
7339
7440mod compose;
7541mod html;
@@ -77,8 +43,7 @@ mod printer;
7743mod state;
7844
7945pub use self::compose::{text_to_message, text_to_text_message_event_content};
80use self::state::{body_cow_state, html_state};
81pub use html::TreeGenState;
46pub use self::html::TreeGenState;
8247
8348type ProtocolPreview<'a> = (&'a SlicedProtocol, u16, u16);
8449
@@ -1473,20 +1438,19 @@ impl Display for Message {
14731438
14741439#[cfg(test)]
14751440pub mod tests {
1476 use matrix_sdk::ruma::events::room::{
1477 ImageInfo,
1478 message::{
1479 AudioInfo,
1480 AudioMessageEventContent,
1481 FileInfo,
1482 FileMessageEventContent,
1483 ImageMessageEventContent,
1484 VideoInfo,
1485 VideoMessageEventContent,
1486 },
1441 use super::*;
1442
1443 use matrix_sdk::ruma::events::room::ImageInfo;
1444 use matrix_sdk::ruma::events::room::message::{
1445 AudioInfo,
1446 AudioMessageEventContent,
1447 FileInfo,
1448 FileMessageEventContent,
1449 ImageMessageEventContent,
1450 VideoInfo,
1451 VideoMessageEventContent,
14871452 };
14881453
1489 use super::*;
14901454 use crate::tests::*;
14911455
14921456 #[test]
src/message/printer.rs +3 −8
@@ -3,15 +3,9 @@
33//! The [TextPrinter] handles wrapping stylized text and inserting spaces for padding at the end of
44//! lines to make concatenation work right (e.g., combining table cells after wrapping their
55//! contents).
6use std::borrow::Cow;
76
8use ratatui::layout::Alignment;
9use ratatui::style::Style;
10use ratatui::text::{Line, Span, Text};
11use unicode_segmentation::UnicodeSegmentation;
12use unicode_width::UnicodeWidthStr;
13
14use crate::config::{ApplicationSettings, TunableValues};
7use crate::config::TunableValues;
8use crate::prelude::*;
159use crate::util::{
1610 replace_emojis_in_line,
1711 replace_emojis_in_span,
@@ -295,6 +289,7 @@ impl<'a> TextPrinter<'a> {
295289#[cfg(test)]
296290pub mod tests {
297291 use super::*;
292
298293 use crate::tests::mock_settings;
299294
300295 #[test]
src/message/state.rs +6 −16
@@ -1,20 +1,10 @@
11//! Code for displaying state events.
2use std::borrow::Cow;
3use std::str::FromStr;
4
5use matrix_sdk::ruma::{
6 OwnedRoomId,
7 UserId,
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};
2
3use matrix_sdk::ruma::events::room::member::MembershipChange;
4use matrix_sdk::ruma::events::{AnyStateEventContentChange, StateEventContentChange};
5
6use crate::message::html::{StyleTree, StyleTreeNode};
7use crate::prelude::*;
188
199fn bold(s: impl Into<Cow<'static, str>>) -> StyleTreeNode {
2010 let bold = Style::default().add_modifier(StyleModifier::BOLD);
src/notifications.rs +11 −18
@@ -1,25 +1,18 @@
11use std::time::SystemTime;
22
3use matrix_sdk::{
4 Client,
5 EncryptionState,
6 deserialized_responses::RawAnySyncOrStrippedTimelineEvent,
7 notification_settings::{IsEncrypted, IsOneToOne, NotificationSettings, RoomNotificationMode},
8 room::Room as MatrixRoom,
9 ruma::{
10 MilliSecondsSinceUnixEpoch,
11 OwnedRoomId,
12 RoomId,
13 events::{AnyMessageLikeEventContent, AnySyncTimelineEvent, room::message::MessageType},
14 serde::Raw,
15 },
3use matrix_sdk::EncryptionState;
4use matrix_sdk::deserialized_responses::RawAnySyncOrStrippedTimelineEvent;
5use matrix_sdk::notification_settings::{
6 IsEncrypted,
7 IsOneToOne,
8 NotificationSettings,
9 RoomNotificationMode,
1610};
17use unicode_segmentation::UnicodeSegmentation;
11use matrix_sdk::ruma::events::{AnyMessageLikeEventContent, AnySyncTimelineEvent};
12use matrix_sdk::ruma::serde::Raw;
1813
19use crate::{
20 base::{AsyncProgramStore, IambError, IambResult, ProgramStore},
21 config::{ApplicationSettings, NotifyVia},
22};
14use crate::config::NotifyVia;
15use crate::prelude::*;
2316
2417const IAMB_XDG_NAME: &str = match option_env!("IAMB_XDG_NAME") {
2518 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};
2
3use matrix_sdk::{
4 Media,
5 media::{MediaFormat, MediaRequestParameters, UniqueKey},
6 ruma::events::room::MediaSource,
7};
8use ratatui::layout::Size;
1use matrix_sdk::Media;
2use matrix_sdk::media::{MediaFormat, MediaRequestParameters, UniqueKey};
3use ratatui_image::picker::Picker;
94use ratatui_image::sliced::SlicedProtocol;
10use ratatui_image::{FilterType, Resize, picker::Picker};
5use ratatui_image::{FilterType, Resize};
116use tokio::sync::Semaphore;
127
13use crate::{
14 base::{AsyncProgramStore, IambError},
15 config::{ApplicationSettings, ImagePreviewValues},
16 worker::Requester,
17};
8use crate::config::ImagePreviewValues;
9use crate::prelude::*;
1810
1911pub enum ImageStatus {
2012 Queued(Size),
src/sled_export.rs +3 −3
@@ -10,11 +10,11 @@
1010//! time to upgrade off of pre-0.0.9 versions.
1111//!
1212//! [sled]: https://docs.rs/sled/0.34.7/sled/index.html
13use sled::{Config, IVec};
14use std::path::Path;
1513
16use crate::base::IambError;
1714use matrix_sdk_crypto::olm::{ExportedRoomKey, InboundGroupSession, PickledInboundGroupSession};
15use sled::{Config, IVec};
16
17use crate::prelude::*;
1818
1919#[derive(Debug, thiserror::Error)]
2020pub enum SledMigrationError {
src/tests.rs +6 −24
@@ -1,32 +1,14 @@
1use std::path::PathBuf;
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};
1use std::iter::FromIterator as _;
172
183use 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};
206use serde_json::{Map, Value};
217use tokio::sync::mpsc::unbounded_channel;
228
23use crate::message::MessageTimeStamp;
24use crate::{
25 base::{ChatStore, EventLocation, ProgramStore, RoomInfo},
26 config::*,
27 message::{Message, MessageEvent, MessageKey, Messages},
28 worker::Requester,
29};
9use crate::base::EventLocation;
10use crate::config::*;
11use crate::prelude::*;
3012
3113const TEST_ROOM1_ALIAS: &str = "#room1:example.com";
3214
src/util.rs +1 −5
@@ -1,12 +1,8 @@
11//! # Utility functions
2use std::borrow::Cow;
32
43use regex::{Regex, RegexBuilder};
5use unicode_segmentation::UnicodeSegmentation;
6use unicode_width::UnicodeWidthStr;
74
8use ratatui::style::Style;
9use ratatui::text::{Line, Span, Text};
5use crate::prelude::*;
106
117pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) {
128 match cow {
src/verifications.rs +4 −10
@@ -1,15 +1,9 @@
1use matrix_sdk::Client;
2use matrix_sdk::encryption::verification::{
3 Verification,
4 VerificationRequest,
5 VerificationRequestState,
6};
1use matrix_sdk::encryption::verification::{Verification, VerificationRequestState};
2use matrix_sdk::ruma::OwnedDeviceId;
73use matrix_sdk::ruma::events::key::verification::VerificationMethod;
8use matrix_sdk::ruma::{OwnedDeviceId, OwnedUserId, UserId};
9use modalkit::errors::UIError;
10use modalkit::prelude::{EditInfo, InfoMessage};
114
12use crate::base::{AsyncProgramStore, IambError, IambResult, ProgramStore, VerifyAction};
5use crate::base::VerifyAction;
6use crate::prelude::*;
137
148const SUPPORTED_METHODS: [VerificationMethod; 3] = [
159 // Emoji verification
src/windows/mod.rs +16 −77
@@ -6,84 +6,22 @@
66//! Additionally, some of the iamb commands delegate behaviour to the current UI element. For
77//! example, [sending messages][crate::base::SendAction] delegate to the [room window][RoomState],
88//! where we have the message bar and room ID easily accessible and resettable.
9use std::cmp::{Ord, Ordering};
10use std::fmt::{self, Display};
11use std::ops::Deref;
12use std::sync::Arc;
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;
9
10use std::cmp::Ord;
11use std::fmt::{self};
12
8613use 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;
8725
8826pub mod room;
8927pub mod verify;
@@ -1587,6 +1525,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
15871525#[cfg(test)]
15881526mod tests {
15891527 use super::*;
1528
15901529 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, room_alias_id, server_name};
15911530
15921531 #[derive(Debug, Eq, PartialEq)]
src/windows/room/chat.rs +18 −87
@@ -1,106 +1,37 @@
11//! Window for Matrix rooms
2use std::borrow::Cow;
32use std::convert::TryInto;
43use std::ffi::{OsStr, OsString};
54use std::fs;
6use std::path::{Path, PathBuf};
5use std::process::Command;
76
87use edit::Builder;
98use edit::edit_with_builder as external_edit;
9use matrix_sdk::RoomState as MatrixRoomState;
10use matrix_sdk::attachment::AttachmentConfig;
1011use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
12use matrix_sdk::media::{MediaFormat, MediaRequestParameters};
1113use 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};
1219use modalkit::editing::store::RegisterError;
13use std::process::Command;
14use tokio;
15use url::Url;
16
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};
20use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem};
21use modalkit_ratatui::PromptActions;
22use modalkit_ratatui::textbox::{TextBox, TextBoxState};
23use ratatui::prelude::Stylize;
4924
50use modalkit_ratatui::{
51 PromptActions,
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};
25use crate::base::{DownloadFlags, EchoLocation};
26use crate::config::EncryptionIndicatorLocation;
9327use crate::message::{
94 MessageEvent,
9528 MessageId,
96 MessageKey,
9729 TreeGenState,
9830 text_to_message,
9931 text_to_text_message_event_content,
10032};
101use crate::worker::Requester;
102
103use super::scrollback::{Scrollback, ScrollbackState};
33use crate::prelude::*;
34use crate::windows::room::scrollback::{Scrollback, ScrollbackState};
10435
10536/// State needed for rendering [Chat].
10637pub struct ChatState {
@@ -151,7 +82,7 @@ impl ChatState {
15182 return Err(IambError::NotJoined);
15283 };
15384
154 if room.state() == RoomState::Joined {
85 if room.state() == MatrixRoomState::Joined {
15586 Ok(room)
15687 } else {
15788 Err(IambError::NotJoined)
src/windows/room/mod.rs +16 −69
@@ -1,78 +1,25 @@
11//! # Windows for Matrix rooms and spaces
22use std::collections::HashSet;
33
4use matrix_sdk::{
5 RoomDisplayName,
6 RoomState as MatrixRoomState,
7 notification_settings::RoomNotificationMode,
8 room::Room as MatrixRoom,
9 ruma::{
10 OwnedEventId,
11 OwnedRoomAliasId,
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},
4use matrix_sdk::RoomDisplayName;
5use matrix_sdk::notification_settings::RoomNotificationMode;
6use matrix_sdk::ruma::api::client::room::upgrade_room::v3::Request as UpgradeRoomRequest;
7use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind;
8use matrix_sdk::ruma::events::room::canonical_alias::RoomCanonicalAliasEventContent;
9use matrix_sdk::ruma::events::room::history_visibility::{
10 HistoryVisibility,
11 RoomHistoryVisibilityEventContent,
3712};
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};
3817
39use modalkit::actions::{
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};
18use crate::base::{MemberUpdateAction, RoomField};
7319use crate::config::EncryptionIndicatorLocation;
74
75use std::convert::TryFrom;
20use crate::prelude::*;
21use crate::windows::room::chat::ChatState;
22use crate::windows::room::space::{Space, SpaceState};
7623
7724mod chat;
7825mod scrollback;
src/windows/room/scrollback.rs +14 −51
@@ -1,62 +1,23 @@
11//! 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
162use modalkit::actions::{
17 Action,
183 CursorAction,
194 EditAction,
20 Editable,
21 EditorAction,
225 EditorActions,
236 HistoryAction,
24 InsertTextAction,
25 Jumpable,
26 PromptAction,
27 Promptable,
28 Scrollable,
297 Searchable,
308 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},
599};
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::*;
6021
6122fn no_msgs() -> EditError<IambInfo> {
6223 let msg = "No messages to select.";
@@ -1535,7 +1496,9 @@ impl StatefulWidget for Scrollback<'_> {
15351496#[cfg(test)]
15361497mod tests {
15371498 use super::*;
1538 use crate::{base::Need, tests::*};
1499
1500 use crate::base::Need;
1501 use crate::tests::*;
15391502
15401503 #[tokio::test]
15411504 async fn test_search_messages() {
src/windows/room/space.rs +2 −34
@@ -1,43 +1,11 @@
11//! Window for Matrix spaces
2use std::ops::{Deref, DerefMut};
3use std::str::FromStr;
4use std::time::{Duration, Instant};
52
63use matrix_sdk::ruma::OwnedSpaceChildOrder;
74use matrix_sdk::ruma::events::StateEventType;
85use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
9use matrix_sdk::{
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};
6use modalkit_ratatui::list::{List, ListState};
407
8use crate::prelude::*;
419use crate::windows::{RoomItem, RoomLikeItem, room_fields_cmp};
4210
4311const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
src/windows/verify.rs +2 −15
@@ -1,23 +1,10 @@
1use std::cmp::Ordering;
2use std::fmt;
3
4use matrix_sdk::encryption::verification::{
5 Verification,
6 VerificationRequest,
7 VerificationRequestState,
8};
1use matrix_sdk::encryption::verification::{Verification, VerificationRequestState};
92use matrix_sdk::ruma::events::key::verification::VerificationMethod;
103use matrix_sdk_crypto::matrix_sdk_qrcode::qrcode::render::unicode::Dense1x2;
114use matrix_sdk_crypto::{QrVerificationState, SasState, format_emojis};
12
13use modalkit::actions::{PromptAction, Promptable};
14use modalkit::errors::{EditError, EditResult};
15use modalkit::prelude::ViewportContext;
165use modalkit_ratatui::list::{ListCursor, ListItem};
17use ratatui::style::{Color, Modifier as StyleModifier, Style};
18use ratatui::text::{Line, Span, Text};
196
20use crate::base::{IambInfo, ProgramAction, ProgramContext, ProgramStore};
7use crate::prelude::*;
218
229const BLACK_ON_WHITE: Style = Style::new().fg(Color::Black).bg(Color::White);
2310
src/windows/welcome.rs +2 −8
@@ -1,14 +1,8 @@
11//! Welcome Window
2use std::ops::{Deref, DerefMut};
32
4use ratatui::{buffer::Buffer, layout::Rect};
3use modalkit_ratatui::textbox::TextBoxState;
54
6use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps, textbox::TextBoxState};
7
8use modalkit::editing::completion::CompletionList;
9use modalkit::prelude::*;
10
11use crate::base::{IambBufferId, IambInfo, IambResult, ProgramStore};
5use crate::prelude::*;
126
137const WELCOME_TEXT: &str = include_str!("welcome.md");
148
src/worker.rs +58 −92
@@ -2,116 +2,81 @@
22//!
33//! The worker thread handles asynchronous work, and can receive messages from the main thread that
44//! block on a reply from the async worker.
5use std::collections::HashMap;
6use std::convert::TryFrom;
5
76use std::fmt::{Debug, Formatter};
8use std::ops::DerefMut;
9use std::str::FromStr;
10use std::sync::Arc;
117use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
12use std::time::{Duration, Instant};
138
14use futures::{StreamExt, stream::FuturesUnordered};
9use futures::StreamExt;
10use futures::stream::FuturesUnordered;
1511use 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;
1630use matrix_sdk::ruma::events::key::verification::ready::{
1731 OriginalSyncKeyVerificationReadyEvent,
1832 ToDeviceKeyVerificationReadyEvent,
1933};
20use matrix_sdk_base::RoomStateFilter;
21use ratatui::layout::Size;
22use ratatui_image::picker::Picker;
23use tokio::sync::Semaphore;
24use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
25use tokio::task::JoinHandle;
26use tracing::{Instrument as _, error, warn};
27use url::Url;
28
34use matrix_sdk::ruma::events::key::verification::request::ToDeviceKeyVerificationRequestEvent;
35use matrix_sdk::ruma::events::key::verification::start::{
36 OriginalSyncKeyVerificationStartEvent,
37 ToDeviceKeyVerificationStartEvent,
38};
39use matrix_sdk::ruma::events::presence::PresenceEvent;
40use matrix_sdk::ruma::events::reaction::ReactionEventContent;
41use matrix_sdk::ruma::events::receipt::{ReceiptEventContent, ReceiptType};
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};
2960use matrix_sdk::{
30 Client,
3161 ClientBuildError,
3262 Error as MatrixError,
3363 RoomDisplayName,
3464 RoomMemberships,
35 authentication::matrix::MatrixSession,
36 config::{RequestConfig, SyncSettings},
37 encryption::{BackupDownloadStrategy, EncryptionSettings},
38 event_handler::Ctx,
3965 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},
9066};
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};
9173
92use modalkit::errors::UIError;
93use modalkit::prelude::{EditInfo, InfoMessage};
94
95use crate::base::{EchoLocation, MessageNeed};
74use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed, RoomFetchStatus};
9675use crate::config::ProxyUrl;
97use crate::message::{Message, MessageEvent, MessageId, MessageKey};
76use crate::message::MessageId;
9877use crate::notifications::register_notifications;
99use crate::preview::PreviewKind;
78use crate::prelude::*;
10079use 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};
11580
11681const DEFAULT_ENCRYPTION_SETTINGS: EncryptionSettings = EncryptionSettings {
11782 auto_enable_cross_signing: true,
@@ -265,7 +230,8 @@ async fn load_older_one(
265230 };
266231 opts.limit = limit.into();
267232
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)?;
269235
270236 let mut msgs = vec![];
271237