gomuks/ui/message-view.go

524 lines
14 KiB
Go
Raw Normal View History

2018-03-17 00:27:30 +01:00
// gomuks - A terminal Matrix client written in Go.
2019-01-17 13:13:25 +01:00
// Copyright (C) 2019 Tulir Asokan
2018-03-17 00:27:30 +01:00
//
// This program is free software: you can redistribute it and/or modify
2019-01-17 13:13:25 +01:00
// it under the terms of the GNU Affero General Public License as published by
2018-03-17 00:27:30 +01:00
// 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
2019-01-17 13:13:25 +01:00
// GNU Affero General Public License for more details.
2018-03-17 00:27:30 +01:00
//
2019-01-17 13:13:25 +01:00
// 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/>.
2018-03-17 00:27:30 +01:00
package ui
2018-03-17 00:27:30 +01:00
import (
"fmt"
"math"
"strings"
2018-03-17 00:27:30 +01:00
"github.com/mattn/go-runewidth"
2019-01-17 13:13:25 +01:00
2019-03-25 23:37:35 +01:00
"maunium.net/go/mauview"
2019-01-17 13:13:25 +01:00
"maunium.net/go/tcell"
2018-06-01 23:44:21 +02:00
"maunium.net/go/gomuks/config"
"maunium.net/go/gomuks/debug"
"maunium.net/go/gomuks/interface"
2018-04-14 14:33:20 +02:00
"maunium.net/go/gomuks/lib/open"
"maunium.net/go/gomuks/ui/messages"
2018-04-14 14:33:20 +02:00
"maunium.net/go/gomuks/ui/messages/tstring"
"maunium.net/go/gomuks/ui/widget"
2018-03-17 00:27:30 +01:00
)
type MessageView struct {
2018-04-14 14:33:20 +02:00
parent *RoomView
2018-06-01 23:43:56 +02:00
config *config.Config
2018-04-14 14:33:20 +02:00
2018-03-17 00:27:30 +01:00
ScrollOffset int
MaxSenderWidth int
DateFormat string
2018-03-17 00:27:30 +01:00
TimestampFormat string
TimestampWidth int
2018-03-20 11:16:32 +01:00
LoadingMessages bool
2018-03-17 00:27:30 +01:00
2018-03-20 11:16:32 +01:00
widestSender int
2019-03-25 23:37:35 +01:00
width int
height int
2018-03-20 11:16:32 +01:00
prevWidth int
prevHeight int
prevMsgCount int
2018-06-01 23:43:56 +02:00
prevPrefs config.UserPreferences
2018-03-17 00:27:30 +01:00
messageIDs map[string]messages.UIMessage
messages []messages.UIMessage
2018-03-20 11:16:32 +01:00
textBuffer []tstring.TString
metaBuffer []ifc.MessageMeta
2018-03-17 00:27:30 +01:00
}
2018-04-14 14:33:20 +02:00
func NewMessageView(parent *RoomView) *MessageView {
2018-03-17 00:27:30 +01:00
return &MessageView{
2018-04-14 14:33:20 +02:00
parent: parent,
2018-06-01 23:43:56 +02:00
config: parent.config,
2018-04-14 14:33:20 +02:00
MaxSenderWidth: 15,
TimestampWidth: len(messages.TimeFormat),
ScrollOffset: 0,
2018-03-17 00:27:30 +01:00
messages: make([]messages.UIMessage, 0),
messageIDs: make(map[string]messages.UIMessage),
textBuffer: make([]tstring.TString, 0),
metaBuffer: make([]ifc.MessageMeta, 0),
2019-04-07 17:21:38 +02:00
width: 80,
2018-03-20 11:16:32 +01:00
widestSender: 5,
prevWidth: -1,
prevHeight: -1,
prevMsgCount: -1,
2018-03-17 00:27:30 +01:00
}
}
func (view *MessageView) updateWidestSender(sender string) {
2018-03-17 00:27:30 +01:00
if len(sender) > view.widestSender {
view.widestSender = len(sender)
if view.widestSender > view.MaxSenderWidth {
view.widestSender = view.MaxSenderWidth
}
}
}
func (view *MessageView) UpdateMessageID(ifcMessage ifc.Message, newID string) {
message, ok := ifcMessage.(messages.UIMessage)
if !ok {
debug.Print("[Warning] Passed non-UIMessage ifc.Message object to UpdateMessageID().")
debug.PrintStack()
return
}
delete(view.messageIDs, message.ID())
message.SetID(newID)
view.messageIDs[message.ID()] = message
}
func (view *MessageView) AddMessage(ifcMessage ifc.Message, direction ifc.MessageDirection) {
if ifcMessage == nil {
return
}
message, ok := ifcMessage.(messages.UIMessage)
if !ok {
debug.Print("[Warning] Passed non-UIMessage ifc.Message object to AddMessage().")
debug.PrintStack()
2018-03-22 18:51:20 +01:00
return
}
oldMsg, messageExists := view.messageIDs[message.ID()]
if messageExists {
view.replaceMessage(oldMsg, message)
direction = ifc.IgnoreMessage
2018-03-17 00:27:30 +01:00
}
view.updateWidestSender(message.Sender())
2019-03-25 23:37:35 +01:00
width := view.width
2018-06-01 23:43:56 +02:00
bare := view.config.Preferences.BareMessageView
if !bare {
width -= view.TimestampWidth + TimestampSenderGap + view.widestSender + SenderMessageGap
}
2018-06-01 23:43:56 +02:00
message.CalculateBuffer(view.config.Preferences, width)
if direction == ifc.AppendMessage {
if view.ScrollOffset > 0 {
2018-03-22 18:51:20 +01:00
view.ScrollOffset += message.Height()
}
view.messages = append(view.messages, message)
view.appendBuffer(message)
} else if direction == ifc.PrependMessage {
view.messages = append([]messages.UIMessage{message}, view.messages...)
} else if oldMsg != nil {
view.replaceBuffer(oldMsg, message)
} else {
2018-04-24 15:51:40 +02:00
debug.Print("Unexpected AddMessage() call: Direction is not append or prepend, but message is new.")
debug.PrintStack()
2018-03-17 00:27:30 +01:00
}
view.messageIDs[message.ID()] = message
2018-03-20 11:16:32 +01:00
}
2018-03-17 00:27:30 +01:00
func (view *MessageView) appendBuffer(message messages.UIMessage) {
2018-03-20 11:16:32 +01:00
if len(view.metaBuffer) > 0 {
prevMeta := view.metaBuffer[len(view.metaBuffer)-1]
if prevMeta != nil && prevMeta.FormatDate() != message.FormatDate() {
view.textBuffer = append(view.textBuffer, tstring.NewColorTString(
fmt.Sprintf("Date changed to %s", message.FormatDate()),
tcell.ColorGreen))
view.metaBuffer = append(view.metaBuffer, &messages.BasicMeta{
BTimestampColor: tcell.ColorDefault, BTextColor: tcell.ColorGreen})
2018-03-20 11:16:32 +01:00
}
}
2018-03-17 00:27:30 +01:00
2019-04-07 17:21:38 +02:00
for i := 0; i < message.Height(); i++ {
view.textBuffer = append(view.textBuffer, nil)
2018-03-20 11:16:32 +01:00
view.metaBuffer = append(view.metaBuffer, message)
}
view.prevMsgCount++
2018-03-20 11:16:32 +01:00
}
func (view *MessageView) replaceMessage(original messages.UIMessage, new messages.UIMessage) {
view.messageIDs[new.ID()] = new
for index, msg := range view.messages {
if msg == original {
view.messages[index] = new
}
}
}
func (view *MessageView) replaceBuffer(original messages.UIMessage, new messages.UIMessage) {
start := -1
end := -1
for index, meta := range view.metaBuffer {
if meta == original {
if start == -1 {
start = index
}
end = index
} else if start != -1 {
break
}
}
if start == -1 {
2018-04-24 15:51:40 +02:00
debug.Print("Called replaceBuffer() with message that was not in the buffer:", original.ID())
2018-04-24 16:12:08 +02:00
debug.PrintStack()
view.appendBuffer(new)
return
}
if len(view.textBuffer) > end {
end++
}
2019-04-07 17:21:38 +02:00
if new.Height() == 0 {
new.CalculateBuffer(view.prevPrefs, view.prevWidth)
}
textBuf := make([]tstring.TString, new.Height())
view.textBuffer = append(append(view.textBuffer[0:start], textBuf...), view.textBuffer[end:]...)
if new.Height() != end-start {
metaBuffer := view.metaBuffer[0:start]
2019-04-07 17:21:38 +02:00
for i := 0; i < new.Height(); i++ {
metaBuffer = append(metaBuffer, new)
}
view.metaBuffer = append(metaBuffer, view.metaBuffer[end:]...)
} else {
for i := start; i < end; i++ {
view.metaBuffer[i] = new
}
}
}
func (view *MessageView) recalculateBuffers() {
2018-06-01 23:43:56 +02:00
prefs := view.config.Preferences
2019-03-25 23:37:35 +01:00
recalculateMessageBuffers := view.width != view.prevWidth ||
2018-06-01 23:43:56 +02:00
view.prevPrefs.BareMessageView != prefs.BareMessageView ||
view.prevPrefs.DisableImages != prefs.DisableImages
if recalculateMessageBuffers || len(view.messages) != view.prevMsgCount {
2019-03-25 23:37:35 +01:00
width := view.width
if !prefs.BareMessageView {
width -= view.TimestampWidth + TimestampSenderGap + view.widestSender + SenderMessageGap
}
view.textBuffer = []tstring.TString{}
view.metaBuffer = []ifc.MessageMeta{}
view.prevMsgCount = 0
for i, message := range view.messages {
if message == nil {
debug.Print("O.o found nil message at", i)
break
}
if recalculateMessageBuffers {
2018-06-01 23:43:56 +02:00
message.CalculateBuffer(prefs, width)
}
2018-03-20 11:16:32 +01:00
view.appendBuffer(message)
2018-03-17 00:27:30 +01:00
}
}
2019-03-25 23:37:35 +01:00
view.prevHeight = view.height
view.prevWidth = view.width
2018-06-01 23:43:56 +02:00
view.prevPrefs = prefs
2018-03-17 00:27:30 +01:00
}
2018-04-15 13:03:05 +02:00
func (view *MessageView) handleMessageClick(message ifc.MessageMeta) bool {
switch message := message.(type) {
case *messages.ImageMessage:
open.Open(message.Path())
case messages.UIMessage:
debug.Print("Message clicked:", message.NotificationContent())
}
return false
}
func (view *MessageView) handleUsernameClick(message ifc.MessageMeta, prevMessage ifc.MessageMeta) bool {
uiMessage, ok := message.(messages.UIMessage)
if !ok {
return false
}
prevUIMessage, _ := prevMessage.(messages.UIMessage)
if prevUIMessage != nil && prevUIMessage.Sender() == uiMessage.Sender() {
return false
}
if len(uiMessage.Sender()) == 0 {
2018-04-15 13:03:05 +02:00
return false
}
sender := fmt.Sprintf("[%s](https://matrix.to/#/%s)", uiMessage.Sender(), uiMessage.SenderID())
2018-04-15 13:03:05 +02:00
cursorPos := view.parent.input.GetCursorOffset()
text := view.parent.input.GetText()
var buf strings.Builder
2018-04-15 13:03:05 +02:00
if cursorPos == 0 {
buf.WriteString(sender)
buf.WriteRune(':')
buf.WriteRune(' ')
buf.WriteString(text)
2018-04-15 13:03:05 +02:00
} else {
textBefore := runewidth.Truncate(text, cursorPos, "")
textAfter := text[len(textBefore):]
buf.WriteString(textBefore)
buf.WriteString(sender)
buf.WriteRune(' ')
buf.WriteString(textAfter)
2018-04-15 13:03:05 +02:00
}
newText := buf.String()
2018-04-15 13:03:05 +02:00
view.parent.input.SetText(string(newText))
view.parent.input.SetCursorOffset(cursorPos + len(newText) - len(text))
return true
}
2019-03-25 23:37:35 +01:00
func (view *MessageView) OnMouseEvent(event mauview.MouseEvent) bool {
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
}
2019-03-25 23:37:35 +01:00
message := view.metaBuffer[line]
var prevMessage ifc.MessageMeta
if y != 0 && line > 0 {
prevMessage = view.metaBuffer[line-1]
}
2018-04-14 14:33:20 +02:00
2019-03-25 23:37:35 +01:00
usernameX := view.TimestampWidth + TimestampSenderGap
messageX := usernameX + view.widestSender + SenderMessageGap
2018-04-15 13:03:05 +02:00
2019-03-25 23:37:35 +01:00
if x >= messageX {
return view.handleMessageClick(message)
} else if x >= usernameX {
return view.handleUsernameClick(message, prevMessage)
}
2018-04-14 14:33:20 +02:00
}
2019-03-25 23:37:35 +01:00
return false
}
2018-03-20 11:16:32 +01:00
const PaddingAtTop = 5
func (view *MessageView) AddScrollOffset(diff int) {
totalHeight := view.TotalHeight()
2019-03-25 23:37:35 +01:00
if diff >= 0 && view.ScrollOffset+diff >= totalHeight-view.height+PaddingAtTop {
view.ScrollOffset = totalHeight - view.height + PaddingAtTop
2018-03-26 13:31:44 +02:00
} else {
view.ScrollOffset += diff
2018-03-20 11:16:32 +01:00
}
2019-03-25 23:37:35 +01:00
if view.ScrollOffset > totalHeight-view.height+PaddingAtTop {
view.ScrollOffset = totalHeight - view.height + PaddingAtTop
2018-03-26 13:31:44 +02:00
}
if view.ScrollOffset < 0 {
view.ScrollOffset = 0
2018-03-20 11:16:32 +01:00
}
}
func (view *MessageView) Height() int {
2019-03-25 23:37:35 +01:00
return view.height
}
func (view *MessageView) TotalHeight() int {
return len(view.textBuffer)
2018-03-17 00:27:30 +01:00
}
func (view *MessageView) IsAtTop() bool {
totalHeight := len(view.textBuffer)
2019-03-25 23:37:35 +01:00
return view.ScrollOffset >= totalHeight-view.height+PaddingAtTop
2018-03-17 00:27:30 +01:00
}
const (
TimestampSenderGap = 1
SenderSeparatorGap = 1
SenderMessageGap = 3
)
2018-03-26 13:31:44 +02:00
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
}
2018-04-15 13:03:05 +02:00
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
}
2019-03-25 23:37:35 +01:00
func (view *MessageView) getIndexOffset(screen mauview.Screen, height, messageX int) (indexOffset int) {
2018-04-15 13:03:05 +02:00
indexOffset = view.TotalHeight() - view.ScrollOffset - height
if indexOffset <= -PaddingAtTop {
message := "Scroll up to load more messages."
if view.LoadingMessages {
message = "Loading more messages..."
}
2019-03-25 23:37:35 +01:00
widget.WriteLineSimpleColor(screen, message, messageX, 0, tcell.ColorGreen)
2018-04-15 13:03:05 +02:00
}
return
}
2018-03-17 00:27:30 +01:00
2018-05-22 23:44:29 +02:00
func (view *MessageView) CapturePlaintext(height int) string {
var buf strings.Builder
indexOffset := view.TotalHeight() - view.ScrollOffset - height
var prevMessage messages.UIMessage
for line := 0; line < height; line++ {
index := indexOffset + line
if index < 0 {
continue
}
meta := view.metaBuffer[index]
message, ok := meta.(messages.UIMessage)
if ok && message != prevMessage {
var sender string
if len(message.Sender()) > 0 {
sender = fmt.Sprintf(" <%s>", message.Sender())
} else if message.Type() == "m.emote" {
sender = fmt.Sprintf(" * %s", message.RealSender())
}
fmt.Fprintf(&buf, "%s%s %s\n", message.FormatTime(), sender, message.PlainText())
2018-05-22 23:44:29 +02:00
prevMessage = message
}
}
return buf.String()
}
2019-03-25 23:37:35 +01:00
func (view *MessageView) Draw(screen mauview.Screen) {
view.width, view.height = screen.Size()
view.recalculateBuffers()
if view.TotalHeight() == 0 {
2019-03-25 23:37:35 +01:00
widget.WriteLineSimple(screen, "It's quite empty in here.", 0, view.height)
return
2018-03-17 00:27:30 +01:00
}
2019-03-25 23:37:35 +01:00
usernameX := view.TimestampWidth + TimestampSenderGap
messageX := usernameX + view.widestSender + SenderMessageGap
separatorX := usernameX + view.widestSender + SenderSeparatorGap
2018-03-17 00:27:30 +01:00
2018-06-01 23:43:56 +02:00
bareMode := view.config.Preferences.BareMessageView
if bareMode {
2019-03-25 23:37:35 +01:00
messageX = 0
}
2019-03-25 23:37:35 +01:00
indexOffset := view.getIndexOffset(screen, view.height, messageX)
2018-03-22 22:40:26 +01:00
if len(view.textBuffer) != len(view.metaBuffer) {
debug.Printf("Unexpected text/meta buffer length mismatch: %d != %d.", len(view.textBuffer), len(view.metaBuffer))
2018-06-01 23:28:21 +02:00
view.prevMsgCount = 0
return
}
2018-03-22 22:40:26 +01:00
2019-03-25 23:37:35 +01:00
scrollBarHeight, scrollBarPos := view.calculateScrollBar(view.height)
var prevMeta ifc.MessageMeta
viewStart := 0
if indexOffset < 0 {
viewStart = -indexOffset
}
for line := viewStart; line < view.height; line++ {
showScrollbar := line-viewStart >= scrollBarPos-scrollBarHeight && line-viewStart < scrollBarPos
isTop := line == viewStart && view.ScrollOffset+view.height >= view.TotalHeight()
2019-03-25 23:37:35 +01:00
isBottom := line == view.height-1 && view.ScrollOffset == 0
2018-03-26 13:31:44 +02:00
borderChar, borderStyle := getScrollbarStyle(showScrollbar, isTop, isBottom)
if !bareMode {
2019-03-25 23:37:35 +01:00
screen.SetContent(separatorX, line, borderChar, nil, borderStyle)
}
}
for line := viewStart; line < view.height && indexOffset+line < view.TotalHeight(); line++ {
index := indexOffset + line
2018-03-20 11:16:32 +01:00
text, meta := view.textBuffer[index], view.metaBuffer[index]
if meta != prevMeta {
if len(meta.FormatTime()) > 0 {
2019-03-25 23:37:35 +01:00
widget.WriteLineSimpleColor(screen, meta.FormatTime(), 0, line, meta.TimestampColor())
2018-03-20 12:01:59 +01:00
}
// TODO hiding senders might not be that nice after all, maybe an option? (disabled for now)
//if !bareMode && (prevMeta == nil || meta.Sender() != prevMeta.Sender()) {
widget.WriteLineColor(
screen, mauview.AlignRight, meta.Sender(),
usernameX, line, view.widestSender,
meta.SenderColor())
//}
2018-03-20 11:16:32 +01:00
prevMeta = meta
2019-04-07 17:21:38 +02:00
}
message, ok := meta.(messages.UIMessage)
if ok {
for i := index - 1; i >= 0 && view.metaBuffer[i] == meta; i-- {
line--
}
message.Draw(mauview.NewProxyScreen(screen, messageX, line, view.width-messageX, message.Height()))
line += message.Height() - 1
} else {
text.Draw(screen, messageX, line)
2018-03-17 00:27:30 +01:00
}
}
}