package main import ( "fmt" "github.com/godbus/dbus/v5" "github.com/godbus/dbus/v5/introspect" "github.com/rivo/tview" ) type Editors struct { conn *dbus.Conn // Assigned from app. env *[]string // Assigned from app. setFocusFunc func(tview.Primitive) // Calls app's SetFocus editors []*Term lastFocusedEditor int *tview.Flex } func (s *Editors) Setup() error { // UI s.Flex = tview.NewFlex() // D-Bus if err := app.Conn.ExportMethodTable(map[string]any{ "SetFocus": func() *dbus.Error { if editor := s.GetLastFocusedEditor(); editor != nil { s.setFocusFunc(editor) } return nil }, "SendString": func(str string) *dbus.Error { if editor := s.GetLastFocusedEditor(); editor != nil { return editor.SendString(str) } return nil }, "SendBytes": func(b []byte) *dbus.Error { if editor := s.GetLastFocusedEditor(); editor != nil { return editor.SendBytes(b) } return nil }, }, dbus.ObjectPath("/panels/editor/active"), "net.kettek.Aight.Panel"); err != nil { return err } if err := app.Conn.Export(introspect.Introspectable(termIntro), dbus.ObjectPath("/panels/editor/active"), "org.freedesktop.DBus.Introspectable"); err != nil { return err } return nil } func (s *Editors) Cleanup() error { // D-Bus for _, editor := range s.editors { editor.RemoveFromConn(s.conn) } s.conn.Export(nil, dbus.ObjectPath("/panels/editor/active"), "org.freedesktop.DBus.Introspectable") s.conn.Export(nil, dbus.ObjectPath("/panels/editor/active"), "net.kettek.Aight.Status") return nil } func (s *Editors) AddEditor() error { id := len(s.editors) editor := NewTerm(fmt.Sprintf("editor/%d", id), cfg.Editor) editor.SetFocusFunc(func() { s.lastFocusedEditor = id }) // Add focus handler. if err := s.conn.ExportMethodTable(map[string]any{ "SetFocus": func() *dbus.Error { if editor := s.GetEditorByIndex(s.lastFocusedEditor); editor != nil { s.setFocusFunc(editor) } return nil }, "SendString": func(s string) *dbus.Error { return editor.SendString(s) }, "SendBytes": func(b []byte) *dbus.Error { return editor.SendBytes(b) }, }, dbus.ObjectPath(fmt.Sprintf("/panels/editor/%d", id)), "net.kettek.Aight.Panel"); err != nil { return err } // Start 'er up. if err := editor.Start(*s.env); err != nil { return err } s.editors = append(s.editors, editor) // Add to UI. s.AddItem(editor, 0, 1, true) return editor.AddToConn(s.conn) } func (s *Editors) GetEditorByIndex(id int) *Term { if id > len(s.editors) { return nil } return s.editors[id] } func (s *Editors) GetLastFocusedEditor() *Term { return s.GetEditorByIndex(s.lastFocusedEditor) }