v0.4.0 b6be3a8

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	focused := c.cur()
355	c.screens = slices.Delete(c.screens, i, i+1)
356	c.focusScreen = max(slices.Index(c.screens, focused), 0)
357	host := c.cur()
358	for pos, w := range gone.mon.Workspaces {
359		if w.empty() && w.Name == "" {
360			continue
361		}
362		switch {
363		case host.mon.matches(w.home):
364			// A guest from the host goes home.
365			w.home = ""
366			host.mon.adopt(w, false, w.homePos)
367			continue
368		case w.home == "":
369			w.home, w.homePos = gone.info.Key(), pos
370		}
371		host.mon.adopt(w, false, len(host.mon.Workspaces))
372	}
373	for _, w := range gone.mon.hidden {
374		switch {
375		case host.mon.matches(w.home):
376			w.home = ""
377		case w.home == "":
378			w.home = gone.info.Key()
379		}
380		host.mon.adopt(w, true, 0)
381	}
382	c.order()
383}
384
385// settleGuests returns guests to their connected home monitor, at their
386// original positions. A guest on screen stays until the user leaves it
387// (golden rule: automatic events never move the user).
388func (c *Core) settleGuests() {
389	for _, home := range c.screens {
390		type guest struct {
391			w, anchor *Workspace
392			host      *Monitor
393			hidden    bool
394		}
395		var list []guest
396		for _, host := range c.screens {
397			if host == home {
398				continue
399			}
400			for w := range host.mon.all() {
401				if home.mon.matches(w.home) && host.mon.Current() != w {
402					list = append(list, guest{w: w, anchor: w.overviewAfter, host: host.mon, hidden: host.mon.isHidden(w)})
403				}
404			}
405		}
406		// Snapshot every anchor before take normalizes a host and clears
407		// references to numbered workspaces returning alongside named rows.
408		for _, g := range list {
409			g.host.take(g.w)
410		}
411		slices.SortStableFunc(list, func(a, b guest) int { return a.w.homePos - b.w.homePos })
412		// A monitor showing an empty workspace (just plugged in) shows
413		// its first returning workspace instead.
414		idle := home.mon.Current().empty() && home.mon.Current().Name == ""
415		for _, g := range list {
416			g.w.home = ""
417			home.mon.adopt(g.w, g.hidden, g.w.homePos)
418			if idle && !g.hidden {
419				home.mon.show(g.w)
420				idle = false
421			}
422		}
423		for _, g := range list {
424			if g.hidden && indexOf(home.mon.Workspaces, g.anchor) >= 0 {
425				g.w.overviewAfter = g.anchor
426			}
427		}
428	}
429}
430
431// named applies the named workspaces from config. One that exists stays on
432// its screen; a new one is created on its home monitor, or on the first
433// screen as a guest when its home is not connected.
434func (c *Core) named() {
435	target := map[string]*screen{}
436	for _, spec := range c.specs {
437		if s, _ := c.byName(spec.Name); s != nil {
438			target[spec.Name] = s
439			continue
440		}
441		target[spec.Name] = c.screens[0]
442		for _, s := range c.screens {
443			if s.mon.matches(spec.Monitor) {
444				target[spec.Name] = s
445			}
446		}
447	}
448	for _, s := range c.screens {
449		var mine []NamedWorkspace
450		for _, spec := range c.specs {
451			if target[spec.Name] == s {
452				mine = append(mine, spec)
453			}
454		}
455		s.mon.SetNamed(mine)
456		s.mon.useSpecs(c.specs)
457	}
458	for _, spec := range c.specs {
459		s, w := c.byName(spec.Name)
460		w.home = ""
461		if spec.Monitor != "" && !s.mon.matches(spec.Monitor) {
462			w.home = spec.Monitor
463		}
464	}
465}
466
467// bringNamed prepares a "workspace <name>" toggle from the focused screen.
468// The workspace goes to its home monitor when connected, else to the focused
469// screen; that screen takes the focus. It reports true when the workspace
470// is already on screen there after a focus change: reaching it must not
471// toggle it away.
472func (c *Core) bringNamed(name string) bool {
473	src, w := c.byName(name)
474	i := slices.IndexFunc(c.specs, func(s NamedWorkspace) bool { return s.Name == name })
475	if w == nil || i < 0 {
476		return false
477	}
478	to, home := c.focusScreen, c.specs[i].Monitor
479	if h := slices.IndexFunc(c.screens, func(s *screen) bool { return s.mon.matches(home) }); h >= 0 {
480		to, home = h, ""
481	}
482	dst := c.screens[to]
483	if to != c.focusScreen {
484		c.focusScreen = to
485		if src == dst && dst.mon.Current() == w {
486			return true
487		}
488	}
489	if src != dst {
490		moveNamed(src, dst, w, home)
491	}
492	return false
493}
494
495// moveNamed moves the named workspace w from src to dst, without changing
496// what dst shows. home is its new w.home: a guest keeps waiting for its
497// home; any other forgets the output it was unplugged from.
498func moveNamed(src, dst *screen, w *Workspace, home string) {
499	hidden := src.mon.isHidden(w)
500	src.mon.take(w)
501	w.home = home
502	dst.mon.adopt(w, hidden, len(dst.mon.Workspaces))
503}
504
505// settings applies output-wide config to a monitor.
506func (c *Core) settings(m *Monitor) {
507	rules := c.cfg.Layout.LayoutRules
508	for _, o := range c.cfg.Layout.Outputs {
509		if m.matches(o.Output) {
510			rules = o.Over(rules)
511		}
512	}
513	m.SetOverflow(Overflow(rules.Overflow))
514	m.SetMaxColumns(rules.MaxColumns)
515	m.SetPresets(c.presets)
516	m.SetGaps(c.cfg.Layout.Gaps)
517	m.SetBorder(c.cfg.Border.Width)
518	m.SetStash(c.cfg.Stash.Width, c.cfg.Stash.Gap)
519	m.SetStashCapture(c.cfg.Stash.Capture)
520	m.SetFollowMove(c.cfg.Focus.FollowMove)
521}
522
523// direction is where a monitor action looks for a neighbor screen.
524type direction uint8
525
526const (
527	dirLeft direction = iota + 1
528	dirRight
529	dirUp
530	dirDown
531)
532
533// neighbor returns the index of the screen next to the focused one in
534// direction d, or -1 at the edge. Candidates lie fully beyond the focused
535// screen's edge; one sharing part of that edge wins over a diagonal one, then
536// the smallest gap, the largest shared edge, the closest centers and the
537// lowest index decide. Overlapping outputs (for instance two anchored to the
538// same reference) are reached only when no screen lies fully beyond the edge
539// in that direction: a second pass then takes the screens whose rectangle
540// intersects the focused one and whose center is strictly beyond the focused
541// center, ranked the same way with a gap of 0. A screen that does have a
542// strict candidate never falls back, so an overlapping one can stay out of
543// reach. Screens with the same center on the axis are unreachable by direction
544// (the pointer still reaches them). There is no wrap.
545func (c *Core) neighbor(d direction) int {
546	if d < dirLeft || d > dirDown {
547		return -1
548	}
549	// span is the extent of s along the move (lo, hi) and across it.
550	span := func(s *screen) (lo, hi, clo, chi int) {
551		r := s.rect()
552		if d == dirUp || d == dirDown {
553			return r.Y, r.Y + r.H, r.X, r.X + r.W
554		}
555		return r.X, r.X + r.W, r.Y, r.Y + r.H
556	}
557	lo, hi, clo, chi := span(c.cur())
558	pick := func(fallback bool) int {
559		best, bestKey := -1, [4]int{}
560		for i, s := range c.screens {
561			if i == c.focusScreen || s.name() == "" {
562				continue
563			}
564			l, h, cl, ch := span(s)
565			gap := l - hi
566			beyond := l+h > lo+hi // centers, doubled
567			if d == dirLeft || d == dirUp {
568				gap = lo - h
569				beyond = l+h < lo+hi
570			}
571			if fallback {
572				if !beyond || min(hi, h)-max(lo, l) <= 0 || min(chi, ch)-max(clo, cl) <= 0 {
573					continue
574				}
575				gap = 0
576			} else if gap < 0 {
577				continue
578			}
579			overlap := min(chi, ch) - max(clo, cl)
580			diagonal := 0
581			if overlap <= 0 {
582				diagonal = 1
583			}
584			key := [4]int{diagonal, gap, -max(overlap, 0), abs(cl + ch - clo - chi)}
585			if best < 0 || slices.Compare(key[:], bestKey[:]) < 0 {
586				best, bestKey = i, key
587			}
588		}
589		return best
590	}
591	if i := pick(false); i >= 0 {
592		return i
593	}
594	return pick(true)
595}
596
597// moveWorkspace moves the workspace on screen to the neighbor screen, where
598// it is appended and shown; it becomes its new home (ADR 011).
599func (c *Core) moveWorkspace(d direction) {
600	to := c.neighbor(d)
601	if to < 0 {
602		return
603	}
604	from := c.cur()
605	w := from.mon.Current()
606	if w.empty() && w.Name == "" {
607		return
608	}
609	hidden := from.mon.isHidden(w)
610	from.mon.take(w)
611	w.home = ""
612	dst := c.screens[to]
613	dst.mon.adopt(w, hidden, len(dst.mon.Workspaces))
614	dst.mon.show(w)
615	c.focusScreen = to
616}

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 26

Tags 10

↑↓ moveenter openesc close