src/render.rs

6ac4b2b57f6fde2b45b12118ac45d05c54b7ef2f
weechat-matrix-rs/src/render.rs history · blame · raw

255 lines · 9061 bytes

  1use matrix_sdk::{
  2    events::room::{
  3        encrypted::EncryptedEvent,
  4        member::{MemberEvent, MembershipChange, MembershipState},
  5        message::{
  6            AudioMessageEventContent, EmoteMessageEventContent,
  7            FileMessageEventContent, ImageMessageEventContent, MessageEvent,
  8            MessageEventContent, NoticeMessageEventContent,
  9            TextMessageEventContent, VideoMessageEventContent,
 10        },
 11    },
 12    identifiers::UserId,
 13};
 14use weechat::Weechat;
 15
 16/// This trait describes events that can be rendered in the weechat UI
 17pub(crate) trait RenderableEvent {
 18    /// Convert the event into a string that will be displayed in the UI.
 19    /// The displayname is taken as a parameter since it cannot be calculated from the event
 20    /// context alone.
 21    fn render(&self, displayname: &str) -> String;
 22
 23    /// Get the sender for this event this can be used to get the displayname.
 24    fn sender(&self) -> &UserId;
 25}
 26
 27impl RenderableEvent for EncryptedEvent {
 28    // TODO: this is not implemented yet
 29    fn render(&self, displayname: &str) -> String {
 30        let color_user = Weechat::color("green"); // TODO: get per-user color
 31        let color_reset = Weechat::color("reset");
 32        format!(
 33            "{color_user}{}{color_reset}\t{}",
 34            displayname,
 35            "Unable to decrypt message",
 36            color_user = color_user,
 37            color_reset = color_reset
 38        )
 39    }
 40
 41    fn sender(&self) -> &UserId {
 42        &self.sender
 43    }
 44}
 45
 46impl RenderableEvent for MemberEvent {
 47    fn render(&self, displayname: &str) -> String {
 48        use MembershipChange::*;
 49        let change_op = self.membership_change();
 50        let operation = match change_op {
 51            None => "did nothing",
 52            Error => "caused an error", // must never happen
 53            Joined => "has joined the room",
 54            Left => "has left the room",
 55            Banned => "was banned",
 56            Unbanned => "was unbanned",
 57            Kicked => "was kicked from the room",
 58            Invited => "was invited to the room",
 59            KickedAndBanned => "was kicked and banned",
 60            InvitationRejected => "rejected the invitation",
 61            InvitationRevoked => "had the invitation revoked",
 62            ProfileChanged => "changed the display name or avatar",
 63            NotImplemented => "performed an unimplemented operation",
 64        };
 65
 66        let (prefix, color_action) = match change_op {
 67            Joined => ("join", "green"),
 68            Banned | ProfileChanged | Invited => ("network", "magenta"),
 69            _ => ("quit", "red"),
 70        };
 71
 72        format!(
 73            "{prefix}{color_user}{name} {color_deli}({color_reset}{state}{color_deli}){color_reset} {color_action}{op}",
 74            prefix = Weechat::prefix(prefix),
 75            color_user = Weechat::color("reset"), // TODO
 76            color_deli = Weechat::color("chat_delimiters"),
 77            color_action = Weechat::color(color_action),
 78            color_reset = Weechat::color("reset"),
 79            name = displayname,
 80            state = self.state_key,
 81            op = operation,
 82        )
 83    }
 84
 85    fn sender(&self) -> &UserId {
 86        &self.sender
 87    }
 88}
 89
 90impl RenderableEvent for MessageEvent {
 91    fn render(&self, displayname: &str) -> String {
 92        use MessageEventContent::*;
 93
 94        // TODO: Need to render power level indicators as well.
 95
 96        // In case it's not clear, self.sender is the MXID. We're basing the nick color on it so
 97        // that it doesn't change with display name changes.
 98        let colorname_user =
 99            Weechat::info_get("nick_color_name", self.sender.as_ref())
100                .unwrap_or(String::from("default"));
101        let color_user = Weechat::color(&colorname_user);
102
103        let color_reset = Weechat::color("reset");
104
105        match &self.content {
106            // TODO: formatting for inline markdown and so on
107            Text(t) => format!(
108                "{color_user}{}{color_reset}\t{}",
109                displayname,
110                t.resolve_body(),
111                color_user = color_user,
112                color_reset = color_reset
113            ),
114            Emote(e) => format!(
115                "{prefix}\t{color_user}{}{color_reset} {}",
116                displayname,
117                e.resolve_body(),
118                prefix = Weechat::prefix("action"),
119                color_user = color_user,
120                color_reset = color_reset
121            ),
122            Audio(a) => format!(
123                "{color_user}{}{color_reset}\t{}: {}",
124                displayname,
125                a.body,
126                a.resolve_url(),
127                color_user = color_user,
128                color_reset = color_reset
129            ),
130            File(f) => format!(
131                "{color_user}{}{color_reset}\t{}: {}",
132                displayname,
133                f.body,
134                f.resolve_url(),
135                color_user = color_user,
136                color_reset = color_reset
137            ),
138            Image(i) => format!(
139                "{color_user}{}{color_reset}\t{}: {}",
140                displayname,
141                i.body,
142                i.resolve_url(),
143                color_user = color_user,
144                color_reset = color_reset
145            ),
146            Location(l) => format!(
147                "{color_user}{}{color_reset}\t{}: {}",
148                displayname,
149                l.body,
150                l.geo_uri,
151                color_user = color_user,
152                color_reset = color_reset
153            ),
154            Notice(n) => format!(
155                "{prefix}{color_notice}Notice{color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
156                displayname,
157                n.resolve_body(),
158                prefix = Weechat::prefix("network"),
159                color_notice = Weechat::color("irc.color.notice"),
160                color_delim = Weechat::color("chat_delimiters"),
161                color_reset = color_reset
162            ),
163            Video(v) => format!(
164                "{color_user}{}{color_reset}\t{}: {}",
165                displayname,
166                v.body,
167                v.resolve_url(),
168                color_user = color_user,
169                color_reset = color_reset
170            ),
171            ServerNotice(n) => format!(
172                "{prefix}{color_notice}Server notice{color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
173                displayname,
174                n.body,
175                prefix = Weechat::prefix("network"),
176                color_notice = Weechat::color("irc.color.notice"),
177                color_delim = Weechat::color("chat_delimiters"),
178                color_reset = color_reset
179            ),
180        }
181    }
182
183    fn sender(&self) -> &UserId {
184        &self.sender
185    }
186}
187
188/// Trait for message event types that contain an optional formatted body. `resolve_body` will
189/// return the formatted body if present, else fallback to the regular body.
190trait HasFormattedBody {
191    fn body(&self) -> &str;
192    fn formatted_body(&self) -> Option<&str>;
193    #[inline]
194    fn resolve_body(&self) -> &str {
195        self.formatted_body().unwrap_or_else(|| self.body())
196    }
197}
198
199// Repeating this for each event type would get boring fast so lets use a simple macro to implement
200// the trait for a struct that has a `body` and `formatted_body` field
201macro_rules! has_formatted_body {
202    ($content: ident) => {
203        impl HasFormattedBody for $content {
204            #[inline]
205            fn body(&self) -> &str {
206                &self.body
207            }
208
209            #[inline]
210            fn formatted_body(&self) -> Option<&str> {
211                self.formatted_body.as_deref()
212            }
213        }
214    };
215}
216
217/// This trait is implemented for message types that can contain either an URL or an encrypted
218/// file. One of both _must_ be present.
219trait HasUrlOrFile {
220    fn url(&self) -> Option<&str>;
221    fn file(&self) -> Option<&str>;
222    #[inline]
223    fn resolve_url(&self) -> &str {
224        // the file is either encrypted or not encrypted so either `url` or `file` must
225        // exist and unwrapping will never panic
226        self.url().or_else(|| self.file()).unwrap()
227    }
228}
229
230// Same as above: a simple macro to implement the trait for structs with `url` and `file` fields.
231macro_rules! has_url_or_file {
232    ($content: ident) => {
233        impl HasUrlOrFile for $content {
234            #[inline]
235            fn url(&self) -> Option<&str> {
236                self.url.as_deref()
237            }
238
239            #[inline]
240            fn file(&self) -> Option<&str> {
241                self.file.as_ref().map(|f| f.url.as_str())
242            }
243        }
244    };
245}
246
247// this actually implements the trait for different event types
248has_formatted_body!(EmoteMessageEventContent);
249has_formatted_body!(NoticeMessageEventContent);
250has_formatted_body!(TextMessageEventContent);
251
252has_url_or_file!(AudioMessageEventContent);
253has_url_or_file!(FileMessageEventContent);
254has_url_or_file!(ImageMessageEventContent);
255has_url_or_file!(VideoMessageEventContent);