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