add SortItems param to Menu, AddItems method

This commit is contained in:
Bradley Cicenas 2017-02-15 06:01:35 +00:00
parent b9bdc1c9c5
commit eb66f32a71
3 changed files with 32 additions and 23 deletions

View File

@ -17,10 +17,11 @@ func HelpMenu() {
ResetView()
defer ResetView()
m := widgets.NewMenu(helpDialog)
m := widgets.NewMenu()
m.TextFgColor = ui.ColorWhite
m.BorderLabel = "Help"
m.BorderFg = ui.ColorCyan
m.AddItems(widgets.NewMenuItems(helpDialog)...)
ui.Render(m)
ui.Handle("/sys/kbd/", func(ui.Event) {
ui.StopLoop()
@ -50,12 +51,15 @@ func SortMenu() {
ResetView()
defer ResetView()
m := widgets.NewMenu(SortFields())
m := widgets.NewMenu()
m.Selectable = true
m.SortItems = true
m.TextFgColor = ui.ColorWhite
m.BorderLabel = "Sort Field"
m.BorderFg = ui.ColorCyan
m.AddItems(widgets.NewMenuItems(SortFields())...)
// set cursor position to current sort field
current := config.Get("sortField")
for n, item := range m.Items {

10
sort.go
View File

@ -1,8 +1,6 @@
package main
import (
"sort"
"github.com/bcicen/ctop/config"
)
@ -17,13 +15,11 @@ var Sorters = map[string]sortMethod{
"net": func(c1, c2 *Container) bool { return sumNet(c1) < sumNet(c2) },
}
func SortFields() []string {
a := sort.StringSlice{}
func SortFields() (fields []string) {
for k := range Sorters {
a = append(a, k)
fields = append(fields, k)
}
sort.Sort(a)
return a
return fields
}
type Containers []*Container

View File

@ -23,6 +23,14 @@ func (m MenuItem) Text() string {
type MenuItems []MenuItem
// Create new MenuItems from string array
func NewMenuItems(a []string) (items MenuItems) {
for _, s := range a {
items = append(items, MenuItem{Val: s})
}
return items
}
// Sort methods for MenuItems
func (m MenuItems) Len() int { return len(m) }
func (m MenuItems) Swap(a, b int) { m[a], m[b] = m[b], m[a] }
@ -33,6 +41,7 @@ func (m MenuItems) Less(a, b int) bool {
type Menu struct {
ui.Block
Items MenuItems
SortItems bool // enable automatic sorting of menu items
TextFgColor ui.Attribute
TextBgColor ui.Attribute
Selectable bool
@ -40,28 +49,28 @@ type Menu struct {
padding Padding
}
func NewMenu(items []string) *Menu {
m := &Menu{
func NewMenu() *Menu {
return &Menu{
Block: *ui.NewBlock(),
TextFgColor: ui.ThemeAttr("par.text.fg"),
TextBgColor: ui.ThemeAttr("par.text.bg"),
Selectable: false,
CursorPos: 0,
padding: Padding{4, 2},
}
for _, s := range items {
m.Items = append(m.Items, MenuItem{Val: s})
}
sort.Sort(m.Items)
m.calcSize()
return m
}
func (m *Menu) SetItems(items []MenuItem) {
m.Items = items
sort.Sort(m.Items)
func (m *Menu) AddItems(items ...MenuItem) {
for _, i := range items {
m.Items = append(m.Items, i)
}
m.refresh()
}
// Sort menu items(if enabled) and re-calculate window size
func (m *Menu) refresh() {
if m.SortItems {
sort.Sort(m.Items)
}
m.calcSize()
}