1package core
2
3import (
4 "cmp"
5 "reflect"
6 "slices"
7
8 "github.com/bnema/neferwl/internal/ports"
9)
10
11// publishState sends the script-facing snapshot when it changed.
12func (c *Core) publishState() {
13 if c.ch.State == nil {
14 return
15 }
16 st := c.state()
17 if reflect.DeepEqual(st, c.sentState) {
18 return
19 }
20 c.sentState = st
21 latest(c.ch.State, st)
22}
23
24// state builds the snapshot. The placeholder screen is not an output.
25func (c *Core) state() ports.State {
26 st := ports.State{Output: c.cur().name(), Outputs: []ports.OutputState{}, Windows: []ports.WindowState{}}
27 focus, _ := c.cur().mon.Focused()
28 for _, s := range c.screens {
29 if s.name() == "" {
30 continue
31 }
32 m := s.mon
33 cur := m.Current()
34 o := ports.OutputState{Name: s.name(), Count: numbered(m), Workspace: cur.Name, WorkspaceID: cur.ID}
35 if i := indexOf(m.Workspaces, cur); i >= 0 {
36 o.Active = i + 1
37 }
38 st.Outputs = append(st.Outputs, o)
39 // Visible follows the configures: drawn on the output.
40 shown := map[WindowID]bool{}
41 for _, p := range m.Layout() {
42 shown[p.ID] = onScreen(p, m.Frame())
43 }
44 for w := range m.all() {
45 n := indexOf(m.Workspaces, w) + 1
46 for _, id := range w.windows() {
47 rec := c.windows.lookup(id)
48 v := ports.WindowState{ID: id, AppID: rec.client.AppID, PID: rec.client.PID, Output: s.name(), Workspace: n, WorkspaceID: w.ID, WorkspaceName: w.Name, Visible: shown[id], IdleInhibit: rec.idleInhibit, Floating: w.isFloat(id)}
49 if i := w.stashIndex(id); i >= 0 {
50 v.StashIndex, v.StashCount, v.Hidden = i+1, len(w.Stash), w.stashHidden
51 }
52 st.Windows = append(st.Windows, v)
53 }
54 }
55 }
56 slices.SortFunc(st.Windows, func(a, b ports.WindowState) int { return cmp.Compare(a.ID, b.ID) })
57 for i := range st.Windows {
58 if st.Windows[i].ID == focus && focus != 0 {
59 w := st.Windows[i]
60 st.Window = &w
61 }
62 }
63 return st
64}
65
66// numbered counts numbered workspaces, without the trailing spare one
67// unless it is on screen.
68func numbered(m *Monitor) int {
69 n := len(m.Workspaces)
70 if last := m.Workspaces[n-1]; n > 1 && last.empty() && last.Name == "" && m.Current() != last {
71 n--
72 }
73 return n
74}