src/room/buffer.rs

4fddc50d6d9f3d82220a4e3264d792d54fc940cf
weechat-matrix-rs/src/room/buffer.rs history · blame · raw

274 lines · 8615 bytes

  1use std::{borrow::Cow, cell::RefCell, rc::Rc};
  2
  3use matrix_sdk::{
  4    ruma::{EventId, OwnedRoomAliasId, TransactionId, UserId},
  5    Room, StoreError,
  6};
  7use tokio::runtime::Handle;
  8use weechat::{
  9    buffer::{Buffer, BufferHandle, BufferLine, LineData},
 10    Prefix, Weechat,
 11};
 12
 13use crate::{render::RenderedEvent, utils::ToTag};
 14
 15#[derive(Clone)]
 16pub struct RoomBuffer {
 17    room: Room,
 18    runtime: Handle,
 19    pub(super) inner: Rc<RefCell<Option<BufferHandle>>>,
 20}
 21
 22impl RoomBuffer {
 23    pub fn new(room: Room, runtime: Handle) -> Self {
 24        Self {
 25            room,
 26            runtime,
 27            inner: Rc::new(RefCell::new(None)),
 28        }
 29    }
 30
 31    pub fn buffer_handle(&self) -> BufferHandle {
 32        self.inner
 33            .borrow()
 34            .as_ref()
 35            .expect("Room struct wasn't initialized properly")
 36            .clone()
 37    }
 38
 39    pub fn short_name(&self) -> String {
 40        self.inner
 41            .borrow()
 42            .as_ref()
 43            .and_then(|b| b.upgrade().ok().map(|b| b.short_name().to_string()))
 44            .unwrap_or_default()
 45    }
 46
 47    /// Replace the local echo of an event with a fully rendered one.
 48    pub fn replace_local_echo(
 49        &self,
 50        transaction_id: &TransactionId,
 51        rendered: RenderedEvent,
 52    ) {
 53        if let Ok(buffer) = self.buffer_handle().upgrade() {
 54            let uuid_tag = Cow::from(format!("matrix_echo_{}", transaction_id));
 55            let line_contains_uuid =
 56                |l: &BufferLine| l.tags().contains(&uuid_tag);
 57
 58            let mut lines = buffer.lines();
 59            let mut current_line = lines.rfind(line_contains_uuid);
 60
 61            // We go in reverse order here since we also use rfind(). We got from
 62            // the bottom of the buffer to the top since we're expecting these
 63            // lines to be freshly printed and thus at the bottom.
 64            let mut line_num = rendered.content.lines.len();
 65
 66            while let Some(line) = &current_line {
 67                line_num -= 1;
 68                let rendered_line = &rendered.content.lines[line_num];
 69
 70                line.set_message(&rendered_line.message);
 71                current_line = lines.next_back().filter(line_contains_uuid);
 72            }
 73        }
 74    }
 75
 76    pub fn replace_edit(
 77        &self,
 78        event_id: &EventId,
 79        sender: &UserId,
 80        event: RenderedEvent,
 81    ) {
 82        if let Ok(buffer) = self.buffer_handle().upgrade() {
 83            let sender_tag = Cow::from(sender.to_tag());
 84            let event_id_tag = Cow::from(event_id.to_tag());
 85
 86            let lines: Vec<BufferLine> = buffer
 87                .lines()
 88                .filter(|l| l.tags().contains(&event_id_tag))
 89                .collect();
 90
 91            if lines
 92                .get(0)
 93                .map(|l| l.tags().contains(&sender_tag))
 94                .unwrap_or(false)
 95            {
 96                self.replace_event_helper(&buffer, lines, event);
 97            }
 98        }
 99    }
100
101    fn replace_event_helper(
102        &self,
103        buffer: &Buffer,
104        lines: Vec<BufferLine<'_>>,
105        event: RenderedEvent,
106    ) {
107        use std::cmp::Ordering;
108        let date = lines.get(0).map(|l| l.date()).unwrap_or_default();
109
110        for (line, new) in lines.iter().zip(event.content.lines.iter()) {
111            let data = LineData {
112                // Our prefixes always come with a \t character, but when we
113                // replace stuff we're able to replace the prefix and the
114                // message separately, so trim the whitespace in the prefix.
115                prefix: Some(event.prefix.trim_end()),
116                message: Some(&new.message),
117                ..Default::default()
118            };
119
120            line.update(data);
121        }
122
123        match lines.len().cmp(&event.content.lines.len()) {
124            Ordering::Greater => {
125                for line in &lines[event.content.lines.len()..] {
126                    line.set_message("");
127                }
128            }
129            Ordering::Less => {
130                for line in &event.content.lines[lines.len()..] {
131                    let message = format!("{}{}", &event.prefix, &line.message);
132                    let tags: Vec<&str> =
133                        line.tags.iter().map(|t| t.as_str()).collect();
134                    buffer.print_date_tags(date, &tags, &message)
135                }
136
137                self.sort_messages()
138            }
139            Ordering::Equal => (),
140        }
141    }
142
143    pub fn sort_messages(&self) {
144        struct LineCopy {
145            date: isize,
146            date_printed: isize,
147            tags: Vec<String>,
148            prefix: String,
149            message: String,
150        }
151
152        impl<'a> From<BufferLine<'a>> for LineCopy {
153            fn from(line: BufferLine) -> Self {
154                Self {
155                    date: line.date(),
156                    date_printed: line.date_printed(),
157                    message: line.message().to_string(),
158                    prefix: line.prefix().to_string(),
159                    tags: line.tags().iter().map(|t| t.to_string()).collect(),
160                }
161            }
162        }
163
164        // TODO update the highlight once Weechat starts supporting it.
165        if let Ok(buffer) = self.buffer_handle().upgrade() {
166            let mut lines: Vec<LineCopy> =
167                buffer.lines().map(|l| l.into()).collect();
168            lines.sort_by_key(|l| l.date);
169
170            for (line, new) in buffer.lines().zip(lines.drain(..)) {
171                let tags =
172                    new.tags.iter().map(|t| t.as_str()).collect::<Vec<&str>>();
173                let data = LineData {
174                    prefix: Some(&new.prefix),
175                    message: Some(&new.message),
176                    date: Some(new.date),
177                    date_printed: Some(new.date_printed),
178                    tags: Some(&tags),
179                };
180                line.update(data)
181            }
182        }
183    }
184
185    pub fn set_topic(&self) {
186        if let Ok(buffer) = self.buffer_handle().upgrade() {
187            buffer.set_title(&self.room.topic().unwrap_or_default());
188        }
189    }
190
191    pub fn set_alias(&self) {
192        if let Some(alias) = self.alias() {
193            if let Ok(b) = self.buffer_handle().upgrade() {
194                b.set_localvar("alias", alias.as_str());
195            }
196        }
197    }
198
199    fn alias(&self) -> Option<OwnedRoomAliasId> {
200        self.room.canonical_alias()
201    }
202
203    pub fn calculate_buffer_name(&self) -> Result<String, StoreError> {
204        let room = self.room.clone();
205        let room_name = self.runtime.block_on(room.display_name())?.to_string();
206
207        let room_name = if room_name == "#" {
208            "##".to_owned()
209        } else if room_name.starts_with('#')
210            || self.runtime.block_on(room.is_direct()).unwrap_or(false)
211        {
212            room_name
213        } else {
214            format!("#{}", room_name)
215        };
216
217        Ok(room_name.to_string())
218    }
219
220    pub fn update_buffer_name(&self) {
221        let buffer = self.buffer_handle();
222
223        let buffer = if let Ok(b) = buffer.upgrade() {
224            b
225        } else {
226            return;
227        };
228
229        match self.calculate_buffer_name() {
230            Ok(name) => buffer.set_short_name(&name),
231            Err(e) => {
232                Weechat::print(&format!(
233                    "{}: Error fetching the room name from the store: {}",
234                    Weechat::prefix(Prefix::Error),
235                    e.to_string(),
236                ));
237            }
238        }
239    }
240
241    pub fn replace_verification_event(
242        &self,
243        event_id: &EventId,
244        event: RenderedEvent,
245    ) {
246        if let Ok(buffer) = self.buffer_handle().upgrade() {
247            let event_id_tag = Cow::from(event_id.to_tag());
248
249            let lines: Vec<BufferLine> = buffer
250                .lines()
251                .filter(|l| l.tags().contains(&event_id_tag))
252                .collect();
253
254            self.replace_event_helper(&buffer, lines, event);
255        }
256    }
257
258    pub fn print_rendered_event(&self, rendered: RenderedEvent) {
259        let buffer = self.buffer_handle();
260
261        if let Ok(buffer) = buffer.upgrade() {
262            for line in rendered.content.lines {
263                let message = format!("{}{}", &rendered.prefix, &line.message);
264                let tags: Vec<&str> =
265                    line.tags.iter().map(|t| t.as_str()).collect();
266                buffer.print_date_tags(
267                    rendered.message_timestamp,
268                    &tags,
269                    &message,
270                )
271            }
272        }
273    }
274}