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.
1use std::borrow::Cow; 4use std::borrow::Cow;
2use std::collections::{HashMap, HashSet}; 5use std::collections::{HashMap, HashSet};
3use std::convert::TryFrom; 6use std::convert::TryFrom;
@@ -84,6 +87,7 @@ use crate::{
84 ApplicationSettings, 87 ApplicationSettings,
85}; 88};
86 89
90/// The set of characters used in different Matrix IDs.
87pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char); 91pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
88 92
89/// Find the boundaries for a Matrix username, room alias, or room ID. 93/// Find the boundaries for a Matrix username, room alias, or room ID.
@@ -100,17 +104,27 @@ fn is_mxid_char(c: char) -> bool {
100 104
101const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2); 105const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
102 106
107/// Empty type used solely to implement [ApplicationInfo].
103#[derive(Clone, Debug, Eq, PartialEq)] 108#[derive(Clone, Debug, Eq, PartialEq)]
104pub enum IambInfo {} 109pub enum IambInfo {}
105 110
111/// An action taken against an ongoing verification request.
106#[derive(Clone, Debug, Eq, PartialEq)] 112#[derive(Clone, Debug, Eq, PartialEq)]
107pub enum VerifyAction { 113pub enum VerifyAction {
114 /// Accept a verification request.
108 Accept, 115 Accept,
116
117 /// Cancel an in-progress verification.
109 Cancel, 118 Cancel,
119
120 /// Confirm an in-progress verification.
110 Confirm, 121 Confirm,
122
123 /// Reject an in-progress verification due to mismatched Emoji.
111 Mismatch, 124 Mismatch,
112} 125}
113 126
127/// An action taken against the currently selected message.
114#[derive(Clone, Debug, Eq, PartialEq)] 128#[derive(Clone, Debug, Eq, PartialEq)]
115pub enum MessageAction { 129pub enum MessageAction {
116 /// Cance the current reply or edit. 130 /// Cance the current reply or edit.
@@ -145,6 +159,7 @@ pub enum MessageAction {
145 Unreact(Option<String>), 159 Unreact(Option<String>),
146} 160}
147 161
162/// The type of room being created.
148#[derive(Clone, Debug, Eq, PartialEq)] 163#[derive(Clone, Debug, Eq, PartialEq)]
149pub enum CreateRoomType { 164pub enum CreateRoomType {
150 /// A direct message room. 165 /// A direct message room.
@@ -158,7 +173,9 @@ pub enum CreateRoomType {
158} 173}
159 174
160bitflags::bitflags! { 175bitflags::bitflags! {
176 /// Available options for newly created rooms.
161 pub struct CreateRoomFlags: u32 { 177 pub struct CreateRoomFlags: u32 {
178 /// No flags specified.
162 const NONE = 0b00000000; 179 const NONE = 0b00000000;
163 180
164 /// Make the room public. 181 /// Make the room public.
@@ -170,7 +187,9 @@ bitflags::bitflags! {
170} 187}
171 188
172bitflags::bitflags! { 189bitflags::bitflags! {
190 /// Available options when downloading files.
173 pub struct DownloadFlags: u32 { 191 pub struct DownloadFlags: u32 {
192 /// No flags specified.
174 const NONE = 0b00000000; 193 const NONE = 0b00000000;
175 194
176 /// Overwrite file if it already exists. 195 /// Overwrite file if it already exists.
@@ -181,45 +200,91 @@ bitflags::bitflags! {
181 } 200 }
182} 201}
183 202
203/// A room property.
184#[derive(Clone, Debug, Eq, PartialEq)] 204#[derive(Clone, Debug, Eq, PartialEq)]
185pub enum RoomField { 205pub enum RoomField {
206 /// The room name.
186 Name, 207 Name,
208
209 /// A room tag.
187 Tag(TagName), 210 Tag(TagName),
211
212 /// The room topic.
188 Topic, 213 Topic,
189} 214}
190 215
216/// An action that operates on a focused room.
191#[derive(Clone, Debug, Eq, PartialEq)] 217#[derive(Clone, Debug, Eq, PartialEq)]
192pub enum RoomAction { 218pub enum RoomAction {
219 /// Accept an invitation to join this room.
193 InviteAccept, 220 InviteAccept,
221
222 /// Reject an invitation to join this room.
194 InviteReject, 223 InviteReject,
224
225 /// Invite a user to this room.
195 InviteSend(OwnedUserId), 226 InviteSend(OwnedUserId),
227
228 /// Leave this room.
196 Leave(bool), 229 Leave(bool),
230
231 /// Open the members window.
197 Members(Box<CommandContext<ProgramContext>>), 232 Members(Box<CommandContext<ProgramContext>>),
233
234 /// Set a room property.
198 Set(RoomField, String), 235 Set(RoomField, String),
236
237 /// Unset a room property.
199 Unset(RoomField), 238 Unset(RoomField),
200} 239}
201 240
241/// An action that sends a message to a room.
202#[derive(Clone, Debug, Eq, PartialEq)] 242#[derive(Clone, Debug, Eq, PartialEq)]
203pub enum SendAction { 243pub enum SendAction {
244 /// Send the text in the message bar.
204 Submit, 245 Submit,
246
247 /// Send text provided from an external editor.
205 SubmitFromEditor, 248 SubmitFromEditor,
249
250 /// Upload a file.
206 Upload(String), 251 Upload(String),
252
253 /// Upload the image data.
207 UploadImage(usize, usize, Cow<'static, [u8]>), 254 UploadImage(usize, usize, Cow<'static, [u8]>),
208} 255}
209 256
257/// An action performed against the user's homeserver.
210#[derive(Clone, Debug, Eq, PartialEq)] 258#[derive(Clone, Debug, Eq, PartialEq)]
211pub enum HomeserverAction { 259pub enum HomeserverAction {
260 /// Create a new room with an optional localpart.
212 CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags), 261 CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
213} 262}
214 263
264/// An action that the main program loop should.
265///
266/// See [the commands module][super::commands] for where these are usually created.
215#[derive(Clone, Debug, Eq, PartialEq)] 267#[derive(Clone, Debug, Eq, PartialEq)]
216pub enum IambAction { 268pub enum IambAction {
269 /// Perform an action against the homeserver.
217 Homeserver(HomeserverAction), 270 Homeserver(HomeserverAction),
271
272 /// Perform an action on the currently selected message.
218 Message(MessageAction), 273 Message(MessageAction),
274
275 /// Perform an action on the currently focused room.
219 Room(RoomAction), 276 Room(RoomAction),
277
278 /// Send a message to the currently focused room.
220 Send(SendAction), 279 Send(SendAction),
280
281 /// Perform an action for an in-progress verification.
221 Verify(VerifyAction, String), 282 Verify(VerifyAction, String),
283
284 /// Request a new verification with the specified user.
222 VerifyRequest(String), 285 VerifyRequest(String),
286
287 /// Toggle the focus within the focused room.
223 ToggleScrollbackFocus, 288 ToggleScrollbackFocus,
224} 289}
225 290
@@ -316,14 +381,21 @@ impl From<IambAction> for ProgramAction {
316 } 381 }
317} 382}
318 383
384/// Alias for program actions.
319pub type ProgramAction = Action<IambInfo>; 385pub type ProgramAction = Action<IambInfo>;
386/// Alias for program context.
320pub type ProgramContext = VimContext<IambInfo>; 387pub type ProgramContext = VimContext<IambInfo>;
388/// Alias for program keybindings.
321pub type Keybindings = VimMachine<TerminalKey, IambInfo>; 389pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
390/// Alias for a program command.
322pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>; 391pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
392/// Alias for mapped program commands.
323pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>; 393pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
394/// Alias for program store.
324pub type ProgramStore = Store<IambInfo>; 395pub type ProgramStore = Store<IambInfo>;
396/// Alias for shared program store.
325pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>; 397pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
326 398/// Alias for an action result.
327pub type IambResult<T> = UIResult<T, IambInfo>; 399pub type IambResult<T> = UIResult<T, IambInfo>;
328 400
329/// Reaction events for some message. 401/// Reaction events for some message.
@@ -332,61 +404,81 @@ pub type IambResult<T> = UIResult<T, IambInfo>;
332/// it's reacting to. 404/// it's reacting to.
333pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>; 405pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
334 406
407/// Map of read receipts for different events.
335pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>; 408pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
336 409
410/// Errors encountered during application use.
337#[derive(thiserror::Error, Debug)] 411#[derive(thiserror::Error, Debug)]
338pub enum IambError { 412pub enum IambError {
413 /// An invalid user identifier was specified.
339 #[error("Invalid user identifier: {0}")] 414 #[error("Invalid user identifier: {0}")]
340 InvalidUserId(String), 415 InvalidUserId(String),
341 416
417 /// An invalid verification identifier was specified.
342 #[error("Invalid verification user/device pair: {0}")] 418 #[error("Invalid verification user/device pair: {0}")]
343 InvalidVerificationId(String), 419 InvalidVerificationId(String),
344 420
421 /// A failure related to the cryptographic store.
345 #[error("Cryptographic storage error: {0}")] 422 #[error("Cryptographic storage error: {0}")]
346 CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError), 423 CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
347 424
425 /// An HTTP error.
348 #[error("HTTP client error: {0}")] 426 #[error("HTTP client error: {0}")]
349 Http(#[from] matrix_sdk::HttpError), 427 Http(#[from] matrix_sdk::HttpError),
350 428
429 /// A failure from the Matrix client.
351 #[error("Matrix client error: {0}")] 430 #[error("Matrix client error: {0}")]
352 Matrix(#[from] matrix_sdk::Error), 431 Matrix(#[from] matrix_sdk::Error),
353 432
433 /// A failure in the sled storage.
354 #[error("Matrix client storage error: {0}")] 434 #[error("Matrix client storage error: {0}")]
355 Store(#[from] matrix_sdk::StoreError), 435 Store(#[from] matrix_sdk::StoreError),
356 436
437 /// A failure during serialization or deserialization.
357 #[error("Serialization/deserialization error: {0}")] 438 #[error("Serialization/deserialization error: {0}")]
358 Serde(#[from] serde_json::Error), 439 Serde(#[from] serde_json::Error),
359 440
441 /// A failure due to not having a configured download directory.
360 #[error("No download directory configured")] 442 #[error("No download directory configured")]
361 NoDownloadDir, 443 NoDownloadDir,
362 444
445 /// A failure due to not having a message with an attachment selected.
363 #[error("Selected message does not have any attachments")] 446 #[error("Selected message does not have any attachments")]
364 NoAttachment, 447 NoAttachment,
365 448
449 /// A failure due to not having a message selected.
366 #[error("No message currently selected")] 450 #[error("No message currently selected")]
367 NoSelectedMessage, 451 NoSelectedMessage,
368 452
453 /// A failure due to not having a room or space selected.
369 #[error("Current window is not a room or space")] 454 #[error("Current window is not a room or space")]
370 NoSelectedRoomOrSpace, 455 NoSelectedRoomOrSpace,
371 456
457 /// A failure due to not having a room selected.
372 #[error("Current window is not a room")] 458 #[error("Current window is not a room")]
373 NoSelectedRoom, 459 NoSelectedRoom,
374 460
461 /// A failure due to not having an outstanding room invitation.
375 #[error("You do not have a current invitation to this room")] 462 #[error("You do not have a current invitation to this room")]
376 NotInvited, 463 NotInvited,
377 464
465 /// A failure due to not being a joined room member.
378 #[error("You need to join the room before you can do that")] 466 #[error("You need to join the room before you can do that")]
379 NotJoined, 467 NotJoined,
380 468
469 /// An unknown room was specified.
381 #[error("Unknown room identifier: {0}")] 470 #[error("Unknown room identifier: {0}")]
382 UnknownRoom(OwnedRoomId), 471 UnknownRoom(OwnedRoomId),
383 472
473 /// A failure occurred during verification.
384 #[error("Verification request error: {0}")] 474 #[error("Verification request error: {0}")]
385 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError), 475 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
386 476
477 /// A failure related to images.
387 #[error("Image error: {0}")] 478 #[error("Image error: {0}")]
388 Image(#[from] image::ImageError), 479 Image(#[from] image::ImageError),
389 480
481 /// A failure to access the system's clipboard.
390 #[error("Could not use system clipboard data")] 482 #[error("Could not use system clipboard data")]
391 Clipboard, 483 Clipboard,
392} 484}
@@ -399,16 +491,26 @@ impl From<IambError> for UIError<IambInfo> {
399 491
400impl ApplicationError for IambError {} 492impl ApplicationError for IambError {}
401 493
494/// Status for tracking how much room scrollback we've fetched.
402#[derive(Default)] 495#[derive(Default)]
403pub enum RoomFetchStatus { 496pub enum RoomFetchStatus {
497 /// Room history has been completely fetched.
404 Done, 498 Done,
499
500 /// More room history can be fetched.
405 HaveMore(String), 501 HaveMore(String),
502
503 /// We have not yet started fetching history for this room.
406 #[default] 504 #[default]
407 NotStarted, 505 NotStarted,
408} 506}
409 507
508/// Indicates where an [EventId] lives in the [ChatStore].
410pub enum EventLocation { 509pub enum EventLocation {
510 /// The [EventId] belongs to a message.
411 Message(MessageKey), 511 Message(MessageKey),
512
513 /// The [EventId] belongs to a reaction to the given event.
412 Reaction(OwnedEventId), 514 Reaction(OwnedEventId),
413} 515}
414 516
@@ -422,6 +524,7 @@ impl EventLocation {
422 } 524 }
423} 525}
424 526
527/// Information about room's the user's joined.
425#[derive(Default)] 528#[derive(Default)]
426pub struct RoomInfo { 529pub struct RoomInfo {
427 /// The display name for this room. 530 /// The display name for this room.
@@ -462,6 +565,7 @@ pub struct RoomInfo {
462} 565}
463 566
464impl RoomInfo { 567impl RoomInfo {
568 /// Get the reactions and their counts for a message.
465 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> { 569 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
466 if let Some(reacts) = self.reactions.get(event_id) { 570 if let Some(reacts) = self.reactions.get(event_id) {
467 let mut counts = HashMap::new(); 571 let mut counts = HashMap::new();
@@ -480,14 +584,17 @@ impl RoomInfo {
480 } 584 }
481 } 585 }
482 586
587 /// Map an event identifier to its [MessageKey].
483 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> { 588 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
484 self.keys.get(event_id)?.to_message_key() 589 self.keys.get(event_id)?.to_message_key()
485 } 590 }
486 591
592 /// Get an event for an identifier.
487 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> { 593 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
488 self.messages.get(self.get_message_key(event_id)?) 594 self.messages.get(self.get_message_key(event_id)?)
489 } 595 }
490 596
597 /// Insert a reaction to a message.
491 pub fn insert_reaction(&mut self, react: ReactionEvent) { 598 pub fn insert_reaction(&mut self, react: ReactionEvent) {
492 match react { 599 match react {
493 MessageLikeEvent::Original(react) => { 600 MessageLikeEvent::Original(react) => {
@@ -509,6 +616,7 @@ impl RoomInfo {
509 } 616 }
510 } 617 }
511 618
619 /// Insert an edit.
512 pub fn insert_edit(&mut self, msg: Replacement) { 620 pub fn insert_edit(&mut self, msg: Replacement) {
513 let event_id = msg.event_id; 621 let event_id = msg.event_id;
514 let new_content = msg.new_content; 622 let new_content = msg.new_content;
@@ -551,6 +659,7 @@ impl RoomInfo {
551 self.messages.insert(key, msg.into()); 659 self.messages.insert(key, msg.into());
552 } 660 }
553 661
662 /// Insert a new message.
554 pub fn insert_message(&mut self, msg: RoomMessageEvent) { 663 pub fn insert_message(&mut self, msg: RoomMessageEvent) {
555 let event_id = msg.event_id().to_owned(); 664 let event_id = msg.event_id().to_owned();
556 let key = (msg.origin_server_ts().into(), event_id.clone()); 665 let key = (msg.origin_server_ts().into(), event_id.clone());
@@ -563,6 +672,7 @@ impl RoomInfo {
563 let _ = self.messages.remove(&key); 672 let _ = self.messages.remove(&key);
564 } 673 }
565 674
675 /// Insert a new message event.
566 pub fn insert(&mut self, msg: RoomMessageEvent) { 676 pub fn insert(&mut self, msg: RoomMessageEvent) {
567 match msg { 677 match msg {
568 RoomMessageEvent::Original(OriginalRoomMessageEvent { 678 RoomMessageEvent::Original(OriginalRoomMessageEvent {
@@ -574,6 +684,7 @@ impl RoomInfo {
574 } 684 }
575 } 685 }
576 686
687 /// Indicates whether we've recently fetched scrollback for this room.
577 pub fn recently_fetched(&self) -> bool { 688 pub fn recently_fetched(&self) -> bool {
578 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE) 689 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
579 } 690 }
@@ -617,10 +728,12 @@ impl RoomInfo {
617 } 728 }
618 } 729 }
619 730
731 /// Update typing information for this room.
620 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) { 732 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
621 self.users_typing = (Instant::now(), user_ids).into(); 733 self.users_typing = (Instant::now(), user_ids).into();
622 } 734 }
623 735
736 /// Create a [Rect] that displays what users are typing.
624 pub fn render_typing( 737 pub fn render_typing(
625 &mut self, 738 &mut self,
626 area: Rect, 739 area: Rect,
@@ -646,6 +759,7 @@ impl RoomInfo {
646 } 759 }
647} 760}
648 761
762/// Generate a [CompletionMap] for Emoji shortcodes.
649fn emoji_map() -> CompletionMap<String, &'static Emoji> { 763fn emoji_map() -> CompletionMap<String, &'static Emoji> {
650 let mut emojis = CompletionMap::default(); 764 let mut emojis = CompletionMap::default();
651 765
@@ -658,27 +772,54 @@ fn emoji_map() -> CompletionMap<String, &'static Emoji> {
658 return emojis; 772 return emojis;
659} 773}
660 774
775/// Information gathered during server syncs about joined rooms.
661#[derive(Default)] 776#[derive(Default)]
662pub struct SyncInfo { 777pub struct SyncInfo {
778 /// Spaces that the user is a member of.
663 pub spaces: Vec<MatrixRoom>, 779 pub spaces: Vec<MatrixRoom>,
780
781 /// Rooms that the user is a member of.
664 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>, 782 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
783
784 /// DMs that the user is a member of.
665 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>, 785 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
666} 786}
667 787
788/// The main application state.
668pub struct ChatStore { 789pub struct ChatStore {
790 /// `:`-commands
669 pub cmds: ProgramCommands, 791 pub cmds: ProgramCommands,
792
793 /// Handle for communicating w/ the worker thread.
670 pub worker: Requester, 794 pub worker: Requester,
795
796 /// Map of joined rooms.
671 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>, 797 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
798
799 /// Map of room names.
672 pub names: CompletionMap<String, OwnedRoomId>, 800 pub names: CompletionMap<String, OwnedRoomId>,
801
802 /// Presence information for other users.
673 pub presences: CompletionMap<OwnedUserId, PresenceState>, 803 pub presences: CompletionMap<OwnedUserId, PresenceState>,
804
805 /// In-progress and completed verifications.
674 pub verifications: HashMap<String, SasVerification>, 806 pub verifications: HashMap<String, SasVerification>,
807
808 /// Settings for the current profile loaded from config file.
675 pub settings: ApplicationSettings, 809 pub settings: ApplicationSettings,
810
811 /// Set of rooms that need more messages loaded in their scrollback.
676 pub need_load: HashSet<OwnedRoomId>, 812 pub need_load: HashSet<OwnedRoomId>,
813
814 /// [CompletionMap] of Emoji shortcodes.
677 pub emojis: CompletionMap<String, &'static Emoji>, 815 pub emojis: CompletionMap<String, &'static Emoji>,
816
817 /// Information gathered by the background thread.
678 pub sync_info: SyncInfo, 818 pub sync_info: SyncInfo,
679} 819}
680 820
681impl ChatStore { 821impl ChatStore {
822 /// Create a new [ChatStore].
682 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self { 823 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
683 ChatStore { 824 ChatStore {
684 worker, 825 worker,
@@ -696,10 +837,12 @@ impl ChatStore {
696 } 837 }
697 } 838 }
698 839
840 /// Get a joined room.
699 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> { 841 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
700 self.worker.client.get_joined_room(room_id) 842 self.worker.client.get_joined_room(room_id)
701 } 843 }
702 844
845 /// Get the title for a room.
703 pub fn get_room_title(&self, room_id: &RoomId) -> String { 846 pub fn get_room_title(&self, room_id: &RoomId) -> String {
704 self.rooms 847 self.rooms
705 .get(room_id) 848 .get(room_id)
@@ -708,6 +851,7 @@ impl ChatStore {
708 .unwrap_or_else(|| "Untitled Matrix Room".to_string()) 851 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
709 } 852 }
710 853
854 /// Update the receipts for multiple rooms.
711 pub async fn set_receipts( 855 pub async fn set_receipts(
712 &mut self, 856 &mut self,
713 receipts: Vec<(OwnedRoomId, Receipts)>, 857 receipts: Vec<(OwnedRoomId, Receipts)>,
@@ -727,18 +871,22 @@ impl ChatStore {
727 return updates; 871 return updates;
728 } 872 }
729 873
874 /// Mark a room for loading more scrollback.
730 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) { 875 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
731 self.need_load.insert(room_id); 876 self.need_load.insert(room_id);
732 } 877 }
733 878
879 /// Get the [RoomInfo] for a given room identifier.
734 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo { 880 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
735 self.rooms.get_or_default(room_id) 881 self.rooms.get_or_default(room_id)
736 } 882 }
737 883
884 /// Set the name for a room.
738 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) { 885 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
739 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into(); 886 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
740 } 887 }
741 888
889 /// Insert a new E2EE verification.
742 pub fn insert_sas(&mut self, sas: SasVerification) { 890 pub fn insert_sas(&mut self, sas: SasVerification) {
743 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id()); 891 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
744 892
@@ -748,6 +896,7 @@ impl ChatStore {
748 896
749impl ApplicationStore for ChatStore {} 897impl ApplicationStore for ChatStore {}
750 898
899/// Identified used to track window content.
751#[derive(Clone, Debug, Eq, Hash, PartialEq)] 900#[derive(Clone, Debug, Eq, Hash, PartialEq)]
752pub enum IambId { 901pub enum IambId {
753 /// A Matrix room. 902 /// A Matrix room.
@@ -810,6 +959,7 @@ impl<'de> Deserialize<'de> for IambId {
810 } 959 }
811} 960}
812 961
962/// [serde] visitor for deserializing [IambId].
813struct IambIdVisitor; 963struct IambIdVisitor;
814 964
815impl<'de> Visitor<'de> for IambIdVisitor { 965impl<'de> Visitor<'de> for IambIdVisitor {
@@ -903,35 +1053,61 @@ impl<'de> Visitor<'de> for IambIdVisitor {
903 } 1053 }
904} 1054}
905 1055
1056/// Which part of the room window's UI is focused.
906#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] 1057#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
907pub enum RoomFocus { 1058pub enum RoomFocus {
1059 /// The scrollback for a room window is focused.
908 Scrollback, 1060 Scrollback,
1061
1062 /// The message bar for a room window is focused.
909 MessageBar, 1063 MessageBar,
910} 1064}
911 1065
912impl RoomFocus { 1066impl RoomFocus {
1067 /// Whether this is [RoomFocus::Scrollback].
913 pub fn is_scrollback(&self) -> bool { 1068 pub fn is_scrollback(&self) -> bool {
914 matches!(self, RoomFocus::Scrollback) 1069 matches!(self, RoomFocus::Scrollback)
915 } 1070 }
916 1071
1072 /// Whether this is [RoomFocus::MessageBar].
917 pub fn is_msgbar(&self) -> bool { 1073 pub fn is_msgbar(&self) -> bool {
918 matches!(self, RoomFocus::MessageBar) 1074 matches!(self, RoomFocus::MessageBar)
919 } 1075 }
920} 1076}
921 1077
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.
922#[derive(Clone, Debug, Eq, Hash, PartialEq)] 1082#[derive(Clone, Debug, Eq, Hash, PartialEq)]
923pub enum IambBufferId { 1083pub enum IambBufferId {
1084 /// The command bar buffer.
924 Command(CommandType), 1085 Command(CommandType),
1086
1087 /// The message buffer or a specific message in a room.
925 Room(OwnedRoomId, RoomFocus), 1088 Room(OwnedRoomId, RoomFocus),
1089
1090 /// The `:dms` window.
926 DirectList, 1091 DirectList,
1092
1093 /// The `:members` window for a room.
927 MemberList(OwnedRoomId), 1094 MemberList(OwnedRoomId),
1095
1096 /// The `:rooms` window.
928 RoomList, 1097 RoomList,
1098
1099 /// The `:spaces` window.
929 SpaceList, 1100 SpaceList,
1101
1102 /// The `:verify` window.
930 VerifyList, 1103 VerifyList,
1104
1105 /// The buffer for the `:rooms` window.
931 Welcome, 1106 Welcome,
932} 1107}
933 1108
934impl IambBufferId { 1109impl IambBufferId {
1110 /// Get the identifier for the window that contains this buffer.
935 pub fn to_window(&self) -> Option<IambId> { 1111 pub fn to_window(&self) -> Option<IambId> {
936 match self { 1112 match self {
937 IambBufferId::Command(_) => None, 1113 IambBufferId::Command(_) => None,
@@ -982,6 +1158,7 @@ impl ApplicationInfo for IambInfo {
982 } 1158 }
983} 1159}
984 1160
1161/// Tab completion for user IDs.
985fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> { 1162fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
986 let id = text 1163 let id = text
987 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD) 1164 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
@@ -997,6 +1174,7 @@ fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) ->
997 .collect() 1174 .collect()
998} 1175}
999 1176
1177/// Tab completion within the message bar.
1000fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> { 1178fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1001 let id = text 1179 let id = text
1002 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD) 1180 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
@@ -1044,6 +1222,7 @@ fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -
1044 } 1222 }
1045} 1223}
1046 1224
1225/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1047fn complete_matrix_names( 1226fn complete_matrix_names(
1048 text: &EditRope, 1227 text: &EditRope,
1049 cursor: &mut Cursor, 1228 cursor: &mut Cursor,
@@ -1073,6 +1252,7 @@ fn complete_matrix_names(
1073 .collect() 1252 .collect()
1074} 1253}
1075 1254
1255/// Tab completion for Emoji shortcode names.
1076fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> { 1256fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1077 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little); 1257 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1078 let sc = sc.unwrap_or_else(EditRope::empty); 1258 let sc = sc.unwrap_or_else(EditRope::empty);
@@ -1081,6 +1261,7 @@ fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) ->
1081 store.application.emojis.complete(sc.as_ref()) 1261 store.application.emojis.complete(sc.as_ref())
1082} 1262}
1083 1263
1264/// Tab completion for command names.
1084fn complete_cmdname( 1265fn complete_cmdname(
1085 desc: CommandDescription, 1266 desc: CommandDescription,
1086 text: &EditRope, 1267 text: &EditRope,
@@ -1092,6 +1273,7 @@ fn complete_cmdname(
1092 store.application.cmds.complete_name(desc.command.as_str()) 1273 store.application.cmds.complete_name(desc.command.as_str())
1093} 1274}
1094 1275
1276/// Tab completion for command arguments.
1095fn complete_cmdarg( 1277fn complete_cmdarg(
1096 desc: CommandDescription, 1278 desc: CommandDescription,
1097 text: &EditRope, 1279 text: &EditRope,
@@ -1120,6 +1302,7 @@ fn complete_cmdarg(
1120 } 1302 }
1121} 1303}
1122 1304
1305/// Tab completion for commands.
1123fn complete_cmd( 1306fn complete_cmd(
1124 cmd: &str, 1307 cmd: &str,
1125 text: &EditRope, 1308 text: &EditRope,
@@ -1141,6 +1324,7 @@ fn complete_cmd(
1141 } 1324 }
1142} 1325}
1143 1326
1327/// Tab completion for the command bar.
1144fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> { 1328fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1145 let eo = text.cursor_to_offset(cursor); 1329 let eo = text.cursor_to_offset(cursor);
1146 let slice = text.slice(0.into(), eo, false); 1330 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.
1use std::convert::TryFrom; 5use std::convert::TryFrom;
2 6
3use matrix_sdk::ruma::{events::tag::TagName, OwnedUserId}; 7use matrix_sdk::ruma::{events::tag::TagName, OwnedUserId};
@@ -555,6 +559,7 @@ fn add_iamb_commands(cmds: &mut ProgramCommands) {
555 }); 559 });
556} 560}
557 561
562/// Initialize the default command state.
558pub fn setup_commands() -> ProgramCommands { 563pub fn setup_commands() -> ProgramCommands {
559 let mut cmds = ProgramCommands::default(); 564 let mut cmds = ProgramCommands::default();
560 565
src/config.rs +1
@@ -1,3 +1,4 @@
1//! # Logic for loading and validating application configuration
1use std::borrow::Cow; 2use std::borrow::Cow;
2use std::collections::hash_map::DefaultHasher; 3use std::collections::hash_map::DefaultHasher;
3use std::collections::HashMap; 4use 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].
1use modalkit::{ 5use modalkit::{
2 editing::action::WindowAction, 6 editing::action::WindowAction,
3 env::vim::keybindings::{InputStep, VimBindings}, 7 env::vim::keybindings::{InputStep, VimBindings},
@@ -10,6 +14,7 @@ use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
10 14
11type IambStep = InputStep<IambInfo>; 15type IambStep = InputStep<IambInfo>;
12 16
17/// Initialize the default keybinding state.
13pub fn setup_keybindings() -> Keybindings { 18pub fn setup_keybindings() -> Keybindings {
14 let mut ism = Keybindings::empty(); 19 let mut ism = Keybindings::empty();
15 20
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.
1#![allow(clippy::manual_range_contains)] 14#![allow(clippy::manual_range_contains)]
2#![allow(clippy::needless_return)] 15#![allow(clippy::needless_return)]
3#![allow(clippy::result_large_err)] 16#![allow(clippy::result_large_err)]
@@ -200,6 +213,7 @@ fn setup_screen(
200 return Ok(ScreenState::new(win, cmd)); 213 return Ok(ScreenState::new(win, cmd));
201} 214}
202 215
216/// The main application state and event loop.
203struct Application { 217struct Application {
204 /// Terminal backend. 218 /// Terminal backend.
205 terminal: Terminal<CrosstermBackend<Stdout>>, 219 terminal: Terminal<CrosstermBackend<Stdout>>,
src/message/html.rs +10 −1
@@ -37,7 +37,8 @@ use crate::{
37 util::{join_cell_text, space_text}, 37 util::{join_cell_text, space_text},
38}; 38};
39 39
40struct BulletIterator { 40/// Generate bullet points from a [ListStyle].
41pub struct BulletIterator {
41 style: ListStyle, 42 style: ListStyle,
42 pos: usize, 43 pos: usize,
43 len: usize, 44 len: usize,
@@ -74,6 +75,7 @@ impl Iterator for BulletIterator {
74 } 75 }
75} 76}
76 77
78/// Whether this list is ordered or unordered.
77#[derive(Clone, Copy, Debug)] 79#[derive(Clone, Copy, Debug)]
78pub enum ListStyle { 80pub enum ListStyle {
79 Ordered, 81 Ordered,
@@ -88,11 +90,13 @@ impl ListStyle {
88 90
89pub type StyleTreeChildren = Vec<StyleTreeNode>; 91pub type StyleTreeChildren = Vec<StyleTreeNode>;
90 92
93/// Type of contents in a table cell.
91pub enum CellType { 94pub enum CellType {
92 Data, 95 Data,
93 Header, 96 Header,
94} 97}
95 98
99/// A collection of cells for a single row in a table.
96pub struct TableRow { 100pub struct TableRow {
97 cells: Vec<(CellType, StyleTreeNode)>, 101 cells: Vec<(CellType, StyleTreeNode)>,
98} 102}
@@ -103,6 +107,7 @@ impl TableRow {
103 } 107 }
104} 108}
105 109
110/// A collection of rows in a table.
106pub struct TableSection { 111pub struct TableSection {
107 rows: Vec<TableRow>, 112 rows: Vec<TableRow>,
108} 113}
@@ -113,6 +118,7 @@ impl TableSection {
113 } 118 }
114} 119}
115 120
121/// A table.
116pub struct Table { 122pub struct Table {
117 caption: Option<Box<StyleTreeNode>>, 123 caption: Option<Box<StyleTreeNode>>,
118 sections: Vec<TableSection>, 124 sections: Vec<TableSection>,
@@ -229,6 +235,7 @@ impl Table {
229 } 235 }
230} 236}
231 237
238/// A processed HTML element that we can render to the terminal.
232pub enum StyleTreeNode { 239pub enum StyleTreeNode {
233 Blockquote(Box<StyleTreeNode>), 240 Blockquote(Box<StyleTreeNode>),
234 Break, 241 Break,
@@ -380,6 +387,7 @@ impl StyleTreeNode {
380 } 387 }
381} 388}
382 389
390/// A processed HTML document.
383pub struct StyleTree { 391pub struct StyleTree {
384 children: StyleTreeChildren, 392 children: StyleTreeChildren,
385} 393}
@@ -649,6 +657,7 @@ fn dom_to_style_tree(dom: RcDom) -> StyleTree {
649 StyleTree { children: h2t(&dom.document) } 657 StyleTree { children: h2t(&dom.document) }
650} 658}
651 659
660/// Parse an HTML document from a string.
652pub fn parse_matrix_html(s: &str) -> StyleTree { 661pub fn parse_matrix_html(s: &str) -> StyleTree {
653 let dom = parse_fragment( 662 let dom = parse_fragment(
654 RcDom::default(), 663 RcDom::default(),
src/message/mod.rs +1
@@ -1,3 +1,4 @@
1//! # Room Messages
1use std::borrow::Cow; 2use std::borrow::Cow;
2use std::cmp::{Ord, Ordering, PartialOrd}; 3use std::cmp::{Ord, Ordering, PartialOrd};
3use std::collections::hash_map::DefaultHasher; 4use 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).
1use std::borrow::Cow; 6use std::borrow::Cow;
2 7
3use modalkit::tui::layout::Alignment; 8use modalkit::tui::layout::Alignment;
@@ -8,6 +13,7 @@ use unicode_width::UnicodeWidthStr;
8 13
9use crate::util::{space_span, take_width}; 14use crate::util::{space_span, take_width};
10 15
16/// Wrap styled text for the current terminal width.
11pub struct TextPrinter<'a> { 17pub struct TextPrinter<'a> {
12 text: Text<'a>, 18 text: Text<'a>,
13 width: usize, 19 width: usize,
@@ -21,6 +27,7 @@ pub struct TextPrinter<'a> {
21} 27}
22 28
23impl<'a> TextPrinter<'a> { 29impl<'a> TextPrinter<'a> {
30 /// Create a new printer.
24 pub fn new(width: usize, base_style: Style, hide_reply: bool) -> Self { 31 pub fn new(width: usize, base_style: Style, hide_reply: bool) -> Self {
25 TextPrinter { 32 TextPrinter {
26 text: Text::default(), 33 text: Text::default(),
@@ -35,24 +42,29 @@ impl<'a> TextPrinter<'a> {
35 } 42 }
36 } 43 }
37 44
45 /// Configure the alignment for each line.
38 pub fn align(mut self, alignment: Alignment) -> Self { 46 pub fn align(mut self, alignment: Alignment) -> Self {
39 self.alignment = alignment; 47 self.alignment = alignment;
40 self 48 self
41 } 49 }
42 50
51 /// Set whether newlines should be treated literally, or turned into spaces.
43 pub fn literal(mut self, literal: bool) -> Self { 52 pub fn literal(mut self, literal: bool) -> Self {
44 self.literal = literal; 53 self.literal = literal;
45 self 54 self
46 } 55 }
47 56
57 /// Indicates whether replies should be pushed to the printer.
48 pub fn hide_reply(&self) -> bool { 58 pub fn hide_reply(&self) -> bool {
49 self.hide_reply 59 self.hide_reply
50 } 60 }
51 61
62 /// Indicates the current printer's width.
52 pub fn width(&self) -> usize { 63 pub fn width(&self) -> usize {
53 self.width 64 self.width
54 } 65 }
55 66
67 /// Create a new printer with a smaller width.
56 pub fn sub(&self, indent: usize) -> Self { 68 pub fn sub(&self, indent: usize) -> Self {
57 TextPrinter { 69 TextPrinter {
58 text: Text::default(), 70 text: Text::default(),
@@ -71,6 +83,7 @@ impl<'a> TextPrinter<'a> {
71 self.width - self.curr_width 83 self.width - self.curr_width
72 } 84 }
73 85
86 /// If there is any text on the current line, start a new one.
74 pub fn commit(&mut self) { 87 pub fn commit(&mut self) {
75 if self.curr_width > 0 { 88 if self.curr_width > 0 {
76 self.push_break(); 89 self.push_break();
@@ -82,6 +95,7 @@ impl<'a> TextPrinter<'a> {
82 self.text.lines.push(Spans(std::mem::take(&mut self.curr_spans))); 95 self.text.lines.push(Spans(std::mem::take(&mut self.curr_spans)));
83 } 96 }
84 97
98 /// Start a new line.
85 pub fn push_break(&mut self) { 99 pub fn push_break(&mut self) {
86 if self.curr_width == 0 && self.text.lines.is_empty() { 100 if self.curr_width == 0 && self.text.lines.is_empty() {
87 // Disallow leading breaks. 101 // Disallow leading breaks.
@@ -149,6 +163,7 @@ impl<'a> TextPrinter<'a> {
149 } 163 }
150 } 164 }
151 165
166 /// Push a [Span] that isn't allowed to break across lines.
152 pub fn push_span_nobreak(&mut self, span: Span<'a>) { 167 pub fn push_span_nobreak(&mut self, span: Span<'a>) {
153 let sw = UnicodeWidthStr::width(span.content.as_ref()); 168 let sw = UnicodeWidthStr::width(span.content.as_ref());
154 169
@@ -161,6 +176,7 @@ impl<'a> TextPrinter<'a> {
161 self.curr_width += sw; 176 self.curr_width += sw;
162 } 177 }
163 178
179 /// Push text with a [Style].
164 pub fn push_str(&mut self, s: &'a str, style: Style) { 180 pub fn push_str(&mut self, s: &'a str, style: Style) {
165 let style = self.base_style.patch(style); 181 let style = self.base_style.patch(style);
166 182
@@ -212,16 +228,19 @@ impl<'a> TextPrinter<'a> {
212 } 228 }
213 } 229 }
214 230
231 /// Push [Spans] into the printer.
215 pub fn push_line(&mut self, spans: Spans<'a>) { 232 pub fn push_line(&mut self, spans: Spans<'a>) {
216 self.commit(); 233 self.commit();
217 self.text.lines.push(spans); 234 self.text.lines.push(spans);
218 } 235 }
219 236
237 /// Push multiline [Text] into the printer.
220 pub fn push_text(&mut self, text: Text<'a>) { 238 pub fn push_text(&mut self, text: Text<'a>) {
221 self.commit(); 239 self.commit();
222 self.text.lines.extend(text.lines); 240 self.text.lines.extend(text.lines);
223 } 241 }
224 242
243 /// Render the contents of this printer as [Text].
225 pub fn finish(mut self) -> Text<'a> { 244 pub fn finish(mut self) -> Text<'a> {
226 self.commit(); 245 self.commit();
227 self.text 246 self.text
src/util.rs +1
@@ -1,3 +1,4 @@
1//! # Utility functions
1use std::borrow::Cow; 2use std::borrow::Cow;
2 3
3use unicode_segmentation::UnicodeSegmentation; 4use 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.
1use std::cmp::{Ord, Ordering, PartialOrd}; 9use std::cmp::{Ord, Ordering, PartialOrd};
2use std::ops::Deref; 10use std::ops::Deref;
3use std::sync::Arc; 11use std::sync::Arc;
src/windows/room/chat.rs +3
@@ -1,3 +1,4 @@
1//! Window for Matrix rooms
1use std::borrow::Cow; 2use std::borrow::Cow;
2use std::ffi::{OsStr, OsString}; 3use std::ffi::{OsStr, OsString};
3use std::fs; 4use std::fs;
@@ -85,6 +86,7 @@ use crate::worker::Requester;
85 86
86use super::scrollback::{Scrollback, ScrollbackState}; 87use super::scrollback::{Scrollback, ScrollbackState};
87 88
89/// State needed for rendering [Chat].
88pub struct ChatState { 90pub struct ChatState {
89 room_id: OwnedRoomId, 91 room_id: OwnedRoomId,
90 room: MatrixRoom, 92 room: MatrixRoom,
@@ -786,6 +788,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
786 } 788 }
787} 789}
788 790
791/// [StatefulWidget] for Matrix rooms.
789pub struct Chat<'a> { 792pub struct Chat<'a> {
790 store: &'a mut ProgramStore, 793 store: &'a mut ProgramStore,
791 focused: bool, 794 focused: bool,
src/windows/room/mod.rs +6
@@ -1,3 +1,4 @@
1//! # Windows for Matrix rooms and spaces
1use matrix_sdk::{ 2use matrix_sdk::{
2 room::{Invited, Room as MatrixRoom}, 3 room::{Invited, Room as MatrixRoom},
3 ruma::{ 4 ruma::{
@@ -79,6 +80,11 @@ macro_rules! delegate {
79 }; 80 };
80} 81}
81 82
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.
82pub enum RoomState { 88pub enum RoomState {
83 Chat(ChatState), 89 Chat(ChatState),
84 Space(SpaceState), 90 Space(SpaceState),
src/windows/room/scrollback.rs +1
@@ -1,3 +1,4 @@
1//! Message scrollback
1use std::collections::HashSet; 2use std::collections::HashSet;
2 3
3use regex::Regex; 4use regex::Regex;
src/windows/room/space.rs +3
@@ -1,3 +1,4 @@
1//! Window for Matrix spaces
1use std::ops::{Deref, DerefMut}; 2use std::ops::{Deref, DerefMut};
2use std::time::{Duration, Instant}; 3use std::time::{Duration, Instant};
3 4
@@ -25,6 +26,7 @@ use crate::windows::RoomItem;
25 26
26const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5); 27const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
27 28
29/// State needed for rendering [Space].
28pub struct SpaceState { 30pub struct SpaceState {
29 room_id: OwnedRoomId, 31 room_id: OwnedRoomId,
30 room: MatrixRoom, 32 room: MatrixRoom,
@@ -86,6 +88,7 @@ impl DerefMut for SpaceState {
86 } 88 }
87} 89}
88 90
91/// [StatefulWidget] for Matrix spaces.
89pub struct Space<'a> { 92pub struct Space<'a> {
90 focused: bool, 93 focused: bool,
91 store: &'a mut ProgramStore, 94 store: &'a mut ProgramStore,
src/windows/welcome.rs +1
@@ -1,3 +1,4 @@
1//! Welcome Window
1use std::ops::{Deref, DerefMut}; 2use std::ops::{Deref, DerefMut};
2 3
3use modalkit::tui::{buffer::Buffer, layout::Rect}; 4use 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.
1use std::collections::HashMap; 5use std::collections::HashMap;
2use std::convert::TryFrom; 6use std::convert::TryFrom;
3use std::fmt::{Debug, Formatter}; 7use std::fmt::{Debug, Formatter};