gomuks/ui/view-main.go

493 lines
13 KiB
Go
Raw Normal View History

2018-03-13 20:58:43 +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-13 20:58:43 +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-13 20:58:43 +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-13 20:58:43 +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-13 20:58:43 +01:00
2018-03-18 20:24:03 +01:00
package ui
2018-03-13 20:58:43 +01:00
import (
2019-01-17 13:13:25 +01:00
"bufio"
2018-03-17 13:32:01 +01:00
"fmt"
2019-01-17 13:13:25 +01:00
"os"
"time"
2018-03-17 13:32:01 +01:00
"unicode"
2018-03-13 20:58:43 +01:00
2018-07-02 09:00:42 +02:00
"github.com/kyokomi/emoji"
2018-11-13 23:00:35 +01:00
"maunium.net/go/mautrix"
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-03-18 20:24:03 +01:00
"maunium.net/go/gomuks/config"
"maunium.net/go/gomuks/debug"
2018-03-18 20:24:03 +01:00
"maunium.net/go/gomuks/interface"
"maunium.net/go/gomuks/lib/notification"
"maunium.net/go/gomuks/matrix/pushrules"
"maunium.net/go/gomuks/matrix/rooms"
"maunium.net/go/gomuks/ui/messages/parser"
2018-03-18 20:24:03 +01:00
"maunium.net/go/gomuks/ui/widget"
2018-03-13 20:58:43 +01:00
)
2018-03-15 19:53:04 +01:00
type MainView struct {
2019-03-25 23:37:35 +01:00
flex *mauview.Flex
2018-03-15 19:53:04 +01:00
2018-05-27 13:54:07 +02:00
roomList *RoomList
2019-03-25 23:37:35 +01:00
roomView *mauview.Box
currentRoom *RoomView
2018-05-27 13:54:07 +02:00
rooms map[string]*RoomView
cmdProcessor *CommandProcessor
2019-03-25 23:37:35 +01:00
focused mauview.Focusable
modal mauview.Component
2018-03-15 19:53:04 +01:00
lastFocusTime time.Time
2018-03-18 20:24:03 +01:00
matrix ifc.MatrixContainer
gmx ifc.Gomuks
config *config.Config
2018-03-15 19:53:04 +01:00
parent *GomuksUI
}
2019-03-25 23:37:35 +01:00
func (ui *GomuksUI) NewMainView() mauview.Component {
2018-03-15 20:28:21 +01:00
mainView := &MainView{
2019-03-25 23:37:35 +01:00
flex: mauview.NewFlex().SetDirection(mauview.FlexColumn),
roomView: mauview.NewBox(nil).SetBorder(false),
rooms: make(map[string]*RoomView),
2018-03-15 19:53:04 +01:00
2018-03-23 13:44:36 +01:00
matrix: ui.gmx.Matrix(),
2018-03-15 19:53:04 +01:00
gmx: ui.gmx,
2018-03-18 20:24:03 +01:00
config: ui.gmx.Config(),
2018-03-15 19:53:04 +01:00
parent: ui,
}
2019-03-25 23:37:35 +01:00
mainView.roomList = NewRoomList(mainView)
2018-05-27 13:54:07 +02:00
mainView.cmdProcessor = NewCommandProcessor(mainView)
2018-03-15 19:53:04 +01:00
2019-03-25 23:37:35 +01:00
mainView.flex.
AddFixedComponent(mainView.roomList, 25).
AddFixedComponent(widget.NewBorder(), 1).
AddProportionalComponent(mainView.roomView, 1)
mainView.BumpFocus(nil)
2018-03-13 20:58:43 +01:00
2018-03-15 20:28:21 +01:00
ui.mainView = mainView
return mainView
2018-03-13 20:58:43 +01:00
}
2019-03-25 23:37:35 +01:00
func (view *MainView) ShowModal(modal mauview.Component) {
view.modal = modal
var ok bool
view.focused, ok = modal.(mauview.Focusable)
if !ok {
view.focused = nil
2019-03-28 22:28:27 +01:00
} else {
view.focused.Focus()
2019-03-25 23:37:35 +01:00
}
}
func (view *MainView) HideModal() {
view.modal = nil
view.focused = view.roomView
}
func (view *MainView) Draw(screen mauview.Screen) {
2018-06-01 23:43:56 +02:00
if view.config.Preferences.HideRoomList {
view.roomView.Draw(screen)
} else {
2019-03-25 23:37:35 +01:00
view.flex.Draw(screen)
}
if view.modal != nil {
view.modal.Draw(screen)
}
}
func (view *MainView) BumpFocus(roomView *RoomView) {
2019-03-25 23:37:35 +01:00
if roomView != nil {
view.lastFocusTime = time.Now()
view.MarkRead(roomView)
}
}
func (view *MainView) MarkRead(roomView *RoomView) {
if roomView != nil && roomView.Room.HasNewMessages() && roomView.MessageView().ScrollOffset == 0 {
msgList := roomView.MessageView().messages
msg := msgList[len(msgList)-1]
roomView.Room.MarkRead(msg.ID())
view.matrix.MarkRead(roomView.Room.ID, msg.ID())
}
}
func (view *MainView) InputChanged(roomView *RoomView, text string) {
if !roomView.config.Preferences.DisableTypingNotifs {
if len(text) == 0 {
go view.matrix.SendTyping(roomView.Room.ID, false)
} else if text[0] != '/' {
go view.matrix.SendTyping(roomView.Room.ID, true)
}
2018-03-15 20:28:21 +01:00
}
2018-03-15 19:53:04 +01:00
}
2018-03-17 13:32:01 +01:00
func findWordToTabComplete(text string) string {
output := ""
runes := []rune(text)
for i := len(runes) - 1; i >= 0; i-- {
if unicode.IsSpace(runes[i]) {
break
}
output = string(runes[i]) + output
}
return output
}
func (view *MainView) InputSubmit(roomView *RoomView, text string) {
if len(text) == 0 {
return
} else if text[0] == '/' {
2018-05-27 13:54:07 +02:00
cmd := view.cmdProcessor.ParseCommand(roomView, text)
go view.cmdProcessor.HandleCommand(cmd)
} else {
2018-03-22 20:44:46 +01:00
view.SendMessage(roomView, text)
}
2018-03-22 15:44:24 +01:00
roomView.SetInputText("")
}
func (view *MainView) SendMessage(roomView *RoomView, text string) {
2018-03-22 20:44:46 +01:00
tempMessage := roomView.NewTempMessage("m.text", text)
go view.sendTempMessage(roomView, tempMessage, text)
2018-03-22 20:44:46 +01:00
}
func (view *MainView) sendTempMessage(roomView *RoomView, tempMessage ifc.Message, text string) {
defer debug.Recover()
2018-05-10 14:47:24 +02:00
debug.Print("Sending message", tempMessage.Type(), text)
2018-07-02 09:00:42 +02:00
if !roomView.config.Preferences.DisableEmojis {
text = emoji.Sprint(text)
}
eventID, err := view.matrix.SendMarkdownMessage(roomView.Room.ID, tempMessage.Type(), text)
2018-03-22 20:44:46 +01:00
if err != nil {
tempMessage.SetState(ifc.MessageStateFailed)
2018-11-13 23:00:35 +01:00
if httpErr, ok := err.(mautrix.HTTPError); ok {
2019-03-26 18:57:44 +01:00
if respErr := httpErr.RespError; respErr != nil {
// Show shorter version if available
err = respErr
}
}
2018-04-21 18:41:19 +02:00
roomView.AddServiceMessage(fmt.Sprintf("Failed to send message: %v", err))
view.parent.Render()
2018-03-22 20:44:46 +01:00
} else {
2018-05-10 14:47:24 +02:00
debug.Print("Event ID received:", eventID)
2018-03-22 20:44:46 +01:00
roomView.MessageView().UpdateMessageID(tempMessage, eventID)
}
2018-03-15 19:53:04 +01:00
}
2018-05-22 23:44:29 +02:00
func (view *MainView) ShowBare(roomView *RoomView) {
2019-03-25 23:37:35 +01:00
if roomView == nil {
return
}
_, height := view.parent.app.Screen().Size()
2018-05-22 23:44:29 +02:00
view.parent.app.Suspend(func() {
print("\033[2J\033[0;0H")
// We don't know how much space there exactly is. Too few messages looks weird,
// and too many messages shouldn't cause any problems, so we just show too many.
height *= 2
fmt.Println(roomView.MessageView().CapturePlaintext(height))
fmt.Println("Press enter to return to normal mode.")
reader := bufio.NewReader(os.Stdin)
reader.ReadRune()
print("\033[2J\033[0;0H")
})
}
2019-03-25 23:37:35 +01:00
func (view *MainView) OnKeyEvent(event mauview.KeyEvent) bool {
view.BumpFocus(view.currentRoom)
if view.modal != nil {
return view.modal.OnKeyEvent(event)
}
2019-03-25 23:37:35 +01:00
k := event.Key()
c := event.Rune()
if event.Modifiers() == tcell.ModCtrl || event.Modifiers() == tcell.ModAlt {
switch {
case k == tcell.KeyDown:
view.SwitchRoom(view.roomList.Next())
case k == tcell.KeyUp:
view.SwitchRoom(view.roomList.Previous())
case k == tcell.KeyEnter:
2019-03-25 23:37:35 +01:00
view.ShowModal(NewFuzzySearchModal(view, 42, 12))
case k == tcell.KeyHome:
msgView := view.currentRoom.MessageView()
msgView.AddScrollOffset(msgView.TotalHeight())
case k == tcell.KeyEnd:
msgView := view.currentRoom.MessageView()
msgView.AddScrollOffset(-msgView.TotalHeight())
2019-03-30 17:51:26 +01:00
case c == 'n' || k == tcell.KeyCtrlN:
return view.flex.OnKeyEvent(tcell.NewEventKey(tcell.KeyEnter, '\n', event.Modifiers()|tcell.ModShift))
case c == 'a':
view.SwitchRoom(view.roomList.NextWithActivity())
2019-03-30 17:51:26 +01:00
case c == 'l' || k == tcell.KeyCtrlL:
2019-03-25 23:37:35 +01:00
view.ShowBare(view.currentRoom)
2018-03-25 13:21:59 +02:00
default:
2019-03-25 23:37:35 +01:00
goto defaultHandler
2018-03-13 20:58:43 +01:00
}
2019-03-25 23:37:35 +01:00
return true
}
defaultHandler:
if view.config.Preferences.HideRoomList {
return view.roomView.OnKeyEvent(event)
2018-03-13 20:58:43 +01:00
}
2019-03-25 23:37:35 +01:00
return view.flex.OnKeyEvent(event)
2018-03-13 20:58:43 +01:00
}
const WheelScrollOffsetDiff = 3
2019-03-25 23:37:35 +01:00
func (view *MainView) OnMouseEvent(event mauview.MouseEvent) bool {
2019-03-30 17:51:26 +01:00
if event.HasMotion() {
return false
}
2019-03-28 22:28:27 +01:00
if view.modal != nil {
return view.modal.OnMouseEvent(event)
}
2019-03-25 23:37:35 +01:00
if view.config.Preferences.HideRoomList {
return view.roomView.OnMouseEvent(event)
}
2019-03-25 23:37:35 +01:00
return view.flex.OnMouseEvent(event)
}
func (view *MainView) OnPasteEvent(event mauview.PasteEvent) bool {
if view.modal != nil {
return view.modal.OnPasteEvent(event)
} else if view.config.Preferences.HideRoomList {
return view.roomView.OnPasteEvent(event)
}
return view.flex.OnPasteEvent(event)
}
func (view *MainView) Focus() {
if view.focused != nil {
view.focused.Focus()
}
}
func (view *MainView) Blur() {
if view.focused != nil {
view.focused.Blur()
}
}
2018-04-24 01:13:17 +02:00
func (view *MainView) SwitchRoom(tag string, room *rooms.Room) {
if room == nil {
return
}
roomView := view.rooms[room.ID]
if roomView == nil {
debug.Print("Tried to switch to non-nil room with nil roomView!")
debug.Print(tag, room)
return
}
2019-03-25 23:37:35 +01:00
view.roomView.SetInnerComponent(roomView)
view.currentRoom = roomView
view.MarkRead(roomView)
2018-04-24 01:13:17 +02:00
view.roomList.SetSelected(tag, room)
2018-03-15 19:53:04 +01:00
view.parent.Render()
}
2018-03-22 18:51:20 +01:00
func (view *MainView) SaveAllHistory() {
for _, room := range view.rooms {
err := room.SaveHistory(view.config.HistoryDir)
if err != nil {
debug.Printf("Failed to save history of %s: %v", room.Room.GetTitle(), err)
}
}
}
func (view *MainView) addRoomPage(room *rooms.Room) {
2019-03-25 23:37:35 +01:00
if _, ok := view.rooms[room.ID]; !ok {
roomView := NewRoomView(view, room).
2018-03-22 15:44:24 +01:00
SetInputSubmitFunc(view.InputSubmit).
2019-03-25 23:37:35 +01:00
SetInputChangedFunc(view.InputChanged)
view.rooms[room.ID] = roomView
2018-03-16 15:24:11 +01:00
roomView.UpdateUserList()
2018-03-22 18:51:20 +01:00
_, err := roomView.LoadHistory(view.matrix, view.config.HistoryDir)
2018-03-22 18:51:20 +01:00
if err != nil {
debug.Printf("Failed to load history of %s: %v", roomView.Room.GetTitle(), err)
}
2018-03-16 15:24:11 +01:00
}
}
func (view *MainView) GetRoom(roomID string) ifc.RoomView {
2018-04-24 01:13:17 +02:00
room, ok := view.rooms[roomID]
if !ok {
view.AddRoom(view.matrix.GetRoom(roomID))
room, ok := view.rooms[roomID]
if !ok {
return nil
}
2018-04-24 01:13:17 +02:00
return room
}
return room
}
func (view *MainView) AddRoom(room *rooms.Room) {
if view.roomList.Contains(room.ID) {
debug.Print("Add aborted (room exists)", room.ID, room.GetTitle())
2018-03-16 15:24:11 +01:00
return
}
debug.Print("Adding", room.ID, room.GetTitle())
view.roomList.Add(room)
view.addRoomPage(room)
if !view.roomList.HasSelected() {
view.SwitchRoom(view.roomList.First())
}
2018-03-16 15:24:11 +01:00
}
func (view *MainView) RemoveRoom(room *rooms.Room) {
roomView := view.GetRoom(room.ID)
2018-03-25 13:21:59 +02:00
if roomView == nil {
debug.Print("Remove aborted (not found)", room.ID, room.GetTitle())
2018-03-16 15:24:11 +01:00
return
}
debug.Print("Removing", room.ID, room.GetTitle())
view.roomList.Remove(room)
view.SwitchRoom(view.roomList.Selected())
delete(view.rooms, room.ID)
2018-03-20 11:16:32 +01:00
view.parent.Render()
2018-03-16 15:24:11 +01:00
}
2018-04-24 15:51:40 +02:00
func (view *MainView) SetRooms(rooms map[string]*rooms.Room) {
2018-03-15 19:53:04 +01:00
view.roomList.Clear()
view.rooms = make(map[string]*RoomView)
2018-04-24 15:51:40 +02:00
for _, room := range rooms {
if room.HasLeft {
continue
}
view.roomList.Add(room)
view.addRoomPage(room)
2018-04-24 01:13:17 +02:00
}
view.SwitchRoom(view.roomList.First())
}
func (view *MainView) UpdateTags(room *rooms.Room) {
if !view.roomList.Contains(room.ID) {
return
2018-03-13 20:58:43 +01:00
}
view.roomList.Remove(room)
view.roomList.Add(room)
2018-03-13 20:58:43 +01:00
}
2018-03-15 19:53:04 +01:00
func (view *MainView) SetTyping(room string, users []string) {
roomView, ok := view.rooms[room]
2018-03-14 23:14:39 +01:00
if ok {
2018-03-15 18:45:52 +01:00
roomView.SetTyping(users)
2018-03-15 19:53:04 +01:00
view.parent.Render()
2018-03-14 23:14:39 +01:00
}
}
2018-03-26 17:04:10 +02:00
func sendNotification(room *rooms.Room, sender, text string, critical, sound bool) {
if room.GetTitle() != sender {
sender = fmt.Sprintf("%s (%s)", sender, room.GetTitle())
}
2018-04-25 06:01:00 +02:00
debug.Printf("Sending notification with body \"%s\" from %s in room ID %s (critical=%v, sound=%v)", text, sender, room.ID, critical, sound)
2018-03-26 17:04:10 +02:00
notification.Send(sender, text, critical, sound)
}
func (view *MainView) NotifyMessage(room *rooms.Room, message ifc.Message, should pushrules.PushActionArrayShould) {
2018-05-16 20:42:07 +02:00
view.roomList.Bump(room)
if message.SenderID() == view.config.UserID {
2018-05-16 20:42:07 +02:00
return
}
// Whether or not the room where the message came is the currently shown room.
2018-04-24 01:13:17 +02:00
isCurrent := room == view.roomList.SelectedRoom()
// Whether or not the terminal window is focused.
recentlyFocused := time.Now().Add(-30 * time.Second).Before(view.lastFocusTime)
isFocused := time.Now().Add(-5 * time.Second).Before(view.lastFocusTime)
// Whether or not the push rules say this message should be notified about.
2018-05-16 20:42:07 +02:00
shouldNotify := should.Notify || !should.NotifySpecified
if !isCurrent || !isFocused {
// The message is not in the current room, show new message status in room list.
room.AddUnread(message.ID(), shouldNotify, should.Highlight)
} else {
view.matrix.MarkRead(room.ID, message.ID())
}
if shouldNotify && !recentlyFocused {
// Push rules say notify and the terminal is not focused, send desktop notification.
2018-03-26 17:04:10 +02:00
shouldPlaySound := should.PlaySound && should.SoundName == "default"
sendNotification(room, message.Sender(), message.NotificationContent(), should.Highlight, shouldPlaySound)
}
message.SetIsHighlight(should.Highlight)
2018-03-13 20:58:43 +01:00
}
func (view *MainView) InitialSyncDone() {
view.roomList.Clear()
for _, room := range view.rooms {
view.roomList.Add(room.Room)
room.UpdateUserList()
}
}
func (view *MainView) LoadHistory(room string) {
defer debug.Recover()
roomView := view.rooms[room]
2018-03-20 11:16:32 +01:00
batch := roomView.Room.PrevBatch
lockTime := time.Now().Unix() + 1
2018-03-22 16:36:06 +01:00
roomView.Room.LockHistory()
2018-03-20 11:16:32 +01:00
roomView.MessageView().LoadingMessages = true
defer func() {
2018-03-22 16:36:06 +01:00
roomView.Room.UnlockHistory()
2018-03-20 11:16:32 +01:00
roomView.MessageView().LoadingMessages = false
}()
// There's no clean way to try to lock a mutex, so we just check if we still
// want to continue after we get the lock. This function should always be ran
// in a goroutine, so the blocking doesn't matter.
if time.Now().Unix() >= lockTime || batch != roomView.Room.PrevBatch {
return
}
debug.Print("Fetching history for", room, "starting from", batch)
2018-03-20 11:16:32 +01:00
history, prevBatch, err := view.matrix.GetHistory(roomView.Room.ID, batch, 50)
if err != nil {
roomView.AddServiceMessage("Failed to fetch history")
2018-03-18 20:24:03 +01:00
debug.Print("Failed to fetch history for", roomView.Room.ID, err)
return
}
2018-03-20 11:16:32 +01:00
roomView.Room.PrevBatch = prevBatch
for _, evt := range history {
message := view.ParseEvent(roomView, evt)
if message != nil {
roomView.AddMessage(message, ifc.PrependMessage)
}
}
2018-03-22 18:51:20 +01:00
err = roomView.SaveHistory(view.config.HistoryDir)
if err != nil {
2018-03-23 00:07:44 +01:00
debug.Printf("Failed to save history of %s: %v", roomView.Room.GetTitle(), err)
2018-03-22 18:51:20 +01:00
}
view.config.PutRoom(roomView.Room)
2018-03-20 11:16:32 +01:00
view.parent.Render()
}
2018-11-13 23:00:35 +01:00
func (view *MainView) ParseEvent(roomView ifc.RoomView, evt *mautrix.Event) ifc.Message {
return parser.ParseEvent(view.matrix, roomView.MxRoom(), evt)
}