src/render.rs
384 lines · 15490 bytes
1use crate::room_buffer::WeechatRoomMember;
2use matrix_sdk::{
3 events::{
4 room::{
5 member::{MemberEventContent, MembershipChange},
6 message::{
7 AudioMessageEventContent, EmoteMessageEventContent,
8 FileMessageEventContent, ImageMessageEventContent,
9 MessageEventContent, NoticeMessageEventContent,
10 TextMessageEventContent, VideoMessageEventContent,
11 },
12 },
13 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent,
14 SyncStateEvent,
15 },
16 PossiblyRedactedExt,
17};
18use weechat::Weechat;
19
20/// Rendering function for membership events (joins, leaves, bans, profile
21/// changes, etc).
22// TODO: We should not return raw strings here but something like [Block]
23// where Block is (String, [Tags]). Each Block represents one or several lines
24// which have the same tags.
25pub fn render_membership(
26 member: &SyncStateEvent<MemberEventContent>,
27 sender: &WeechatRoomMember,
28 target: &WeechatRoomMember,
29) -> String {
30 use MembershipChange::*;
31 let change_op = member.membership_change();
32
33 let operation = match change_op {
34 None => "did nothing",
35 Error => "caused an error", // must never happen
36 Joined => "has joined the room",
37 Left => "has left the room",
38 Banned => "was banned by",
39 Unbanned => "was unbanned by",
40 Kicked => "was kicked from the room by",
41 Invited => "was invited to the room by",
42 KickedAndBanned => "was kicked and banned by",
43 InvitationRejected => "rejected the invitation",
44 InvitationRevoked => "had the invitation revoked by",
45 ProfileChanged { .. } => "_",
46 NotImplemented => "performed an unimplemented operation",
47 _ => "caused an unhandled membership change",
48 };
49
50 fn formatted_name(member: &WeechatRoomMember) -> String {
51 match &member.display_name {
52 Some(display_name) => {
53 format!("{name} {color_delim}({color_reset}{user_id}{color_delim}){color_reset}",
54 name = display_name,
55 user_id = &member.user_id,
56 color_delim = Weechat::color("chat_delimiters"),
57 color_reset = Weechat::color("reset"))
58 }
59
60 std::option::Option::None => {
61 member.user_id.as_ref().to_string()
62 }
63 }
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 let color_action = Weechat::color(color_action);
73 let color_reset = Weechat::color("reset");
74
75 let operation = format!(
76 "{color_action}{op}{color_reset}",
77 color_action = color_action,
78 op = operation,
79 color_reset = color_reset
80 );
81
82 let target_name = format!(
83 "{color_user}{target_name}{color_reset}",
84 target_name = formatted_name(target),
85 color_user = Weechat::color("reset"), // TODO
86 color_reset = Weechat::color("reset")
87 );
88
89 let sender_name = format!(
90 "{color_user}{sender_name}{color_reset}",
91 sender_name = formatted_name(sender),
92 color_user = Weechat::color("reset"), // TODO
93 color_reset = Weechat::color("reset")
94 );
95
96 match change_op {
97 ProfileChanged {
98 displayname_changed,
99 avatar_url_changed,
100 } => {
101 let new_display_name = &member.content.displayname;
102
103 // TODO: Should we display the new avatar URL?
104 // let new_avatar = member.content.avatar_url.as_ref();
105
106 match (displayname_changed, avatar_url_changed) {
107 (false, true) =>
108 format!(
109 "{prefix} {target} {color_action}changed their avatar{color_reset}",
110 prefix = Weechat::prefix(prefix),
111 target = target_name,
112 color_action = color_action,
113 color_reset = color_reset
114 ),
115 (true, false) => {
116 match new_display_name {
117 Some(name) => format!(
118 "{prefix} {target} {color_action}changed their display name to{color_reset} {new}",
119 prefix = Weechat::prefix(prefix),
120 target = target_name,
121 new = name,
122 color_action = color_action,
123 color_reset = color_reset
124 ),
125 std::option::Option::None => format!(
126 "{prefix} {target} {color_action}removed their display name{color_reset}",
127 prefix = Weechat::prefix(prefix),
128 target = target_name,
129 color_action = color_action,
130 color_reset = color_reset
131 ),
132 }
133 }
134 (true, true) =>
135 match new_display_name {
136 Some(name) => format!(
137 "{prefix} {target} {color_action}changed their avatar and changed their display name to{color_reset} {new}",
138 prefix = Weechat::prefix(prefix),
139 target = target_name,
140 new = name,
141 color_action = color_action,
142 color_reset = color_reset
143 ),
144 std::option::Option::None => format!(
145 "{prefix} {target} {color_action}changed their avatar and removed display name{color_reset}",
146 prefix = Weechat::prefix(prefix),
147 target = target_name,
148 color_action = color_action,
149 color_reset = color_reset
150 ),
151 }
152 (false, false) =>
153 "Cannot happen: got profile changed but nothing really changed".to_string()
154 }
155 }
156 None | Error | Joined | Left | InvitationRejected | NotImplemented => {
157 format!(
158 "{prefix} {target} {op}",
159 prefix = Weechat::prefix(prefix),
160 target = target_name,
161 op = operation
162 )
163 }
164 Banned | Unbanned | Kicked | Invited | InvitationRevoked
165 | KickedAndBanned => format!(
166 "{prefix} {target} {op} {sender}",
167 prefix = Weechat::prefix(prefix),
168 target = target_name,
169 op = operation,
170 sender = sender_name
171 ),
172
173 // This means an unsupported membership change happened so we just print a generic
174 // message to indicate this.
175 _ => format!(
176 "{prefix} {sender} {op}",
177 prefix = Weechat::prefix(prefix),
178 sender = sender_name,
179 op = operation,
180 ),
181 }
182}
183
184/// Rendering function for room messages.
185// FIXME: Pass room member
186// TODO: We should not return raw strings here but something like [Block]
187// where Block is (String, [Tags]). Each Block represents one or several lines
188// which have the same tags.
189pub fn render_message(
190 message: &AnyPossiblyRedactedSyncMessageEvent,
191 displayname: String,
192) -> String {
193 use AnyPossiblyRedactedSyncMessageEvent::*;
194 use MessageEventContent::*;
195
196 // TODO: Need to render power level indicators as well.
197
198 // In case it's not clear, self.sender is the MXID. We're basing the nick color on it so
199 // that it doesn't change with display name changes.
200 let colorname_user =
201 Weechat::info_get("nick_color_name", message.sender().as_ref())
202 .unwrap_or_else(|| String::from("default"));
203 let color_user = Weechat::color(&colorname_user);
204
205 let color_reset = Weechat::color("reset");
206
207 match message {
208 Regular(message) => {
209 match message.content() {
210 AnyMessageEventContent::RoomEncrypted(_) => format!(
211 "{color_user}{}{color_reset}\t{}",
212 displayname,
213 "Unable to decrypt message",
214 color_user = color_user,
215 color_reset = color_reset
216 ),
217
218 AnyMessageEventContent::RoomMessage(content) => {
219 match content {
220 // TODO: formatting for inline markdown and so on
221 Text(t) => format!(
222 "{color_user}{}{color_reset}\t{}",
223 displayname,
224 t.resolve_body(),
225 color_user = color_user,
226 color_reset = color_reset
227 ),
228 Emote(e) => format!(
229 "{prefix}\t{color_user}{}{color_reset} {}",
230 displayname,
231 e.resolve_body(),
232 prefix = Weechat::prefix("action"),
233 color_user = color_user,
234 color_reset = color_reset
235 ),
236 Audio(a) => format!(
237 "{color_user}{}{color_reset}\t{}: {}",
238 displayname,
239 a.body,
240 a.resolve_url(),
241 color_user = color_user,
242 color_reset = color_reset
243 ),
244 File(f) => format!(
245 "{color_user}{}{color_reset}\t{}: {}",
246 displayname,
247 f.body,
248 f.resolve_url(),
249 color_user = color_user,
250 color_reset = color_reset
251 ),
252 Image(i) => format!(
253 "{color_user}{}{color_reset}\t{}: {}",
254 displayname,
255 i.body,
256 i.resolve_url(),
257 color_user = color_user,
258 color_reset = color_reset
259 ),
260 Location(l) => format!(
261 "{color_user}{}{color_reset}\t{}: {}",
262 displayname,
263 l.body,
264 l.geo_uri,
265 color_user = color_user,
266 color_reset = color_reset
267 ),
268 Notice(n) => format!(
269 "{prefix}{color_notice}Notice{color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
270 displayname,
271 n.resolve_body(),
272 prefix = Weechat::prefix("network"),
273 color_notice = Weechat::color("irc.color.notice"),
274 color_delim = Weechat::color("chat_delimiters"),
275 color_reset = color_reset
276 ),
277 Video(v) => format!(
278 "{color_user}{}{color_reset}\t{}: {}",
279 displayname,
280 v.body,
281 v.resolve_url(),
282 color_user = color_user,
283 color_reset = color_reset
284 ),
285 ServerNotice(n) => format!(
286 "{prefix}{color_notice}Server notice{color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
287 displayname,
288 n.body,
289 prefix = Weechat::prefix("network"),
290 color_notice = Weechat::color("irc.color.notice"),
291 color_delim = Weechat::color("chat_delimiters"),
292 color_reset = color_reset
293 ),
294 e => format!(
295 "{color_user}{}{color_reset}\tUnknown message type: {:#?}",
296 displayname,
297 e,
298 color_user = color_user,
299 color_reset = color_reset
300 ),
301 }
302 }
303 _ => {
304 // TODO: Handle rendering of message types other than RoomMessage
305 todo!("Handle rendering of message types other than RoomMessage");
306 }
307 }
308 }
309
310 AnyPossiblyRedactedSyncMessageEvent::Redacted(_message) => {
311 // TODO: Handle rendering redacted events
312 todo!("Handle rendering redacted events");
313 }
314 }
315}
316
317/// Trait for message event types that contain an optional formatted body. `resolve_body` will
318/// return the formatted body if present, else fallback to the regular body.
319trait HasFormattedBody {
320 fn body(&self) -> &str;
321 fn formatted_body(&self) -> Option<&str>;
322 #[inline]
323 fn resolve_body(&self) -> &str {
324 self.formatted_body().unwrap_or_else(|| self.body())
325 }
326}
327
328// Repeating this for each event type would get boring fast so lets use a simple macro to implement
329// the trait for a struct that has a `body` and `formatted_body` field
330macro_rules! has_formatted_body {
331 ($content: ident) => {
332 impl HasFormattedBody for $content {
333 #[inline]
334 fn body(&self) -> &str {
335 &self.body
336 }
337
338 #[inline]
339 fn formatted_body(&self) -> Option<&str> {
340 self.formatted.as_ref().map(|f| f.body.as_ref())
341 }
342 }
343 };
344}
345
346/// This trait is implemented for message types that can contain either an URL or an encrypted
347/// file. One of these _must_ be present.
348trait HasUrlOrFile {
349 fn url(&self) -> Option<&str>;
350 fn file(&self) -> Option<&str>;
351 #[inline]
352 fn resolve_url(&self) -> &str {
353 // the file is either encrypted or not encrypted so either `url` or `file` must
354 // exist and unwrapping will never panic
355 self.url().or_else(|| self.file()).unwrap()
356 }
357}
358
359// Same as above: a simple macro to implement the trait for structs with `url` and `file` fields.
360macro_rules! has_url_or_file {
361 ($content: ident) => {
362 impl HasUrlOrFile for $content {
363 #[inline]
364 fn url(&self) -> Option<&str> {
365 self.url.as_deref()
366 }
367
368 #[inline]
369 fn file(&self) -> Option<&str> {
370 self.file.as_ref().map(|f| f.url.as_str())
371 }
372 }
373 };
374}
375
376// this actually implements the trait for different event types
377has_formatted_body!(EmoteMessageEventContent);
378has_formatted_body!(NoticeMessageEventContent);
379has_formatted_body!(TextMessageEventContent);
380
381has_url_or_file!(AudioMessageEventContent);
382has_url_or_file!(FileMessageEventContent);
383has_url_or_file!(ImageMessageEventContent);
384has_url_or_file!(VideoMessageEventContent);