Commit 9197864c5c

9197864c5cd383b13a12a1091f0fd7644106f720

parent: 2673cfaeb9

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-10-07 05:35 UTC

Add more documentation (#166)

Layout: unified · split

src/base.rs +185 −1
@@ -1,3 +1,6 @@
1//! # Common types and utilities
2//!
3//! The types defined here get used throughout iamb.
14use std::borrow::Cow;
25use std::collections::{HashMap, HashSet};
36use std::convert::TryFrom;
@@ -84,6 +87,7 @@ use crate::{
8487 ApplicationSettings,
8588};
8689
90/// The set of characters used in different Matrix IDs.
8791pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
8892
8993/// Find the boundaries for a Matrix username, room alias, or room ID.
@@ -100,17 +104,27 @@ fn is_mxid_char(c: char) -> bool {
100104
101105const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
102106
107/// Empty type used solely to implement [ApplicationInfo].
103108#[derive(Clone, Debug, Eq, PartialEq)]
104109pub enum IambInfo {}
105110
111/// An action taken against an ongoing verification request.
106112#[derive(Clone, Debug, Eq, PartialEq)]
107113pub enum VerifyAction {
114 /// Accept a verification request.
108115 Accept,
116
117 /// Cancel an in-progress verification.
109118 Cancel,
119
120 /// Confirm an in-progress verification.
110121 Confirm,
122
123 /// Reject an in-progress verification due to mismatched Emoji.
111124 Mismatch,
112125}
113126
127/// An action taken against the currently selected message.
114128#[derive(Clone, Debug, Eq, PartialEq)]
115129pub enum MessageAction {
116130 /// Cance the current reply or edit.
@@ -145,6 +159,7 @@ pub enum MessageAction {
145159 Unreact(Option<String>),
146160}
147161
162/// The type of room being created.
148163#[derive(Clone, Debug, Eq, PartialEq)]
149164pub enum CreateRoomType {
150165 /// A direct message room.
@@ -158,7 +173,9 @@ pub enum CreateRoomType {
158173}
159174
160175bitflags::bitflags! {
176 /// Available options for newly created rooms.
161177 pub struct CreateRoomFlags: u32 {
178 /// No flags specified.
162179 const NONE = 0b00000000;
163180
164181 /// Make the room public.
@@ -170,7 +187,9 @@ bitflags::bitflags! {
170187}
171188
172189bitflags::bitflags! {
190 /// Available options when downloading files.
173191 pub struct DownloadFlags: u32 {
192 /// No flags specified.
174193 const NONE = 0b00000000;
175194
176195 /// Overwrite file if it already exists.
@@ -181,45 +200,91 @@ bitflags::bitflags! {
181200 }
182201}
183202
203/// A room property.
184204#[derive(Clone, Debug, Eq, PartialEq)]
185205pub enum RoomField {
206 /// The room name.
186207 Name,
208
209 /// A room tag.
187210 Tag(TagName),
211
212 /// The room topic.
188213 Topic,
189214}
190215
216/// An action that operates on a focused room.
191217#[derive(Clone, Debug, Eq, PartialEq)]
192218pub enum RoomAction {
219 /// Accept an invitation to join this room.
193220 InviteAccept,
221
222 /// Reject an invitation to join this room.
194223 InviteReject,
224
225 /// Invite a user to this room.
195226 InviteSend(OwnedUserId),
227
228 /// Leave this room.
196229 Leave(bool),
230
231 /// Open the members window.
197232 Members(Box<CommandContext<ProgramContext>>),
233
234 /// Set a room property.
198235 Set(RoomField, String),
236
237 /// Unset a room property.
199238 Unset(RoomField),
200239}
201240
241/// An action that sends a message to a room.
202242#[derive(Clone, Debug, Eq, PartialEq)]
203243pub enum SendAction {
244 /// Send the text in the message bar.
204245 Submit,
246
247 /// Send text provided from an external editor.
205248 SubmitFromEditor,
249
250 /// Upload a file.
206251 Upload(String),
252
253 /// Upload the image data.
207254 UploadImage(usize, usize, Cow<'static, [u8]>),
208255}
209256
257/// An action performed against the user's homeserver.
210258#[derive(Clone, Debug, Eq, PartialEq)]
211259pub enum HomeserverAction {
260 /// Create a new room with an optional localpart.
212261 CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
213262}
214263
264/// An action that the main program loop should.
265///
266/// See [the commands module][super::commands] for where these are usually created.
215267#[derive(Clone, Debug, Eq, PartialEq)]
216268pub enum IambAction {
269 /// Perform an action against the homeserver.
217270 Homeserver(HomeserverAction),
271
272 /// Perform an action on the currently selected message.
218273 Message(MessageAction),
274
275 /// Perform an action on the currently focused room.
219276 Room(RoomAction),
277
278 /// Send a message to the currently focused room.
220279 Send(SendAction),
280
281 /// Perform an action for an in-progress verification.
221282 Verify(VerifyAction, String),
283
284 /// Request a new verification with the specified user.
222285 VerifyRequest(String),
286
287 /// Toggle the focus within the focused room.
223288 ToggleScrollbackFocus,
224289}
225290
@@ -316,14 +381,21 @@ impl From<IambAction> for ProgramAction {
316381 }
317382}
318383
384/// Alias for program actions.
319385pub type ProgramAction = Action<IambInfo>;
386/// Alias for program context.
320387pub type ProgramContext = VimContext<IambInfo>;
388/// Alias for program keybindings.
321389pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
390/// Alias for a program command.
322391pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
392/// Alias for mapped program commands.
323393pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
394/// Alias for program store.
324395pub type ProgramStore = Store<IambInfo>;
396/// Alias for shared program store.
325397pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
326
398/// Alias for an action result.
327399pub type IambResult<T> = UIResult<T, IambInfo>;
328400
329401/// Reaction events for some message.
@@ -332,61 +404,81 @@ pub type IambResult<T> = UIResult<T, IambInfo>;
332404/// it's reacting to.
333405pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
334406
407/// Map of read receipts for different events.
335408pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
336409
410/// Errors encountered during application use.
337411#[derive(thiserror::Error, Debug)]
338412pub enum IambError {
413 /// An invalid user identifier was specified.
339414 #[error("Invalid user identifier: {0}")]
340415 InvalidUserId(String),
341416
417 /// An invalid verification identifier was specified.
342418 #[error("Invalid verification user/device pair: {0}")]
343419 InvalidVerificationId(String),
344420
421 /// A failure related to the cryptographic store.
345422 #[error("Cryptographic storage error: {0}")]
346423 CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
347424
425 /// An HTTP error.
348426 #[error("HTTP client error: {0}")]
349427 Http(#[from] matrix_sdk::HttpError),
350428
429 /// A failure from the Matrix client.
351430 #[error("Matrix client error: {0}")]
352431 Matrix(#[from] matrix_sdk::Error),
353432
433 /// A failure in the sled storage.
354434 #[error("Matrix client storage error: {0}")]
355435 Store(#[from] matrix_sdk::StoreError),
356436
437 /// A failure during serialization or deserialization.
357438 #[error("Serialization/deserialization error: {0}")]
358439 Serde(#[from] serde_json::Error),
359440
441 /// A failure due to not having a configured download directory.
360442 #[error("No download directory configured")]
361443 NoDownloadDir,
362444
445 /// A failure due to not having a message with an attachment selected.
363446 #[error("Selected message does not have any attachments")]
364447 NoAttachment,
365448
449 /// A failure due to not having a message selected.
366450 #[error("No message currently selected")]
367451 NoSelectedMessage,
368452
453 /// A failure due to not having a room or space selected.
369454 #[error("Current window is not a room or space")]
370455 NoSelectedRoomOrSpace,
371456
457 /// A failure due to not having a room selected.
372458 #[error("Current window is not a room")]
373459 NoSelectedRoom,
374460
461 /// A failure due to not having an outstanding room invitation.
375462 #[error("You do not have a current invitation to this room")]
376463 NotInvited,
377464
465 /// A failure due to not being a joined room member.
378466 #[error("You need to join the room before you can do that")]
379467 NotJoined,
380468
469 /// An unknown room was specified.
381470 #[error("Unknown room identifier: {0}")]
382471 UnknownRoom(OwnedRoomId),
383472
473 /// A failure occurred during verification.
384474 #[error("Verification request error: {0}")]
385475 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
386476
477 /// A failure related to images.
387478 #[error("Image error: {0}")]
388479 Image(#[from] image::ImageError),
389480
481 /// A failure to access the system's clipboard.
390482 #[error("Could not use system clipboard data")]
391483 Clipboard,
392484}
@@ -399,16 +491,26 @@ impl From<IambError> for UIError<IambInfo> {
399491
400492impl ApplicationError for IambError {}
401493
494/// Status for tracking how much room scrollback we've fetched.
402495#[derive(Default)]
403496pub enum RoomFetchStatus {
497 /// Room history has been completely fetched.
404498 Done,
499
500 /// More room history can be fetched.
405501 HaveMore(String),
502
503 /// We have not yet started fetching history for this room.
406504 #[default]
407505 NotStarted,
408506}
409507
508/// Indicates where an [EventId] lives in the [ChatStore].
410509pub enum EventLocation {
510 /// The [EventId] belongs to a message.
411511 Message(MessageKey),
512
513 /// The [EventId] belongs to a reaction to the given event.
412514 Reaction(OwnedEventId),
413515}
414516
@@ -422,6 +524,7 @@ impl EventLocation {
422524 }
423525}
424526
527/// Information about room's the user's joined.
425528#[derive(Default)]
426529pub struct RoomInfo {
427530 /// The display name for this room.
@@ -462,6 +565,7 @@ pub struct RoomInfo {
462565}
463566
464567impl RoomInfo {
568 /// Get the reactions and their counts for a message.
465569 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
466570 if let Some(reacts) = self.reactions.get(event_id) {
467571 let mut counts = HashMap::new();
@@ -480,14 +584,17 @@ impl RoomInfo {
480584 }
481585 }
482586
587 /// Map an event identifier to its [MessageKey].
483588 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
484589 self.keys.get(event_id)?.to_message_key()
485590 }
486591
592 /// Get an event for an identifier.
487593 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
488594 self.messages.get(self.get_message_key(event_id)?)
489595 }
490596
597 /// Insert a reaction to a message.
491598 pub fn insert_reaction(&mut self, react: ReactionEvent) {
492599 match react {
493600 MessageLikeEvent::Original(react) => {
@@ -509,6 +616,7 @@ impl RoomInfo {
509616 }
510617 }
511618
619 /// Insert an edit.
512620 pub fn insert_edit(&mut self, msg: Replacement) {
513621 let event_id = msg.event_id;
514622 let new_content = msg.new_content;
@@ -551,6 +659,7 @@ impl RoomInfo {
551659 self.messages.insert(key, msg.into());
552660 }
553661
662 /// Insert a new message.
554663 pub fn insert_message(&mut self, msg: RoomMessageEvent) {
555664 let event_id = msg.event_id().to_owned();
556665 let key = (msg.origin_server_ts().into(), event_id.clone());
@@ -563,6 +672,7 @@ impl RoomInfo {
563672 let _ = self.messages.remove(&key);
564673 }
565674
675 /// Insert a new message event.
566676 pub fn insert(&mut self, msg: RoomMessageEvent) {
567677 match msg {
568678 RoomMessageEvent::Original(OriginalRoomMessageEvent {
@@ -574,6 +684,7 @@ impl RoomInfo {
574684 }
575685 }
576686
687 /// Indicates whether we've recently fetched scrollback for this room.
577688 pub fn recently_fetched(&self) -> bool {
578689 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
579690 }
@@ -617,10 +728,12 @@ impl RoomInfo {
617728 }
618729 }
619730
731 /// Update typing information for this room.
620732 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
621733 self.users_typing = (Instant::now(), user_ids).into();
622734 }
623735
736 /// Create a [Rect] that displays what users are typing.
624737 pub fn render_typing(
625738 &mut self,
626739 area: Rect,
@@ -646,6 +759,7 @@ impl RoomInfo {
646759 }
647760}
648761
762/// Generate a [CompletionMap] for Emoji shortcodes.
649763fn emoji_map() -> CompletionMap<String, &'static Emoji> {
650764 let mut emojis = CompletionMap::default();
651765
@@ -658,27 +772,54 @@ fn emoji_map() -> CompletionMap<String, &'static Emoji> {
658772 return emojis;
659773}
660774
775/// Information gathered during server syncs about joined rooms.
661776#[derive(Default)]
662777pub struct SyncInfo {
778 /// Spaces that the user is a member of.
663779 pub spaces: Vec<MatrixRoom>,
780
781 /// Rooms that the user is a member of.
664782 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
783
784 /// DMs that the user is a member of.
665785 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
666786}
667787
788/// The main application state.
668789pub struct ChatStore {
790 /// `:`-commands
669791 pub cmds: ProgramCommands,
792
793 /// Handle for communicating w/ the worker thread.
670794 pub worker: Requester,
795
796 /// Map of joined rooms.
671797 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
798
799 /// Map of room names.
672800 pub names: CompletionMap<String, OwnedRoomId>,
801
802 /// Presence information for other users.
673803 pub presences: CompletionMap<OwnedUserId, PresenceState>,
804
805 /// In-progress and completed verifications.
674806 pub verifications: HashMap<String, SasVerification>,
807
808 /// Settings for the current profile loaded from config file.
675809 pub settings: ApplicationSettings,
810
811 /// Set of rooms that need more messages loaded in their scrollback.
676812 pub need_load: HashSet<OwnedRoomId>,
813
814 /// [CompletionMap] of Emoji shortcodes.
677815 pub emojis: CompletionMap<String, &'static Emoji>,
816
817 /// Information gathered by the background thread.
678818 pub sync_info: SyncInfo,
679819}
680820
681821impl ChatStore {
822 /// Create a new [ChatStore].
682823 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
683824 ChatStore {
684825 worker,
@@ -696,10 +837,12 @@ impl ChatStore {
696837 }
697838 }
698839
840 /// Get a joined room.
699841 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
700842 self.worker.client.get_joined_room(room_id)
701843 }
702844
845 /// Get the title for a room.
703846 pub fn get_room_title(&self, room_id: &RoomId) -> String {
704847 self.rooms
705848 .get(room_id)
@@ -708,6 +851,7 @@ impl ChatStore {
708851 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
709852 }
710853
854 /// Update the receipts for multiple rooms.
711855 pub async fn set_receipts(
712856 &mut self,
713857 receipts: Vec<(OwnedRoomId, Receipts)>,
@@ -727,18 +871,22 @@ impl ChatStore {
727871 return updates;
728872 }
729873
874 /// Mark a room for loading more scrollback.
730875 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
731876 self.need_load.insert(room_id);
732877 }
733878
879 /// Get the [RoomInfo] for a given room identifier.
734880 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
735881 self.rooms.get_or_default(room_id)
736882 }
737883
884 /// Set the name for a room.
738885 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
739886 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
740887 }
741888
889 /// Insert a new E2EE verification.
742890 pub fn insert_sas(&mut self, sas: SasVerification) {
743891 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
744892
@@ -748,6 +896,7 @@ impl ChatStore {
748896
749897impl ApplicationStore for ChatStore {}
750898
899/// Identified used to track window content.
751900#[derive(Clone, Debug, Eq, Hash, PartialEq)]
752901pub enum IambId {
753902 /// A Matrix room.
@@ -810,6 +959,7 @@ impl<'de> Deserialize<'de> for IambId {
810959 }
811960}
812961
962/// [serde] visitor for deserializing [IambId].
813963struct IambIdVisitor;
814964
815965impl<'de> Visitor<'de> for IambIdVisitor {
@@ -903,35 +1053,61 @@ impl<'de> Visitor<'de> for IambIdVisitor {
9031053 }
9041054}
9051055
1056/// Which part of the room window's UI is focused.
9061057#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
9071058pub enum RoomFocus {
1059 /// The scrollback for a room window is focused.
9081060 Scrollback,
1061
1062 /// The message bar for a room window is focused.
9091063 MessageBar,
9101064}
9111065
9121066impl RoomFocus {
1067 /// Whether this is [RoomFocus::Scrollback].
9131068 pub fn is_scrollback(&self) -> bool {
9141069 matches!(self, RoomFocus::Scrollback)
9151070 }
9161071
1072 /// Whether this is [RoomFocus::MessageBar].
9171073 pub fn is_msgbar(&self) -> bool {
9181074 matches!(self, RoomFocus::MessageBar)
9191075 }
9201076}
9211077
1078/// Identifiers used to track where a mark was placed.
1079///
1080/// While this is the "buffer identifier" for the mark,
1081/// not all of these are necessarily actual buffers.
9221082#[derive(Clone, Debug, Eq, Hash, PartialEq)]
9231083pub enum IambBufferId {
1084 /// The command bar buffer.
9241085 Command(CommandType),
1086
1087 /// The message buffer or a specific message in a room.
9251088 Room(OwnedRoomId, RoomFocus),
1089
1090 /// The `:dms` window.
9261091 DirectList,
1092
1093 /// The `:members` window for a room.
9271094 MemberList(OwnedRoomId),
1095
1096 /// The `:rooms` window.
9281097 RoomList,
1098
1099 /// The `:spaces` window.
9291100 SpaceList,
1101
1102 /// The `:verify` window.
9301103 VerifyList,
1104
1105 /// The buffer for the `:rooms` window.
9311106 Welcome,
9321107}
9331108
9341109impl IambBufferId {
1110 /// Get the identifier for the window that contains this buffer.
9351111 pub fn to_window(&self) -> Option<IambId> {
9361112 match self {
9371113 IambBufferId::Command(_) => None,
@@ -982,6 +1158,7 @@ impl ApplicationInfo for IambInfo {
9821158 }
9831159}
9841160
1161/// Tab completion for user IDs.
9851162fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
9861163 let id = text
9871164 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
@@ -997,6 +1174,7 @@ fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) ->
9971174 .collect()
9981175}
9991176
1177/// Tab completion within the message bar.
10001178fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
10011179 let id = text
10021180 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
@@ -1044,6 +1222,7 @@ fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -
10441222 }
10451223}
10461224
1225/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
10471226fn complete_matrix_names(
10481227 text: &EditRope,
10491228 cursor: &mut Cursor,
@@ -1073,6 +1252,7 @@ fn complete_matrix_names(
10731252 .collect()
10741253}
10751254
1255/// Tab completion for Emoji shortcode names.
10761256fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
10771257 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
10781258 let sc = sc.unwrap_or_else(EditRope::empty);
@@ -1081,6 +1261,7 @@ fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) ->
10811261 store.application.emojis.complete(sc.as_ref())
10821262}
10831263
1264/// Tab completion for command names.
10841265fn complete_cmdname(
10851266 desc: CommandDescription,
10861267 text: &EditRope,
@@ -1092,6 +1273,7 @@ fn complete_cmdname(
10921273 store.application.cmds.complete_name(desc.command.as_str())
10931274}
10941275
1276/// Tab completion for command arguments.
10951277fn complete_cmdarg(
10961278 desc: CommandDescription,
10971279 text: &EditRope,
@@ -1120,6 +1302,7 @@ fn complete_cmdarg(
11201302 }
11211303}
11221304
1305/// Tab completion for commands.
11231306fn complete_cmd(
11241307 cmd: &str,
11251308 text: &EditRope,
@@ -1141,6 +1324,7 @@ fn complete_cmd(
11411324 }
11421325}
11431326
1327/// Tab completion for the command bar.
11441328fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
11451329 let eo = text.cursor_to_offset(cursor);
11461330 let slice = text.slice(0.into(), eo, false);
src/commands.rs +5
@@ -1,3 +1,7 @@
1//! # Default Commands
2//!
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.
15use std::convert::TryFrom;
26
37use matrix_sdk::ruma::{events::tag::TagName, OwnedUserId};
@@ -555,6 +559,7 @@ fn add_iamb_commands(cmds: &mut ProgramCommands) {
555559 });
556560}
557561
562/// Initialize the default command state.
558563pub fn setup_commands() -> ProgramCommands {
559564 let mut cmds = ProgramCommands::default();
560565
src/config.rs +1
@@ -1,3 +1,4 @@
1//! # Logic for loading and validating application configuration
12use std::borrow::Cow;
23use std::collections::hash_map::DefaultHasher;
34use std::collections::HashMap;
src/keybindings.rs +5
@@ -1,3 +1,7 @@
1//! # Default Keybindings
2//!
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].
15use modalkit::{
26 editing::action::WindowAction,
37 env::vim::keybindings::{InputStep, VimBindings},
@@ -10,6 +14,7 @@ use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
1014
1115type IambStep = InputStep<IambInfo>;
1216
17/// Initialize the default keybinding state.
1318pub fn setup_keybindings() -> Keybindings {
1419 let mut ism = Keybindings::empty();
1520
src/main.rs +14
@@ -1,3 +1,16 @@
1//! # iamb
2//!
3//! The iamb client loops over user input and commands, and turns them into actions, [some of
4//! which][IambAction] are specific to iamb, and [some of which][Action] come from [modalkit]. When
5//! adding new functionality, you will usually want to extend [IambAction] or one of its variants
6//! (like [RoomAction][base::RoomAction]), and then add an appropriate [command][commands] or
7//! [keybinding][keybindings].
8//!
9//! For more complicated changes, you may need to update [the async worker thread][worker], which
10//! handles background Matrix tasks with [matrix-rust-sdk][matrix_sdk].
11//!
12//! Most rendering logic lives under the [windows] module, but [Matrix messages][message] have
13//! their own module.
114#![allow(clippy::manual_range_contains)]
215#![allow(clippy::needless_return)]
316#![allow(clippy::result_large_err)]
@@ -200,6 +213,7 @@ fn setup_screen(
200213 return Ok(ScreenState::new(win, cmd));
201214}
202215
216/// The main application state and event loop.
203217struct Application {
204218 /// Terminal backend.
205219 terminal: Terminal<CrosstermBackend<Stdout>>,
src/message/html.rs +10 −1
@@ -37,7 +37,8 @@ use crate::{
3737 util::{join_cell_text, space_text},
3838};
3939
40struct BulletIterator {
40/// Generate bullet points from a [ListStyle].
41pub struct BulletIterator {
4142 style: ListStyle,
4243 pos: usize,
4344 len: usize,
@@ -74,6 +75,7 @@ impl Iterator for BulletIterator {
7475 }
7576}
7677
78/// Whether this list is ordered or unordered.
7779#[derive(Clone, Copy, Debug)]
7880pub enum ListStyle {
7981 Ordered,
@@ -88,11 +90,13 @@ impl ListStyle {
8890
8991pub type StyleTreeChildren = Vec<StyleTreeNode>;
9092
93/// Type of contents in a table cell.
9194pub enum CellType {
9295 Data,
9396 Header,
9497}
9598
99/// A collection of cells for a single row in a table.
96100pub struct TableRow {
97101 cells: Vec<(CellType, StyleTreeNode)>,
98102}
@@ -103,6 +107,7 @@ impl TableRow {
103107 }
104108}
105109
110/// A collection of rows in a table.
106111pub struct TableSection {
107112 rows: Vec<TableRow>,
108113}
@@ -113,6 +118,7 @@ impl TableSection {
113118 }
114119}
115120
121/// A table.
116122pub struct Table {
117123 caption: Option<Box<StyleTreeNode>>,
118124 sections: Vec<TableSection>,
@@ -229,6 +235,7 @@ impl Table {
229235 }
230236}
231237
238/// A processed HTML element that we can render to the terminal.
232239pub enum StyleTreeNode {
233240 Blockquote(Box<StyleTreeNode>),
234241 Break,
@@ -380,6 +387,7 @@ impl StyleTreeNode {
380387 }
381388}
382389
390/// A processed HTML document.
383391pub struct StyleTree {
384392 children: StyleTreeChildren,
385393}
@@ -649,6 +657,7 @@ fn dom_to_style_tree(dom: RcDom) -> StyleTree {
649657 StyleTree { children: h2t(&dom.document) }
650658}
651659
660/// Parse an HTML document from a string.
652661pub fn parse_matrix_html(s: &str) -> StyleTree {
653662 let dom = parse_fragment(
654663 RcDom::default(),
src/message/mod.rs +1
@@ -1,3 +1,4 @@
1//! # Room Messages
12use std::borrow::Cow;
23use std::cmp::{Ord, Ordering, PartialOrd};
34use std::collections::hash_map::DefaultHasher;
src/message/printer.rs +19
@@ -1,3 +1,8 @@
1//! # Line Wrapping Logic
2//!
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
5//! contents).
16use std::borrow::Cow;
27
38use modalkit::tui::layout::Alignment;
@@ -8,6 +13,7 @@ use unicode_width::UnicodeWidthStr;
813
914use crate::util::{space_span, take_width};
1015
16/// Wrap styled text for the current terminal width.
1117pub struct TextPrinter<'a> {
1218 text: Text<'a>,
1319 width: usize,
@@ -21,6 +27,7 @@ pub struct TextPrinter<'a> {
2127}
2228
2329impl<'a> TextPrinter<'a> {
30 /// Create a new printer.
2431 pub fn new(width: usize, base_style: Style, hide_reply: bool) -> Self {
2532 TextPrinter {
2633 text: Text::default(),
@@ -35,24 +42,29 @@ impl<'a> TextPrinter<'a> {
3542 }
3643 }
3744
45 /// Configure the alignment for each line.
3846 pub fn align(mut self, alignment: Alignment) -> Self {
3947 self.alignment = alignment;
4048 self
4149 }
4250
51 /// Set whether newlines should be treated literally, or turned into spaces.
4352 pub fn literal(mut self, literal: bool) -> Self {
4453 self.literal = literal;
4554 self
4655 }
4756
57 /// Indicates whether replies should be pushed to the printer.
4858 pub fn hide_reply(&self) -> bool {
4959 self.hide_reply
5060 }
5161
62 /// Indicates the current printer's width.
5263 pub fn width(&self) -> usize {
5364 self.width
5465 }
5566
67 /// Create a new printer with a smaller width.
5668 pub fn sub(&self, indent: usize) -> Self {
5769 TextPrinter {
5870 text: Text::default(),
@@ -71,6 +83,7 @@ impl<'a> TextPrinter<'a> {
7183 self.width - self.curr_width
7284 }
7385
86 /// If there is any text on the current line, start a new one.
7487 pub fn commit(&mut self) {
7588 if self.curr_width > 0 {
7689 self.push_break();
@@ -82,6 +95,7 @@ impl<'a> TextPrinter<'a> {
8295 self.text.lines.push(Spans(std::mem::take(&mut self.curr_spans)));
8396 }
8497
98 /// Start a new line.
8599 pub fn push_break(&mut self) {
86100 if self.curr_width == 0 && self.text.lines.is_empty() {
87101 // Disallow leading breaks.
@@ -149,6 +163,7 @@ impl<'a> TextPrinter<'a> {
149163 }
150164 }
151165
166 /// Push a [Span] that isn't allowed to break across lines.
152167 pub fn push_span_nobreak(&mut self, span: Span<'a>) {
153168 let sw = UnicodeWidthStr::width(span.content.as_ref());
154169
@@ -161,6 +176,7 @@ impl<'a> TextPrinter<'a> {
161176 self.curr_width += sw;
162177 }
163178
179 /// Push text with a [Style].
164180 pub fn push_str(&mut self, s: &'a str, style: Style) {
165181 let style = self.base_style.patch(style);
166182
@@ -212,16 +228,19 @@ impl<'a> TextPrinter<'a> {
212228 }
213229 }
214230
231 /// Push [Spans] into the printer.
215232 pub fn push_line(&mut self, spans: Spans<'a>) {
216233 self.commit();
217234 self.text.lines.push(spans);
218235 }
219236
237 /// Push multiline [Text] into the printer.
220238 pub fn push_text(&mut self, text: Text<'a>) {
221239 self.commit();
222240 self.text.lines.extend(text.lines);
223241 }
224242
243 /// Render the contents of this printer as [Text].
225244 pub fn finish(mut self) -> Text<'a> {
226245 self.commit();
227246 self.text
src/util.rs +1
@@ -1,3 +1,4 @@
1//! # Utility functions
12use std::borrow::Cow;
23
34use unicode_segmentation::UnicodeSegmentation;
src/windows/mod.rs +8
@@ -1,3 +1,11 @@
1//! # Windows for the User Interface
2//!
3//! This module contains the logic for rendering windows, and handling UI actions that get
4//! delegated to individual windows/UI elements (e.g., typing text or selecting a list item).
5//!
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],
8//! where we have the message bar and room ID easily accesible and resetable.
19use std::cmp::{Ord, Ordering, PartialOrd};
210use std::ops::Deref;
311use std::sync::Arc;
src/windows/room/chat.rs +3
@@ -1,3 +1,4 @@
1//! Window for Matrix rooms
12use std::borrow::Cow;
23use std::ffi::{OsStr, OsString};
34use std::fs;
@@ -85,6 +86,7 @@ use crate::worker::Requester;
8586
8687use super::scrollback::{Scrollback, ScrollbackState};
8788
89/// State needed for rendering [Chat].
8890pub struct ChatState {
8991 room_id: OwnedRoomId,
9092 room: MatrixRoom,
@@ -786,6 +788,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
786788 }
787789}
788790
791/// [StatefulWidget] for Matrix rooms.
789792pub struct Chat<'a> {
790793 store: &'a mut ProgramStore,
791794 focused: bool,
src/windows/room/mod.rs +6
@@ -1,3 +1,4 @@
1//! # Windows for Matrix rooms and spaces
12use matrix_sdk::{
23 room::{Invited, Room as MatrixRoom},
34 ruma::{
@@ -79,6 +80,11 @@ macro_rules! delegate {
7980 };
8081}
8182
83/// State for a Matrix room or space.
84///
85/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
86/// that operations like sending and accepting invites, opening the members window, etc., all work
87/// similarly.
8288pub enum RoomState {
8389 Chat(ChatState),
8490 Space(SpaceState),
src/windows/room/scrollback.rs +1
@@ -1,3 +1,4 @@
1//! Message scrollback
12use std::collections::HashSet;
23
34use regex::Regex;
src/windows/room/space.rs +3
@@ -1,3 +1,4 @@
1//! Window for Matrix spaces
12use std::ops::{Deref, DerefMut};
23use std::time::{Duration, Instant};
34
@@ -25,6 +26,7 @@ use crate::windows::RoomItem;
2526
2627const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
2728
29/// State needed for rendering [Space].
2830pub struct SpaceState {
2931 room_id: OwnedRoomId,
3032 room: MatrixRoom,
@@ -86,6 +88,7 @@ impl DerefMut for SpaceState {
8688 }
8789}
8890
91/// [StatefulWidget] for Matrix spaces.
8992pub struct Space<'a> {
9093 focused: bool,
9194 store: &'a mut ProgramStore,
src/windows/welcome.rs +1
@@ -1,3 +1,4 @@
1//! Welcome Window
12use std::ops::{Deref, DerefMut};
23
34use modalkit::tui::{buffer::Buffer, layout::Rect};
src/worker.rs +4
@@ -1,3 +1,7 @@
1//! # Async Matrix Client Worker
2//!
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.
15use std::collections::HashMap;
26use std::convert::TryFrom;
37use std::fmt::{Debug, Formatter};