main
6d86999 ยท 6 months ago 26 commits
  1package app
  2
  3import (
  4	"github.com/The-Robin-Hood/ufWall/internal/keys"
  5	"github.com/The-Robin-Hood/ufWall/internal/sections"
  6	"github.com/The-Robin-Hood/ufWall/internal/sections/rules"
  7	"github.com/The-Robin-Hood/ufWall/internal/ufw"
  8
  9	"github.com/charmbracelet/bubbles/key"
 10	tea "github.com/charmbracelet/bubbletea"
 11)
 12
 13func (m model) Init() tea.Cmd {
 14	return nil
 15}
 16
 17func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 18	switch msg := msg.(type) {
 19
 20	case tea.KeyMsg:
 21
 22		if !m.isMenuOpen() {
 23			switch {
 24			case key.Matches(msg, keys.Bindings.NextSection):
 25				m.blurAllSections()
 26				m.activeSection = (m.activeSection + 1) % 3
 27				m.focusActiveSection()
 28				return m, nil
 29
 30			case key.Matches(msg, keys.Bindings.PrevSection):
 31				m.blurAllSections()
 32				m.activeSection = (m.activeSection - 1 + 3) % 3
 33				m.focusActiveSection()
 34				return m, nil
 35
 36			case key.Matches(msg, keys.Bindings.Refresh):
 37				return m, keys.Refresh()
 38
 39			case key.Matches(msg, keys.Bindings.Quit):
 40				return m, tea.Quit
 41
 42			case key.Matches(msg, keys.Bindings.Execute):
 43				if !m.stats.Active {
 44					ufw.Enable()
 45					return m, keys.Refresh()
 46				}
 47			}
 48		}
 49
 50		switch m.activeSection {
 51		case sections.StatsSection:
 52			newStats, sectionCmd := m.statsSection.Update(msg)
 53			m.statsSection = newStats
 54			return m, sectionCmd
 55
 56		case sections.PolicySection:
 57			newPolicy, sectionCmd := m.policySection.Update(msg, m.policy)
 58			m.policySection = newPolicy
 59			return m, sectionCmd
 60
 61		case sections.RulesSection:
 62			newRules, sectionCmd := m.rulesSection.Update(msg, rules.RulesData{IPv4: m.ipv4Rules, IPv6: m.ipv6Rules})
 63			m.rulesSection = newRules
 64			return m, sectionCmd
 65		}
 66
 67	case keys.RefreshMsg:
 68		data := ufw.GetUFWData()
 69		m.rules = data.Rules
 70		m.ipv4Rules = data.IPv4Rules
 71		m.ipv6Rules = data.IPv6Rules
 72		m.policy = data.Policy
 73		m.stats = data.Stats
 74		m.err = data.Error
 75		return m, nil
 76
 77	case tea.WindowSizeMsg:
 78		m.width = msg.Width
 79		m.height = msg.Height
 80		return m, nil
 81	}
 82
 83	return m, nil
 84}
 85
 86func (m *model) blurAllSections() {
 87	m.statsSection.Blur()
 88	m.policySection.Blur()
 89	m.rulesSection.Blur()
 90}
 91
 92func (m *model) focusActiveSection() {
 93	switch m.activeSection {
 94	case sections.StatsSection:
 95		m.statsSection.Focus()
 96	case sections.PolicySection:
 97		m.policySection.Focus()
 98	case sections.RulesSection:
 99		m.rulesSection.Focus()
100	}
101}
102
103func (m *model) isMenuOpen() bool {
104	return m.statsSection.HasOpenMenu() || m.rulesSection.HasOpenMenu()
105}