src/room/buffer.rs

1aebd1afe96d6b9a2f26ca598c88d5aae0ba5008
weechat-matrix-rs/src/room/buffer.rs history · blame · raw

1415 lines · 41799 bytes

89 symbols in this file
   1use std::{borrow::Cow, cell::RefCell, collections::HashMap, rc::Rc};
   2
   3use futures_util::StreamExt;
   4use matrix_sdk::{
   5    deserialized_responses::SyncOrStrippedState,
   6    room::ParentSpace,
   7    ruma::{
   8        events::{space::child::SpaceChildEventContent, SyncStateEvent},
   9        EventId, OwnedEventId, OwnedRoomAliasId, OwnedRoomId, OwnedServerName,
  10        OwnedUserId, TransactionId, UserId,
  11    },
  12    Error, Room, RoomState,
  13};
  14use tokio::runtime::Handle;
  15use weechat::{
  16    buffer::{Buffer, BufferHandle, BufferLine, LineData},
  17    Prefix, Weechat,
  18};
  19
  20use crate::{render::RenderedEvent, utils::ToTag};
  21
  22use super::{maybe_active_room, SharedRoom};
  23
  24#[derive(Clone)]
  25pub struct RoomBuffer {
  26    room: SharedRoom,
  27    runtime: Handle,
  28    pub(super) inner: Rc<RefCell<Option<BufferHandle>>>,
  29    room_metadata: Rc<RefCell<Option<(bool, Option<String>)>>>,
  30    thread_buffers: Rc<RefCell<HashMap<OwnedEventId, BufferHandle>>>,
  31    space_children: Rc<RefCell<Vec<SpaceChildInfo>>>,
  32}
  33
  34struct LineCopy {
  35    date: isize,
  36    date_printed: isize,
  37    tags: Vec<String>,
  38    prefix: String,
  39    message: String,
  40}
  41
  42impl<'a> From<BufferLine<'a>> for LineCopy {
  43    fn from(line: BufferLine) -> Self {
  44        Self {
  45            date: line.date(),
  46            date_printed: line.date_printed(),
  47            message: line.message().to_string(),
  48            prefix: line.prefix().to_string(),
  49            tags: line.tags().iter().map(|t| t.to_string()).collect(),
  50        }
  51    }
  52}
  53
  54impl RoomBuffer {
  55    pub fn new(room: SharedRoom, runtime: Handle) -> Self {
  56        Self {
  57            room,
  58            runtime,
  59            inner: Rc::new(RefCell::new(None)),
  60            room_metadata: Rc::new(RefCell::new(None)),
  61            thread_buffers: Rc::new(RefCell::new(HashMap::new())),
  62            space_children: Rc::new(RefCell::new(Vec::new())),
  63        }
  64    }
  65
  66    pub fn buffer_handle(&self) -> BufferHandle {
  67        self.inner
  68            .borrow()
  69            .as_ref()
  70            .expect("Room struct wasn't initialized properly")
  71            .clone()
  72    }
  73
  74    pub fn short_name(&self) -> String {
  75        self.inner
  76            .borrow()
  77            .as_ref()
  78            .and_then(|b| b.upgrade().ok().map(|b| b.short_name().to_string()))
  79            .unwrap_or_default()
  80    }
  81
  82    pub fn short_names(&self) -> Vec<String> {
  83        let mut handles =
  84            self.inner.borrow().iter().cloned().collect::<Vec<_>>();
  85        handles.extend(self.thread_buffers.borrow().values().cloned());
  86
  87        handles
  88            .into_iter()
  89            .filter_map(|handle| {
  90                let buffer = handle.upgrade().ok()?;
  91                Some(buffer.short_name().into_owned())
  92            })
  93            .collect()
  94    }
  95
  96    pub fn buffer_handle_for_short_name(
  97        &self,
  98        short_name: &str,
  99    ) -> Option<BufferHandle> {
 100        if let Some(handle) = self.inner.borrow().as_ref() {
 101            if handle
 102                .upgrade()
 103                .is_ok_and(|buffer| buffer.short_name() == short_name)
 104            {
 105                return Some(handle.clone());
 106            }
 107        }
 108
 109        self.thread_buffers
 110            .borrow()
 111            .values()
 112            .find(|handle| {
 113                handle
 114                    .upgrade()
 115                    .is_ok_and(|buffer| buffer.short_name() == short_name)
 116            })
 117            .cloned()
 118    }
 119
 120    pub fn owns_buffer(&self, buffer: &Buffer) -> bool {
 121        if self.is_main_buffer(buffer) {
 122            return true;
 123        }
 124
 125        self.thread_buffers
 126            .borrow()
 127            .values()
 128            .any(|handle| handle.upgrade().is_ok_and(|b| &b == buffer))
 129    }
 130
 131    pub fn is_main_buffer(&self, buffer: &Buffer) -> bool {
 132        self.inner
 133            .borrow()
 134            .as_ref()
 135            .and_then(|b| b.upgrade().ok())
 136            .is_some_and(|b| &b == buffer)
 137    }
 138
 139    pub fn thread_root_for_buffer(
 140        &self,
 141        buffer: &Buffer,
 142    ) -> Option<OwnedEventId> {
 143        self.thread_buffers
 144            .borrow()
 145            .iter()
 146            .find_map(|(thread_root, handle)| {
 147                handle
 148                    .upgrade()
 149                    .is_ok_and(|b| &b == buffer)
 150                    .then(|| thread_root.clone())
 151            })
 152    }
 153
 154    pub fn thread_buffer(&self, thread_root: &EventId) -> Option<BufferHandle> {
 155        self.thread_buffers.borrow().get(thread_root).cloned()
 156    }
 157
 158    pub fn set_thread_buffer(
 159        &self,
 160        thread_root: OwnedEventId,
 161        handle: BufferHandle,
 162    ) {
 163        self.thread_buffers.borrow_mut().insert(thread_root, handle);
 164    }
 165
 166    pub fn remove_thread_buffer(&self, thread_root: &EventId) {
 167        self.thread_buffers.borrow_mut().remove(thread_root);
 168    }
 169
 170    /// Return the sender ID for an event that is still in the buffer.
 171    ///
 172    /// Reply rendering uses this local lookup so it never blocks on a
 173    /// homeserver request. Callers retain the event-id fallback when the target
 174    /// line is no longer available.
 175    pub fn reply_sender_id(&self, event_id: &EventId) -> Option<OwnedUserId> {
 176        let buffer_handle = self.buffer_handle();
 177        let buffer = buffer_handle.upgrade().ok()?;
 178        let event_id_tag = Cow::from(event_id.to_tag());
 179        let line = buffer
 180            .lines()
 181            .rfind(|line| line.tags().contains(&event_id_tag))?;
 182
 183        reply_sender_id_from_tags(&line.tags())
 184    }
 185
 186    /// Count printed lines after an event that is still visible in a buffer.
 187    pub fn reply_line_distance(&self, event_id: &EventId) -> Option<usize> {
 188        let event_id_tag = Cow::from(event_id.to_tag());
 189
 190        self.buffer_handle()
 191            .upgrade()
 192            .ok()
 193            .and_then(|buffer| buffer_line_distance(&buffer, &event_id_tag))
 194            .or_else(|| {
 195                self.thread_buffers.borrow().values().find_map(|handle| {
 196                    handle.upgrade().ok().and_then(|buffer| {
 197                        buffer_line_distance(&buffer, &event_id_tag)
 198                    })
 199                })
 200            })
 201    }
 202
 203    /// Return whether an event is already rendered in the buffer.
 204    pub fn contains_event(&self, event_id: &EventId) -> bool {
 205        let event_id_tag = Cow::from(event_id.to_tag());
 206
 207        let main_buffer_contains_event = self
 208            .buffer_handle()
 209            .upgrade()
 210            .is_ok_and(|buffer| buffer_contains_tag(&buffer, &event_id_tag));
 211
 212        main_buffer_contains_event
 213            || self.thread_buffers.borrow().values().any(|handle| {
 214                handle.upgrade().is_ok_and(|buffer| {
 215                    buffer_contains_tag(&buffer, &event_id_tag)
 216                })
 217            })
 218    }
 219
 220    /// Return encrypted event IDs represented by placeholder lines restored
 221    /// from WeeChat logs or currently displayed in a room/thread buffer.
 222    pub fn encrypted_event_ids(&self) -> Vec<OwnedEventId> {
 223        const ENCRYPTED_TAG: &str = "matrix_encrypted";
 224        const EVENT_TAG_PREFIX: &str = "matrix_id_";
 225
 226        let mut event_ids = Vec::new();
 227        let mut handles =
 228            self.inner.borrow().iter().cloned().collect::<Vec<_>>();
 229        handles.extend(self.thread_buffers.borrow().values().cloned());
 230
 231        for handle in handles {
 232            let Ok(buffer) = handle.upgrade() else {
 233                continue;
 234            };
 235
 236            for line in buffer.lines() {
 237                let tags = line.tags();
 238                if !tags.iter().any(|tag| tag.as_ref() == ENCRYPTED_TAG) {
 239                    continue;
 240                }
 241
 242                let Some(event_id) = tags.iter().find_map(|tag| {
 243                    tag.as_ref()
 244                        .strip_prefix(EVENT_TAG_PREFIX)
 245                        .and_then(|event_id| EventId::parse(event_id).ok())
 246                }) else {
 247                    continue;
 248                };
 249
 250                if !event_ids.contains(&event_id) {
 251                    event_ids.push(event_id);
 252                }
 253            }
 254        }
 255
 256        event_ids
 257    }
 258
 259    /// Return whether an event is already rendered in a specific thread
 260    /// buffer.
 261    pub fn thread_contains_event(
 262        &self,
 263        thread_root: &EventId,
 264        event_id: &EventId,
 265    ) -> bool {
 266        let event_id_tag = Cow::from(event_id.to_tag());
 267        let Some(handle) = self.thread_buffer(thread_root) else {
 268            return false;
 269        };
 270
 271        handle
 272            .upgrade()
 273            .is_ok_and(|buffer| buffer_contains_tag(&buffer, &event_id_tag))
 274    }
 275
 276    /// Copy the root event line into a newly created thread buffer.
 277    pub fn seed_thread_buffer(
 278        &self,
 279        thread_root: &EventId,
 280        thread_buffer: &Buffer,
 281    ) -> bool {
 282        let event_id_tag = Cow::from(thread_root.to_tag());
 283
 284        if buffer_contains_tag(thread_buffer, &event_id_tag) {
 285            return false;
 286        }
 287
 288        self.buffer_handle().upgrade().is_ok_and(|buffer| {
 289            copy_buffer_line_by_tag(&buffer, thread_buffer, &event_id_tag)
 290        })
 291    }
 292
 293    /// Copy a newly rendered root event into its already-open thread buffer.
 294    pub fn seed_open_thread_buffer(&self, thread_root: &EventId) -> bool {
 295        let Some(handle) = self.thread_buffer(thread_root) else {
 296            return false;
 297        };
 298
 299        if let Ok(buffer) = handle.upgrade() {
 300            self.seed_thread_buffer(thread_root, &buffer)
 301        } else {
 302            self.remove_thread_buffer(thread_root);
 303            false
 304        }
 305    }
 306
 307    /// Replace the local echo of an event with a fully rendered one.
 308    pub fn replace_local_echo(
 309        &self,
 310        transaction_id: &TransactionId,
 311        rendered: RenderedEvent,
 312    ) {
 313        let uuid_tag = Cow::from(format!("matrix_echo_{}", transaction_id));
 314
 315        if self.buffer_handle().upgrade().is_ok_and(|buffer| {
 316            replace_local_echo_in_buffer(&buffer, &uuid_tag, &rendered)
 317        }) {
 318            return;
 319        }
 320
 321        self.thread_buffers.borrow().values().any(|handle| {
 322            handle.upgrade().is_ok_and(|buffer| {
 323                replace_local_echo_in_buffer(&buffer, &uuid_tag, &rendered)
 324            })
 325        });
 326    }
 327
 328    pub fn replace_edit(
 329        &self,
 330        event_id: &EventId,
 331        sender: &UserId,
 332        event: RenderedEvent,
 333    ) {
 334        let sender_tag = Cow::from(sender.to_tag());
 335        let event_id_tag = Cow::from(event_id.to_tag());
 336
 337        let _ = self.buffer_handle().upgrade().is_ok_and(|buffer| {
 338            self.replace_edit_in_buffer(
 339                &buffer,
 340                &event_id_tag,
 341                &sender_tag,
 342                &event,
 343            )
 344        });
 345
 346        for handle in self.thread_buffers.borrow().values() {
 347            if let Ok(buffer) = handle.upgrade() {
 348                let replaced = self.replace_edit_in_buffer(
 349                    &buffer,
 350                    &event_id_tag,
 351                    &sender_tag,
 352                    &event,
 353                );
 354
 355                if replaced
 356                    && self
 357                        .thread_root_for_buffer(&buffer)
 358                        .is_some_and(|thread_root| thread_root == event_id)
 359                {
 360                    sort_buffer_lines(&buffer, Some(event_id_tag.as_ref()));
 361                }
 362            }
 363        }
 364    }
 365
 366    pub fn redact_event_lines<F, G>(
 367        &self,
 368        event_id_tag: &Cow<str>,
 369        redacted_tag: &Cow<str>,
 370        redact_first_line: F,
 371        redact_rest_line: G,
 372    ) -> bool
 373    where
 374        F: Fn(Cow<str>) -> String,
 375        G: Fn(Cow<str>) -> String,
 376    {
 377        let mut redacted = self.buffer_handle().upgrade().is_ok_and(|buffer| {
 378            redact_event_lines_in_buffer(
 379                &buffer,
 380                event_id_tag,
 381                redacted_tag,
 382                &redact_first_line,
 383                &redact_rest_line,
 384            )
 385        });
 386
 387        for handle in self.thread_buffers.borrow().values() {
 388            redacted |= handle.upgrade().is_ok_and(|buffer| {
 389                redact_event_lines_in_buffer(
 390                    &buffer,
 391                    event_id_tag,
 392                    redacted_tag,
 393                    &redact_first_line,
 394                    &redact_rest_line,
 395                )
 396            });
 397        }
 398
 399        redacted
 400    }
 401
 402    fn replace_edit_in_buffer(
 403        &self,
 404        buffer: &Buffer,
 405        event_id_tag: &Cow<str>,
 406        sender_tag: &Cow<str>,
 407        event: &RenderedEvent,
 408    ) -> bool {
 409        let lines: Vec<BufferLine> = buffer
 410            .lines()
 411            .filter(|l| l.tags().contains(event_id_tag))
 412            .collect();
 413
 414        if lines
 415            .get(0)
 416            .map(|l| l.tags().contains(sender_tag))
 417            .unwrap_or(false)
 418        {
 419            self.replace_event_helper(buffer, lines, event);
 420            true
 421        } else {
 422            false
 423        }
 424    }
 425
 426    fn replace_event_helper(
 427        &self,
 428        buffer: &Buffer,
 429        lines: Vec<BufferLine<'_>>,
 430        event: &RenderedEvent,
 431    ) {
 432        use std::cmp::Ordering;
 433        let date = lines.get(0).map(|l| l.date()).unwrap_or_default();
 434
 435        for (line, new) in lines.iter().zip(event.content.lines.iter()) {
 436            let data = LineData {
 437                // Our prefixes always come with a \t character, but when we
 438                // replace stuff we're able to replace the prefix and the
 439                // message separately, so trim the whitespace in the prefix.
 440                prefix: Some(event.prefix.trim_end()),
 441                message: Some(&new.message),
 442                ..Default::default()
 443            };
 444
 445            line.update(data);
 446            let tags: Vec<&str> = new.tags.iter().map(String::as_str).collect();
 447            line.set_tags(&tags);
 448        }
 449
 450        match lines.len().cmp(&event.content.lines.len()) {
 451            Ordering::Greater => {
 452                for line in &lines[event.content.lines.len()..] {
 453                    line.set_message("");
 454                }
 455            }
 456            Ordering::Less => {
 457                for line in &event.content.lines[lines.len()..] {
 458                    let message = format!("{}{}", &event.prefix, &line.message);
 459                    let tags: Vec<&str> =
 460                        line.tags.iter().map(|t| t.as_str()).collect();
 461                    buffer.print_date_tags(date, &tags, &message)
 462                }
 463
 464                sort_buffer_lines(buffer, None)
 465            }
 466            Ordering::Equal => (),
 467        }
 468    }
 469
 470    pub fn sort_messages(&self) {
 471        if let Ok(buffer) = self.buffer_handle().upgrade() {
 472            sort_buffer_lines(&buffer, None);
 473        }
 474    }
 475
 476    pub fn sort_thread_messages(&self, thread_root: &EventId) {
 477        let Some(handle) = self.thread_buffer(thread_root) else {
 478            return;
 479        };
 480
 481        if let Ok(buffer) = handle.upgrade() {
 482            let root_tag = thread_root.to_tag();
 483            sort_buffer_lines(&buffer, Some(root_tag.as_ref()));
 484        }
 485    }
 486
 487    pub fn set_topic(&self) {
 488        let Some(room) = maybe_active_room(&self.room) else {
 489            return;
 490        };
 491
 492        if let Ok(buffer) = self.buffer_handle().upgrade() {
 493            buffer.set_title(&room.topic().unwrap_or_default());
 494        }
 495    }
 496
 497    pub fn set_alias(&self) {
 498        if let Some(alias) = self.alias() {
 499            if let Ok(b) = self.buffer_handle().upgrade() {
 500                b.set_localvar("alias", alias.as_str());
 501            }
 502        }
 503    }
 504
 505    pub fn update_avatar(&self) {
 506        let Some(room) = maybe_active_room(&self.room) else {
 507            return;
 508        };
 509
 510        if let Ok(buffer) = self.buffer_handle().upgrade() {
 511            buffer.set_localvar(
 512                "matrix_avatar_mxc",
 513                room.avatar_url()
 514                    .as_ref()
 515                    .map(|uri| uri.as_str())
 516                    .unwrap_or_default(),
 517            );
 518        }
 519    }
 520
 521    pub fn update_parent_spaces(&self) {
 522        let Some(room) = maybe_active_room(&self.room) else {
 523            return;
 524        };
 525
 526        let spaces = self.runtime.block_on(parent_spaces(room));
 527
 528        if let Ok(buffer) = self.buffer_handle().upgrade() {
 529            match spaces {
 530                Ok(spaces) => {
 531                    let ids = spaces
 532                        .iter()
 533                        .map(|s| s.id.as_str())
 534                        .collect::<Vec<_>>()
 535                        .join(",");
 536                    let names = spaces
 537                        .iter()
 538                        .map(|s| s.name.as_str())
 539                        .collect::<Vec<_>>()
 540                        .join(",");
 541
 542                    buffer.set_localvar("space_ids", &ids);
 543                    buffer.set_localvar("spaces", &names);
 544
 545                    if let Some(space) = spaces.first() {
 546                        buffer.set_localvar("space_id", space.id.as_str());
 547                        buffer.set_localvar("space", &space.name);
 548                    } else {
 549                        buffer.set_localvar("space_id", "");
 550                        buffer.set_localvar("space", "");
 551                    }
 552                }
 553                Err(e) => {
 554                    Weechat::print(&format!(
 555                        "{}: Error fetching parent spaces from the store: {}",
 556                        Weechat::prefix(Prefix::Error),
 557                        e,
 558                    ));
 559                }
 560            }
 561        }
 562    }
 563
 564    pub fn refresh_space_children(&self) {
 565        let Some(room) = maybe_active_room(&self.room) else {
 566            return;
 567        };
 568
 569        if !room.is_space() {
 570            return;
 571        }
 572
 573        match self.runtime.block_on(space_children(room)) {
 574            Ok(children) => {
 575                *self.space_children.borrow_mut() = children;
 576                self.render_space_children();
 577            }
 578            Err(error) => {
 579                Weechat::print(&format!(
 580                    "{}: Error fetching space children from the store: {}",
 581                    Weechat::prefix(Prefix::Error),
 582                    error,
 583                ));
 584            }
 585        }
 586    }
 587
 588    /// Reuse the room buffer input as a live filter, like WeeChat's `/fset`.
 589    ///
 590    /// The stable numbers refer to the unfiltered hierarchy so narrowing and
 591    /// selecting never changes the target underneath the user.
 592    pub fn render_space_children(&self) {
 593        let buffer_handle = self.buffer_handle();
 594        let Ok(buffer) = buffer_handle.upgrade() else {
 595            return;
 596        };
 597
 598        let input = buffer.input();
 599        let children = self.space_children.borrow();
 600        let visible = filter_space_children(&children, &input);
 601
 602        buffer.clear();
 603        buffer.set_title(&format!(
 604            "Space rooms: showing {} of {}. Type to filter; press Enter on a \
 605             number or unique name to open/join.",
 606            visible.len(),
 607            children.len(),
 608        ));
 609
 610        if visible.is_empty() {
 611            buffer.print("No rooms match this filter.");
 612            return;
 613        }
 614
 615        for (index, child) in visible {
 616            let action = if child.joined { "open" } else { "join" };
 617            let kind = if child.is_space { "space" } else { "room" };
 618
 619            buffer.print(&format!(
 620                "{:>3}  [{action} {kind}] {}  {}",
 621                index + 1,
 622                child.name,
 623                child.room_id,
 624            ));
 625        }
 626    }
 627
 628    pub fn space_child_command(
 629        &self,
 630        input: &str,
 631        server_name: &str,
 632    ) -> SpaceChildSelection {
 633        select_space_child(&self.space_children.borrow(), input)
 634            .map_or(SpaceChildSelection::NoMatch, |child| {
 635                space_child_selection(server_name, child)
 636            })
 637    }
 638
 639    fn alias(&self) -> Option<OwnedRoomAliasId> {
 640        maybe_active_room(&self.room).and_then(|room| room.canonical_alias())
 641    }
 642
 643    pub fn calculate_buffer_name(&self) -> String {
 644        let Some(room) = maybe_active_room(&self.room) else {
 645            return self.short_name();
 646        };
 647        let (is_direct, metadata_name) =
 648            self.room_metadata.borrow().clone().unwrap_or_default();
 649        let is_space = room.is_space();
 650
 651        let room_name = room_display_name(
 652            room.name().as_deref(),
 653            room.canonical_alias().as_deref().map(|alias| alias.alias()),
 654            metadata_name.as_deref(),
 655            room.room_id().as_str(),
 656        );
 657
 658        format_buffer_name(&room_name, is_direct, is_space)
 659    }
 660
 661    pub fn set_room_metadata(
 662        &self,
 663        is_direct: bool,
 664        display_name: Option<String>,
 665    ) {
 666        *self.room_metadata.borrow_mut() = Some((is_direct, display_name));
 667    }
 668
 669    pub fn calculate_thread_buffer_name(
 670        &self,
 671        thread_root: &EventId,
 672    ) -> String {
 673        format_thread_buffer_name(thread_root)
 674    }
 675
 676    pub fn thread_buffer_suffix(thread_root: &EventId) -> String {
 677        sanitize_thread_id(thread_root)
 678    }
 679}
 680
 681#[derive(Clone, Debug, Eq, PartialEq)]
 682struct SpaceChildInfo {
 683    room_id: OwnedRoomId,
 684    name: String,
 685    joined: bool,
 686    is_space: bool,
 687    order: Option<String>,
 688    via: Vec<OwnedServerName>,
 689}
 690
 691#[derive(Clone, Debug, Eq, PartialEq)]
 692pub(super) enum SpaceChildSelection {
 693    Open(String),
 694    Join {
 695        room_id: OwnedRoomId,
 696        via: Vec<OwnedServerName>,
 697    },
 698    NoMatch,
 699}
 700
 701fn filter_space_children<'a>(
 702    children: &'a [SpaceChildInfo],
 703    input: &str,
 704) -> Vec<(usize, &'a SpaceChildInfo)> {
 705    let query = input.trim().to_lowercase();
 706
 707    children
 708        .iter()
 709        .enumerate()
 710        .filter(|(_, child)| {
 711            query.is_empty()
 712                || child.name.to_lowercase().contains(&query)
 713                || child.room_id.as_str().to_lowercase().contains(&query)
 714        })
 715        .collect()
 716}
 717
 718fn select_space_child<'a>(
 719    children: &'a [SpaceChildInfo],
 720    input: &str,
 721) -> Option<&'a SpaceChildInfo> {
 722    let input = input.trim();
 723
 724    if input.is_empty() {
 725        return None;
 726    }
 727
 728    if let Ok(index) = input.parse::<usize>() {
 729        return index.checked_sub(1).and_then(|index| children.get(index));
 730    }
 731
 732    let matches = filter_space_children(children, input);
 733
 734    if matches.len() == 1 {
 735        matches.first().map(|(_, child)| *child)
 736    } else {
 737        None
 738    }
 739}
 740
 741fn space_child_selection(
 742    server_name: &str,
 743    child: &SpaceChildInfo,
 744) -> SpaceChildSelection {
 745    if child.joined {
 746        SpaceChildSelection::Open(format!(
 747            "/buffer {}.{}",
 748            server_name, child.room_id
 749        ))
 750    } else {
 751        SpaceChildSelection::Join {
 752            room_id: child.room_id.clone(),
 753            via: child.via.clone(),
 754        }
 755    }
 756}
 757
 758fn buffer_contains_tag(buffer: &Buffer, tag: &Cow<str>) -> bool {
 759    buffer
 760        .lines()
 761        .rfind(|line| line.tags().contains(tag))
 762        .is_some()
 763}
 764
 765fn copy_buffer_line_by_tag(
 766    source: &Buffer,
 767    target: &Buffer,
 768    tag: &Cow<str>,
 769) -> bool {
 770    let lines: Vec<LineCopy> = source
 771        .lines()
 772        .filter(|line| line.tags().contains(tag))
 773        .map(Into::into)
 774        .collect();
 775
 776    if lines.is_empty() {
 777        return false;
 778    }
 779
 780    for line in lines {
 781        let message = if line.prefix.is_empty() {
 782            line.message
 783        } else {
 784            format!("{}\t{}", line.prefix, line.message)
 785        };
 786        let tags: Vec<&str> = line.tags.iter().map(String::as_str).collect();
 787
 788        target.print_date_tags(line.date, &tags, &message);
 789    }
 790
 791    // A thread buffer may already contain the reply that caused its creation.
 792    // Keep every line of the triggering event first even when Matrix timestamps
 793    // have only second-level precision or the root arrived through a later sync.
 794    sort_buffer_lines(target, Some(tag.as_ref()));
 795
 796    true
 797}
 798
 799fn line_sort_key(
 800    date: isize,
 801    tags: &[String],
 802    priority_tag: Option<&str>,
 803) -> (bool, isize) {
 804    let is_priority =
 805        priority_tag.is_some_and(|tag| tags.iter().any(|item| item == tag));
 806
 807    (!is_priority, date)
 808}
 809
 810fn sort_buffer_lines(buffer: &Buffer, priority_tag: Option<&str>) {
 811    let mut lines: Vec<LineCopy> = buffer.lines().map(Into::into).collect();
 812    lines
 813        .sort_by_key(|line| line_sort_key(line.date, &line.tags, priority_tag));
 814
 815    // TODO update the highlight once Weechat starts supporting it.
 816    for (line, new) in buffer.lines().zip(lines.drain(..)) {
 817        let tags = new.tags.iter().map(String::as_str).collect::<Vec<&str>>();
 818        let data = LineData {
 819            prefix: Some(&new.prefix),
 820            message: Some(&new.message),
 821            date: Some(new.date),
 822            date_printed: Some(new.date_printed),
 823            tags: Some(&tags),
 824        };
 825        line.update(data)
 826    }
 827}
 828
 829fn redact_event_lines_in_buffer<F, G>(
 830    buffer: &Buffer,
 831    event_id_tag: &Cow<str>,
 832    redacted_tag: &Cow<str>,
 833    redact_first_line: &F,
 834    redact_rest_line: &G,
 835) -> bool
 836where
 837    F: Fn(Cow<str>) -> String,
 838    G: Fn(Cow<str>) -> String,
 839{
 840    let predicate = |line: &BufferLine| {
 841        let tags = line.tags();
 842        tags.contains(event_id_tag) && !tags.contains(redacted_tag)
 843    };
 844
 845    let mut lines = buffer.lines();
 846    let first_line = lines.rfind(predicate);
 847
 848    if let Some(line) = first_line {
 849        modify_line(line, redacted_tag.clone(), redact_first_line);
 850    } else {
 851        return false;
 852    }
 853
 854    while let Some(line) = lines.next_back().filter(predicate) {
 855        modify_line(line, redacted_tag.clone(), redact_rest_line);
 856    }
 857
 858    true
 859}
 860
 861fn modify_line<F>(line: BufferLine, tag: Cow<str>, redaction_func: F)
 862where
 863    F: Fn(Cow<str>) -> String,
 864{
 865    let message = line.message();
 866    let new_message = redaction_func(message);
 867
 868    let mut tags = line.tags();
 869    tags.push(tag);
 870    let tags: Vec<&str> = tags.iter().map(|tag| tag.as_ref()).collect();
 871
 872    line.set_message(&new_message);
 873    line.set_tags(&tags);
 874}
 875
 876fn buffer_line_distance(buffer: &Buffer, tag: &Cow<str>) -> Option<usize> {
 877    let mut lines_after = 0;
 878
 879    for line in buffer.lines().rev() {
 880        if line.tags().contains(tag) {
 881            return Some(lines_after);
 882        }
 883
 884        lines_after += 1;
 885    }
 886
 887    None
 888}
 889
 890fn sanitize_thread_id(thread_root: &EventId) -> String {
 891    const THREAD_ID_DISPLAY_CHARS: usize = 12;
 892
 893    let mut sanitized: String = thread_root
 894        .as_str()
 895        .trim_start_matches('$')
 896        .chars()
 897        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
 898        .take(THREAD_ID_DISPLAY_CHARS)
 899        .collect();
 900
 901    if sanitized.is_empty() {
 902        sanitized.push_str("unknown");
 903    }
 904
 905    sanitized
 906}
 907
 908fn reply_sender_id_from_tags<T: AsRef<str>>(tags: &[T]) -> Option<OwnedUserId> {
 909    tags.iter().find_map(|tag| {
 910        tag.as_ref()
 911            .strip_prefix("matrix_sender_")
 912            .and_then(|sender| UserId::parse(sender).ok())
 913    })
 914}
 915
 916fn non_empty_room_name(name: &str) -> Option<String> {
 917    let name = name.trim();
 918
 919    if name.is_empty() {
 920        None
 921    } else {
 922        Some(name.to_owned())
 923    }
 924}
 925
 926fn room_display_name(
 927    explicit_name: Option<&str>,
 928    alias: Option<&str>,
 929    metadata_name: Option<&str>,
 930    room_id: &str,
 931) -> String {
 932    explicit_name
 933        .and_then(non_empty_room_name)
 934        .or_else(|| alias.and_then(non_empty_room_name))
 935        .or_else(|| metadata_name.and_then(non_empty_room_name))
 936        .unwrap_or_else(|| room_id.to_owned())
 937}
 938
 939fn format_buffer_name(
 940    room_name: &str,
 941    is_direct: bool,
 942    is_space: bool,
 943) -> String {
 944    if is_direct || room_name.starts_with('!') {
 945        return room_name.to_owned();
 946    }
 947
 948    if is_space {
 949        if room_name == "+" {
 950            return "++".to_owned();
 951        }
 952
 953        return room_name
 954            .strip_prefix('#')
 955            .map(|name| format!("+{}", name))
 956            .unwrap_or_else(|| {
 957                if room_name.starts_with('+') {
 958                    room_name.to_owned()
 959                } else {
 960                    format!("+{}", room_name)
 961                }
 962            });
 963    }
 964
 965    let room_name = if room_name == "#" {
 966        "##".to_owned()
 967    } else if room_name.starts_with('#') {
 968        room_name.to_owned()
 969    } else {
 970        format!("#{}", room_name)
 971    };
 972
 973    room_name
 974}
 975
 976fn format_thread_buffer_name(thread_root: &EventId) -> String {
 977    format!("thread.{}", RoomBuffer::thread_buffer_suffix(thread_root))
 978}
 979
 980impl RoomBuffer {
 981    pub fn update_buffer_name(&self) {
 982        let buffer = self.buffer_handle();
 983
 984        let buffer = if let Ok(b) = buffer.upgrade() {
 985            b
 986        } else {
 987            return;
 988        };
 989
 990        buffer.set_short_name(&self.calculate_buffer_name());
 991    }
 992
 993    pub fn replace_verification_event(
 994        &self,
 995        event_id: &EventId,
 996        event: RenderedEvent,
 997    ) {
 998        self.replace_event(event_id, event);
 999    }
1000
1001    pub fn replace_event(
1002        &self,
1003        event_id: &EventId,
1004        event: RenderedEvent,
1005    ) -> bool {
1006        if let Ok(buffer) = self.buffer_handle().upgrade() {
1007            let event_id_tag = Cow::from(event_id.to_tag());
1008
1009            let lines: Vec<BufferLine> = buffer
1010                .lines()
1011                .filter(|l| l.tags().contains(&event_id_tag))
1012                .collect();
1013
1014            if !lines.is_empty() {
1015                self.replace_event_helper(&buffer, lines, &event);
1016                return true;
1017            }
1018        }
1019
1020        self.thread_buffers.borrow().values().any(|handle| {
1021            handle.upgrade().is_ok_and(|buffer| {
1022                let event_id_tag = Cow::from(event_id.to_tag());
1023                let lines: Vec<BufferLine> = buffer
1024                    .lines()
1025                    .filter(|line| line.tags().contains(&event_id_tag))
1026                    .collect();
1027
1028                if lines.is_empty() {
1029                    false
1030                } else {
1031                    self.replace_event_helper(&buffer, lines, &event);
1032                    true
1033                }
1034            })
1035        })
1036    }
1037
1038    pub fn print_rendered_event(&self, rendered: RenderedEvent) {
1039        let buffer = self.buffer_handle();
1040
1041        if let Ok(buffer) = buffer.upgrade() {
1042            print_rendered_event_to_buffer(&buffer, &rendered);
1043        }
1044    }
1045}
1046
1047pub fn print_rendered_event_to_buffer(
1048    buffer: &Buffer,
1049    rendered: &RenderedEvent,
1050) {
1051    for line in &rendered.content.lines {
1052        let message = format!("{}{}", &rendered.prefix, &line.message);
1053        let tags: Vec<&str> = line.tags.iter().map(|t| t.as_str()).collect();
1054        buffer.print_date_tags(rendered.message_timestamp, &tags, &message)
1055    }
1056}
1057
1058fn replace_local_echo_in_buffer(
1059    buffer: &Buffer,
1060    uuid_tag: &Cow<str>,
1061    rendered: &RenderedEvent,
1062) -> bool {
1063    let line_contains_uuid = |line: &BufferLine| line.tags().contains(uuid_tag);
1064    let mut lines = buffer.lines();
1065    let mut current_line = lines.rfind(line_contains_uuid);
1066    let mut replaced = false;
1067
1068    // We go from bottom to top since local echoes are expected to be fresh.
1069    let mut line_num = rendered.content.lines.len();
1070
1071    while let Some(line) = &current_line {
1072        line_num -= 1;
1073        let rendered_line = &rendered.content.lines[line_num];
1074        let tags: Vec<&str> =
1075            rendered_line.tags.iter().map(String::as_str).collect();
1076
1077        line.set_message(&rendered_line.message);
1078        line.set_tags(&tags);
1079        replaced = true;
1080        current_line = lines.next_back().filter(line_contains_uuid);
1081    }
1082
1083    replaced
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088    use matrix_sdk::ruma::{event_id, room_id, user_id};
1089
1090    use super::{
1091        filter_space_children, format_buffer_name, format_thread_buffer_name,
1092        line_sort_key, reply_sender_id_from_tags, room_display_name,
1093        sanitize_thread_id, select_space_child, space_child_selection,
1094        RoomBuffer, SpaceChildInfo, SpaceChildSelection,
1095    };
1096
1097    fn space_child(
1098        room_id: &matrix_sdk::ruma::RoomId,
1099        name: &str,
1100        joined: bool,
1101    ) -> SpaceChildInfo {
1102        SpaceChildInfo {
1103            room_id: room_id.to_owned(),
1104            name: name.to_owned(),
1105            joined,
1106            is_space: false,
1107            order: None,
1108            via: vec!["example.org".parse().unwrap()],
1109        }
1110    }
1111
1112    #[test]
1113    fn reply_sender_uses_matrix_sender_tag() {
1114        let tags = ["matrix_text", "matrix_sender_@alice:example.org"];
1115
1116        assert_eq!(
1117            Some(user_id!("@alice:example.org").to_owned()),
1118            reply_sender_id_from_tags(&tags)
1119        );
1120    }
1121
1122    #[test]
1123    fn reply_sender_is_unknown_without_matrix_sender_tag() {
1124        let tags = ["matrix_text", "matrix_reply"];
1125
1126        assert_eq!(None, reply_sender_id_from_tags(&tags));
1127    }
1128
1129    #[test]
1130    fn thread_root_lines_sort_before_existing_replies() {
1131        let root_tag = "matrix_id_$root:example.org";
1132        let root_tags = vec![root_tag.to_owned(), "matrix_text".to_owned()];
1133        let reply_tags = vec!["matrix_text".to_owned()];
1134
1135        assert!(
1136            line_sort_key(200, &root_tags, Some(root_tag))
1137                < line_sort_key(100, &reply_tags, Some(root_tag))
1138        );
1139    }
1140
1141    #[test]
1142    fn thread_root_wins_same_timestamp_ties() {
1143        let root_tag = "matrix_id_$root:example.org";
1144        let root_tags = vec![root_tag.to_owned()];
1145        let reply_tags = vec!["matrix_text".to_owned()];
1146
1147        assert!(
1148            line_sort_key(100, &root_tags, Some(root_tag))
1149                < line_sort_key(100, &reply_tags, Some(root_tag))
1150        );
1151    }
1152
1153    #[test]
1154    fn ordinary_lines_remain_chronological() {
1155        let tags = vec!["matrix_text".to_owned()];
1156
1157        assert!(
1158            line_sort_key(100, &tags, None) < line_sort_key(200, &tags, None)
1159        );
1160    }
1161
1162    #[test]
1163    fn async_display_name_fills_unnamed_room_without_overriding_explicit_names()
1164    {
1165        assert_eq!(
1166            room_display_name(
1167                None,
1168                None,
1169                Some("Orbit"),
1170                "!fallback:example.org"
1171            ),
1172            "Orbit"
1173        );
1174        assert_eq!(
1175            room_display_name(
1176                Some("Named"),
1177                Some("#alias"),
1178                Some("Orbit"),
1179                "!fallback:example.org"
1180            ),
1181            "Named"
1182        );
1183        assert_eq!(
1184            room_display_name(
1185                None,
1186                Some("#alias"),
1187                Some("Orbit"),
1188                "!fallback:example.org"
1189            ),
1190            "#alias"
1191        );
1192    }
1193
1194    #[test]
1195    fn preserves_named_channel_prefix() {
1196        assert_eq!(format_buffer_name("OSGeo", false, false), "#OSGeo");
1197    }
1198
1199    #[test]
1200    fn preserves_direct_room_names() {
1201        assert_eq!(format_buffer_name("Alice", true, false), "Alice");
1202    }
1203
1204    #[test]
1205    fn preserves_alias_like_names() {
1206        assert_eq!(format_buffer_name("#lounge", false, false), "#lounge");
1207        assert_eq!(format_buffer_name("#", false, false), "##");
1208    }
1209
1210    #[test]
1211    fn preserves_room_id_fallbacks() {
1212        assert_eq!(
1213            format_buffer_name("!roomid:matrix.osgeo.org", false, false),
1214            "!roomid:matrix.osgeo.org"
1215        );
1216    }
1217
1218    #[test]
1219    fn marks_space_buffers_with_plus_prefix() {
1220        assert_eq!(format_buffer_name("OSGeo", false, true), "+OSGeo");
1221        assert_eq!(format_buffer_name("#OSGeo", false, true), "+OSGeo");
1222        assert_eq!(format_buffer_name("+OSGeo", false, true), "+OSGeo");
1223        assert_eq!(format_buffer_name("+", false, true), "++");
1224    }
1225
1226    #[test]
1227    fn filters_space_children_by_name_or_room_id() {
1228        let children = [
1229            space_child(room_id!("!alpha:example.org"), "Alpha", true),
1230            space_child(room_id!("!beta:example.org"), "Release room", false),
1231        ];
1232
1233        let by_name = filter_space_children(&children, "RELEASE");
1234        let by_id = filter_space_children(&children, "!ALPHA");
1235
1236        assert_eq!(by_name.len(), 1);
1237        assert_eq!(by_name[0].1.room_id, room_id!("!beta:example.org"));
1238        assert_eq!(by_id.len(), 1);
1239        assert_eq!(by_id[0].1.room_id, room_id!("!alpha:example.org"));
1240    }
1241
1242    #[test]
1243    fn selects_space_child_by_number_or_unique_filter() {
1244        let children = [
1245            space_child(room_id!("!alpha:example.org"), "Alpha", true),
1246            space_child(room_id!("!alpine:example.org"), "Alpine", false),
1247            space_child(room_id!("!beta:example.org"), "Beta", false),
1248        ];
1249
1250        assert_eq!(
1251            select_space_child(&children, "2")
1252                .map(|child| child.room_id.as_ref()),
1253            Some(room_id!("!alpine:example.org")),
1254        );
1255        assert_eq!(
1256            select_space_child(&children, "bet")
1257                .map(|child| child.room_id.as_ref()),
1258            Some(room_id!("!beta:example.org")),
1259        );
1260        assert!(select_space_child(&children, "alp").is_none());
1261    }
1262
1263    #[test]
1264    fn opens_joined_space_children_and_joins_other_children() {
1265        let joined =
1266            space_child(room_id!("!joined:example.org"), "Joined", true);
1267        let left = space_child(room_id!("!left:example.org"), "Left", false);
1268
1269        assert_eq!(
1270            space_child_selection("matrix", &joined),
1271            SpaceChildSelection::Open(
1272                "/buffer matrix.!joined:example.org".to_owned()
1273            ),
1274        );
1275        assert_eq!(
1276            space_child_selection("matrix", &left),
1277            SpaceChildSelection::Join {
1278                room_id: room_id!("!left:example.org").to_owned(),
1279                via: vec!["example.org".parse().unwrap()],
1280            },
1281        );
1282    }
1283
1284    #[test]
1285    fn sanitizes_thread_event_id_for_buffer_name() {
1286        assert_eq!(
1287            sanitize_thread_id(event_id!("$abc/def:example.org")),
1288            "abc_def_exam"
1289        );
1290    }
1291
1292    #[test]
1293    fn thread_buffer_suffix_uses_short_human_id() {
1294        assert_eq!(
1295            RoomBuffer::thread_buffer_suffix(event_id!(
1296                "$abcdef0123456789:example.org"
1297            )),
1298            "abcdef012345"
1299        );
1300    }
1301
1302    #[test]
1303    fn thread_buffer_name_uses_thread_prefix_and_short_suffix() {
1304        assert_eq!(
1305            format_thread_buffer_name(event_id!(
1306                "$abcdef0123456789:example.org"
1307            )),
1308            "thread.abcdef012345"
1309        );
1310    }
1311}
1312
1313struct ParentSpaceInfo {
1314    id: String,
1315    name: String,
1316}
1317
1318async fn parent_spaces(room: Room) -> Result<Vec<ParentSpaceInfo>, Error> {
1319    let mut stream = room.parent_spaces().await?;
1320    let mut spaces = Vec::new();
1321
1322    while let Some(parent) = stream.next().await {
1323        match parent? {
1324            ParentSpace::Reciprocal(room)
1325            | ParentSpace::WithPowerlevel(room)
1326            | ParentSpace::Illegitimate(room) => {
1327                let id = room.room_id().to_string();
1328                let name = room
1329                    .display_name()
1330                    .await
1331                    .map(|name| name.to_string())
1332                    .unwrap_or_else(|_| id.clone());
1333
1334                spaces.push(ParentSpaceInfo { id, name });
1335            }
1336            ParentSpace::Unverifiable(room_id) => {
1337                let id = room_id.to_string();
1338                spaces.push(ParentSpaceInfo {
1339                    id: id.clone(),
1340                    name: id,
1341                });
1342            }
1343        }
1344    }
1345
1346    Ok(spaces)
1347}
1348
1349async fn space_children(room: Room) -> Result<Vec<SpaceChildInfo>, Error> {
1350    let client = room.client();
1351    let mut children = Vec::new();
1352
1353    for raw_event in room
1354        .get_state_events_static::<SpaceChildEventContent>()
1355        .await?
1356    {
1357        let event =
1358            match raw_event.deserialize() {
1359                Ok(SyncOrStrippedState::Sync(SyncStateEvent::Original(
1360                    event,
1361                ))) if !event.content.via.is_empty() => event,
1362                Ok(_) => continue,
1363                Err(error) => {
1364                    tracing::warn!(
1365                        room_id = ?room.room_id(),
1366                        "Could not deserialize m.space.child: {error}"
1367                    );
1368                    continue;
1369                }
1370            };
1371
1372        let room_id = event.state_key;
1373        let order = event.content.order.map(|order| order.to_string());
1374
1375        let (name, joined, is_space) =
1376            if let Some(child_room) = client.get_room(&room_id) {
1377                let joined = child_room.state() == RoomState::Joined;
1378                let is_space = child_room.is_space();
1379                let name = child_room
1380                    .display_name()
1381                    .await
1382                    .map(|name| name.to_string())
1383                    .unwrap_or_else(|_| room_id.to_string());
1384
1385                (name, joined, is_space)
1386            } else {
1387                // The local state store knows the hierarchy relation but not a
1388                // summary for rooms we have never joined. The room ID remains
1389                // a useful, selectable fallback.
1390                (room_id.to_string(), false, false)
1391            };
1392
1393        children.push(SpaceChildInfo {
1394            room_id,
1395            name,
1396            joined,
1397            is_space,
1398            order,
1399            via: event.content.via,
1400        });
1401    }
1402
1403    children.sort_by(|left, right| {
1404        left.order
1405            .is_none()
1406            .cmp(&right.order.is_none())
1407            .then_with(|| left.order.cmp(&right.order))
1408            .then_with(|| {
1409                left.name.to_lowercase().cmp(&right.name.to_lowercase())
1410            })
1411            .then_with(|| left.room_id.cmp(&right.room_id))
1412    });
1413
1414    Ok(children)
1415}