From d1306f194f1ee8fdfb5721a81c036966bb88d42a Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 17:54:14 +0530 Subject: [PATCH 01/12] Making r (Renderer) Global RENDERER --- app.go | 4 ++-- main.go | 9 +++++---- progressBar.go | 10 +++++----- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/app.go b/app.go index 13c2383..9ce62a2 100644 --- a/app.go +++ b/app.go @@ -16,9 +16,9 @@ type Application struct { Pages *tview.Pages } -func newApplication(r *Renderer) *Application { +func newApplication() *Application { - var pBar *progressBar = newProgressBar(r) + var pBar *progressBar = newProgressBar() expandedView := tview.NewTable() Navbar := tview.NewTable() searchBar := tview.NewInputField() diff --git a/main.go b/main.go index 0dc677e..69eb553 100644 --- a/main.go +++ b/main.go @@ -18,6 +18,7 @@ var ( CONN *mpd.Client UI *Application NOTIFICATION_SERVER *NotificationServer + RENDERER *Renderer Volume int64 Random bool Repeat bool @@ -36,15 +37,15 @@ func main() { } defer CONN.Close() cache.SetCacheDir(viper.GetString("CACHE_DIR")) - r := newRenderer() + RENDERER = newRenderer() c, _ := CONN.CurrentSong() if len(c) != 0 { - r.Start(c["file"]) + RENDERER.Start(c["file"]) } else { - r.Start("stop") + RENDERER.Start("stop") } - UI = newApplication(r) + UI = newApplication() fileMap, err := CONN.GetFiles() dirTree := generateDirectoryTree(fileMap) diff --git a/progressBar.go b/progressBar.go index 677a9ac..b321d23 100644 --- a/progressBar.go +++ b/progressBar.go @@ -26,7 +26,7 @@ type progressBar struct { // This Function returns a progressBar with a table of two rows // the First row will contain information about the current Song // and the Second one will contain the progressBar -func newProgressBar(r *Renderer) *progressBar { +func newProgressBar() *progressBar { p := progressBar{} a := tview.NewTable(). @@ -38,7 +38,7 @@ func newProgressBar(r *Renderer) *progressBar { a.SetBorder(true) a.SetDrawFunc(func(s tcell.Screen, x, y, width, height int) (int, int, int, int) { - p.updateTitle(r) + p.updateTitle() p.updateProgress() return p.t.GetInnerRect() }) @@ -49,16 +49,16 @@ func newProgressBar(r *Renderer) *progressBar { return &p } -func (s *progressBar) updateTitle(r *Renderer) { +func (s *progressBar) updateTitle() { _currentAttributes, err := CONN.CurrentSong() if err == nil { song := "[green::bi]" + _currentAttributes["Title"] + "[-:-:-] - " + "[blue::b]" + _currentAttributes["Artist"] + "\n" s.t.GetCell(0, 0).Text = song if len(_currentAttributes) == 0 && CurrentSong != "" { CurrentSong = "" - r.Send("stop") + RENDERER.Send("stop") } else if song != CurrentSong && len(_currentAttributes) != 0 { - r.Send(_currentAttributes["file"]) + RENDERER.Send(_currentAttributes["file"]) CurrentSong = song } } From a54bfc49486755a93de5b44df1767fd9a60cd65b Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 19:56:57 +0530 Subject: [PATCH 02/12] moving client.go filebrowser.go to the new client package --- client.go => client/client.go | 65 ++++++++++++++++++++------------- client/fileBrowser.go | 69 +++++++++++++++++++++++++++++++++++ fileBrowser.go | 69 ----------------------------------- main.go | 43 ++++++++++++---------- 4 files changed, 132 insertions(+), 114 deletions(-) rename client.go => client/client.go (83%) create mode 100644 client/fileBrowser.go delete mode 100644 fileBrowser.go diff --git a/client.go b/client/client.go similarity index 83% rename from client.go rename to client/client.go index da8c3fe..b677c79 100644 --- a/client.go +++ b/client/client.go @@ -1,8 +1,10 @@ -package main +package client import ( "errors" "fmt" + "github.com/fhs/gompd/mpd" + "strings" "github.com/aditya-K2/gomp/utils" @@ -10,10 +12,23 @@ import ( ) var ( + CONN *mpd.Client + ArtistTree map[string]map[string]map[string]string + NotificationServer interface { + Send(string) + } WHITE_AND_BOLD string = "[#ffffff::b]" ) -func togglePlayBack() error { +func SetConnection(c *mpd.Client) { + CONN = c +} + +func SetNotificationServer(n interface{ Send(string) }) { + NotificationServer = n +} + +func TogglePlayBack() error { status, err := CONN.Status() if status["state"] == "play" && err == nil { CONN.Pause(true) @@ -47,24 +62,24 @@ func UpdatePlaylist(inputTable *tview.Table) { func GenerateContentSlice(selectedSuggestion string) ([]interface{}, error) { var ContentSlice []interface{} if strings.TrimRight(selectedSuggestion, " ") == "" { - NOTIFICATION_SERVER.Send("Empty Search!") + NotificationServer.Send("Empty Search!") return nil, errors.New("empty Search String Provided") } - if _, ok := ARTIST_TREE[selectedSuggestion]; ok { + if _, ok := ArtistTree[selectedSuggestion]; ok { ContentSlice = append(ContentSlice, WHITE_AND_BOLD+"Artists :") ContentSlice = append(ContentSlice, selectedSuggestion) ContentSlice = append(ContentSlice, WHITE_AND_BOLD+"Artist Albums :") - for albumName := range ARTIST_TREE[selectedSuggestion] { + for albumName := range ArtistTree[selectedSuggestion] { ContentSlice = append(ContentSlice, [2]string{albumName, selectedSuggestion}) } ContentSlice = append(ContentSlice, WHITE_AND_BOLD+"Artist Tracks :") - for albumName, trackList := range ARTIST_TREE[selectedSuggestion] { + for albumName, trackList := range ArtistTree[selectedSuggestion] { for track := range trackList { ContentSlice = append(ContentSlice, [3]string{track, selectedSuggestion, albumName}) } } } - if aMap := QueryArtistTreeForAlbums(ARTIST_TREE, selectedSuggestion); len(aMap) != 0 { + if aMap := QueryArtistTreeForAlbums(ArtistTree, selectedSuggestion); len(aMap) != 0 { ContentSlice = append(ContentSlice, WHITE_AND_BOLD+"Albums :") for mSlice := range aMap { ContentSlice = append(ContentSlice, mSlice) @@ -76,7 +91,7 @@ func GenerateContentSlice(selectedSuggestion string) ([]interface{}, error) { } } } - if tMap := QueryArtistTreeForTracks(ARTIST_TREE, selectedSuggestion); len(tMap) != 0 { + if tMap := QueryArtistTreeForTracks(ArtistTree, selectedSuggestion); len(tMap) != 0 { ContentSlice = append(ContentSlice, WHITE_AND_BOLD+"Tracks :") for mSlice := range tMap { ContentSlice = append(ContentSlice, mSlice) @@ -122,8 +137,8 @@ func UpdateSearchView(inputTable *tview.Table, c []interface{}) { func Update(f []FileNode, inputTable *tview.Table) { inputTable.Clear() for i, j := range f { - if len(j.children) == 0 { - _songAttributes, err := CONN.ListAllInfo(j.absolutePath) + if len(j.Children) == 0 { + _songAttributes, err := CONN.ListAllInfo(j.AbsolutePath) if err == nil && _songAttributes[0]["Title"] != "" { _, _, w, _ := inputTable.GetInnerRect() inputTable.SetCell(i, 0, @@ -140,19 +155,19 @@ func Update(f []FileNode, inputTable *tview.Table) { } else if _songAttributes[0]["Title"] == "" { inputTable.SetCell(i, 0, - tview.NewTableCell("[blue]"+j.path). + tview.NewTableCell("[blue]"+j.Path). SetAlign(tview.AlignLeft)) } } else { inputTable.SetCell(i, 0, - tview.NewTableCell("[yellow::b]"+j.path). + tview.NewTableCell("[yellow::b]"+j.Path). SetAlign(tview.AlignLeft)) } } } func GenerateArtistTree() (map[string]map[string]map[string]string, error) { - ArtistTree := make(map[string]map[string]map[string]string) + ArtistTree = make(map[string]map[string]map[string]string) AllInfo, err := CONN.ListAllInfo("/") if err == nil { for _, i := range AllInfo { @@ -191,10 +206,10 @@ func AddAlbum(a map[string]map[string]map[string]string, alb string, artist stri for _, v := range a[artist][alb] { err := CONN.Add(v) if err != nil { - NOTIFICATION_SERVER.Send("Could Not Add Song : " + v) + NotificationServer.Send("Could Not Add Song : " + v) } } - NOTIFICATION_SERVER.Send("Album Added : " + alb) + NotificationServer.Send("Album Added : " + alb) } /* @@ -206,11 +221,11 @@ func AddArtist(a map[string]map[string]map[string]string, artist string) { for _, path := range v { err := CONN.Add(path) if err != nil { - NOTIFICATION_SERVER.Send("Could Not Add Song : " + path) + NotificationServer.Send("Could Not Add Song : " + path) } } } - NOTIFICATION_SERVER.Send("Artist Added : " + artist) + NotificationServer.Send("Artist Added : " + artist) } } @@ -222,18 +237,18 @@ func AddTitle(a map[string]map[string]map[string]string, artist, alb, track stri id, err := CONN.AddId(a[artist][alb][track], -1) CONN.PlayId(id) if err != nil { - NOTIFICATION_SERVER.Send("Could Not Add Track : " + track) + NotificationServer.Send("Could Not Add Track : " + track) } } else { err := CONN.Add(a[artist][alb][track]) if err != nil { - NOTIFICATION_SERVER.Send("Could Not Add Track : " + track) + NotificationServer.Send("Could Not Add Track : " + track) } } - NOTIFICATION_SERVER.Send("Track Added : " + track) + NotificationServer.Send("Track Added : " + track) } -/* Querys the Artist Tree for a track and returns a TrackMap (i.e [3]string{artist, album, track} -> path) which will help us +/* Querys the Artist Tree for a track and returns a TrackMap (i.e [3]string{artist, album, track} -> Path) which will help us to add tracks to the playlist */ func QueryArtistTreeForTracks(a map[string]map[string]map[string]string, track string) map[[3]string]string { TrackMap := make(map[[3]string]string) @@ -249,7 +264,7 @@ func QueryArtistTreeForTracks(a map[string]map[string]map[string]string, track s return TrackMap } -/* Querys the Artist Tree for an album and returns a AlbumMap (i.e [3]string{artist, album } ->[]path of songs in the album) +/* Querys the Artist Tree for an album and returns a AlbumMap (i.e [3]string{artist, album } ->[]Path of songs in the album) which will help us to add all album tracks to the playlist */ func QueryArtistTreeForAlbums(a map[string]map[string]map[string]string, album string) map[[2]string][][2]string { AlbumMap := make(map[[2]string][][2]string) @@ -272,17 +287,17 @@ func AddToPlaylist(a interface{}, addAndPlay bool) { case [3]string: { b := a.([3]string) - AddTitle(ARTIST_TREE, b[1], b[2], b[0], addAndPlay) + AddTitle(ArtistTree, b[1], b[2], b[0], addAndPlay) } case [2]string: { b := a.([2]string) - AddAlbum(ARTIST_TREE, b[0], b[1]) + AddAlbum(ArtistTree, b[0], b[1]) } case string: { b := a.(string) - AddArtist(ARTIST_TREE, b) + AddArtist(ArtistTree, b) } } } diff --git a/client/fileBrowser.go b/client/fileBrowser.go new file mode 100644 index 0000000..71cac40 --- /dev/null +++ b/client/fileBrowser.go @@ -0,0 +1,69 @@ +package client + +import ( + "fmt" + "strings" +) + +type FileNode struct { + Children []FileNode + Path string + Parent *FileNode + AbsolutePath string +} + +func (f *FileNode) AddChildren(path string) { + if f.Path != "" { + f.Children = append(f.Children, FileNode{Children: make([]FileNode, 0), Path: path, Parent: f, AbsolutePath: f.AbsolutePath + "/" + path}) + } else { + f.Children = append(f.Children, FileNode{Children: make([]FileNode, 0), Path: path, Parent: f, AbsolutePath: f.AbsolutePath + path}) + } +} + +func (f *FileNode) AddChildNode(m FileNode) { + m.Parent = f + f.Children = append(f.Children, m) +} + +func GenerateDirectoryTree(path []string) *FileNode { + var head *FileNode = new(FileNode) + var head1 *FileNode = head + for i := range path { + sepPaths := strings.Split(path[i], "/") + for j := range sepPaths { + if len(head.Children) == 0 { + head.AddChildren(sepPaths[j]) + head = &(head.Children[len(head.Children)-1]) + } else { + var headIsChanged = false + for k := range head.Children { + if head.Children[k].Path == sepPaths[j] { + head = &(head.Children[k]) + headIsChanged = true + break + } + } + if !headIsChanged { + head.AddChildren(sepPaths[j]) + head = &(head.Children[len(head.Children)-1]) + } + } + } + head = head1 + } + return head +} + +func (f FileNode) Print(count int) { + if len(f.Children) == 0 { + return + } else { + for i := range f.Children { + for j := 0; j < count; j++ { + fmt.Print("---") + } + fmt.Println(f.Children[i].AbsolutePath) + f.Children[i].Print(count + 1) + } + } +} diff --git a/fileBrowser.go b/fileBrowser.go deleted file mode 100644 index fa1eebc..0000000 --- a/fileBrowser.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -import ( - "fmt" - "strings" -) - -type FileNode struct { - children []FileNode - path string - parent *FileNode - absolutePath string -} - -func (f *FileNode) addChildren(path string) { - if f.path != "" { - f.children = append(f.children, FileNode{children: make([]FileNode, 0), path: path, parent: f, absolutePath: f.absolutePath + "/" + path}) - } else { - f.children = append(f.children, FileNode{children: make([]FileNode, 0), path: path, parent: f, absolutePath: f.absolutePath + path}) - } -} - -func (f *FileNode) addChildNode(m FileNode) { - m.parent = f - f.children = append(f.children, m) -} - -func generateDirectoryTree(path []string) *FileNode { - var head *FileNode = new(FileNode) - var head1 *FileNode = head - for i := range path { - sepPaths := strings.Split(path[i], "/") - for j := range sepPaths { - if len(head.children) == 0 { - head.addChildren(sepPaths[j]) - head = &(head.children[len(head.children)-1]) - } else { - var headIsChanged = false - for k := range head.children { - if head.children[k].path == sepPaths[j] { - head = &(head.children[k]) - headIsChanged = true - break - } - } - if !headIsChanged { - head.addChildren(sepPaths[j]) - head = &(head.children[len(head.children)-1]) - } - } - } - head = head1 - } - return head -} - -func (f FileNode) Print(count int) { - if len(f.children) == 0 { - return - } else { - for i := range f.children { - for j := 0; j < count; j++ { - fmt.Print("---") - } - fmt.Println(f.children[i].absolutePath) - f.children[i].Print(count + 1) - } - } -} diff --git a/main.go b/main.go index 69eb553..7c1b602 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "strconv" "time" + "github.com/aditya-K2/gomp/client" "github.com/aditya-K2/gomp/utils" "github.com/aditya-K2/fuzzy" @@ -48,29 +49,31 @@ func main() { UI = newApplication() fileMap, err := CONN.GetFiles() - dirTree := generateDirectoryTree(fileMap) + dirTree := client.GenerateDirectoryTree(fileMap) - UpdatePlaylist(UI.ExpandedView) + client.SetConnection(CONN) + client.UpdatePlaylist(UI.ExpandedView) _v, _ := CONN.Status() Volume, _ = strconv.ParseInt(_v["volume"], 10, 64) Random, _ = strconv.ParseBool(_v["random"]) Repeat, _ = strconv.ParseBool(_v["repeat"]) - ARTIST_TREE, err = GenerateArtistTree() + ARTIST_TREE, err = client.GenerateArtistTree() ARTIST_TREE_CONTENT := utils.ConvertToArray(ARTIST_TREE) NOTIFICATION_SERVER = NewNotificationServer() NOTIFICATION_SERVER.Start() + client.SetNotificationServer(NOTIFICATION_SERVER) var SEARCH_CONTENT_SLICE []interface{} UI.ExpandedView.SetDrawFunc(func(s tcell.Screen, x, y, width, height int) (int, int, int, int) { if InsidePlaylist { - UpdatePlaylist(UI.ExpandedView) + client.UpdatePlaylist(UI.ExpandedView) } else if InsideSearchView { - UpdateSearchView(UI.ExpandedView, SEARCH_CONTENT_SLICE) + client.UpdateSearchView(UI.ExpandedView, SEARCH_CONTENT_SLICE) } else { - Update(dirTree.children, UI.ExpandedView) + client.Update(dirTree.Children, UI.ExpandedView) } return UI.ExpandedView.GetInnerRect() }) @@ -79,28 +82,28 @@ func main() { "showChildrenContent": func() { r, _ := UI.ExpandedView.GetSelection() if !InsidePlaylist && !InsideSearchView { - if len(dirTree.children[r].children) == 0 { - id, _ := CONN.AddId(dirTree.children[r].absolutePath, -1) + if len(dirTree.Children[r].Children) == 0 { + id, _ := CONN.AddId(dirTree.Children[r].AbsolutePath, -1) CONN.PlayId(id) } else { - Update(dirTree.children[r].children, UI.ExpandedView) - dirTree = &dirTree.children[r] + client.Update(dirTree.Children[r].Children, UI.ExpandedView) + dirTree = &dirTree.Children[r] } } else if InsidePlaylist { CONN.Play(r) } else if InsideSearchView { r, _ := UI.ExpandedView.GetSelection() - AddToPlaylist(SEARCH_CONTENT_SLICE[r], true) + client.AddToPlaylist(SEARCH_CONTENT_SLICE[r], true) } }, "togglePlayBack": func() { - togglePlayBack() + client.TogglePlayBack() }, "showParentContent": func() { if !InsidePlaylist && !InsideSearchView { - if dirTree.parent != nil { - Update(dirTree.parent.children, UI.ExpandedView) - dirTree = dirTree.parent + if dirTree.Parent != nil { + client.Update(dirTree.Parent.Children, UI.ExpandedView) + dirTree = dirTree.Parent } } }, @@ -117,10 +120,10 @@ func main() { "addToPlaylist": func() { if !InsidePlaylist && !InsideSearchView { r, _ := UI.ExpandedView.GetSelection() - CONN.Add(dirTree.children[r].absolutePath) + CONN.Add(dirTree.Children[r].AbsolutePath) } else if InsideSearchView { r, _ := UI.ExpandedView.GetSelection() - AddToPlaylist(SEARCH_CONTENT_SLICE[r], false) + client.AddToPlaylist(SEARCH_CONTENT_SLICE[r], false) } }, "toggleRandom": func() { @@ -155,13 +158,13 @@ func main() { InsidePlaylist = false InsideSearchView = false UI.Navbar.Select(1, 0) - Update(dirTree.children, UI.ExpandedView) + client.Update(dirTree.Children, UI.ExpandedView) }, "navigateToPlaylist": func() { InsidePlaylist = true InsideSearchView = false UI.Navbar.Select(0, 0) - UpdatePlaylist(UI.ExpandedView) + client.UpdatePlaylist(UI.ExpandedView) }, "navigateToMostPlayed": func() { InsideSearchView = false @@ -232,7 +235,7 @@ func main() { InsideSearchView = true InsidePlaylist = false SEARCH_CONTENT_SLICE = nil - SEARCH_CONTENT_SLICE, err = GenerateContentSlice(UI.SearchBar.GetText()) + SEARCH_CONTENT_SLICE, err = client.GenerateContentSlice(UI.SearchBar.GetText()) if err != nil { NOTIFICATION_SERVER.Send("Could Not Retrieve the Results") } else { From 0d9227e019eabb75f727aa0afa2970e93dac7107 Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 20:39:01 +0530 Subject: [PATCH 03/12] moving app.go progressbar.go to the new ui package --- main.go | 7 +++++-- render.go | 5 +++-- app.go => ui/app.go | 8 ++++---- progressBar.go => ui/progressBar.go | 17 +++++++++++++++-- 4 files changed, 27 insertions(+), 10 deletions(-) rename app.go => ui/app.go (94%) rename progressBar.go => ui/progressBar.go (92%) diff --git a/main.go b/main.go index 7c1b602..36869de 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "github.com/aditya-K2/gomp/ui" "strconv" "time" @@ -17,7 +18,7 @@ import ( var ( CONN *mpd.Client - UI *Application + UI *ui.Application NOTIFICATION_SERVER *NotificationServer RENDERER *Renderer Volume int64 @@ -39,6 +40,7 @@ func main() { defer CONN.Close() cache.SetCacheDir(viper.GetString("CACHE_DIR")) RENDERER = newRenderer() + ui.SetRenderer(RENDERER) c, _ := CONN.CurrentSong() if len(c) != 0 { RENDERER.Start(c["file"]) @@ -46,12 +48,13 @@ func main() { RENDERER.Start("stop") } - UI = newApplication() + UI = ui.NewApplication() fileMap, err := CONN.GetFiles() dirTree := client.GenerateDirectoryTree(fileMap) client.SetConnection(CONN) + ui.SetConnection(CONN) client.UpdatePlaylist(UI.ExpandedView) _v, _ := CONN.Status() diff --git a/render.go b/render.go index 3d28ee1..3602a28 100644 --- a/render.go +++ b/render.go @@ -1,6 +1,7 @@ package main import ( + "github.com/aditya-K2/gomp/ui" "image" "os" @@ -51,7 +52,7 @@ func openImage(path string, c chan string) { if path != "stop" { extractedImage := getImagePath(path) img2, _ := GetImg(extractedImage) - im, _ = ueberzug.NewImage(img2, int(float32(IMG_X)*fw)+viper.GetInt("ADDITIONAL_PADDING_X"), int(float32(IMG_Y)*fh)+viper.GetInt("ADDITIONAL_PADDING_Y")) + im, _ = ueberzug.NewImage(img2, int(float32(ui.IMG_X)*fw)+viper.GetInt("ADDITIONAL_PADDING_X"), int(float32(ui.IMG_Y)*fh)+viper.GetInt("ADDITIONAL_PADDING_Y")) } d := <-c if im != nil { @@ -114,7 +115,7 @@ func GetImg(uri string) (image.Image, error) { } fw, fh := utils.GetFontWidth() img = resize.Resize( - uint(float32(IMG_W)*(fw+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_X")))), uint(float32(IMG_H)*(fh+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_Y")))), + uint(float32(ui.IMG_W)*(fw+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_X")))), uint(float32(ui.IMG_H)*(fh+float32(viper.GetFloat64("IMAGE_WIDTH_EXTRA_Y")))), img, resize.Bilinear, ) diff --git a/app.go b/ui/app.go similarity index 94% rename from app.go rename to ui/app.go index 9ce62a2..bb86485 100644 --- a/app.go +++ b/ui/app.go @@ -1,4 +1,4 @@ -package main +package ui import ( "github.com/aditya-K2/tview" @@ -16,7 +16,7 @@ type Application struct { Pages *tview.Pages } -func newApplication() *Application { +func NewApplication() *Application { var pBar *progressBar = newProgressBar() expandedView := tview.NewTable() @@ -60,7 +60,7 @@ func newApplication() *Application { AddItem(searchBar, 3, 1, false). AddItem(sNavExpViewFlex, 0, 1, false) - mainFlex := tview.NewFlex().SetDirection(tview.FlexRow). + lex := tview.NewFlex().SetDirection(tview.FlexRow). AddItem(searchBarFlex, 0, 8, false). AddItem(pBar.t, 5, 1, false) @@ -68,7 +68,7 @@ func newApplication() *Application { expandedView.SetSelectable(true, false) rootPages := tview.NewPages() - rootPages.AddPage("Main", mainFlex, true, true) + rootPages.AddPage("Main", lex, true, true) App := tview.NewApplication() App.SetRoot(rootPages, true).SetFocus(expandedView) diff --git a/progressBar.go b/ui/progressBar.go similarity index 92% rename from progressBar.go rename to ui/progressBar.go index b321d23..7b824a2 100644 --- a/progressBar.go +++ b/ui/progressBar.go @@ -1,7 +1,8 @@ -package main +package ui import ( "fmt" + "github.com/fhs/gompd/mpd" "strconv" "github.com/aditya-K2/gomp/utils" @@ -10,7 +11,19 @@ import ( "github.com/gdamore/tcell/v2" ) -var CurrentSong string +var ( + CurrentSong string + CONN *mpd.Client + RENDERER interface{ Send(string) } +) + +func SetConnection(c *mpd.Client) { + CONN = c +} + +func SetRenderer(r interface{ Send(string) }) { + RENDERER = r +} // The progressBar is just a string which is separated by the color formatting String // for e.g From 6b7fff82b79de5de1b889bda6397f49a418450f4 Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 20:41:48 +0530 Subject: [PATCH 04/12] minor changes in formatting --- main.go | 58 +++++++++++++++++++++++++++---------------------------- render.go | 6 +++--- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/main.go b/main.go index 36869de..2f23608 100644 --- a/main.go +++ b/main.go @@ -17,16 +17,16 @@ import ( ) var ( - CONN *mpd.Client - UI *ui.Application - NOTIFICATION_SERVER *NotificationServer - RENDERER *Renderer - Volume int64 - Random bool - Repeat bool - InsidePlaylist bool = true - InsideSearchView bool = false - ARTIST_TREE map[string]map[string]map[string]string + CONN *mpd.Client + UI *ui.Application + Notify *NotificationServer + RENDERER *Renderer + Volume int64 + Random bool + Repeat bool + InsidePlaylist = true + InsideSearchView = false + ArtistTree map[string]map[string]map[string]string ) func main() { @@ -62,26 +62,26 @@ func main() { Random, _ = strconv.ParseBool(_v["random"]) Repeat, _ = strconv.ParseBool(_v["repeat"]) - ARTIST_TREE, err = client.GenerateArtistTree() - ARTIST_TREE_CONTENT := utils.ConvertToArray(ARTIST_TREE) - NOTIFICATION_SERVER = NewNotificationServer() - NOTIFICATION_SERVER.Start() - client.SetNotificationServer(NOTIFICATION_SERVER) + ArtistTree, err = client.GenerateArtistTree() + ArtistTreeContent := utils.ConvertToArray(ArtistTree) + Notify = NewNotificationServer() + Notify.Start() + client.SetNotificationServer(Notify) - var SEARCH_CONTENT_SLICE []interface{} + var SearchContentSlice []interface{} UI.ExpandedView.SetDrawFunc(func(s tcell.Screen, x, y, width, height int) (int, int, int, int) { if InsidePlaylist { client.UpdatePlaylist(UI.ExpandedView) } else if InsideSearchView { - client.UpdateSearchView(UI.ExpandedView, SEARCH_CONTENT_SLICE) + client.UpdateSearchView(UI.ExpandedView, SearchContentSlice) } else { client.Update(dirTree.Children, UI.ExpandedView) } return UI.ExpandedView.GetInnerRect() }) - var FUNC_MAP = map[string]func(){ + var FuncMap = map[string]func(){ "showChildrenContent": func() { r, _ := UI.ExpandedView.GetSelection() if !InsidePlaylist && !InsideSearchView { @@ -96,7 +96,7 @@ func main() { CONN.Play(r) } else if InsideSearchView { r, _ := UI.ExpandedView.GetSelection() - client.AddToPlaylist(SEARCH_CONTENT_SLICE[r], true) + client.AddToPlaylist(SearchContentSlice[r], true) } }, "togglePlayBack": func() { @@ -115,7 +115,7 @@ func main() { }, "clearPlaylist": func() { CONN.Clear() - NOTIFICATION_SERVER.Send("PlayList Cleared") + Notify.Send("PlayList Cleared") }, "previousSong": func() { CONN.Previous() @@ -126,7 +126,7 @@ func main() { CONN.Add(dirTree.Children[r].AbsolutePath) } else if InsideSearchView { r, _ := UI.ExpandedView.GetSelection() - client.AddToPlaylist(SEARCH_CONTENT_SLICE[r], false) + client.AddToPlaylist(SearchContentSlice[r], false) } }, "toggleRandom": func() { @@ -184,14 +184,14 @@ func main() { }, "stop": func() { CONN.Stop() - NOTIFICATION_SERVER.Send("Playback Stopped") + Notify.Send("Playback Stopped") }, "updateDB": func() { _, err = CONN.Update("") if err != nil { panic(err) } - NOTIFICATION_SERVER.Send("Database Updated") + Notify.Send("Database Updated") }, "deleteSongFromPlaylist": func() { if InsidePlaylist { @@ -204,12 +204,12 @@ func main() { }, } - config.GenerateKeyMap(FUNC_MAP) + config.GenerateKeyMap(FuncMap) UI.SearchBar.SetAutocompleteFunc(func(c string) []string { if c != "" && c != " " && c != " " { _, _, w, _ := UI.SearchBar.GetRect() - matches := fuzzy.Find(c, ARTIST_TREE_CONTENT) + matches := fuzzy.Find(c, ArtistTreeContent) var suggestions []string for i, match := range matches { if i == 10 { @@ -225,7 +225,7 @@ func main() { UI.ExpandedView.SetInputCapture(func(e *tcell.EventKey) *tcell.EventKey { if val, ok := config.KEY_MAP[int(e.Rune())]; ok { - FUNC_MAP[val]() + FuncMap[val]() return nil } else { return e @@ -237,10 +237,10 @@ func main() { UI.ExpandedView.Select(0, 0) InsideSearchView = true InsidePlaylist = false - SEARCH_CONTENT_SLICE = nil - SEARCH_CONTENT_SLICE, err = client.GenerateContentSlice(UI.SearchBar.GetText()) + SearchContentSlice = nil + SearchContentSlice, err = client.GenerateContentSlice(UI.SearchBar.GetText()) if err != nil { - NOTIFICATION_SERVER.Send("Could Not Retrieve the Results") + Notify.Send("Could Not Retrieve the Results") } else { UI.SearchBar.SetText("") UI.App.SetFocus(UI.ExpandedView) diff --git a/render.go b/render.go index 3602a28..4cbe828 100644 --- a/render.go +++ b/render.go @@ -90,13 +90,13 @@ func getImagePath(path string) string { if extractedImage == viper.GetString("DEFAULT_IMAGE_PATH") && viper.GetString("GET_COVER_ART_FROM_LAST_FM") == "TRUE" { downloadedImage, err := getImageFromLastFM(a[0]["artist"], a[0]["album"], imagePath) if err == nil { - NOTIFICATION_SERVER.Send("Image From LastFM") + Notify.Send("Image From LastFM") extractedImage = downloadedImage } else { - NOTIFICATION_SERVER.Send("Falling Back to Default Image.") + Notify.Send("Falling Back to Default Image.") } } else { - NOTIFICATION_SERVER.Send("Extracted Image Successfully") + Notify.Send("Extracted Image Successfully") } } } From 6390039ea9e915a804e06b97d2d8eeee9a63ab1e Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 21:19:37 +0530 Subject: [PATCH 05/12] moving lastfm.go render.go imageUtils.go to the new render package --- main.go | 21 ++++++++++++------- {utils => render}/imageUtils.go | 9 +++++---- lastfm.go => render/lastfm.go | 2 +- render.go => render/render.go | 36 +++++++++++++++++++++++---------- 4 files changed, 45 insertions(+), 23 deletions(-) rename {utils => render}/imageUtils.go (88%) rename lastfm.go => render/lastfm.go (98%) rename render.go => render/render.go (81%) diff --git a/main.go b/main.go index 2f23608..32f9c91 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,12 @@ package main import ( - "github.com/aditya-K2/gomp/ui" "strconv" "time" + "github.com/aditya-K2/gomp/render" + "github.com/aditya-K2/gomp/ui" + "github.com/aditya-K2/gomp/client" "github.com/aditya-K2/gomp/utils" @@ -19,8 +21,8 @@ import ( var ( CONN *mpd.Client UI *ui.Application - Notify *NotificationServer - RENDERER *Renderer + Notify *ui.NotificationServer + RENDERER *render.Renderer Volume int64 Random bool Repeat bool @@ -38,8 +40,13 @@ func main() { panic(mpdConnectionError) } defer CONN.Close() + + client.SetConnection(CONN) + ui.SetConnection(CONN) + render.SetConnection(CONN) + cache.SetCacheDir(viper.GetString("CACHE_DIR")) - RENDERER = newRenderer() + RENDERER = render.NewRenderer() ui.SetRenderer(RENDERER) c, _ := CONN.CurrentSong() if len(c) != 0 { @@ -49,12 +56,11 @@ func main() { } UI = ui.NewApplication() + ui.ConnectUI(UI) fileMap, err := CONN.GetFiles() dirTree := client.GenerateDirectoryTree(fileMap) - client.SetConnection(CONN) - ui.SetConnection(CONN) client.UpdatePlaylist(UI.ExpandedView) _v, _ := CONN.Status() @@ -64,9 +70,10 @@ func main() { ArtistTree, err = client.GenerateArtistTree() ArtistTreeContent := utils.ConvertToArray(ArtistTree) - Notify = NewNotificationServer() + Notify = ui.NewNotificationServer() Notify.Start() client.SetNotificationServer(Notify) + render.SetNotificationServer(Notify) var SearchContentSlice []interface{} diff --git a/utils/imageUtils.go b/render/imageUtils.go similarity index 88% rename from utils/imageUtils.go rename to render/imageUtils.go index ce3dfee..8c802c2 100644 --- a/utils/imageUtils.go +++ b/render/imageUtils.go @@ -1,6 +1,7 @@ -package utils +package render import ( + "github.com/aditya-K2/gomp/utils" "os" "strings" @@ -67,17 +68,17 @@ func ExtractImageFromFile(uri string, imagePath string) string { if strings.HasSuffix(uri, ".mp3") { imagePath := GetMp3Image(uri, imagePath) if imagePath == "" { - Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) + utils.Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) return viper.GetString("DEFAULT_IMAGE_PATH") } } else if strings.HasSuffix(uri, ".flac") { imagePath := GetFlacImage(uri, imagePath) if imagePath == "" { - Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) + utils.Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) return viper.GetString("DEFAULT_IMAGE_PATH") } } else { - Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) + utils.Copy(viper.GetString("DEFAULT_IMAGE_PATH"), _i) return viper.GetString("DEFAULT_IMAGE_PATH") } return imagePath diff --git a/lastfm.go b/render/lastfm.go similarity index 98% rename from lastfm.go rename to render/lastfm.go index c1e9b86..4185114 100644 --- a/lastfm.go +++ b/render/lastfm.go @@ -1,4 +1,4 @@ -package main +package render import ( "errors" diff --git a/render.go b/render/render.go similarity index 81% rename from render.go rename to render/render.go index 4cbe828..744352a 100644 --- a/render.go +++ b/render/render.go @@ -1,7 +1,8 @@ -package main +package render import ( "github.com/aditya-K2/gomp/ui" + "github.com/fhs/gompd/mpd" "image" "os" @@ -12,9 +13,22 @@ import ( "gitlab.com/diamondburned/ueberzug-go" ) +var ( + CONN *mpd.Client + Notify interface { Send(string) } +) + +func SetConnection(c *mpd.Client) { + CONN = c +} + +func SetNotificationServer(n interface{ Send(string) }) { + Notify = n +} + /* Renderer is just a channel on which we will send the Path to the song whose - Image is to be Rendered. This channel is passed to the openImage which in turn is called + Image is to be Rendered. This channel is passed to the OpenImage which in turn is called by the Start() function as a go routine. */ type Renderer struct { @@ -24,7 +38,7 @@ type Renderer struct { /* Returns a new Renderer with a string channel */ -func newRenderer() *Renderer { +func NewRenderer() *Renderer { c := make(chan string) return &Renderer{ c: c, @@ -46,11 +60,11 @@ func (self *Renderer) Send(path string) { and saves resources too. */ -func openImage(path string, c chan string) { +func OpenImage(path string, c chan string) { fw, fh := utils.GetFontWidth() var im *ueberzug.Image if path != "stop" { - extractedImage := getImagePath(path) + extractedImage := GetImagePath(path) img2, _ := GetImg(extractedImage) im, _ = ueberzug.NewImage(img2, int(float32(ui.IMG_X)*fw)+viper.GetInt("ADDITIONAL_PADDING_X"), int(float32(ui.IMG_Y)*fh)+viper.GetInt("ADDITIONAL_PADDING_Y")) } @@ -59,25 +73,25 @@ func openImage(path string, c chan string) { im.Clear() } if d != "stop" { - openImage(d, c) + OpenImage(d, c) } else { - openImage("stop", c) + OpenImage("stop", c) } } /* - Initialises the Renderer and calls the go routine openImage and passes the channel + Initialises the Renderer and calls the go routine OpenImage and passes the channel as argument. */ func (self *Renderer) Start(path string) { - go openImage(path, self.c) + go OpenImage(path, self.c) } /* This Function returns the path to the image that is to be rendered it checks first for the image in the cache else it adds the image to the cache and then extracts it and renders it. */ -func getImagePath(path string) string { +func GetImagePath(path string) string { a, err := CONN.ListInfo(path) var extractedImage string if err == nil && len(a) != 0 { @@ -86,7 +100,7 @@ func getImagePath(path string) string { } else { imagePath := cache.GenerateName(a[0]["artist"], a[0]["album"]) absPath := utils.CheckDirectoryFmt(viper.GetString("MUSIC_DIRECTORY")) + path - extractedImage = utils.ExtractImageFromFile(absPath, imagePath) + extractedImage = ExtractImageFromFile(absPath, imagePath) if extractedImage == viper.GetString("DEFAULT_IMAGE_PATH") && viper.GetString("GET_COVER_ART_FROM_LAST_FM") == "TRUE" { downloadedImage, err := getImageFromLastFM(a[0]["artist"], a[0]["album"], imagePath) if err == nil { From f56169cbd3282d78e5674655d9081f3268512067 Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 21:20:01 +0530 Subject: [PATCH 06/12] moving notification to ui package --- notification.go => ui/notification.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) rename notification.go => ui/notification.go (96%) diff --git a/notification.go b/ui/notification.go similarity index 96% rename from notification.go rename to ui/notification.go index 584434a..4741d34 100644 --- a/notification.go +++ b/ui/notification.go @@ -1,4 +1,4 @@ -package main +package ui import ( "time" @@ -9,6 +9,14 @@ import ( "github.com/gdamore/tcell/v2" ) +var ( + UI *Application +) + +func ConnectUI(a *Application) { + UI = a +} + /* Notification Primitive */ type Notification struct { *tview.Box From 5031477cf85b458e92834521d4f9cef23d2d592a Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 21:43:45 +0530 Subject: [PATCH 07/12] Rename : fileBrowser.go -> files.go --- client/{fileBrowser.go => files.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename client/{fileBrowser.go => files.go} (100%) diff --git a/client/fileBrowser.go b/client/files.go similarity index 100% rename from client/fileBrowser.go rename to client/files.go From 33603e1450972b19e60d1253df3f3d7ad24e0672 Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Wed, 22 Dec 2021 23:47:18 +0530 Subject: [PATCH 08/12] Better Focusing Model Previously I was using the InsidePlaylist and InsideSearchView boolean values which was a very hacky and unscalable way. Instead I am using a focus map which can be queried to check which view has focus. Also the Pages Implementation is kind of on hold because it has a lot of problems for e.g resizing doesn't seem to work as I imagined. I am keeping that Idea on hold right now. --- main.go | 58 ++++++++++++++++++++++++----------------------------- ui/focus.go | 21 +++++++++++++++++++ 2 files changed, 47 insertions(+), 32 deletions(-) create mode 100644 ui/focus.go diff --git a/main.go b/main.go index 32f9c91..576871b 100644 --- a/main.go +++ b/main.go @@ -19,16 +19,14 @@ import ( ) var ( - CONN *mpd.Client - UI *ui.Application - Notify *ui.NotificationServer - RENDERER *render.Renderer - Volume int64 - Random bool - Repeat bool - InsidePlaylist = true - InsideSearchView = false - ArtistTree map[string]map[string]map[string]string + CONN *mpd.Client + UI *ui.Application + Notify *ui.NotificationServer + RENDERER *render.Renderer + Volume int64 + Random bool + Repeat bool + ArtistTree map[string]map[string]map[string]string ) func main() { @@ -41,6 +39,8 @@ func main() { } defer CONN.Close() + ui.GenerateFocusMap() + client.SetConnection(CONN) ui.SetConnection(CONN) render.SetConnection(CONN) @@ -78,11 +78,11 @@ func main() { var SearchContentSlice []interface{} UI.ExpandedView.SetDrawFunc(func(s tcell.Screen, x, y, width, height int) (int, int, int, int) { - if InsidePlaylist { + if ui.HasFocus("Playlist") { client.UpdatePlaylist(UI.ExpandedView) - } else if InsideSearchView { + } else if ui.HasFocus("SearchView") { client.UpdateSearchView(UI.ExpandedView, SearchContentSlice) - } else { + } else if ui.HasFocus("FileBrowser") { client.Update(dirTree.Children, UI.ExpandedView) } return UI.ExpandedView.GetInnerRect() @@ -91,7 +91,7 @@ func main() { var FuncMap = map[string]func(){ "showChildrenContent": func() { r, _ := UI.ExpandedView.GetSelection() - if !InsidePlaylist && !InsideSearchView { + if ui.HasFocus("FileBrowser") { if len(dirTree.Children[r].Children) == 0 { id, _ := CONN.AddId(dirTree.Children[r].AbsolutePath, -1) CONN.PlayId(id) @@ -99,9 +99,9 @@ func main() { client.Update(dirTree.Children[r].Children, UI.ExpandedView) dirTree = &dirTree.Children[r] } - } else if InsidePlaylist { + } else if ui.HasFocus("Playlist") { CONN.Play(r) - } else if InsideSearchView { + } else if ui.HasFocus("SearchView") { r, _ := UI.ExpandedView.GetSelection() client.AddToPlaylist(SearchContentSlice[r], true) } @@ -110,7 +110,7 @@ func main() { client.TogglePlayBack() }, "showParentContent": func() { - if !InsidePlaylist && !InsideSearchView { + if ui.HasFocus("FileBrowser") { if dirTree.Parent != nil { client.Update(dirTree.Parent.Children, UI.ExpandedView) dirTree = dirTree.Parent @@ -122,16 +122,16 @@ func main() { }, "clearPlaylist": func() { CONN.Clear() - Notify.Send("PlayList Cleared") + Notify.Send("Playlist Cleared") }, "previousSong": func() { CONN.Previous() }, "addToPlaylist": func() { - if !InsidePlaylist && !InsideSearchView { + if ui.HasFocus("FileBrowser") { r, _ := UI.ExpandedView.GetSelection() CONN.Add(dirTree.Children[r].AbsolutePath) - } else if InsideSearchView { + } else if ui.HasFocus("SearchView") { r, _ := UI.ExpandedView.GetSelection() client.AddToPlaylist(SearchContentSlice[r], false) } @@ -165,25 +165,20 @@ func main() { CONN.SetVolume(int(Volume)) }, "navigateToFiles": func() { - InsidePlaylist = false - InsideSearchView = false + ui.SetFocus("FileBrowser") UI.Navbar.Select(1, 0) client.Update(dirTree.Children, UI.ExpandedView) }, "navigateToPlaylist": func() { - InsidePlaylist = true - InsideSearchView = false + ui.SetFocus("Playlist") UI.Navbar.Select(0, 0) client.UpdatePlaylist(UI.ExpandedView) }, "navigateToMostPlayed": func() { - InsideSearchView = false - InsidePlaylist = false UI.Navbar.Select(2, 0) }, "navigateToSearch": func() { - InsideSearchView = true - InsidePlaylist = false + ui.SetFocus("SearchView") UI.Navbar.Select(3, 0) }, "quit": func() { @@ -201,7 +196,7 @@ func main() { Notify.Send("Database Updated") }, "deleteSongFromPlaylist": func() { - if InsidePlaylist { + if ui.HasFocus("Playlist") { r, _ := UI.ExpandedView.GetSelection() CONN.Delete(r, -1) } @@ -242,8 +237,7 @@ func main() { UI.SearchBar.SetDoneFunc(func(e tcell.Key) { if e == tcell.KeyEnter { UI.ExpandedView.Select(0, 0) - InsideSearchView = true - InsidePlaylist = false + ui.SetFocus("SearchView") SearchContentSlice = nil SearchContentSlice, err = client.GenerateContentSlice(UI.SearchBar.GetText()) if err != nil { @@ -255,7 +249,7 @@ func main() { } } if e == tcell.KeyEscape { - InsideSearchView = false + ui.FocusMap["SearchView"] = false UI.App.SetFocus(UI.ExpandedView) } }) diff --git a/ui/focus.go b/ui/focus.go new file mode 100644 index 0000000..1906a63 --- /dev/null +++ b/ui/focus.go @@ -0,0 +1,21 @@ +package ui + +var FocusMap map[string]bool + +func GenerateFocusMap() { + FocusMap = make(map[string]bool) + FocusMap["Playlist"] = true + FocusMap["FileBrowser"] = false + FocusMap["SearchView"] = false +} + +func HasFocus(s string) bool { + return FocusMap[s] +} + +func SetFocus(s string) { + for k := range FocusMap { + FocusMap[k] = false + } + FocusMap[s] = true +} From b587f5acfdc686e403fc8b9103336590fa2d02e8 Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Thu, 23 Dec 2021 00:16:07 +0530 Subject: [PATCH 09/12] moving notification to notification package inside ui --- main.go | 7 ++++--- ui/{ => notify}/notification.go | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) rename ui/{ => notify}/notification.go (96%) diff --git a/main.go b/main.go index 576871b..0773b2f 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "github.com/aditya-K2/gomp/ui/notify" "strconv" "time" @@ -21,7 +22,7 @@ import ( var ( CONN *mpd.Client UI *ui.Application - Notify *ui.NotificationServer + Notify *notify.NotificationServer RENDERER *render.Renderer Volume int64 Random bool @@ -56,7 +57,7 @@ func main() { } UI = ui.NewApplication() - ui.ConnectUI(UI) + notify.ConnectUI(UI) fileMap, err := CONN.GetFiles() dirTree := client.GenerateDirectoryTree(fileMap) @@ -70,7 +71,7 @@ func main() { ArtistTree, err = client.GenerateArtistTree() ArtistTreeContent := utils.ConvertToArray(ArtistTree) - Notify = ui.NewNotificationServer() + Notify = notify.NewNotificationServer() Notify.Start() client.SetNotificationServer(Notify) render.SetNotificationServer(Notify) diff --git a/ui/notification.go b/ui/notify/notification.go similarity index 96% rename from ui/notification.go rename to ui/notify/notification.go index 4741d34..e05554f 100644 --- a/ui/notification.go +++ b/ui/notify/notification.go @@ -1,6 +1,7 @@ -package ui +package notify import ( + "github.com/aditya-K2/gomp/ui" "time" "github.com/aditya-K2/gomp/utils" @@ -10,10 +11,10 @@ import ( ) var ( - UI *Application + UI *ui.Application ) -func ConnectUI(a *Application) { +func ConnectUI(a *ui.Application) { UI = a } From f56eb1cf1f5136e984624fe004a5f740b759f47c Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Thu, 23 Dec 2021 20:20:27 +0530 Subject: [PATCH 10/12] Removing Globals Globals are no longer needed instead I am connecting each part with ( what were previously ) globals. Also Renaming SetRenderer to ConnectRenderer which describes the name more precisely --- main.go | 36 +++++++++++++----------------------- ui/progressBar.go | 5 +++-- 2 files changed, 16 insertions(+), 25 deletions(-) diff --git a/main.go b/main.go index 0773b2f..aba3124 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,11 @@ package main import ( - "github.com/aditya-K2/gomp/ui/notify" "strconv" "time" + "github.com/aditya-K2/gomp/ui/notify" + "github.com/aditya-K2/gomp/render" "github.com/aditya-K2/gomp/ui" @@ -19,22 +20,11 @@ import ( "github.com/spf13/viper" ) -var ( - CONN *mpd.Client - UI *ui.Application - Notify *notify.NotificationServer - RENDERER *render.Renderer - Volume int64 - Random bool - Repeat bool - ArtistTree map[string]map[string]map[string]string -) - func main() { config.ReadConfig() // Connect to MPD server var mpdConnectionError error - CONN, mpdConnectionError = mpd.Dial("tcp", "localhost:"+viper.GetString("MPD_PORT")) + CONN, mpdConnectionError := mpd.Dial("tcp", "localhost:"+viper.GetString("MPD_PORT")) if mpdConnectionError != nil { panic(mpdConnectionError) } @@ -47,16 +37,16 @@ func main() { render.SetConnection(CONN) cache.SetCacheDir(viper.GetString("CACHE_DIR")) - RENDERER = render.NewRenderer() - ui.SetRenderer(RENDERER) + Renderer := render.NewRenderer() + ui.ConnectRenderer(Renderer) c, _ := CONN.CurrentSong() if len(c) != 0 { - RENDERER.Start(c["file"]) + Renderer.Start(c["file"]) } else { - RENDERER.Start("stop") + Renderer.Start("stop") } - UI = ui.NewApplication() + UI := ui.NewApplication() notify.ConnectUI(UI) fileMap, err := CONN.GetFiles() @@ -65,13 +55,13 @@ func main() { client.UpdatePlaylist(UI.ExpandedView) _v, _ := CONN.Status() - Volume, _ = strconv.ParseInt(_v["volume"], 10, 64) - Random, _ = strconv.ParseBool(_v["random"]) - Repeat, _ = strconv.ParseBool(_v["repeat"]) + Volume, _ := strconv.ParseInt(_v["volume"], 10, 64) + Random, _ := strconv.ParseBool(_v["random"]) + Repeat, _ := strconv.ParseBool(_v["repeat"]) - ArtistTree, err = client.GenerateArtistTree() + ArtistTree, err := client.GenerateArtistTree() ArtistTreeContent := utils.ConvertToArray(ArtistTree) - Notify = notify.NewNotificationServer() + Notify := notify.NewNotificationServer() Notify.Start() client.SetNotificationServer(Notify) render.SetNotificationServer(Notify) diff --git a/ui/progressBar.go b/ui/progressBar.go index 7b824a2..a7d2558 100644 --- a/ui/progressBar.go +++ b/ui/progressBar.go @@ -2,9 +2,10 @@ package ui import ( "fmt" - "github.com/fhs/gompd/mpd" "strconv" + "github.com/fhs/gompd/mpd" + "github.com/aditya-K2/gomp/utils" "github.com/aditya-K2/tview" @@ -21,7 +22,7 @@ func SetConnection(c *mpd.Client) { CONN = c } -func SetRenderer(r interface{ Send(string) }) { +func ConnectRenderer(r interface{ Send(string) }) { RENDERER = r } From 6405bebeed941788f071d0a1915396156d6249ac Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Thu, 23 Dec 2021 21:12:09 +0530 Subject: [PATCH 11/12] minor formatting change --- ui/progressBar.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/ui/progressBar.go b/ui/progressBar.go index a7d2558..103db80 100644 --- a/ui/progressBar.go +++ b/ui/progressBar.go @@ -86,14 +86,28 @@ func (s *progressBar) updateProgress() { if du != 0 { percentage := el / du * 100 if err == nil && err1 == nil { - s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", utils.FormatString(_status["state"]), utils.FormatString(_status["random"]), utils.FormatString(_status["repeat"]), _status["volume"])).SetTitleAlign(tview.AlignRight) + s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", + utils.FormatString(_status["state"]), + utils.FormatString(_status["random"]), + utils.FormatString(_status["repeat"]), + _status["volume"])). + SetTitleAlign(tview.AlignRight) s.t.GetCell(2, 0).Text = utils.GetText(float64(_width), percentage, utils.StrTime(el)+"/"+utils.StrTime(du)+"("+strconv.FormatFloat(percentage, 'f', 2, 32)+"%"+")") } else { - s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s]", utils.FormatString(_status["state"]), utils.FormatString(_status["random"]), utils.FormatString(_status["repeat"]))).SetTitleAlign(tview.AlignRight) + s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s]", + utils.FormatString(_status["state"]), + utils.FormatString(_status["random"]), + utils.FormatString(_status["repeat"]))). + SetTitleAlign(tview.AlignRight) s.t.GetCell(2, 0).Text = "" } } else { - s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", utils.FormatString(_status["state"]), utils.FormatString(_status["random"]), utils.FormatString(_status["repeat"]), _status["volume"])).SetTitleAlign(tview.AlignRight) + s.t.SetTitle(fmt.Sprintf("[[::i] %s [-:-:-]Shuffle: %s Repeat: %s Volume: %s ]", + utils.FormatString(_status["state"]), + utils.FormatString(_status["random"]), + utils.FormatString(_status["repeat"]), + _status["volume"])). + SetTitleAlign(tview.AlignRight) s.t.GetCell(2, 0).Text = utils.GetText(float64(_width), 0, " ---:---") } } From 0118886d5e1bc0eb6ce4b59c873b7d6163f51719 Mon Sep 17 00:00:00 2001 From: aditya-K2 Date: Fri, 24 Dec 2021 15:37:21 +0530 Subject: [PATCH 12/12] chore: Added More Informative Comments --- client/client.go | 31 ++++++++++++------------------ main.go | 25 +++++++++++++++++++++++- render/render.go | 49 ++++++++++++++++++------------------------------ ui/focus.go | 3 +++ 4 files changed, 57 insertions(+), 51 deletions(-) diff --git a/client/client.go b/client/client.go index b677c79..fece67c 100644 --- a/client/client.go +++ b/client/client.go @@ -3,6 +3,7 @@ package client import ( "errors" "fmt" + "github.com/fhs/gompd/mpd" "strings" @@ -54,11 +55,9 @@ func UpdatePlaylist(inputTable *tview.Table) { } } -/* - The GenerateContentSlice returns a slice of the content to be displayed on the Search View. The Slice is generated - because the random nature of maps as they return values randomly hence the draw function keeps changing the order - in which the results. -*/ +// The GenerateContentSlice returns a slice of the content to be displayed on the Search View. The Slice is generated +// because the random nature of maps as they return values randomly hence the draw function keeps changing the order +// in which the results appear. func GenerateContentSlice(selectedSuggestion string) ([]interface{}, error) { var ContentSlice []interface{} if strings.TrimRight(selectedSuggestion, " ") == "" { @@ -100,11 +99,9 @@ func GenerateContentSlice(selectedSuggestion string) ([]interface{}, error) { return ContentSlice, nil } -/* - UpdateSearchView as the name suggests Updates the Search View the idea is to basically keep a fourth option called - Search in the Navigation bar which will render things from a global ContentSlice at least in the context of the main - function this will also help in persisting the Search Results. -*/ +// UpdateSearchView as the name suggests Updates the Search View the idea is to basically keep a fourth option called +// Search in the Navigation bar which will render things from a global ContentSlice at least in the context of the main +// function this will also help in persisting the Search Results. func UpdateSearchView(inputTable *tview.Table, c []interface{}) { inputTable.Clear() _, _, width, _ := inputTable.GetInnerRect() @@ -166,6 +163,8 @@ func Update(f []FileNode, inputTable *tview.Table) { } } +// GenerateArtistTree Artist Tree is a map of Artist to their Album Map +// Album Tree is a map of the tracks in that particular album. func GenerateArtistTree() (map[string]map[string]map[string]string, error) { ArtistTree = make(map[string]map[string]map[string]string) AllInfo, err := CONN.ListAllInfo("/") @@ -199,9 +198,7 @@ func PrintArtistTree(a map[string]map[string]map[string]string) { } } -/* - Adds All tracks from a specified album to a playlist -*/ +// Adds All tracks from a specified album to a playlist func AddAlbum(a map[string]map[string]map[string]string, alb string, artist string) { for _, v := range a[artist][alb] { err := CONN.Add(v) @@ -212,9 +209,7 @@ func AddAlbum(a map[string]map[string]map[string]string, alb string, artist stri NotificationServer.Send("Album Added : " + alb) } -/* - Adds All tracks from a specified artist to a playlist -*/ +// Adds All tracks from a specified artist to a playlist func AddArtist(a map[string]map[string]map[string]string, artist string) { if val, ok := a[artist]; ok { for _, v := range val { @@ -229,9 +224,7 @@ func AddArtist(a map[string]map[string]map[string]string, artist string) { } } -/* - Adds Specified Track to the Playlist -*/ +// Adds Specified Track to the Playlist func AddTitle(a map[string]map[string]map[string]string, artist, alb, track string, addAndPlay bool) { if addAndPlay { id, err := CONN.AddId(a[artist][alb][track], -1) diff --git a/main.go b/main.go index aba3124..5ca3447 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,6 @@ import ( func main() { config.ReadConfig() - // Connect to MPD server var mpdConnectionError error CONN, mpdConnectionError := mpd.Dial("tcp", "localhost:"+viper.GetString("MPD_PORT")) if mpdConnectionError != nil { @@ -37,8 +36,11 @@ func main() { render.SetConnection(CONN) cache.SetCacheDir(viper.GetString("CACHE_DIR")) + Renderer := render.NewRenderer() + // Connecting the Renderer to the Main UI ui.ConnectRenderer(Renderer) + c, _ := CONN.CurrentSong() if len(c) != 0 { Renderer.Start(c["file"]) @@ -47,27 +49,41 @@ func main() { } UI := ui.NewApplication() + + // Connecting the Notification Server to the Main UI notify.ConnectUI(UI) fileMap, err := CONN.GetFiles() + + // Generating the Directory Tree for File Navigation. dirTree := client.GenerateDirectoryTree(fileMap) + // Default View upon Opening is of Playlist. client.UpdatePlaylist(UI.ExpandedView) _v, _ := CONN.Status() + // Setting Volume, Random and Repeat Values Volume, _ := strconv.ParseInt(_v["volume"], 10, 64) Random, _ := strconv.ParseBool(_v["random"]) Repeat, _ := strconv.ParseBool(_v["repeat"]) ArtistTree, err := client.GenerateArtistTree() + + // Used for Fuzzy Searching ArtistTreeContent := utils.ConvertToArray(ArtistTree) + Notify := notify.NewNotificationServer() Notify.Start() + + // Connecting Notification Server to Client and Rendering Module so that they can send Notifications client.SetNotificationServer(Notify) render.SetNotificationServer(Notify) + // This is the Slice that is used to Display Content in the SearchView var SearchContentSlice []interface{} + // This Function Is Responsible for Changing the Focus it uses the Focus Map and Based on it Chooses + // the Draw Function UI.ExpandedView.SetDrawFunc(func(s tcell.Screen, x, y, width, height int) (int, int, int, int) { if ui.HasFocus("Playlist") { client.UpdatePlaylist(UI.ExpandedView) @@ -79,6 +95,9 @@ func main() { return UI.ExpandedView.GetInnerRect() }) + // Function Maps is used For Mapping Keys According to the Value mapped to the Key the respective Function is called + // For e.g. in the config if the User Maps T to togglePlayBack then whenever in the input handler the T is received + // the respective function in this case togglePlayBack is called. var FuncMap = map[string]func(){ "showChildrenContent": func() { r, _ := UI.ExpandedView.GetSelection() @@ -197,6 +216,9 @@ func main() { }, } + // Generating the Key Map Based on the Function Map Here Basically the Values will be flipped + // In the config if togglePlayBack is mapped to [ T , P, SPACE ] then here Basically we will receive a map + // for each event T, P, SPACE mapped to the same function togglePlayBack config.GenerateKeyMap(FuncMap) UI.SearchBar.SetAutocompleteFunc(func(c string) []string { @@ -216,6 +238,7 @@ func main() { } }) + // Input Handler UI.ExpandedView.SetInputCapture(func(e *tcell.EventKey) *tcell.EventKey { if val, ok := config.KEY_MAP[int(e.Rune())]; ok { FuncMap[val]() diff --git a/render/render.go b/render/render.go index 744352a..0515437 100644 --- a/render/render.go +++ b/render/render.go @@ -1,11 +1,12 @@ package render import ( - "github.com/aditya-K2/gomp/ui" - "github.com/fhs/gompd/mpd" "image" "os" + "github.com/aditya-K2/gomp/ui" + "github.com/fhs/gompd/mpd" + "github.com/aditya-K2/gomp/cache" "github.com/aditya-K2/gomp/utils" "github.com/nfnt/resize" @@ -14,8 +15,8 @@ import ( ) var ( - CONN *mpd.Client - Notify interface { Send(string) } + CONN *mpd.Client + Notify interface{ Send(string) } ) func SetConnection(c *mpd.Client) { @@ -26,18 +27,14 @@ func SetNotificationServer(n interface{ Send(string) }) { Notify = n } -/* - Renderer is just a channel on which we will send the Path to the song whose - Image is to be Rendered. This channel is passed to the OpenImage which in turn is called - by the Start() function as a go routine. -*/ +// Renderer is just a channel on which we will send the Path to the song whose +// Image is to be Rendered. This channel is passed to the OpenImage which in turn is called +// by the Start() function as a go routine. type Renderer struct { c chan string } -/* - Returns a new Renderer with a string channel -*/ +// Returns a new Renderer with a string channel func NewRenderer() *Renderer { c := make(chan string) return &Renderer{ @@ -45,21 +42,15 @@ func NewRenderer() *Renderer { } } -/* - Send Image Path to Renderer -*/ +// Send Image Path to Renderer func (self *Renderer) Send(path string) { self.c <- path } -/* - - Go Routine that will Be Called and will listen on the channel c - for changes and on getting a string over the channel will open the Image and - keep listening again. This will keep the image blocked ( i.e no need to use time.Sleep() etc. ) - and saves resources too. - -*/ +// Go Routine that will Be Called and will listen on the channel c +// for changes and on getting a string over the channel will open the Image and +// keep listening again. This will keep the image blocked ( i.e no need to use time.Sleep() etc. ) +// and saves resources too. func OpenImage(path string, c chan string) { fw, fh := utils.GetFontWidth() var im *ueberzug.Image @@ -79,18 +70,14 @@ func OpenImage(path string, c chan string) { } } -/* - Initialises the Renderer and calls the go routine OpenImage and passes the channel - as argument. -*/ +// Initialises the Renderer and calls the go routine OpenImage and passes the channel +// as argument. func (self *Renderer) Start(path string) { go OpenImage(path, self.c) } -/* - This Function returns the path to the image that is to be rendered it checks first for the image in the cache - else it adds the image to the cache and then extracts it and renders it. -*/ +// This Function returns the path to the image that is to be rendered it checks first for the image in the cache +// else it adds the image to the cache and then extracts it and renders it. func GetImagePath(path string) string { a, err := CONN.ListInfo(path) var extractedImage string diff --git a/ui/focus.go b/ui/focus.go index 1906a63..b71c377 100644 --- a/ui/focus.go +++ b/ui/focus.go @@ -1,5 +1,8 @@ package ui +// The Focus Map Helps to keep track of which UI Element Currently Has the Focus It can be queried to get the Current +// UI Element with Focus and also can set UI Focus keep in mind that it isn't Focus Map that is Responsible to change +// the Focus that is Done through the Update Function of UI.ExpandedView */ var FocusMap map[string]bool func GenerateFocusMap() {