Commit f0a595f780

f0a595f7801ba5a58390140c5e6ef11905a97259

parent: 85a3af4f23

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-07-29 11:14 UTC
committer: <strk@kbt.io>

feat: make space buffers useful

Layout: unified · split

src/lib.rs +1 −1
@@ -190,7 +190,7 @@ impl SignalCallback for Servers {
190190 })
191191 .detach();
192192 }
193 "input_text_changed" => room.update_typing_notice(),
193 "input_text_changed" => room.update_input(&buffer),
194194 _ => (),
195195 }
196196 }
src/room/buffer.rs +314 −13
@@ -2,12 +2,14 @@ use std::{borrow::Cow, cell::RefCell, collections::HashMap, rc::Rc};
22
33use futures_util::StreamExt;
44use matrix_sdk::{
5 deserialized_responses::SyncOrStrippedState,
56 room::ParentSpace,
67 ruma::{
7 EventId, OwnedEventId, OwnedRoomAliasId, OwnedUserId, TransactionId,
8 UserId,
8 events::{space::child::SpaceChildEventContent, SyncStateEvent},
9 EventId, OwnedEventId, OwnedRoomAliasId, OwnedRoomId, OwnedServerName,
10 OwnedUserId, TransactionId, UserId,
911 },
10 Error, Room,
12 Error, Room, RoomState,
1113};
1214use tokio::runtime::Handle;
1315use weechat::{
@@ -25,6 +27,7 @@ pub struct RoomBuffer {
2527 runtime: Handle,
2628 pub(super) inner: Rc<RefCell<Option<BufferHandle>>>,
2729 thread_buffers: Rc<RefCell<HashMap<OwnedEventId, BufferHandle>>>,
30 space_children: Rc<RefCell<Vec<SpaceChildInfo>>>,
2831}
2932
3033struct LineCopy {
@@ -54,6 +57,7 @@ impl RoomBuffer {
5457 runtime,
5558 inner: Rc::new(RefCell::new(None)),
5659 thread_buffers: Rc::new(RefCell::new(HashMap::new())),
60 space_children: Rc::new(RefCell::new(Vec::new())),
5761 }
5862 }
5963
@@ -112,13 +116,7 @@ impl RoomBuffer {
112116 }
113117
114118 pub fn owns_buffer(&self, buffer: &Buffer) -> bool {
115 if self
116 .inner
117 .borrow()
118 .as_ref()
119 .and_then(|b| b.upgrade().ok())
120 .is_some_and(|b| &b == buffer)
121 {
119 if self.is_main_buffer(buffer) {
122120 return true;
123121 }
124122
@@ -128,6 +126,14 @@ impl RoomBuffer {
128126 .any(|handle| handle.upgrade().is_ok_and(|b| &b == buffer))
129127 }
130128
129 pub fn is_main_buffer(&self, buffer: &Buffer) -> bool {
130 self.inner
131 .borrow()
132 .as_ref()
133 .and_then(|b| b.upgrade().ok())
134 .is_some_and(|b| &b == buffer)
135 }
136
131137 pub fn thread_root_for_buffer(
132138 &self,
133139 buffer: &Buffer,
@@ -536,6 +542,81 @@ impl RoomBuffer {
536542 }
537543 }
538544
545 pub fn refresh_space_children(&self) {
546 let Some(room) = maybe_active_room(&self.room) else {
547 return;
548 };
549
550 if !room.is_space() {
551 return;
552 }
553
554 match self.runtime.block_on(space_children(room)) {
555 Ok(children) => {
556 *self.space_children.borrow_mut() = children;
557 self.render_space_children();
558 }
559 Err(error) => {
560 Weechat::print(&format!(
561 "{}: Error fetching space children from the store: {}",
562 Weechat::prefix(Prefix::Error),
563 error,
564 ));
565 }
566 }
567 }
568
569 /// Reuse the room buffer input as a live filter, like WeeChat's `/fset`.
570 ///
571 /// The stable numbers refer to the unfiltered hierarchy so narrowing and
572 /// selecting never changes the target underneath the user.
573 pub fn render_space_children(&self) {
574 let buffer_handle = self.buffer_handle();
575 let Ok(buffer) = buffer_handle.upgrade() else {
576 return;
577 };
578
579 let input = buffer.input();
580 let children = self.space_children.borrow();
581 let visible = filter_space_children(&children, &input);
582
583 buffer.clear();
584 buffer.set_title(&format!(
585 "Space rooms: showing {} of {}. Type to filter; press Enter on a \
586 number or unique name to open/join.",
587 visible.len(),
588 children.len(),
589 ));
590
591 if visible.is_empty() {
592 buffer.print("No rooms match this filter.");
593 return;
594 }
595
596 for (index, child) in visible {
597 let action = if child.joined { "open" } else { "join" };
598 let kind = if child.is_space { "space" } else { "room" };
599
600 buffer.print(&format!(
601 "{:>3} [{action} {kind}] {} {}",
602 index + 1,
603 child.name,
604 child.room_id,
605 ));
606 }
607 }
608
609 pub fn space_child_command(
610 &self,
611 input: &str,
612 server_name: &str,
613 ) -> SpaceChildSelection {
614 select_space_child(&self.space_children.borrow(), input)
615 .map_or(SpaceChildSelection::NoMatch, |child| {
616 space_child_selection(server_name, child)
617 })
618 }
619
539620 fn alias(&self) -> Option<OwnedRoomAliasId> {
540621 maybe_active_room(&self.room).and_then(|room| room.canonical_alias())
541622 }
@@ -579,6 +660,83 @@ impl RoomBuffer {
579660 }
580661}
581662
663#[derive(Clone, Debug, Eq, PartialEq)]
664struct SpaceChildInfo {
665 room_id: OwnedRoomId,
666 name: String,
667 joined: bool,
668 is_space: bool,
669 order: Option<String>,
670 via: Vec<OwnedServerName>,
671}
672
673#[derive(Clone, Debug, Eq, PartialEq)]
674pub(super) enum SpaceChildSelection {
675 Open(String),
676 Join {
677 room_id: OwnedRoomId,
678 via: Vec<OwnedServerName>,
679 },
680 NoMatch,
681}
682
683fn filter_space_children<'a>(
684 children: &'a [SpaceChildInfo],
685 input: &str,
686) -> Vec<(usize, &'a SpaceChildInfo)> {
687 let query = input.trim().to_lowercase();
688
689 children
690 .iter()
691 .enumerate()
692 .filter(|(_, child)| {
693 query.is_empty()
694 || child.name.to_lowercase().contains(&query)
695 || child.room_id.as_str().to_lowercase().contains(&query)
696 })
697 .collect()
698}
699
700fn select_space_child<'a>(
701 children: &'a [SpaceChildInfo],
702 input: &str,
703) -> Option<&'a SpaceChildInfo> {
704 let input = input.trim();
705
706 if input.is_empty() {
707 return None;
708 }
709
710 if let Ok(index) = input.parse::<usize>() {
711 return index.checked_sub(1).and_then(|index| children.get(index));
712 }
713
714 let matches = filter_space_children(children, input);
715
716 if matches.len() == 1 {
717 matches.first().map(|(_, child)| *child)
718 } else {
719 None
720 }
721}
722
723fn space_child_selection(
724 server_name: &str,
725 child: &SpaceChildInfo,
726) -> SpaceChildSelection {
727 if child.joined {
728 SpaceChildSelection::Open(format!(
729 "/buffer {}.{}",
730 server_name, child.room_id
731 ))
732 } else {
733 SpaceChildSelection::Join {
734 room_id: child.room_id.clone(),
735 via: child.via.clone(),
736 }
737 }
738}
739
582740fn buffer_contains_tag(buffer: &Buffer, tag: &Cow<str>) -> bool {
583741 buffer
584742 .lines()
@@ -896,13 +1054,30 @@ fn replace_local_echo_in_buffer(
8961054
8971055#[cfg(test)]
8981056mod tests {
899 use matrix_sdk::ruma::{event_id, user_id};
1057 use matrix_sdk::ruma::{event_id, room_id, user_id};
9001058
9011059 use super::{
902 format_buffer_name, format_thread_buffer_name, line_sort_key,
903 reply_sender_id_from_tags, sanitize_thread_id, RoomBuffer,
1060 filter_space_children, format_buffer_name, format_thread_buffer_name,
1061 line_sort_key, reply_sender_id_from_tags, sanitize_thread_id,
1062 select_space_child, space_child_selection, RoomBuffer, SpaceChildInfo,
1063 SpaceChildSelection,
9041064 };
9051065
1066 fn space_child(
1067 room_id: &matrix_sdk::ruma::RoomId,
1068 name: &str,
1069 joined: bool,
1070 ) -> SpaceChildInfo {
1071 SpaceChildInfo {
1072 room_id: room_id.to_owned(),
1073 name: name.to_owned(),
1074 joined,
1075 is_space: false,
1076 order: None,
1077 via: vec!["example.org".parse().unwrap()],
1078 }
1079 }
1080
9061081 #[test]
9071082 fn reply_sender_uses_matrix_sender_tag() {
9081083 let tags = ["matrix_text", "matrix_sender_@alice:example.org"];
@@ -985,6 +1160,64 @@ mod tests {
9851160 assert_eq!(format_buffer_name("+", false, true), "++");
9861161 }
9871162
1163 #[test]
1164 fn filters_space_children_by_name_or_room_id() {
1165 let children = [
1166 space_child(room_id!("!alpha:example.org"), "Alpha", true),
1167 space_child(room_id!("!beta:example.org"), "Release room", false),
1168 ];
1169
1170 let by_name = filter_space_children(&children, "RELEASE");
1171 let by_id = filter_space_children(&children, "!ALPHA");
1172
1173 assert_eq!(by_name.len(), 1);
1174 assert_eq!(by_name[0].1.room_id, room_id!("!beta:example.org"));
1175 assert_eq!(by_id.len(), 1);
1176 assert_eq!(by_id[0].1.room_id, room_id!("!alpha:example.org"));
1177 }
1178
1179 #[test]
1180 fn selects_space_child_by_number_or_unique_filter() {
1181 let children = [
1182 space_child(room_id!("!alpha:example.org"), "Alpha", true),
1183 space_child(room_id!("!alpine:example.org"), "Alpine", false),
1184 space_child(room_id!("!beta:example.org"), "Beta", false),
1185 ];
1186
1187 assert_eq!(
1188 select_space_child(&children, "2")
1189 .map(|child| child.room_id.as_ref()),
1190 Some(room_id!("!alpine:example.org")),
1191 );
1192 assert_eq!(
1193 select_space_child(&children, "bet")
1194 .map(|child| child.room_id.as_ref()),
1195 Some(room_id!("!beta:example.org")),
1196 );
1197 assert!(select_space_child(&children, "alp").is_none());
1198 }
1199
1200 #[test]
1201 fn opens_joined_space_children_and_joins_other_children() {
1202 let joined =
1203 space_child(room_id!("!joined:example.org"), "Joined", true);
1204 let left = space_child(room_id!("!left:example.org"), "Left", false);
1205
1206 assert_eq!(
1207 space_child_selection("matrix", &joined),
1208 SpaceChildSelection::Open(
1209 "/buffer matrix.!joined:example.org".to_owned()
1210 ),
1211 );
1212 assert_eq!(
1213 space_child_selection("matrix", &left),
1214 SpaceChildSelection::Join {
1215 room_id: room_id!("!left:example.org").to_owned(),
1216 via: vec!["example.org".parse().unwrap()],
1217 },
1218 );
1219 }
1220
9881221 #[test]
9891222 fn sanitizes_thread_event_id_for_buffer_name() {
9901223 assert_eq!(
@@ -1049,3 +1282,71 @@ async fn parent_spaces(room: Room) -> Result<Vec<ParentSpaceInfo>, Error> {
10491282
10501283 Ok(spaces)
10511284}
1285
1286async fn space_children(room: Room) -> Result<Vec<SpaceChildInfo>, Error> {
1287 let client = room.client();
1288 let mut children = Vec::new();
1289
1290 for raw_event in room
1291 .get_state_events_static::<SpaceChildEventContent>()
1292 .await?
1293 {
1294 let event =
1295 match raw_event.deserialize() {
1296 Ok(SyncOrStrippedState::Sync(SyncStateEvent::Original(
1297 event,
1298 ))) if !event.content.via.is_empty() => event,
1299 Ok(_) => continue,
1300 Err(error) => {
1301 tracing::warn!(
1302 room_id = ?room.room_id(),
1303 "Could not deserialize m.space.child: {error}"
1304 );
1305 continue;
1306 }
1307 };
1308
1309 let room_id = event.state_key;
1310 let order = event.content.order.map(|order| order.to_string());
1311
1312 let (name, joined, is_space) =
1313 if let Some(child_room) = client.get_room(&room_id) {
1314 let joined = child_room.state() == RoomState::Joined;
1315 let is_space = child_room.is_space();
1316 let name = child_room
1317 .display_name()
1318 .await
1319 .map(|name| name.to_string())
1320 .unwrap_or_else(|_| room_id.to_string());
1321
1322 (name, joined, is_space)
1323 } else {
1324 // The local state store knows the hierarchy relation but not a
1325 // summary for rooms we have never joined. The room ID remains
1326 // a useful, selectable fallback.
1327 (room_id.to_string(), false, false)
1328 };
1329
1330 children.push(SpaceChildInfo {
1331 room_id,
1332 name,
1333 joined,
1334 is_space,
1335 order,
1336 via: event.content.via,
1337 });
1338 }
1339
1340 children.sort_by(|left, right| {
1341 left.order
1342 .is_none()
1343 .cmp(&right.order.is_none())
1344 .then_with(|| left.order.cmp(&right.order))
1345 .then_with(|| {
1346 left.name.to_lowercase().cmp(&right.name.to_lowercase())
1347 })
1348 .then_with(|| left.room_id.cmp(&right.room_id))
1349 });
1350
1351 Ok(children)
1352}
src/room/mod.rs +97 −3
@@ -26,7 +26,7 @@ mod buffer;
2626mod members;
2727mod verification;
2828
29use buffer::{print_rendered_event_to_buffer, RoomBuffer};
29use buffer::{print_rendered_event_to_buffer, RoomBuffer, SpaceChildSelection};
3030use members::Members;
3131pub use members::WeechatRoomMember;
3232use tokio::runtime::Handle;
@@ -44,6 +44,7 @@ use std::{
4444 atomic::{AtomicBool, Ordering},
4545 Mutex, MutexGuard,
4646 },
47 time::Duration,
4748};
4849
4950use unicode_segmentation::UnicodeSegmentation;
@@ -75,8 +76,8 @@ use matrix_sdk::{
7576 },
7677 serde::Raw,
7778 EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomAliasId,
78 OwnedRoomId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId,
79 UInt, UserId,
79 OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedTransactionId,
80 OwnedUserId, RoomId, TransactionId, UInt, UserId,
8081 },
8182 StoreError,
8283};
@@ -103,6 +104,8 @@ pub struct RoomHandle {
103104
104105pub(super) type SharedRoom = Rc<RefCell<Option<Room>>>;
105106
107const SPACE_JOIN_TIMEOUT: Duration = Duration::from_secs(120);
108
106109pub(super) fn maybe_active_room(room: &SharedRoom) -> Option<Room> {
107110 room.borrow().as_ref().cloned()
108111}
@@ -591,6 +594,14 @@ impl RoomHandle {
591594 *room.buffer.inner.borrow_mut() = Some(buffer_handle.clone());
592595 room.buffer.update_parent_spaces();
593596
597 if room.room().is_space() {
598 buffer.disable_nicklist();
599 buffer.disable_nicklist_groups();
600 buffer.disable_multiline();
601 buffer.disable_log();
602 room.buffer.refresh_space_children();
603 }
604
594605 Self { inner: room }
595606 }
596607
@@ -639,6 +650,7 @@ impl RoomHandle {
639650 room_buffer.buffer.update_buffer_name();
640651 room_buffer.buffer.set_topic();
641652 room_buffer.buffer.update_parent_spaces();
653 room_buffer.buffer.refresh_space_children();
642654
643655 Ok(room_buffer)
644656 }
@@ -647,6 +659,30 @@ impl RoomHandle {
647659#[async_trait(?Send)]
648660impl BufferInputCallbackAsync for MatrixRoom {
649661 async fn callback(&mut self, buffer: BufferHandle, input: String) {
662 // Only the main Space buffer is a hierarchy selector. A thread buffer
663 // belonging to the same Matrix room keeps normal message semantics.
664 let space_buffer = buffer.upgrade().ok().filter(|buffer| {
665 self.room().is_space() && self.buffer.is_main_buffer(buffer)
666 });
667
668 if let Some(buffer) = space_buffer {
669 let Some(server_name) = buffer.get_localvar("server") else {
670 return;
671 };
672
673 match self.buffer.space_child_command(&input, &server_name) {
674 SpaceChildSelection::Open(command) => {
675 let _ = buffer.run_command(&command);
676 }
677 SpaceChildSelection::Join { room_id, via } => {
678 self.join_space_child(room_id, via).await;
679 }
680 SpaceChildSelection::NoMatch => {}
681 }
682
683 return;
684 }
685
650686 let thread_root = buffer
651687 .upgrade()
652688 .ok()
@@ -687,6 +723,49 @@ impl MatrixRoom {
687723 )
688724 }
689725
726 async fn join_space_child(
727 &self,
728 room_id: OwnedRoomId,
729 via: Vec<OwnedServerName>,
730 ) {
731 let Some(connection) = self.connection.borrow().clone() else {
732 self.print_error("Not connected. Please connect first.");
733 return;
734 };
735
736 self.print_network(&format!("Joining room {}...", room_id));
737
738 let client = connection.client().clone();
739 let target = room_id.to_string();
740 let room_id_or_alias: OwnedRoomOrAliasId =
741 room_id.as_str().parse().expect("valid Matrix room ID");
742 let result = connection
743 .spawn(async move {
744 tokio::time::timeout(SPACE_JOIN_TIMEOUT, async move {
745 client
746 .join_room_by_id_or_alias(&room_id_or_alias, &via)
747 .await
748 })
749 .await
750 })
751 .await;
752
753 match result {
754 Ok(Ok(room)) => self.print_network(&format!(
755 "Successfully joined room {}",
756 room.room_id()
757 )),
758 Ok(Err(error)) => self
759 .print_error(&format!("Failed to join {}: {}", target, error)),
760 Err(error) => self.print_error(&format!(
761 "Timed out joining {} after {} seconds: {}",
762 target,
763 SPACE_JOIN_TIMEOUT.as_secs(),
764 error
765 )),
766 }
767 }
768
690769 pub fn owns_buffer(&self, buffer: &Buffer) -> bool {
691770 self.buffer.owns_buffer(buffer)
692771 }
@@ -787,6 +866,10 @@ impl MatrixRoom {
787866 self.buffer.update_parent_spaces();
788867 }
789868
869 pub fn refresh_space_children(&self) {
870 self.buffer.refresh_space_children();
871 }
872
790873 pub fn accept_verification(&self) {
791874 let verification = self.verification.clone();
792875 Weechat::spawn(async move { verification.accept().await }).detach();
@@ -1747,6 +1830,14 @@ impl MatrixRoom {
17471830 }
17481831 }
17491832
1833 pub fn update_input(&self, buffer: &Buffer) {
1834 if self.room().is_space() && self.buffer.is_main_buffer(buffer) {
1835 self.buffer.render_space_children();
1836 } else {
1837 self.update_typing_notice();
1838 }
1839 }
1840
17501841 pub fn is_busy(&self) -> bool {
17511842 self.messages_in_flight.locked()
17521843 }
@@ -2246,6 +2337,9 @@ impl MatrixRoom {
22462337 AnySyncStateEvent::SpaceParent(_) => {
22472338 self.buffer.update_parent_spaces()
22482339 }
2340 AnySyncStateEvent::SpaceChild(_) => {
2341 self.buffer.refresh_space_children()
2342 }
22492343 AnySyncStateEvent::RoomEncryption(_)
22502344 | AnySyncStateEvent::RoomJoinRules(_) => {
22512345 Weechat::bar_item_update("buffer_modes");
src/server.rs +5
@@ -852,6 +852,10 @@ impl InnerServer {
852852 &login_state.user_id,
853853 );
854854 self.rooms.borrow_mut().insert(room_id.to_owned(), buffer);
855
856 for room in self.rooms() {
857 room.refresh_space_children();
858 }
855859 }
856860
857861 self.rooms.borrow().get(room_id).cloned().unwrap()
@@ -1353,6 +1357,7 @@ impl InnerServer {
13531357 if refresh_parent_spaces {
13541358 for room in self.rooms() {
13551359 room.update_parent_spaces();
1360 room.refresh_space_children();
13561361 }
13571362 }
13581363 }