1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-12-12 11:15:00 +02:00
lazygit/pkg/gui/gui.go

742 lines
21 KiB
Go
Raw Normal View History

package gui
2018-05-19 03:16:34 +02:00
import (
"fmt"
"io/ioutil"
2021-04-05 00:52:09 +02:00
"log"
"os"
2018-12-07 20:22:22 +02:00
"sync"
2018-05-26 05:23:39 +02:00
2018-08-12 13:04:47 +02:00
"os/exec"
"strings"
"time"
"github.com/jesseduffield/gocui"
2018-08-13 12:26:02 +02:00
"github.com/jesseduffield/lazygit/pkg/commands"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
2018-08-18 05:22:05 +02:00
"github.com/jesseduffield/lazygit/pkg/config"
2021-03-21 06:25:29 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/filetree"
2021-04-18 08:30:34 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/lbl"
2021-04-18 10:07:10 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/mergeconflicts"
2021-06-05 07:08:36 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/modes/cherrypicking"
"github.com/jesseduffield/lazygit/pkg/gui/modes/diffing"
2021-04-03 02:32:14 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/modes/filtering"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/authors"
2021-11-02 23:23:47 +02:00
"github.com/jesseduffield/lazygit/pkg/gui/presentation/graph"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/i18n"
allow fast flicking through any list panel Up till now our approach to rendering things like file diffs, branch logs, and commit patches, has been to run a command on the command line, wait for it to complete, take its output as a string, and then write that string to the main view (or secondary view e.g. when showing both staged and unstaged changes of a file). This has caused various issues. For once, if you are flicking through a list of files and an untracked file is particularly large, not only will this require lazygit to load that whole file into memory (or more accurately it's equally large diff), it also will slow down the UI thread while loading that file, and if the user continued down the list, the original command might eventually resolve and replace whatever the diff is for the newly selected file. Following what we've done in lazydocker, I've added a tasks package for when you need something done but you want it to cancel as soon as something newer comes up. Given this typically involves running a command to display to a view, I've added a viewBufferManagerMap struct to the Gui struct which allows you to define these tasks on a per-view basis. viewBufferManagers can run files and directly write the output to their view, meaning we no longer need to use so much memory. In the tasks package there is a helper method called NewCmdTask which takes a command, an initial amount of lines to read, and then runs that command, reads that number of lines, and allows for a readLines channel to tell it to read more lines. We read more lines when we scroll or resize the window. There is an adapter for the tasks package in a file called tasks_adapter which wraps the functions from the tasks package in gui-specific stuff like clearing the main view before starting the next task that wants to write to the main view. I've removed some small features as part of this work, namely the little headers that were at the top of the main view for some situations. For example, we no longer show the upstream of a selected branch. I want to re-introduce this in the future, but I didn't want to make this tasks system too complicated, and in order to facilitate a header section in the main view we'd need to have a task that gets the upstream for the current branch, writes it to the header, then tells another task to write the branch log to the main view, but without clearing inbetween. So it would get messy. I'm thinking instead of having a separate 'header' view atop the main view to render that kind of thing (which can happen in another PR) I've also simplified the 'git show' to just call 'git show' and not do anything fancy when it comes to merge commits. I considered using this tasks approach whenever we write to a view. The only thing is that the renderString method currently resets the origin of a view and I don't want to lose that. So I've left some in there that I consider harmless, but we should probably be just using tasks now for all rendering, even if it's just strings we can instantly make.
2020-01-11 05:54:59 +02:00
"github.com/jesseduffield/lazygit/pkg/tasks"
"github.com/jesseduffield/lazygit/pkg/theme"
2018-08-19 15:28:29 +02:00
"github.com/jesseduffield/lazygit/pkg/updates"
2019-02-25 13:11:35 +02:00
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/sirupsen/logrus"
"gopkg.in/ozeidan/fuzzy-patricia.v3/patricia"
2018-05-19 03:16:34 +02:00
)
// screen sizing determines how much space your selected window takes up (window
// as in panel, not your terminal's window). Sometimes you want a bit more space
// to see the contents of a panel, and this keeps track of how much maximisation
// you've set
type WindowMaximisation int
2020-02-24 23:32:46 +02:00
const (
SCREEN_NORMAL WindowMaximisation = iota
2020-02-24 23:32:46 +02:00
SCREEN_HALF
SCREEN_FULL
)
2021-04-20 10:34:47 +02:00
const StartupPopupVersion = 5
2019-11-10 13:07:45 +02:00
// OverlappingEdges determines if panel edges overlap
var OverlappingEdges = false
type ContextManager struct {
ContextStack []Context
sync.RWMutex
}
func NewContextManager(initialContext Context) ContextManager {
return ContextManager{
ContextStack: []Context{initialContext},
RWMutex: sync.RWMutex{},
}
}
type Repo string
2018-08-13 12:26:02 +02:00
// Gui wraps the gocui Gui object which handles rendering and events
type Gui struct {
2021-04-03 06:56:11 +02:00
g *gocui.Gui
Log *logrus.Entry
GitCommand *commands.GitCommand
OSCommand *oscommands.OSCommand
// this is the state of the GUI for the current repo
State *guiState
// this is a mapping of repos to gui states, so that we can restore the original
// gui state when returning from a subrepo
RepoStateMap map[Repo]*guiState
allow fast flicking through any list panel Up till now our approach to rendering things like file diffs, branch logs, and commit patches, has been to run a command on the command line, wait for it to complete, take its output as a string, and then write that string to the main view (or secondary view e.g. when showing both staged and unstaged changes of a file). This has caused various issues. For once, if you are flicking through a list of files and an untracked file is particularly large, not only will this require lazygit to load that whole file into memory (or more accurately it's equally large diff), it also will slow down the UI thread while loading that file, and if the user continued down the list, the original command might eventually resolve and replace whatever the diff is for the newly selected file. Following what we've done in lazydocker, I've added a tasks package for when you need something done but you want it to cancel as soon as something newer comes up. Given this typically involves running a command to display to a view, I've added a viewBufferManagerMap struct to the Gui struct which allows you to define these tasks on a per-view basis. viewBufferManagers can run files and directly write the output to their view, meaning we no longer need to use so much memory. In the tasks package there is a helper method called NewCmdTask which takes a command, an initial amount of lines to read, and then runs that command, reads that number of lines, and allows for a readLines channel to tell it to read more lines. We read more lines when we scroll or resize the window. There is an adapter for the tasks package in a file called tasks_adapter which wraps the functions from the tasks package in gui-specific stuff like clearing the main view before starting the next task that wants to write to the main view. I've removed some small features as part of this work, namely the little headers that were at the top of the main view for some situations. For example, we no longer show the upstream of a selected branch. I want to re-introduce this in the future, but I didn't want to make this tasks system too complicated, and in order to facilitate a header section in the main view we'd need to have a task that gets the upstream for the current branch, writes it to the header, then tells another task to write the branch log to the main view, but without clearing inbetween. So it would get messy. I'm thinking instead of having a separate 'header' view atop the main view to render that kind of thing (which can happen in another PR) I've also simplified the 'git show' to just call 'git show' and not do anything fancy when it comes to merge commits. I considered using this tasks approach whenever we write to a view. The only thing is that the renderString method currently resets the origin of a view and I don't want to lose that. So I've left some in there that I consider harmless, but we should probably be just using tasks now for all rendering, even if it's just strings we can instantly make.
2020-01-11 05:54:59 +02:00
Config config.AppConfigurer
2020-10-04 02:00:48 +02:00
Tr *i18n.TranslationSet
allow fast flicking through any list panel Up till now our approach to rendering things like file diffs, branch logs, and commit patches, has been to run a command on the command line, wait for it to complete, take its output as a string, and then write that string to the main view (or secondary view e.g. when showing both staged and unstaged changes of a file). This has caused various issues. For once, if you are flicking through a list of files and an untracked file is particularly large, not only will this require lazygit to load that whole file into memory (or more accurately it's equally large diff), it also will slow down the UI thread while loading that file, and if the user continued down the list, the original command might eventually resolve and replace whatever the diff is for the newly selected file. Following what we've done in lazydocker, I've added a tasks package for when you need something done but you want it to cancel as soon as something newer comes up. Given this typically involves running a command to display to a view, I've added a viewBufferManagerMap struct to the Gui struct which allows you to define these tasks on a per-view basis. viewBufferManagers can run files and directly write the output to their view, meaning we no longer need to use so much memory. In the tasks package there is a helper method called NewCmdTask which takes a command, an initial amount of lines to read, and then runs that command, reads that number of lines, and allows for a readLines channel to tell it to read more lines. We read more lines when we scroll or resize the window. There is an adapter for the tasks package in a file called tasks_adapter which wraps the functions from the tasks package in gui-specific stuff like clearing the main view before starting the next task that wants to write to the main view. I've removed some small features as part of this work, namely the little headers that were at the top of the main view for some situations. For example, we no longer show the upstream of a selected branch. I want to re-introduce this in the future, but I didn't want to make this tasks system too complicated, and in order to facilitate a header section in the main view we'd need to have a task that gets the upstream for the current branch, writes it to the header, then tells another task to write the branch log to the main view, but without clearing inbetween. So it would get messy. I'm thinking instead of having a separate 'header' view atop the main view to render that kind of thing (which can happen in another PR) I've also simplified the 'git show' to just call 'git show' and not do anything fancy when it comes to merge commits. I considered using this tasks approach whenever we write to a view. The only thing is that the renderString method currently resets the origin of a view and I don't want to lose that. So I've left some in there that I consider harmless, but we should probably be just using tasks now for all rendering, even if it's just strings we can instantly make.
2020-01-11 05:54:59 +02:00
Updater *updates.Updater
statusManager *statusManager
credentials credentials
waitForIntro sync.WaitGroup
fileWatcher *fileWatcher
viewBufferManagerMap map[string]*tasks.ViewBufferManager
stopChan chan struct{}
// when lazygit is opened outside a git directory we want to open to the most
// recent repo with the recent repos popup showing
showRecentRepos bool
2021-04-10 03:40:42 +02:00
Mutexes guiMutexes
2020-11-28 11:01:45 +02:00
// findSuggestions will take a string that the user has typed into a prompt
// and return a slice of suggestions which match that string.
findSuggestions func(string) []*types.Suggestion
// when you enter into a submodule we'll append the superproject's path to this array
// so that you can return to the superproject
RepoPathStack []string
2021-04-03 06:56:11 +02:00
// this tells us whether our views have been initially set up
ViewsSetup bool
2021-04-04 15:51:59 +02:00
Views Views
// if we've suspended the gui (e.g. because we've switched to a subprocess)
// we typically want to pause some things that are running like background
// file refreshes
PauseBackgroundThreads bool
2021-04-10 05:08:51 +02:00
// Log of the commands that get run, to be displayed to the user.
CmdLog []string
OnRunCommand func(entry oscommands.CmdLogEntry)
// the extras window contains things like the command log
ShowExtrasWindow bool
suggestionsAsyncHandler *tasks.AsyncHandler
}
type listPanelState struct {
2020-08-20 00:53:10 +02:00
SelectedLineIdx int
2020-08-19 13:51:50 +02:00
}
func (h *listPanelState) SetSelectedLineIdx(value int) {
2020-08-20 00:53:10 +02:00
h.SelectedLineIdx = value
}
func (h *listPanelState) GetSelectedLineIdx() int {
2020-08-20 00:53:10 +02:00
return h.SelectedLineIdx
}
2018-12-07 09:52:31 +02:00
// for now the staging panel state, unlike the other panel states, is going to be
// non-mutative, so that we don't accidentally end up
// with mismatches of data. We might change this in the future
2021-04-18 08:30:34 +02:00
type LblPanelState struct {
*lbl.State
SecondaryFocused bool // this is for if we show the left or right panel
}
2021-04-18 10:07:10 +02:00
type MergingPanelState struct {
*mergeconflicts.State
2021-11-02 11:35:53 +02:00
// UserVerticalScrolling tells us if the user has started scrolling through the file themselves
// in which case we won't auto-scroll to a conflict.
2021-11-02 11:35:53 +02:00
UserVerticalScrolling bool
2018-12-08 07:54:54 +02:00
}
type filePanelState struct {
listPanelState
}
2019-11-13 14:18:31 +02:00
// TODO: consider splitting this out into the window and the branches view
type branchPanelState struct {
listPanelState
2019-11-13 14:18:31 +02:00
}
type remotePanelState struct {
listPanelState
}
2019-11-16 08:35:59 +02:00
type remoteBranchesState struct {
listPanelState
2019-11-16 08:35:59 +02:00
}
2019-11-18 00:38:36 +02:00
type tagsPanelState struct {
listPanelState
2019-11-18 00:38:36 +02:00
}
type commitPanelState struct {
listPanelState
2020-08-19 13:51:50 +02:00
LimitCommits bool
}
2020-01-09 12:34:17 +02:00
type reflogCommitPanelState struct {
listPanelState
2020-01-09 12:34:17 +02:00
}
2020-08-22 00:49:02 +02:00
type subCommitPanelState struct {
listPanelState
// e.g. name of branch whose commits we're looking at
refName string
}
type stashPanelState struct {
listPanelState
}
type menuPanelState struct {
listPanelState
2020-08-23 01:42:30 +02:00
OnPress func() error
}
type commitFilesPanelState struct {
listPanelState
// this is the SHA of the commit or the stash index of the stash.
// Not sure if ref is actually the right word here
refName string
canRebase bool
}
2020-09-30 00:27:23 +02:00
type submodulePanelState struct {
listPanelState
}
type suggestionsPanelState struct {
listPanelState
}
type panelStates struct {
2019-11-16 08:35:59 +02:00
Files *filePanelState
Branches *branchPanelState
Remotes *remotePanelState
RemoteBranches *remoteBranchesState
2019-11-18 00:38:36 +02:00
Tags *tagsPanelState
2019-11-16 08:35:59 +02:00
Commits *commitPanelState
2020-01-09 12:34:17 +02:00
ReflogCommits *reflogCommitPanelState
2020-08-22 00:49:02 +02:00
SubCommits *subCommitPanelState
2019-11-16 08:35:59 +02:00
Stash *stashPanelState
Menu *menuPanelState
2021-04-18 08:30:34 +02:00
LineByLine *LblPanelState
2021-04-18 10:07:10 +02:00
Merging *MergingPanelState
2019-11-16 08:35:59 +02:00
CommitFiles *commitFilesPanelState
2020-09-30 00:27:23 +02:00
Submodules *submodulePanelState
Suggestions *suggestionsPanelState
}
2021-04-04 15:51:59 +02:00
type Views struct {
Status *gocui.View
Files *gocui.View
Branches *gocui.View
Commits *gocui.View
Stash *gocui.View
Main *gocui.View
Secondary *gocui.View
Options *gocui.View
Confirmation *gocui.View
Menu *gocui.View
Credentials *gocui.View
CommitMessage *gocui.View
CommitFiles *gocui.View
Information *gocui.View
AppStatus *gocui.View
Search *gocui.View
SearchPrefix *gocui.View
Limit *gocui.View
Suggestions *gocui.View
2021-04-11 03:43:07 +02:00
Extras *gocui.View
2021-04-04 15:51:59 +02:00
}
type searchingState struct {
view *gocui.View
isSearching bool
searchString string
}
// startup stages so we don't need to load everything at once
type StartupStage int
const (
INITIAL StartupStage = iota
COMPLETE
)
2020-08-22 03:05:37 +02:00
type Modes struct {
2021-04-03 02:32:14 +02:00
Filtering filtering.Filtering
2021-06-05 07:08:36 +02:00
CherryPicking cherrypicking.CherryPicking
Diffing diffing.Diffing
2020-08-22 03:05:37 +02:00
}
2021-04-10 03:40:42 +02:00
type guiMutexes struct {
RefreshingFilesMutex sync.Mutex
RefreshingStatusMutex sync.Mutex
FetchMutex sync.Mutex
BranchCommitsMutex sync.Mutex
LineByLinePanelMutex sync.Mutex
2021-04-10 03:40:42 +02:00
SubprocessMutex sync.Mutex
}
2018-08-13 13:16:21 +02:00
type guiState struct {
2021-03-31 15:24:41 +02:00
// the file panels (files and commit files) can render as a tree, so we have
// managers for them which handle rendering a flat list of files in tree form
FileManager *filetree.FileManager
CommitFileManager *filetree.CommitFileManager
Submodules []*models.SubmoduleConfig
Branches []*models.Branch
Commits []*models.Commit
StashEntries []*models.StashEntry
// Suggestions will sometimes appear when typing into a prompt
Suggestions []*types.Suggestion
// FilteredReflogCommits are the ones that appear in the reflog panel.
// when in filtering mode we only include the ones that match the given path
2020-09-29 10:36:54 +02:00
FilteredReflogCommits []*models.Commit
// ReflogCommits are the ones used by the branches panel to obtain recency values
// if we're not in filtering mode, CommitFiles and FilteredReflogCommits will be
// one and the same
ReflogCommits []*models.Commit
SubCommits []*models.Commit
Remotes []*models.Remote
RemoteBranches []*models.RemoteBranch
Tags []*models.Tag
MenuItems []*menuItem
Updating bool
Panels *panelStates
SplitMainPanel bool
2021-04-04 15:51:59 +02:00
MainContext ContextKey // used to keep the main and secondary views' contexts in sync
RetainOriginalDir bool
IsRefreshingFiles bool
Searching searchingState
2021-11-02 12:16:00 +02:00
// if this is true, we'll load our commits using `git log --all`
ShowWholeGitGraph bool
ScreenMode WindowMaximisation
Ptmx *os.File
PrevMainWidth int
PrevMainHeight int
OldInformation string
StartupStage StartupStage // Allows us to not load everything at once
2020-08-22 03:05:37 +02:00
Modes Modes
2020-08-16 02:05:45 +02:00
ContextManager ContextManager
2021-04-03 06:56:11 +02:00
Contexts ContextTree
ViewContextMap map[string]Context
ViewTabContextMap map[string][]tabContext
2020-08-16 05:58:29 +02:00
2020-08-23 01:27:42 +02:00
// WindowViewNameMap is a mapping of windows to the current view of that window.
// Some views move between windows for example the commitFiles view and when cycling through
// side windows we need to know which view to give focus to for a given window
2020-08-16 05:58:29 +02:00
WindowViewNameMap map[string]string
2021-04-03 06:56:11 +02:00
// tells us whether we've set up our views for the current repo. We'll need to
// do this whenever we switch back and forth between repos to get the views
// back in sync with the repo state
ViewsSetup bool
// flag as to whether or not the diff view should ignore whitespace
IgnoreWhitespaceInDiffView bool
// for displaying suggestions while typing in a file name
FilesTrie *patricia.Trie
2018-08-13 12:26:02 +02:00
}
// reuseState determines if we pull the repo state from our repo state map or
// just re-initialize it. For now we're only re-using state when we're going
// in and out of submodules, for the sake of having the cursor back on the submodule
// when we return.
//
// I tried out always reverting to the repo's original state but found that in fact
// it gets a bit confusing to land back in the status panel when visiting a repo
// you've already switched from. There's no doubt some easy way to make the UX
// optimal for all cases but I'm too lazy to think about what that is right now
func (gui *Gui) resetState(filterPath string, reuseState bool) {
currentDir, err := os.Getwd()
if reuseState {
if err == nil {
if state := gui.RepoStateMap[Repo(currentDir)]; state != nil {
gui.State = state
gui.State.ViewsSetup = false
return
}
} else {
gui.Log.Error(err)
}
}
showTree := gui.Config.GetUserConfig().Gui.ShowFileTree
2020-08-22 03:05:37 +02:00
contexts := gui.contextTree()
screenMode := SCREEN_NORMAL
initialContext := contexts.Files
if filterPath != "" {
screenMode = SCREEN_HALF
initialContext = contexts.BranchCommits
}
gui.State = &guiState{
2021-04-01 16:36:30 +02:00
FileManager: filetree.NewFileManager(make([]*models.File, 0), gui.Log, showTree),
CommitFileManager: filetree.NewCommitFileManager(make([]*models.CommitFile, 0), gui.Log, showTree),
Commits: make([]*models.Commit, 0),
FilteredReflogCommits: make([]*models.Commit, 0),
ReflogCommits: make([]*models.Commit, 0),
StashEntries: make([]*models.StashEntry, 0),
Panels: &panelStates{
2020-08-22 00:49:02 +02:00
// TODO: work out why some of these are -1 and some are 0. Last time I checked there was a good reason but I'm less certain now
2020-08-20 00:53:10 +02:00
Files: &filePanelState{listPanelState{SelectedLineIdx: -1}},
2020-09-30 00:27:23 +02:00
Submodules: &submodulePanelState{listPanelState{SelectedLineIdx: -1}},
2020-08-20 00:53:10 +02:00
Branches: &branchPanelState{listPanelState{SelectedLineIdx: 0}},
Remotes: &remotePanelState{listPanelState{SelectedLineIdx: 0}},
RemoteBranches: &remoteBranchesState{listPanelState{SelectedLineIdx: -1}},
Tags: &tagsPanelState{listPanelState{SelectedLineIdx: -1}},
2021-11-02 07:39:15 +02:00
Commits: &commitPanelState{listPanelState: listPanelState{SelectedLineIdx: 0}, LimitCommits: true},
2020-08-22 00:49:02 +02:00
ReflogCommits: &reflogCommitPanelState{listPanelState{SelectedLineIdx: 0}},
SubCommits: &subCommitPanelState{listPanelState: listPanelState{SelectedLineIdx: 0}, refName: ""},
CommitFiles: &commitFilesPanelState{listPanelState: listPanelState{SelectedLineIdx: -1}, refName: ""},
2020-08-20 00:53:10 +02:00
Stash: &stashPanelState{listPanelState{SelectedLineIdx: -1}},
Menu: &menuPanelState{listPanelState: listPanelState{SelectedLineIdx: 0}, OnPress: nil},
Suggestions: &suggestionsPanelState{listPanelState: listPanelState{SelectedLineIdx: 0}},
2021-04-18 10:07:10 +02:00
Merging: &MergingPanelState{
2021-11-02 11:35:53 +02:00
State: mergeconflicts.NewState(),
UserVerticalScrolling: false,
2018-12-08 07:54:54 +02:00
},
},
Ptmx: nil,
Modes: Modes{
2021-06-05 07:08:36 +02:00
Filtering: filtering.New(filterPath),
CherryPicking: cherrypicking.New(),
Diffing: diffing.New(),
},
2021-04-03 06:56:11 +02:00
ViewContextMap: contexts.initialViewContextMap(),
ViewTabContextMap: contexts.initialViewTabContextMap(),
ScreenMode: screenMode,
2021-04-03 06:56:11 +02:00
// TODO: put contexts in the context manager
ContextManager: NewContextManager(initialContext),
2021-04-03 06:56:11 +02:00
Contexts: contexts,
FilesTrie: patricia.NewTrie(),
2018-08-13 12:26:02 +02:00
}
2021-04-03 02:32:14 +02:00
2021-04-03 06:56:11 +02:00
gui.RepoStateMap[Repo(currentDir)] = gui.State
}
2018-08-13 12:26:02 +02:00
// for now the split view will always be on
// NewGui builds a new gui handler
2020-10-04 02:00:48 +02:00
func NewGui(log *logrus.Entry, gitCommand *commands.GitCommand, oSCommand *oscommands.OSCommand, tr *i18n.TranslationSet, config config.AppConfigurer, updater *updates.Updater, filterPath string, showRecentRepos bool) (*Gui, error) {
gui := &Gui{
Log: log,
GitCommand: gitCommand,
OSCommand: oSCommand,
Config: config,
Tr: tr,
Updater: updater,
statusManager: &statusManager{},
viewBufferManagerMap: map[string]*tasks.ViewBufferManager{},
showRecentRepos: showRecentRepos,
RepoPathStack: []string{},
RepoStateMap: map[Repo]*guiState{},
CmdLog: []string{},
2021-10-23 03:45:02 +02:00
ShowExtrasWindow: config.ShowCommandLogOnStartup(),
suggestionsAsyncHandler: tasks.NewAsyncHandler(),
}
gui.resetState(filterPath, false)
gui.watchFilesForChanges()
2021-04-11 11:17:18 +02:00
onRunCommand := gui.GetOnRunCommand()
oSCommand.SetOnRunCommand(onRunCommand)
gui.OnRunCommand = onRunCommand
authors.SetCustomAuthors(gui.Config.GetUserConfig().Gui.AuthorColors)
2021-04-11 11:17:18 +02:00
return gui, nil
}
2021-04-11 07:01:49 +02:00
var RuneReplacements = map[rune]string{
// for the commit graph
2021-11-02 23:23:47 +02:00
graph.MergeSymbol: "M",
graph.CommitSymbol: "o",
}
2018-08-13 12:26:02 +02:00
// Run setup the gui with keybindings and start the mainloop
2018-08-13 13:16:21 +02:00
func (gui *Gui) Run() error {
recordEvents := recordingEvents()
2021-04-05 00:52:09 +02:00
playMode := gocui.NORMAL
if recordEvents {
playMode = gocui.RECORDING
} else if replaying() {
playMode = gocui.REPLAYING
}
g, err := gocui.NewGui(gocui.OutputTrue, OverlappingEdges, playMode, headless(), RuneReplacements)
if err != nil {
2018-08-13 13:16:21 +02:00
return err
}
2021-04-10 03:40:42 +02:00
2021-03-20 03:07:11 +02:00
gui.g = g // TODO: always use gui.g rather than passing g around everywhere
defer g.Close()
2021-04-05 00:52:09 +02:00
if replaying() {
g.RecordingConfig = gocui.RecordingConfig{
Speed: getRecordingSpeed(),
2021-04-05 02:20:02 +02:00
Leeway: 100,
2021-04-05 00:52:09 +02:00
}
g.Recording, err = gui.loadRecording()
if err != nil {
return err
}
go utils.Safe(func() {
2021-04-05 13:56:17 +02:00
time.Sleep(time.Second * 40)
log.Fatal("40 seconds is up, lazygit recording took too long to complete")
2021-04-05 00:52:09 +02:00
})
}
g.OnSearchEscape = gui.onSearchEscape
if err := gui.Config.ReloadUserConfig(); err != nil {
return nil
}
2020-10-03 06:54:55 +02:00
userConfig := gui.Config.GetUserConfig()
g.SearchEscapeKey = gui.getKey(userConfig.Keybinding.Universal.Return)
g.NextSearchMatchKey = gui.getKey(userConfig.Keybinding.Universal.NextMatch)
g.PrevSearchMatchKey = gui.getKey(userConfig.Keybinding.Universal.PrevMatch)
2021-06-14 10:17:08 +02:00
g.ShowListFooter = userConfig.Gui.ShowListFooter
2021-06-10 10:26:29 +02:00
2020-10-03 06:54:55 +02:00
if userConfig.Gui.MouseEvents {
g.Mouse = true
}
2019-02-25 13:11:35 +02:00
if err := gui.setColorScheme(); err != nil {
2018-08-18 05:53:58 +02:00
return err
}
2018-08-11 07:09:37 +02:00
2019-11-10 13:07:45 +02:00
gui.waitForIntro.Add(1)
2020-10-03 06:54:55 +02:00
if gui.Config.GetUserConfig().Git.AutoFetch {
2020-10-07 12:19:38 +02:00
go utils.Safe(gui.startBackgroundFetch)
2019-07-19 13:56:53 +02:00
}
2019-11-10 13:07:45 +02:00
2021-04-03 12:56:42 +02:00
gui.goEvery(time.Second*time.Duration(userConfig.Refresher.RefreshInterval), gui.stopChan, gui.refreshFilesAndSubmodules)
g.SetManager(gocui.ManagerFunc(gui.layout), gocui.ManagerFunc(gui.getFocusLayout()))
2018-05-19 09:04:33 +02:00
gui.Log.Info("starting main loop")
2019-11-10 13:07:45 +02:00
2018-08-07 10:05:43 +02:00
err = g.MainLoop()
2018-08-13 13:16:21 +02:00
return err
2018-08-13 12:26:02 +02:00
}
// RunAndHandleError
func (gui *Gui) RunAndHandleError() error {
gui.stopChan = make(chan struct{})
return utils.SafeWithError(func() error {
2018-08-13 12:26:02 +02:00
if err := gui.Run(); err != nil {
allow fast flicking through any list panel Up till now our approach to rendering things like file diffs, branch logs, and commit patches, has been to run a command on the command line, wait for it to complete, take its output as a string, and then write that string to the main view (or secondary view e.g. when showing both staged and unstaged changes of a file). This has caused various issues. For once, if you are flicking through a list of files and an untracked file is particularly large, not only will this require lazygit to load that whole file into memory (or more accurately it's equally large diff), it also will slow down the UI thread while loading that file, and if the user continued down the list, the original command might eventually resolve and replace whatever the diff is for the newly selected file. Following what we've done in lazydocker, I've added a tasks package for when you need something done but you want it to cancel as soon as something newer comes up. Given this typically involves running a command to display to a view, I've added a viewBufferManagerMap struct to the Gui struct which allows you to define these tasks on a per-view basis. viewBufferManagers can run files and directly write the output to their view, meaning we no longer need to use so much memory. In the tasks package there is a helper method called NewCmdTask which takes a command, an initial amount of lines to read, and then runs that command, reads that number of lines, and allows for a readLines channel to tell it to read more lines. We read more lines when we scroll or resize the window. There is an adapter for the tasks package in a file called tasks_adapter which wraps the functions from the tasks package in gui-specific stuff like clearing the main view before starting the next task that wants to write to the main view. I've removed some small features as part of this work, namely the little headers that were at the top of the main view for some situations. For example, we no longer show the upstream of a selected branch. I want to re-introduce this in the future, but I didn't want to make this tasks system too complicated, and in order to facilitate a header section in the main view we'd need to have a task that gets the upstream for the current branch, writes it to the header, then tells another task to write the branch log to the main view, but without clearing inbetween. So it would get messy. I'm thinking instead of having a separate 'header' view atop the main view to render that kind of thing (which can happen in another PR) I've also simplified the 'git show' to just call 'git show' and not do anything fancy when it comes to merge commits. I considered using this tasks approach whenever we write to a view. The only thing is that the renderString method currently resets the origin of a view and I don't want to lose that. So I've left some in there that I consider harmless, but we should probably be just using tasks now for all rendering, even if it's just strings we can instantly make.
2020-01-11 05:54:59 +02:00
for _, manager := range gui.viewBufferManagerMap {
manager.Close()
}
if !gui.fileWatcher.Disabled {
gui.fileWatcher.Watcher.Close()
}
close(gui.stopChan)
2020-08-23 12:20:05 +02:00
switch err {
case gocui.ErrQuit:
if !gui.State.RetainOriginalDir {
if err := gui.recordCurrentDirectory(); err != nil {
return err
}
}
2021-04-05 00:52:09 +02:00
if err := gui.saveRecording(gui.g.Recording); err != nil {
return err
}
2020-08-23 12:20:05 +02:00
return nil
2020-08-23 12:20:05 +02:00
default:
return err
2018-08-13 12:26:02 +02:00
}
}
return nil
})
2018-05-19 09:04:33 +02:00
}
2021-04-10 03:40:42 +02:00
// returns whether command exited without error or not
func (gui *Gui) runSubprocessWithSuspenseAndRefresh(subprocess *exec.Cmd) error {
_, err := gui.runSubprocessWithSuspense(subprocess)
if err != nil {
return err
}
if err := gui.refreshSidePanels(refreshOptions{mode: ASYNC}); err != nil {
return err
}
return nil
}
// returns whether command exited without error or not
func (gui *Gui) runSubprocessWithSuspense(subprocess *exec.Cmd) (bool, error) {
gui.Mutexes.SubprocessMutex.Lock()
defer gui.Mutexes.SubprocessMutex.Unlock()
2021-04-05 04:18:21 +02:00
if replaying() {
// we do not yet support running subprocesses within integration tests. So if
// we're replaying an integration test and we're inside this method, something
// has gone wrong, so we should fail
log.Fatal("opening subprocesses not yet supported in integration tests. Chances are that this test is running too fast and a subprocess is accidentally opened")
}
2021-04-10 03:40:42 +02:00
if err := gui.g.Suspend(); err != nil {
return false, gui.surfaceError(err)
}
gui.PauseBackgroundThreads = true
cmdErr := gui.runSubprocess(subprocess)
2021-04-10 03:40:42 +02:00
if err := gui.g.Resume(); err != nil {
return false, err
}
gui.PauseBackgroundThreads = false
2021-04-10 03:40:42 +02:00
return cmdErr == nil, gui.surfaceError(cmdErr)
}
func (gui *Gui) runSubprocess(subprocess *exec.Cmd) error {
subprocess.Stdout = os.Stdout
subprocess.Stderr = os.Stdout
subprocess.Stdin = os.Stdin
2019-03-12 12:43:56 +02:00
fmt.Fprintf(os.Stdout, "\n%s\n\n", style.FgBlue.Sprint("+ "+strings.Join(subprocess.Args, " ")))
if err := subprocess.Run(); err != nil {
2019-03-12 12:43:56 +02:00
// not handling the error explicitly because usually we're going to see it
// in the output anyway
gui.Log.Error(err)
}
subprocess.Stdout = ioutil.Discard
subprocess.Stderr = ioutil.Discard
subprocess.Stdin = nil
fmt.Fprintf(os.Stdout, "\n%s", style.FgGreen.Sprint(gui.Tr.PressEnterToReturn))
fmt.Scanln() // wait for enter press
return nil
2019-03-12 12:43:56 +02:00
}
2020-03-29 01:31:34 +02:00
func (gui *Gui) loadNewRepo() error {
if err := gui.updateRecentRepoList(); err != nil {
return err
}
2020-03-29 01:31:34 +02:00
if err := gui.refreshSidePanels(refreshOptions{mode: ASYNC}); err != nil {
return err
}
return nil
2019-02-25 13:11:35 +02:00
}
2020-03-29 01:31:34 +02:00
func (gui *Gui) showInitialPopups(tasks []func(chan struct{}) error) {
gui.waitForIntro.Add(len(tasks))
done := make(chan struct{})
2020-10-07 12:19:38 +02:00
go utils.Safe(func() {
2020-03-29 01:31:34 +02:00
for _, task := range tasks {
2020-11-16 11:38:26 +02:00
task := task
2020-10-07 12:19:38 +02:00
go utils.Safe(func() {
2020-03-29 01:31:34 +02:00
if err := task(done); err != nil {
_ = gui.surfaceError(err)
}
2020-10-07 12:19:38 +02:00
})
2020-03-29 01:31:34 +02:00
<-done
gui.waitForIntro.Done()
}
2020-10-07 12:19:38 +02:00
})
}
2019-11-10 07:20:35 +02:00
2020-08-15 00:10:56 +02:00
func (gui *Gui) showIntroPopupMessage(done chan struct{}) error {
2020-08-15 08:36:39 +02:00
onConfirm := func() error {
2020-03-29 01:31:34 +02:00
done <- struct{}{}
gui.Config.GetAppState().StartupPopupVersion = StartupPopupVersion
2021-10-16 03:07:24 +02:00
return gui.Config.SaveAppState()
2019-11-10 07:20:35 +02:00
}
2020-08-15 08:38:16 +02:00
return gui.ask(askOpts{
title: "",
2020-10-04 02:00:48 +02:00
prompt: gui.Tr.IntroPopupMessage,
handleConfirm: onConfirm,
handleClose: onConfirm,
2020-08-15 08:36:39 +02:00
})
2019-11-10 07:20:35 +02:00
}
2020-03-29 01:31:34 +02:00
func (gui *Gui) goEvery(interval time.Duration, stop chan struct{}, function func() error) {
2020-10-07 12:19:38 +02:00
go utils.Safe(func() {
2020-03-29 01:31:34 +02:00
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if gui.PauseBackgroundThreads {
continue
}
2020-03-29 01:31:34 +02:00
_ = function()
case <-stop:
return
}
}
2020-10-07 12:19:38 +02:00
})
}
2020-03-29 01:31:34 +02:00
func (gui *Gui) startBackgroundFetch() {
gui.waitForIntro.Wait()
isNew := gui.Config.GetIsNewRepo()
2021-01-05 19:38:49 +02:00
userConfig := gui.Config.GetUserConfig()
2020-03-29 01:31:34 +02:00
if !isNew {
2021-01-05 19:38:49 +02:00
time.After(time.Duration(userConfig.Refresher.FetchInterval) * time.Second)
2020-03-29 01:31:34 +02:00
}
2021-04-10 09:31:23 +02:00
err := gui.fetch(false, "")
2020-03-29 01:31:34 +02:00
if err != nil && strings.Contains(err.Error(), "exit status 128") && isNew {
2020-08-15 08:38:16 +02:00
_ = gui.ask(askOpts{
2020-10-04 02:00:48 +02:00
title: gui.Tr.NoAutomaticGitFetchTitle,
prompt: gui.Tr.NoAutomaticGitFetchBody,
2020-08-15 08:36:39 +02:00
})
2020-03-29 01:31:34 +02:00
} else {
2021-04-03 12:56:42 +02:00
gui.goEvery(time.Second*time.Duration(userConfig.Refresher.FetchInterval), gui.stopChan, func() error {
2021-04-10 09:31:23 +02:00
err := gui.fetch(false, "")
gui.render()
2020-03-29 01:31:34 +02:00
return err
})
}
}
2020-03-29 01:11:15 +02:00
2020-03-29 01:31:34 +02:00
// setColorScheme sets the color scheme for the app based on the user config
func (gui *Gui) setColorScheme() error {
userConfig := gui.Config.GetUserConfig()
2020-10-03 06:54:55 +02:00
theme.UpdateTheme(userConfig.Gui.Theme)
2020-03-29 01:31:34 +02:00
gui.g.FgColor = theme.InactiveBorderColor
gui.g.SelFgColor = theme.ActiveBorderColor
gui.g.FrameColor = theme.InactiveBorderColor
gui.g.SelFrameColor = theme.ActiveBorderColor
2020-03-29 01:31:34 +02:00
return nil
2020-03-29 01:11:15 +02:00
}