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