aboutsummaryrefslogtreecommitdiff
path: root/ui/message-view.go
blob: 4f406e14ccb01a97b4d3757eed3517ccce75172f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
// gomuks - A terminal Matrix client written in Go.
// Copyright (C) 2019 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package ui

import (
	"fmt"
	"math"
	"strings"
	"sync/atomic"

	"github.com/mattn/go-runewidth"
	sync "github.com/sasha-s/go-deadlock"

	"maunium.net/go/mautrix"
	"maunium.net/go/mauview"
	"maunium.net/go/tcell"

	"maunium.net/go/gomuks/config"
	"maunium.net/go/gomuks/debug"
	"maunium.net/go/gomuks/interface"
	"maunium.net/go/gomuks/lib/open"
	"maunium.net/go/gomuks/ui/messages"
	"maunium.net/go/gomuks/ui/widget"
)

type MessageView struct {
	parent *RoomView
	config *config.Config

	ScrollOffset    int
	MaxSenderWidth  int
	DateFormat      string
	TimestampFormat string
	TimestampWidth  int

	// Used for locking
	loadingMessages int32

	_widestSender uint32
	_width        uint32
	_height       uint32
	_prevWidth    uint32
	_prevHeight   uint32
	prevMsgCount  int
	prevPrefs     config.UserPreferences

	messageIDLock sync.RWMutex
	messageIDs    map[string]*messages.UIMessage
	messagesLock  sync.RWMutex
	messages      []*messages.UIMessage
	msgBufferLock sync.RWMutex
	msgBuffer     []*messages.UIMessage
	selected      *messages.UIMessage

	initialHistoryLoaded bool
}

func NewMessageView(parent *RoomView) *MessageView {
	return &MessageView{
		parent: parent,
		config: parent.config,

		MaxSenderWidth: 15,
		TimestampWidth: len(messages.TimeFormat),
		ScrollOffset:   0,

		messages:   make([]*messages.UIMessage, 0),
		messageIDs: make(map[string]*messages.UIMessage),
		msgBuffer:  make([]*messages.UIMessage, 0),

		_width:        80,
		_widestSender: 5,
		_prevWidth:    0,
		_prevHeight:   0,
		prevMsgCount:  -1,
	}
}

func (view *MessageView) Unload() {
	debug.Print("Unloading message view", view.parent.Room.ID)
	view.messagesLock.Lock()
	view.msgBufferLock.Lock()
	view.messageIDLock.Lock()
	view.messageIDs = make(map[string]*messages.UIMessage)
	view.msgBuffer = make([]*messages.UIMessage, 0)
	view.messages = make([]*messages.UIMessage, 0)
	view.initialHistoryLoaded = false
	view.ScrollOffset = 0
	view._widestSender = 5
	view.prevMsgCount = -1
	view.messagesLock.Unlock()
	view.msgBufferLock.Unlock()
	view.messageIDLock.Unlock()
}

func (view *MessageView) updateWidestSender(sender string) {
	if len(sender) > int(view._widestSender) {
		if len(sender) > view.MaxSenderWidth {
			atomic.StoreUint32(&view._widestSender, uint32(view.MaxSenderWidth))
		} else {
			atomic.StoreUint32(&view._widestSender, uint32(len(sender)))
		}
	}
}

type MessageDirection int

const (
	AppendMessage MessageDirection = iota
	PrependMessage
	IgnoreMessage
)

func (view *MessageView) AddMessage(ifcMessage ifc.Message, direction MessageDirection) {
	if ifcMessage == nil {
		return
	}
	message, ok := ifcMessage.(*messages.UIMessage)
	if !ok || message == nil {
		debug.Print("[Warning] Passed non-UIMessage ifc.Message object to AddMessage().")
		debug.PrintStack()
		return
	}

	var oldMsg *messages.UIMessage
	if oldMsg = view.getMessageByID(message.EventID); oldMsg != nil {
		view.replaceMessage(oldMsg, message)
		direction = IgnoreMessage
	} else if oldMsg = view.getMessageByID(message.TxnID); oldMsg != nil {
		view.replaceMessage(oldMsg, message)
		view.deleteMessageID(message.TxnID)
		direction = IgnoreMessage
	}

	view.updateWidestSender(message.Sender())

	width := view.width()
	bare := view.config.Preferences.BareMessageView
	if !bare {
		width -= view.TimestampWidth + TimestampSenderGap + view.widestSender() + SenderMessageGap
	}
	message.CalculateBuffer(view.config.Preferences, width)

	makeDateChange := func() *messages.UIMessage {
		dateChange := messages.NewDateChangeMessage(
			fmt.Sprintf("Date changed to %s", message.FormatDate()))
		dateChange.CalculateBuffer(view.config.Preferences, width)
		view.appendBuffer(dateChange)
		return dateChange
	}

	if direction == AppendMessage {
		if view.ScrollOffset > 0 {
			view.ScrollOffset += message.Height()
		}
		view.messagesLock.Lock()
		if len(view.messages) > 0 && !view.messages[len(view.messages)-1].SameDate(message) {
			view.messages = append(view.messages, makeDateChange(), message)
		} else {
			view.messages = append(view.messages, message)
		}
		view.messagesLock.Unlock()
		view.appendBuffer(message)
	} else if direction == PrependMessage {
		view.messagesLock.Lock()
		if len(view.messages) > 0 && !view.messages[0].SameDate(message) {
			view.messages = append([]*messages.UIMessage{message, makeDateChange()}, view.messages...)
		} else {
			view.messages = append([]*messages.UIMessage{message}, view.messages...)
		}
		view.messagesLock.Unlock()
	} else if oldMsg != nil {
		view.replaceBuffer(oldMsg, message)
	} else {
		debug.Print("Unexpected AddMessage() call: Direction is not append or prepend, but message is new.")
		debug.PrintStack()
	}

	if len(message.ID()) > 0 {
		view.setMessageID(message)
	}
}

func (view *MessageView) replaceMessage(original *messages.UIMessage, new *messages.UIMessage) {
	if len(new.ID()) > 0 {
		view.setMessageID(new)
	}
	view.messagesLock.Lock()
	for index, msg := range view.messages {
		if msg == original {
			view.messages[index] = new
		}
	}
	view.messagesLock.Unlock()
}

func (view *MessageView) getMessageByID(id string) *messages.UIMessage {
	if id == "" {
		return nil
	}
	view.messageIDLock.RLock()
	defer view.messageIDLock.RUnlock()
	msg, ok := view.messageIDs[id]
	if !ok {
		return nil
	}
	return msg
}

func (view *MessageView) deleteMessageID(id string) {
	if id == "" {
		return
	}
	view.messageIDLock.Lock()
	delete(view.messageIDs, id)
	view.messageIDLock.Unlock()
}

func (view *MessageView) setMessageID(message *messages.UIMessage) {
	if message.ID() == "" {
		return
	}
	view.messageIDLock.Lock()
	view.messageIDs[message.ID()] = message
	view.messageIDLock.Unlock()
}

func (view *MessageView) appendBuffer(message *messages.UIMessage) {
	view.msgBufferLock.Lock()
	view.appendBufferUnlocked(message)
	view.msgBufferLock.Unlock()
}

func (view *MessageView) appendBufferUnlocked(message *messages.UIMessage) {
	for i := 0; i < message.Height(); i++ {
		view.msgBuffer = append(view.msgBuffer, message)
	}
	view.prevMsgCount++
}

func (view *MessageView) replaceBuffer(original *messages.UIMessage, new *messages.UIMessage) {
	start := -1
	end := -1
	view.msgBufferLock.RLock()
	for index, meta := range view.msgBuffer {
		if meta == original {
			if start == -1 {
				start = index
			}
			end = index
		} else if start != -1 {
			break
		}
	}
	view.msgBufferLock.RUnlock()

	if start == -1 {
		debug.Print("Called replaceBuffer() with message that was not in the buffer:", original)
		//debug.PrintStack()
		view.appendBuffer(new)
		return
	}

	if len(view.msgBuffer) > end {
		end++
	}

	if new.Height() == 0 {
		new.CalculateBuffer(view.prevPrefs, view.prevWidth())
	}

	view.msgBufferLock.Lock()
	if new.Height() != end-start {
		height := new.Height()

		newBuffer := make([]*messages.UIMessage, height+len(view.msgBuffer)-end)
		for i := 0; i < height; i++ {
			newBuffer[i] = new
		}
		for i := height; i < len(newBuffer); i++ {
			newBuffer[i] = view.msgBuffer[end+(i-height)]
		}
		view.msgBuffer = append(view.msgBuffer[0:start], newBuffer...)
	} else {
		for i := start; i < end; i++ {
			view.msgBuffer[i] = new
		}
	}
	view.msgBufferLock.Unlock()
}

func (view *MessageView) recalculateBuffers() {
	prefs := view.config.Preferences
	recalculateMessageBuffers := view.width() != view.prevWidth() ||
		view.prevPrefs.BareMessageView != prefs.BareMessageView ||
		view.prevPrefs.DisableImages != prefs.DisableImages
	view.messagesLock.RLock()
	view.msgBufferLock.Lock()
	if recalculateMessageBuffers || len(view.messages) != view.prevMsgCount {
		width := view.width()
		if !prefs.BareMessageView {
			width -= view.TimestampWidth + TimestampSenderGap + view.widestSender() + SenderMessageGap
		}
		view.msgBuffer = []*messages.UIMessage{}
		view.prevMsgCount = 0
		for i, message := range view.messages {
			if message == nil {
				debug.Print("O.o found nil message at", i)
				break
			}
			if recalculateMessageBuffers {
				message.CalculateBuffer(prefs, width)
			}
			view.appendBufferUnlocked(message)
		}
	}
	view.msgBufferLock.Unlock()
	view.messagesLock.RUnlock()
	view.updatePrevSize()
	view.prevPrefs = prefs
}

func (view *MessageView) SetSelected(message *messages.UIMessage) {
	if view.selected != nil {
		view.selected.IsSelected = false
	}
	if message != nil && (view.selected == message || message.IsService) {
		view.selected = nil
	} else {
		view.selected = message
	}
	if view.selected != nil {
		view.selected.IsSelected = true
	}
}

func (view *MessageView) handleMessageClick(message *messages.UIMessage, mod tcell.ModMask) bool {
	if msg, ok := message.Renderer.(*messages.FileMessage); ok && mod > 0 && !msg.Thumbnail.IsEmpty() {
		open.Open(msg.ThumbnailPath())
		// No need to re-render
		return false
	}
	view.SetSelected(message)
	view.parent.OnSelect(view.selected)
	return true
}

func (view *MessageView) handleUsernameClick(message *messages.UIMessage, prevMessage *messages.UIMessage) bool {
	// TODO this is needed if senders are hidden for messages from the same sender (see Draw method)
	//if prevMessage != nil && prevMessage.SenderName == message.SenderName {
	//	return false
	//}

	if message.SenderName == "---" || message.SenderName == "-->" || message.SenderName == "<--" || message.Type == mautrix.MsgEmote {
		return false
	}

	sender := fmt.Sprintf("[%s](https://matrix.to/#/%s)", message.SenderName, message.SenderID)

	cursorPos := view.parent.input.GetCursorOffset()
	text := view.parent.input.GetText()
	var buf strings.Builder
	if cursorPos == 0 {
		buf.WriteString(sender)
		buf.WriteRune(':')
		buf.WriteRune(' ')
		buf.WriteString(text)
	} else {
		textBefore := runewidth.Truncate(text, cursorPos, "")
		textAfter := text[len(textBefore):]
		buf.WriteString(textBefore)
		buf.WriteString(sender)
		buf.WriteRune(' ')
		buf.WriteString(textAfter)
	}
	newText := buf.String()
	view.parent.input.SetText(string(newText))
	view.parent.input.SetCursorOffset(cursorPos + len(newText) - len(text))
	return true
}

func (view *MessageView) OnMouseEvent(event mauview.MouseEvent) bool {
	if event.HasMotion() {
		return false
	}
	switch event.Buttons() {
	case tcell.WheelUp:
		if view.IsAtTop() {
			go view.parent.parent.LoadHistory(view.parent.Room.ID)
		} else {
			view.AddScrollOffset(WheelScrollOffsetDiff)
			return true
		}
	case tcell.WheelDown:
		view.AddScrollOffset(-WheelScrollOffsetDiff)
		view.parent.parent.MarkRead(view.parent)
		return true
	case tcell.Button1:
		x, y := event.Position()
		line := view.TotalHeight() - view.ScrollOffset - view.Height() + y
		if line < 0 || line >= view.TotalHeight() {
			return false
		}

		view.msgBufferLock.RLock()
		message := view.msgBuffer[line]
		var prevMessage *messages.UIMessage
		if y != 0 && line > 0 {
			prevMessage = view.msgBuffer[line-1]
		}
		view.msgBufferLock.RUnlock()

		usernameX := view.TimestampWidth + TimestampSenderGap
		messageX := usernameX + view.widestSender() + SenderMessageGap

		if x >= messageX {
			return view.handleMessageClick(message, event.Modifiers())
		} else if x >= usernameX {
			return view.handleUsernameClick(message, prevMessage)
		}
	}
	return false
}

const PaddingAtTop = 5

func (view *MessageView) AddScrollOffset(diff int) {
	totalHeight := view.TotalHeight()
	height := view.Height()
	if diff >= 0 && view.ScrollOffset+diff >= totalHeight-height+PaddingAtTop {
		view.ScrollOffset = totalHeight - height + PaddingAtTop
	} else {
		view.ScrollOffset += diff
	}

	if view.ScrollOffset > totalHeight-height+PaddingAtTop {
		view.ScrollOffset = totalHeight - height + PaddingAtTop
	}
	if view.ScrollOffset < 0 {
		view.ScrollOffset = 0
	}
}

func (view *MessageView) setSize(width, height int) {
	atomic.StoreUint32(&view._width, uint32(width))
	atomic.StoreUint32(&view._height, uint32(height))
}

func (view *MessageView) updatePrevSize() {
	atomic.StoreUint32(&view._prevWidth, atomic.LoadUint32(&view._width))
	atomic.StoreUint32(&view._prevHeight, atomic.LoadUint32(&view._height))
}

func (view *MessageView) prevHeight() int {
	return int(atomic.LoadUint32(&view._prevHeight))
}

func (view *MessageView) prevWidth() int {
	return int(atomic.LoadUint32(&view._prevWidth))
}

func (view *MessageView) widestSender() int {
	return int(atomic.LoadUint32(&view._widestSender))
}

func (view *MessageView) Height() int {
	return int(atomic.LoadUint32(&view._height))
}

func (view *MessageView) width() int {
	return int(atomic.LoadUint32(&view._width))
}

func (view *MessageView) TotalHeight() int {
	view.msgBufferLock.RLock()
	defer view.msgBufferLock.RUnlock()
	return len(view.msgBuffer)
}

func (view *MessageView) IsAtTop() bool {
	return view.ScrollOffset >= view.TotalHeight()-view.Height()+PaddingAtTop
}

const (
	TimestampSenderGap = 1
	SenderSeparatorGap = 1
	SenderMessageGap   = 3
)

func getScrollbarStyle(scrollbarHere, isTop, isBottom bool) (char rune, style tcell.Style) {
	char = '│'
	style = tcell.StyleDefault
	if scrollbarHere {
		style = style.Foreground(tcell.ColorGreen)
	}
	if isTop {
		if scrollbarHere {
			char = '╥'
		} else {
			char = '┬'
		}
	} else if isBottom {
		if scrollbarHere {
			char = '╨'
		} else {
			char = '┴'
		}
	} else if scrollbarHere {
		char = '║'
	}
	return
}

func (view *MessageView) calculateScrollBar(height int) (scrollBarHeight, scrollBarPos int) {
	viewportHeight := float64(height)
	contentHeight := float64(view.TotalHeight())

	scrollBarHeight = int(math.Ceil(viewportHeight / (contentHeight / viewportHeight)))

	scrollBarPos = height - int(math.Round(float64(view.ScrollOffset)/contentHeight*viewportHeight))

	return
}

func (view *MessageView) getIndexOffset(screen mauview.Screen, height, messageX int) (indexOffset int) {
	indexOffset = view.TotalHeight() - view.ScrollOffset - height
	if indexOffset <= -PaddingAtTop {
		message := "Scroll up to load more messages."
		if atomic.LoadInt32(&view.loadingMessages) == 1 {
			message = "Loading more messages..."
		}
		widget.WriteLineSimpleColor(screen, message, messageX, 0, tcell.ColorGreen)
	}
	return
}

func (view *MessageView) CapturePlaintext(height int) string {
	var buf strings.Builder
	indexOffset := view.TotalHeight() - view.ScrollOffset - height
	var prevMessage *messages.UIMessage
	view.msgBufferLock.RLock()
	for line := 0; line < height; line++ {
		index := indexOffset + line
		if index < 0 {
			continue
		}

		message := view.msgBuffer[index]
		if message != prevMessage {
			var sender string
			if len(message.Sender()) > 0 {
				sender = fmt.Sprintf(" <%s>", message.Sender())
			} else if message.Type == mautrix.MsgEmote {
				sender = fmt.Sprintf(" * %s", message.SenderName)
			}
			fmt.Fprintf(&buf, "%s%s %s\n", message.FormatTime(), sender, message.PlainText())
			prevMessage = message
		}
	}
	view.msgBufferLock.RUnlock()
	return buf.String()
}

func (view *MessageView) Draw(screen mauview.Screen) {
	view.setSize(screen.Size())
	view.recalculateBuffers()

	height := view.Height()
	if view.TotalHeight() == 0 {
		widget.WriteLineSimple(screen, "It's quite empty in here.", 0, height)
		return
	}

	usernameX := view.TimestampWidth + TimestampSenderGap
	messageX := usernameX + view.widestSender() + SenderMessageGap

	bareMode := view.config.Preferences.BareMessageView
	if bareMode {
		messageX = 0
	}

	indexOffset := view.getIndexOffset(screen, height, messageX)

	viewStart := 0
	if indexOffset < 0 {
		viewStart = -indexOffset
	}

	if !bareMode {
		separatorX := usernameX + view.widestSender() + SenderSeparatorGap
		scrollBarHeight, scrollBarPos := view.calculateScrollBar(height)

		for line := viewStart; line < height; line++ {
			showScrollbar := line-viewStart >= scrollBarPos-scrollBarHeight && line-viewStart < scrollBarPos
			isTop := line == viewStart && view.ScrollOffset+height >= view.TotalHeight()
			isBottom := line == height-1 && view.ScrollOffset == 0

			borderChar, borderStyle := getScrollbarStyle(showScrollbar, isTop, isBottom)

			screen.SetContent(separatorX, line, borderChar, nil, borderStyle)
		}
	}

	var prevMsg *messages.UIMessage
	view.msgBufferLock.RLock()
	for line := viewStart; line < height && indexOffset+line < len(view.msgBuffer); {
		index := indexOffset + line

		msg := view.msgBuffer[index]
		if msg == prevMsg {
			debug.Print("Unexpected re-encounter of", msg, msg.Height(), "at", line, index)
			line++
			continue
		}

		if len(msg.FormatTime()) > 0 {
			widget.WriteLineSimpleColor(screen, msg.FormatTime(), 0, line, msg.TimestampColor())
		}
		// TODO hiding senders might not be that nice after all, maybe an option? (disabled for now)
		//if !bareMode && (prevMsg == nil || meta.Sender() != prevMsg.Sender()) {
		widget.WriteLineColor(
			screen, mauview.AlignRight, msg.Sender(),
			usernameX, line, view.widestSender(),
			msg.SenderColor())
		//}
		if msg.Edited {
			// TODO add better indicator for edits
			screen.SetCell(usernameX+view.widestSender(), line, tcell.StyleDefault.Foreground(tcell.ColorDarkRed), '*')
		}

		for i := index - 1; i >= 0 && view.msgBuffer[i] == msg; i-- {
			line--
		}
		msg.Draw(mauview.NewProxyScreen(screen, messageX, line, view.width()-messageX, msg.Height()))
		line += msg.Height()

		prevMsg = msg
	}
	view.msgBufferLock.RUnlock()
}