Debian Codegraph @

ui/messages/base.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // gomuks - A terminal Matrix client written in Go.
2 // Copyright (C) 2020 Tulir Asokan
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Affero General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU Affero General Public License for more details.
13 //
14 // You should have received a copy of the GNU Affero General Public License
15 // along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17 package messages
18
19 import (
20 "fmt"
21 "sort"
22 "time"
23
24 "maunium.net/go/mautrix/event"
25 "maunium.net/go/mautrix/id"
26
27 "go.mau.fi/mauview"
•28 "github.com/gdamore/tcell/v2"
29
30 "maunium.net/go/gomuks/config"
31 "maunium.net/go/gomuks/matrix/muksevt"
32
33 "maunium.net/go/gomuks/ui/widget"
34 )
35
36 type MessageRenderer interface {
37 Draw(screen mauview.Screen, msg *UIMessage)
38 NotificationContent() string
39 PlainText() string
40 CalculateBuffer(prefs config.UserPreferences, width int, msg *UIMessage)
41 Height() int
42 Clone() MessageRenderer
43 String() string
44 }
45
46 type ReactionItem struct {
47 Key string
48 Count int
49 }
50
51 func (ri ReactionItem) String() string {
52 return fmt.Sprintf("%d×%s", ri.Count, ri.Key)
53 }
54
55 type ReactionSlice []ReactionItem
56
57 func (rs ReactionSlice) Len() int {
58 return len(rs)
59 }
60
61 func (rs ReactionSlice) Less(i, j int) bool {
62 return rs[i].Key < rs[j].Key
63 }
64
65 func (rs ReactionSlice) Swap(i, j int) {
66 rs[i], rs[j] = rs[j], rs[i]
67 }
68
69 type UIMessage struct {
70 EventID id.EventID
71 TxnID string
72 Relation event.RelatesTo
73 Type event.MessageType
74 SenderID id.UserID
75 SenderName string
76 DefaultSenderColor tcell.Color
77 Timestamp time.Time
78 State muksevt.OutgoingState
79 IsHighlight bool
80 IsService bool
81 IsSelected bool
82 Edited bool
83 Event *muksevt.Event
84 ReplyTo *UIMessage
85 Reactions ReactionSlice
86 Renderer MessageRenderer
87 }
88
89 func (msg *UIMessage) GetEvent() *muksevt.Event {
90 if msg == nil {
91 return nil
92 }
93 return msg.Event
94 }
95
96 const DateFormat = "January _2, 2006"
97 const TimeFormat = "15:04:05"
98
99 func newUIMessage(evt *muksevt.Event, displayname string, renderer MessageRenderer) *UIMessage {
100 msgContent := evt.Content.AsMessage()
101 msgtype := msgContent.MsgType
102 if len(msgtype) == 0 {
103 msgtype = event.MessageType(evt.Type.String())
104 }
105
106 reactions := make(ReactionSlice, 0, len(evt.Unsigned.Relations.Annotations.Map))
107 for key, count := range evt.Unsigned.Relations.Annotations.Map {
108 reactions = append(reactions, ReactionItem{
109 Key: key,
110 Count: count,
111 })
112 }
113 sort.Sort(reactions)
114
115 return &UIMessage{
116 SenderID: evt.Sender,
117 SenderName: displayname,
118 Timestamp: unixToTime(evt.Timestamp),
119 DefaultSenderColor: widget.GetHashColor(evt.Sender),
120 Type: msgtype,
121 EventID: evt.ID,
122 TxnID: evt.Unsigned.TransactionID,
123 Relation: *msgContent.GetRelatesTo(),
124 State: evt.Gomuks.OutgoingState,
125 IsHighlight: false,
126 IsService: false,
127 Edited: len(evt.Gomuks.Edits) > 0,
128 Reactions: reactions,
129 Event: evt,
130 Renderer: renderer,
131 }
132 }
133
134 func (msg *UIMessage) AddReaction(key string) {
135 found := false
136 for i, rs := range msg.Reactions {
137 if rs.Key == key {
138 rs.Count++
139 msg.Reactions[i] = rs
140 found = true
141 break
142 }
143 }
144 if !found {
145 msg.Reactions = append(msg.Reactions, ReactionItem{
146 Key: key,
147 Count: 1,
148 })
149 }
150 sort.Sort(msg.Reactions)
151 }
152
153 func unixToTime(unix int64) time.Time {
154 timestamp := time.Now()
155 if unix != 0 {
156 timestamp = time.Unix(unix/1000, unix%1000*1000)
157 }
158 return timestamp
159 }
160
161 // Sender gets the string that should be displayed as the sender of this message.
162 //
163 // If the message is being sent, the sender is "Sending...".
164 // If sending has failed, the sender is "Error".
165 // If the message is an emote, the sender is blank.
166 // In any other case, the sender is the display name of the user who sent the message.
167 func (msg *UIMessage) Sender() string {
168 switch msg.State {
169 case muksevt.StateLocalEcho:
170 return "Sending..."
171 case muksevt.StateSendFail:
172 return "Error"
173 }
174 switch msg.Type {
175 case "m.emote":
176 // Emotes don't show a separate sender, it's included in the buffer.
177 return ""
178 default:
179 return msg.SenderName
180 }
181 }
182
183 func (msg *UIMessage) NotificationSenderName() string {
184 return msg.SenderName
185 }
186
187 func (msg *UIMessage) NotificationContent() string {
188 return msg.Renderer.NotificationContent()
189 }
190
191 func (msg *UIMessage) getStateSpecificColor() tcell.Color {
192 switch msg.State {
193 case muksevt.StateLocalEcho:
194 return tcell.ColorGray
195 case muksevt.StateSendFail:
196 return tcell.ColorRed
197 case muksevt.StateDefault:
198 fallthrough
199 default:
200 return tcell.ColorDefault
201 }
202 }
203
204 // SenderColor returns the color the name of the sender should be shown in.
205 //
206 // If the message is being sent, the color is gray.
207 // If sending has failed, the color is red.
208 //
209 // In any other case, the color is whatever is specified in the Message struct.
210 // Usually that means it is the hash-based color of the sender (see ui/widget/color.go)
211 func (msg *UIMessage) SenderColor() tcell.Color {
212 stateColor := msg.getStateSpecificColor()
213 switch {
214 case stateColor != tcell.ColorDefault:
215 return stateColor
216 case msg.Type == "m.room.member":
217 return widget.GetHashColor(msg.SenderName)
218 case msg.IsService:
219 return tcell.ColorGray
220 default:
221 return msg.DefaultSenderColor
222 }
223 }
224
225 // TextColor returns the color the actual content of the message should be shown in.
226 func (msg *UIMessage) TextColor() tcell.Color {
227 stateColor := msg.getStateSpecificColor()
228 switch {
229 case stateColor != tcell.ColorDefault:
230 return stateColor
231 case msg.IsService, msg.Type == "m.notice":
232 return tcell.ColorGray
233 case msg.IsHighlight:
234 return tcell.ColorYellow
235 case msg.Type == "m.room.member":
236 return tcell.ColorGreen
237 default:
238 return tcell.ColorDefault
239 }
240 }
241
242 // TimestampColor returns the color the timestamp should be shown in.
243 //
244 // As with SenderColor(), messages being sent and messages that failed to be sent are
245 // gray and red respectively.
246 //
247 // However, other messages are the default color instead of a color stored in the struct.
248 func (msg *UIMessage) TimestampColor() tcell.Color {
249 if msg.IsService {
250 return tcell.ColorGray
251 }
252 return msg.getStateSpecificColor()
253 }
254
255 func (msg *UIMessage) ReplyHeight() int {
256 if msg.ReplyTo != nil {
257 return 1 + msg.ReplyTo.Height()
258 }
259 return 0
260 }
261
262 func (msg *UIMessage) ReactionHeight() int {
263 if len(msg.Reactions) > 0 {
264 return 1
265 }
266 return 0
267 }
268
269 // Height returns the number of rows in the computed buffer (see Buffer()).
270 func (msg *UIMessage) Height() int {
271 return msg.ReplyHeight() + msg.Renderer.Height() + msg.ReactionHeight()
272 }
273
274 func (msg *UIMessage) Time() time.Time {
275 return msg.Timestamp
276 }
277
278 // FormatTime returns the formatted time when the message was sent.
279 func (msg *UIMessage) FormatTime() string {
280 return msg.Timestamp.Format(TimeFormat)
281 }
282
283 // FormatDate returns the formatted date when the message was sent.
284 func (msg *UIMessage) FormatDate() string {
285 return msg.Timestamp.Format(DateFormat)
286 }
287
288 func (msg *UIMessage) SameDate(message *UIMessage) bool {
289 year1, month1, day1 := msg.Timestamp.Date()
290 year2, month2, day2 := message.Timestamp.Date()
291 return day1 == day2 && month1 == month2 && year1 == year2
292 }
293
294 func (msg *UIMessage) ID() id.EventID {
295 if len(msg.EventID) == 0 {
296 return id.EventID(msg.TxnID)
297 }
298 return msg.EventID
299 }
300
301 func (msg *UIMessage) SetID(id id.EventID) {
302 msg.EventID = id
303 }
304
305 func (msg *UIMessage) SetIsHighlight(isHighlight bool) {
306 msg.IsHighlight = isHighlight
307 }
308
309 func (msg *UIMessage) DrawReactions(screen mauview.Screen) {
310 if len(msg.Reactions) == 0 {
311 return
312 }
313 width, height := screen.Size()
314 screen = mauview.NewProxyScreen(screen, 0, height-1, width, 1)
315
316 x := 0
317 for _, reaction := range msg.Reactions {
318 _, drawn := mauview.PrintWithStyle(screen, reaction.String(), x, 0, width-x, mauview.AlignLeft, tcell.StyleDefault.Foreground(mauview.Styles.PrimaryTextColor).Background(tcell.ColorDarkGreen))
319 x += drawn + 1
320 if x >= width {
321 break
322 }
323 }
324 }
325
326 func (msg *UIMessage) Draw(screen mauview.Screen) {
327 proxyScreen := msg.DrawReply(screen)
328 msg.Renderer.Draw(proxyScreen, msg)
329 msg.DrawReactions(proxyScreen)
330 if msg.IsSelected {
331 w, h := screen.Size()
332 for x := 0; x < w; x++ {
333 for y := 0; y < h; y++ {
334 mainc, combc, style, _ := screen.GetContent(x, y)
335 _, bg, _ := style.Decompose()
336 if bg == tcell.ColorDefault {
337 screen.SetContent(x, y, mainc, combc, style.Background(tcell.ColorDarkGreen))
338 }
339 }
340 }
341 }
342 }
343
344 func (msg *UIMessage) Clone() *UIMessage {
345 clone := *msg
346 clone.ReplyTo = nil
347 clone.Reactions = nil
348 clone.Renderer = clone.Renderer.Clone()
349 return &clone
350 }
351
352 func (msg *UIMessage) CalculateReplyBuffer(preferences config.UserPreferences, width int) {
353 if msg.ReplyTo == nil {
354 return
355 }
356 msg.ReplyTo.CalculateBuffer(preferences, width-1)
357 }
358
359 func (msg *UIMessage) CalculateBuffer(preferences config.UserPreferences, width int) {
360 msg.Renderer.CalculateBuffer(preferences, width, msg)
361 msg.CalculateReplyBuffer(preferences, width)
362 }
363
364 func (msg *UIMessage) DrawReply(screen mauview.Screen) mauview.Screen {
365 if msg.ReplyTo == nil {
366 return screen
367 }
368 width, height := screen.Size()
369 replyHeight := msg.ReplyTo.Height()
370 widget.WriteLineSimpleColor(screen, "In reply to", 1, 0, tcell.ColorGreen)
371 widget.WriteLineSimpleColor(screen, msg.ReplyTo.SenderName, 13, 0, msg.ReplyTo.SenderColor())
372 for y := 0; y < 1+replyHeight; y++ {
373 screen.SetCell(0, y, tcell.StyleDefault, '▊')
374 }
375 replyScreen := mauview.NewProxyScreen(screen, 1, 1, width-1, replyHeight)
376 msg.ReplyTo.Draw(replyScreen)
377 return mauview.NewProxyScreen(screen, 0, replyHeight+1, width, height-replyHeight-1)
378 }
379
380 func (msg *UIMessage) String() string {
381 return fmt.Sprintf(`&messages.UIMessage{
382 ID="%s", TxnID="%s",
383 Type="%s", Timestamp=%s,
384 Sender={ID="%s", Name="%s", Color=#%X},
385 IsService=%t, IsHighlight=%t,
386 Renderer=%s,
387 }`,
388 msg.EventID, msg.TxnID,
389 msg.Type, msg.Timestamp.String(),
390 msg.SenderID, msg.SenderName, msg.DefaultSenderColor.Hex(),
391 msg.IsService, msg.IsHighlight, msg.Renderer.String())
392 }
393
394 func (msg *UIMessage) PlainText() string {
395 return msg.Renderer.PlainText()
396 }