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 // Read at once, into publish's scratch: the snapshot holds no
42 // placement.
43 c.realBuf = m.layoutInto(c.realBuf)
44 for _, p := range c.realBuf {
45 shown[p.ID] = onScreen(p, m.Frame())
46 }
47 for w := range m.all() {
48 n := indexOf(m.Workspaces, w) + 1
49 for _, id := range w.windows() {
50 rec := c.windows.lookup(id)
51 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)}
52 if i := w.stashIndex(id); i >= 0 {
53 v.StashIndex, v.StashCount, v.Hidden = i+1, len(w.Stash), w.stashHidden
54 }
55 st.Windows = append(st.Windows, v)
56 }
57 }
58 }
59 slices.SortFunc(st.Windows, func(a, b ports.WindowState) int { return cmp.Compare(a.ID, b.ID) })
60 for i := range st.Windows {
61 if st.Windows[i].ID == focus && focus != 0 {
62 w := st.Windows[i]
63 st.Window = &w
64 }
65 }
66 return st
67}
68
69// numbered counts numbered workspaces, without the trailing spare one
70// unless it is on screen.
71func numbered(m *Monitor) int {
72 n := len(m.Workspaces)
73 if last := m.Workspaces[n-1]; n > 1 && last.empty() && last.Name == "" && m.Current() != last {
74 n--
75 }
76 return n
77}