screens.go RawHistoryFolder

1package core
2
3import (
4	"slices"
5
6	"github.com/bnema/neferwl/internal/ports"
7)
8
9// screen is one connected output: its monitor tree, scale, layer surfaces and
10// place in the global layout (ADR 011). Outputs are ordered by config
11// (output.<name>.*), then by connection; order places them (placeOutputs).
12type screen struct {
13	info            ports.OutputInfo
14	mon             *Monitor
15	scale, cfgScale float64
16	// transform is how the physical target holds the screen's logical
17	// output (output.<name>.transform); 90/270 swap width and height.
18	transform ports.BufferTransform
19	primary   bool
20	x, y      int  // logical origin in the global layout
21	off       bool // turned off by a client (output power management)
22	layers    []ports.LayerSurface
23	placed    []ports.SceneLayer
24	// capture holds the attached layers of the capture exclusion: shown over
25	// a fullscreen window (capture.go).
26	capture map[WindowID]bool
27	// capScene and capMarks are what the last scene carried (Capture and
28	// CaptureIndicators): immutable, shared by the next one while unchanged.
29	capScene *ports.SceneCapture
30	capMarks []ports.CaptureIndicator
31	// last is the scene published for this screen: an identical next one
32	// keeps its Seq (Scene.SameAs). Zero after a protected publish.
33	last ports.Scene
34	// settledLayout is the monitor's layout as of the last publish: what
35	// configures are sized from. shown is the same with the rect motions applied: what is
36	// drawn and hit-tested. They are the same slice while no rect motion
37	// runs. Both are built once per publish (refreshShown); shown is nil
38	// before the first publish, then callers measure the monitor's layout.
39	settledLayout, shown []Placement
40	// layoutBuf backs settledLayout (and shown, while no rect motion runs),
41	// rebuilt in place by every refreshShown; shownBuf and settledBuf back
42	// shown and settledLayout while rect motions run. All three are owner
43	// goroutine scratch reused across publishes: a Scene never aliases them
44	// (its windows are copied from the placements), and a caller that
45	// keeps a layout past the next publish copies it (Layout() is fresh).
46	layoutBuf, shownBuf, settledBuf []Placement
47	// leaveIDs is withLeaving's scratch list.
48	leaveIDs []WindowID
49	// rects are the running per-window rect motions (transition.go) of
50	// rectsWS, the workspace they began on (nil: the overview); created
51	// lazily.
52	rects   map[WindowID]rectMotion
53	rectsWS *Workspace
54}
55
56// springing reports whether a camera or rect spring runs on the screen.
57func (s *screen) springing() bool { return s.mon.springing() || len(s.rects) > 0 }
58
59// settled reports whether nothing moves the screen's layout: no swipe,
60// no slide, no rect motion.
61func (s *screen) settled() bool { return s.mon.settled() && len(s.rects) == 0 }
62
63// stopRects drops the rect motions: the windows are drawn where they are.
64func (s *screen) stopRects() { clear(s.rects); s.rectsWS = nil }
65
66// rectsOwner is what the screen's rect motions belong to: its workspace on
67// screen, or nil in the overview, where the rows change under the cards.
68func (s *screen) rectsOwner() *Workspace {
69	if s.mon.ov.open {
70		return nil
71	}
72	return s.mon.Current()
73}
74
75// shownLayout is the layout as drawn, for hit-testing and popups; before
76// the first publish it is the monitor's.
77func (s *screen) shownLayout() []Placement {
78	if s.shown != nil {
79		return s.shown
80	}
81	return s.mon.Layout()
82}
83
84func (s *screen) name() string { return s.info.Name }
85
86// modeSize is the physical mode size in the screen's logical orientation:
87// width and height swap for a 90/270 transform.
88func (s *screen) modeSize() (w, h int) {
89	return s.transform.Size(s.info.Width, s.info.Height)
90}
91
92// rect is the screen's place in the global logical layout.
93func (s *screen) rect() Rect {
94	o := s.mon.Output()
95	return Rect{X: s.x, Y: s.y, W: o.W, H: o.H}
96}
97
98func (s *screen) placement() ports.OutputPlacement {
99	r := s.rect()
100	return ports.OutputPlacement{Info: s.info, X: r.X, Y: r.Y, Width: r.W, Height: r.H, Scale: s.scale, Transform: s.transform, Primary: s.primary}
101}
102
103// setScale resizes the logical output; layer placement follows.
104func (s *screen) setScale(v float64) {
105	s.scale = SnapScale(v)
106	w, h := s.modeSize()
107	s.mon.SetOutput(logical(w, s.scale), logical(h, s.scale))
108	s.arrange()
109}
110
111// arrange places the layer surfaces and gives workspaces the usable area.
112func (s *screen) arrange() {
113	var usable ports.Rect
114	o := s.mon.Output()
115	s.placed, usable = arrangeLayers(o.W, o.H, s.layers)
116	s.mon.SetUsable(usable)
117}
118
119// order sorts screens by config order, then connection order, and places them
120// in the global layout (placeOutputs).
121func (c *Core) order() {
122	rank := func(s *screen) int {
123		if i := c.outputIndex(s.name()); i >= 0 {
124			return i
125		}
126		return len(c.cfg.Outputs)
127	}
128	focused := c.cur()
129	slices.SortStableFunc(c.screens, func(a, b *screen) int { return rank(a) - rank(b) })
130	c.focusScreen = slices.Index(c.screens, focused)
131	items := make([]placeItem, len(c.screens))
132	for i, s := range c.screens {
133		r := s.rect()
134		items[i].name, items[i].w, items[i].h = s.name(), r.W, r.H
135		if cfg, ok := c.outputConfig(s.name()); ok {
136			items[i].pos, items[i].anchor = cfg.Pos, cfg.Anchor
137		}
138	}
139	for i, p := range placeOutputs(items) {
140		c.screens[i].x, c.screens[i].y = p.X, p.Y
141	}
142}
143
144// outputIndex is the position of the output.<name> entry in the config, or
145// -1; names are unique in the config.
146func (c *Core) outputIndex(name string) int {
147	return slices.IndexFunc(c.cfg.Outputs, func(o ports.OutputConfig) bool { return o.Name == name })
148}
149
150// outputConfig returns the output.<name> entry.
151func (c *Core) outputConfig(name string) (ports.OutputConfig, bool) {
152	i := c.outputIndex(name)
153	if i < 0 {
154		return ports.OutputConfig{}, false
155	}
156	return c.cfg.Outputs[i], true
157}
158
159// layout lists the connected outputs; the placeholder is not one.
160func (c *Core) layout() ports.Layout {
161	l := make(ports.Layout, 0, len(c.screens))
162	for _, s := range c.screens {
163		if s.name() != "" {
164			l = append(l, s.placement())
165		}
166	}
167	return l
168}
169
170// cur is the focused screen: new windows open there and binds apply to it.
171func (c *Core) cur() *screen { return c.screens[c.focusScreen] }
172
173func (c *Core) screenIndex(name string) int {
174	return slices.IndexFunc(c.screens, func(s *screen) bool { return s.name() == name })
175}
176
177// screenAt is the index of the first connected screen containing the global
178// point, or -1. It does not allocate.
179func (c *Core) screenAt(x, y float64) int {
180	for i, s := range c.screens {
181		if s.name() == "" {
182			continue
183		}
184		r := s.rect()
185		if x >= float64(r.X) && x < float64(r.X+r.W) && y >= float64(r.Y) && y < float64(r.Y+r.H) {
186			return i
187		}
188	}
189	return -1
190}
191
192// clampPointer keeps the pointer on a screen: a point outside every screen
193// stays on the screen under (fromX, fromY), or the first one, clamped to its
194// edges.
195func (c *Core) clampPointer(fromX, fromY, x, y float64) (float64, float64) {
196	i := c.screenAt(x, y)
197	if i >= 0 {
198		return x, y
199	}
200	if i = c.screenAt(fromX, fromY); i < 0 {
201		i = slices.IndexFunc(c.screens, func(s *screen) bool { return s.name() != "" })
202		if i < 0 {
203			return x, y
204		}
205	}
206	r := c.screens[i].rect()
207	return min(max(x, float64(r.X)), float64(r.X+r.W)-1), min(max(y, float64(r.Y)), float64(r.Y+r.H)-1)
208}
209
210// screenOf returns the screen and workspace holding the window.
211func (c *Core) screenOf(id WindowID) (*screen, *Workspace) {
212	for _, s := range c.screens {
213		if w, _ := s.mon.find(id); w != nil {
214			return s, w
215		}
216	}
217	return nil, nil
218}
219
220// byName finds a named workspace on any screen.
221func (c *Core) byName(name string) (*screen, *Workspace) {
222	for _, s := range c.screens {
223		if w := s.mon.byName(name); w != nil {
224			return s, w
225		}
226	}
227	return nil, nil
228}
229
230// isPrimary reports output.<name>.primary.
231func (c *Core) isPrimary(name string) bool {
232	o, _ := c.outputConfig(name)
233	return o.Primary
234}
235
236// anyWindow reports whether any workspace holds a window.
237func (c *Core) anyWindow() bool {
238	for _, s := range c.screens {
239		for w := range s.mon.all() {
240			if !w.empty() {
241				return true
242			}
243		}
244	}
245	return false
246}
247
248// configScale is output.<name>.scale, else 1.
249func (c *Core) configScale(name string) float64 {
250	v := 1.0
251	if o, ok := c.outputConfig(name); ok && o.Scale != 0 {
252		v = o.Scale
253	}
254	return SnapScale(v)
255}
256
257// configTransform is output.<name>.transform, else 0.
258func (c *Core) configTransform(name string) ports.BufferTransform {
259	o, _ := c.outputConfig(name)
260	return o.Transform
261}
262
263// applyOutputConfig picks up output.<name>.scale and .transform when they
264// changed in the config. A new scale replaces any live scale-up/scale-down
265// adjustment; a transform alone keeps it.
266func (c *Core) applyOutputConfig() {
267	for _, s := range c.screens {
268		v, t := c.configScale(s.name()), c.configTransform(s.name())
269		if v == s.cfgScale && t == s.transform {
270			continue
271		}
272		scale := s.scale
273		if v != s.cfgScale {
274			scale = v
275		}
276		s.cfgScale, s.transform = v, t
277		s.setScale(scale)
278	}
279	c.order()
280}
281
282// addScreen handles a connected output or a new mode for a known one. The
283// first output takes over the placeholder screen core starts with; a new
284// monitor gets its named workspaces and takes its guests back.
285func (c *Core) addScreen(info ports.OutputInfo) {
286	if i := c.screenIndex(info.Name); i >= 0 {
287		s := c.screens[i]
288		s.info = info
289		if s.mon.Key != info.Key() {
290			// Another monitor on the same connector: key rules change.
291			s.mon.Key = info.Key()
292			c.settings(s.mon)
293		}
294		s.transform = c.configTransform(info.Name)
295		s.setScale(s.scale)
296		c.order()
297		return
298	}
299	var s *screen
300	if len(c.screens) == 1 && c.screens[0].name() == "" {
301		s = c.screens[0]
302		s.info = info
303	} else {
304		s = &screen{info: info, mon: newMonitorWithIDs(info.Name, info.Key(), &c.nextWorkspaceID)}
305		c.screens = append(c.screens, s)
306	}
307	s.off = c.offGone[info.Name]
308	delete(c.offGone, info.Name)
309	s.mon.Name, s.mon.Key = info.Name, info.Key()
310	c.settings(s.mon)
311	s.cfgScale = c.configScale(info.Name)
312	s.transform = c.configTransform(info.Name)
313	s.setScale(s.cfgScale)
314	s.primary = c.isPrimary(info.Name)
315	c.order()
316	// The primary output takes the focus while nothing is open yet
317	// (startup). Later, plugging it in never moves the user.
318	if s.primary && !c.anyWindow() {
319		c.focusScreen = slices.Index(c.screens, s)
320	}
321	c.named()
322}
323
324// removeScreen moves every workspace of an unplugged output to the focused
325// screen (another one if it was focused), numbered ones below its numbered
326// workspaces, hidden ones hidden. They remember their home and position and
327// return when it is plugged in again. The last output becomes the
328// placeholder again: it keeps its windows for the next output.
329func (c *Core) removeScreen(name string) {
330	i := c.screenIndex(name)
331	if i < 0 {
332		return
333	}
334	// A capture session's off-screen workspace of this output goes with it.
335	if c.configures.cw.sc == c.screens[i] {
336		c.configures.cw.reset()
337	}
338	if c.screens[i].off {
339		if c.offGone == nil {
340			c.offGone = map[string]bool{}
341		}
342		c.offGone[name] = true
343	}
344	if len(c.screens) == 1 {
345		c.screens[0].info = ports.OutputInfo{}
346		c.screens[0].layers = nil
347		// Nothing draws the placeholder: its springs would only wake the
348		// fallback timer, and start from the old output's geometry if an
349		// output came back.
350		c.screens[0].stopAnimations()
351		return
352	}
353	gone := c.screens[i]
354	if c.swipe != nil && c.swipe.screen == gone {
355		// Its slide would stay on the workspaces the host adopts.
356		c.dropSwipe()
357		c.swipe = nil
358	}
359	focused := c.cur()
360	c.screens = slices.Delete(c.screens, i, i+1)
361	c.focusScreen = max(slices.Index(c.screens, focused), 0)
362	host := c.cur()
363	for pos, w := range gone.mon.Workspaces {
364		if w.empty() && w.Name == "" {
365			continue
366		}
367		switch {
368		case host.mon.matches(w.home):
369			// A guest from the host goes home.
370			w.home = ""
371			host.mon.adopt(w, false, w.homePos)
372			continue
373		case w.home == "":
374			w.home, w.homePos = gone.info.Key(), pos
375		}
376		host.mon.adopt(w, false, len(host.mon.Workspaces))
377	}
378	for _, w := range gone.mon.hidden {
379		switch {
380		case host.mon.matches(w.home):
381			w.home = ""
382		case w.home == "":
383			w.home = gone.info.Key()
384		}
385		host.mon.adopt(w, true, 0)
386	}
387	c.order()
388}
389
390// settleGuests returns guests to their connected home monitor, at their
391// original positions. A guest on screen stays until the user leaves it
392// (golden rule: automatic events never move the user).
393func (c *Core) settleGuests() {
394	for _, home := range c.screens {
395		type guest struct {
396			w, anchor *Workspace
397			host      *Monitor
398			hidden    bool
399		}
400		var list []guest
401		for _, host := range c.screens {
402			if host == home {
403				continue
404			}
405			for w := range host.mon.all() {
406				if home.mon.matches(w.home) && host.mon.Current() != w {
407					list = append(list, guest{w: w, anchor: w.overviewAfter, host: host.mon, hidden: host.mon.isHidden(w)})
408				}
409			}
410		}
411		// Snapshot every anchor before take normalizes a host and clears
412		// references to numbered workspaces returning alongside named rows.
413		for _, g := range list {
414			g.host.take(g.w)
415		}
416		slices.SortStableFunc(list, func(a, b guest) int { return a.w.homePos - b.w.homePos })
417		// A monitor showing an empty workspace (just plugged in) shows
418		// its first returning workspace instead.
419		idle := home.mon.Current().empty() && home.mon.Current().Name == ""
420		for _, g := range list {
421			g.w.home = ""
422			home.mon.adopt(g.w, g.hidden, g.w.homePos)
423			if idle && !g.hidden {
424				home.mon.show(g.w)
425				idle = false
426			}
427		}
428		for _, g := range list {
429			if g.hidden && indexOf(home.mon.Workspaces, g.anchor) >= 0 {
430				g.w.overviewAfter = g.anchor
431			}
432		}
433	}
434}
435
436// named applies the named workspaces from config. One that exists stays on
437// its screen; a new one is created on its home monitor, or on the first
438// screen as a guest when its home is not connected.
439func (c *Core) named() {
440	target := map[string]*screen{}
441	for _, spec := range c.specs {
442		if s, _ := c.byName(spec.Name); s != nil {
443			target[spec.Name] = s
444			continue
445		}
446		target[spec.Name] = c.screens[0]
447		for _, s := range c.screens {
448			if s.mon.matches(spec.Monitor) {
449				target[spec.Name] = s
450			}
451		}
452	}
453	for _, s := range c.screens {
454		var mine []NamedWorkspace
455		for _, spec := range c.specs {
456			if target[spec.Name] == s {
457				mine = append(mine, spec)
458			}
459		}
460		s.mon.SetNamed(mine)
461		s.mon.useSpecs(c.specs)
462	}
463	for _, spec := range c.specs {
464		s, w := c.byName(spec.Name)
465		w.home = ""
466		if spec.Monitor != "" && !s.mon.matches(spec.Monitor) {
467			w.home = spec.Monitor
468		}
469	}
470}
471
472// bringNamed prepares a "workspace <name>" toggle from the focused screen.
473// The workspace goes to its home monitor when connected, else to the focused
474// screen; that screen takes the focus. It reports true when the workspace
475// is already on screen there after a focus change: reaching it must not
476// toggle it away.
477func (c *Core) bringNamed(name string) bool {
478	src, w := c.byName(name)
479	i := slices.IndexFunc(c.specs, func(s NamedWorkspace) bool { return s.Name == name })
480	if w == nil || i < 0 {
481		return false
482	}
483	to, home := c.focusScreen, c.specs[i].Monitor
484	if h := slices.IndexFunc(c.screens, func(s *screen) bool { return s.mon.matches(home) }); h >= 0 {
485		to, home = h, ""
486	}
487	dst := c.screens[to]
488	if to != c.focusScreen {
489		c.focusScreen = to
490		if src == dst && dst.mon.Current() == w {
491			return true
492		}
493	}
494	if src != dst {
495		moveNamed(src, dst, w, home)
496	}
497	return false
498}
499
500// moveNamed moves the named workspace w from src to dst, without changing
501// what dst shows. home is its new w.home: a guest keeps waiting for its
502// home; any other forgets the output it was unplugged from.
503func moveNamed(src, dst *screen, w *Workspace, home string) {
504	hidden := src.mon.isHidden(w)
505	src.mon.take(w)
506	w.home = home
507	dst.mon.adopt(w, hidden, len(dst.mon.Workspaces))
508}
509
510// settings applies output-wide config to a monitor.
511func (c *Core) settings(m *Monitor) {
512	rules := c.cfg.Layout.LayoutRules
513	for _, o := range c.cfg.Layout.Outputs {
514		if m.matches(o.Output) {
515			rules = o.Over(rules)
516		}
517	}
518	m.SetOverflow(Overflow(rules.Overflow))
519	m.SetMaxColumns(rules.MaxColumns)
520	m.SetPresets(c.presets)
521	m.SetGaps(c.cfg.Layout.Gaps)
522	m.SetBorder(c.cfg.Border.Width)
523	m.SetStash(c.cfg.Stash.Width, c.cfg.Stash.Gap)
524	m.SetStashCapture(c.cfg.Stash.Capture)
525	m.SetFollowMove(c.cfg.Focus.FollowMove)
526}
527
528// direction is where a monitor action looks for a neighbor screen.
529type direction uint8
530
531const (
532	dirLeft direction = iota + 1
533	dirRight
534	dirUp
535	dirDown
536)
537
538// neighbor returns the index of the screen next to the focused one in
539// direction d, or -1 at the edge. Candidates lie fully beyond the focused
540// screen's edge; one sharing part of that edge wins over a diagonal one, then
541// the smallest gap, the largest shared edge, the closest centers and the
542// lowest index decide. Overlapping outputs (for instance two anchored to the
543// same reference) are reached only when no screen lies fully beyond the edge
544// in that direction: a second pass then takes the screens whose rectangle
545// intersects the focused one and whose center is strictly beyond the focused
546// center, ranked the same way with a gap of 0. A screen that does have a
547// strict candidate never falls back, so an overlapping one can stay out of
548// reach. Screens with the same center on the axis are unreachable by direction
549// (the pointer still reaches them). There is no wrap.
550func (c *Core) neighbor(d direction) int {
551	if d < dirLeft || d > dirDown {
552		return -1
553	}
554	// span is the extent of s along the move (lo, hi) and across it.
555	span := func(s *screen) (lo, hi, clo, chi int) {
556		r := s.rect()
557		if d == dirUp || d == dirDown {
558			return r.Y, r.Y + r.H, r.X, r.X + r.W
559		}
560		return r.X, r.X + r.W, r.Y, r.Y + r.H
561	}
562	lo, hi, clo, chi := span(c.cur())
563	pick := func(fallback bool) int {
564		best, bestKey := -1, [4]int{}
565		for i, s := range c.screens {
566			if i == c.focusScreen || s.name() == "" {
567				continue
568			}
569			l, h, cl, ch := span(s)
570			gap := l - hi
571			beyond := l+h > lo+hi // centers, doubled
572			if d == dirLeft || d == dirUp {
573				gap = lo - h
574				beyond = l+h < lo+hi
575			}
576			if fallback {
577				if !beyond || min(hi, h)-max(lo, l) <= 0 || min(chi, ch)-max(clo, cl) <= 0 {
578					continue
579				}
580				gap = 0
581			} else if gap < 0 {
582				continue
583			}
584			overlap := min(chi, ch) - max(clo, cl)
585			diagonal := 0
586			if overlap <= 0 {
587				diagonal = 1
588			}
589			key := [4]int{diagonal, gap, -max(overlap, 0), abs(cl + ch - clo - chi)}
590			if best < 0 || slices.Compare(key[:], bestKey[:]) < 0 {
591				best, bestKey = i, key
592			}
593		}
594		return best
595	}
596	if i := pick(false); i >= 0 {
597		return i
598	}
599	return pick(true)
600}
601
602// moveWorkspace moves the workspace on screen to the neighbor screen, where
603// it is appended and shown; it becomes its new home (ADR 011).
604func (c *Core) moveWorkspace(d direction) {
605	to := c.neighbor(d)
606	if to < 0 {
607		return
608	}
609	from := c.cur()
610	w := from.mon.Current()
611	if w.empty() && w.Name == "" {
612		return
613	}
614	hidden := from.mon.isHidden(w)
615	from.mon.take(w)
616	w.home = ""
617	dst := c.screens[to]
618	dst.mon.adopt(w, hidden, len(dst.mon.Workspaces))
619	dst.mon.show(w)
620	c.focusScreen = to
621}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 23

Tags 10

↑↓ moveenter openesc close