Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

Settings → Displays: display numbers, Identify (the number shown big on each monitor, sdk/displaysui.jsx in the notification layer), magnetic arrangement (sdk/displaylayout.js: edge-to-edge and alignment snapping, drops that never overlap or leave a display apart; display_layout_test.mjs 26/26); outputs.c out_fits/out_valid, a fitting position kept exactly, a chain of displays no longer pulled back to the main one (outputs_test 131/131); docs and help

Federico Pereira46287064574a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index acbb75d..89747e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,12 @@ of the matching [GitHub release](https://github.com/lordbasex/LordOS/releases),
### Added
+- **Settings → Displays: numbers, Identify and snapping.** With more than one display each one has a
+ number (the main display is 1); clicking a display in the arrangement, or Identify, shows its number
+ big on that monitor for a moment, so you know which screen is which. Dragging a display snaps it edge
+ to edge and aligns it with the others (side by side, stacked or offset), and a drop never leaves two
+ displays overlapping or apart. The server keeps a position that fits exactly, and a chain of three
+ displays is no longer pulled back onto the main one on every change.
- **A fuller Window menu, in both themes.** Minimize, Zoom, Fill, Center; **Move & Resize** with the
left, right, top and bottom halves, the quarters and thirds, arrangements of two windows (left and
right, right and left, top and bottom, bottom and top) or four (quarters) with the windows behind it,
diff --git a/apps/settings/Displays.jsx b/apps/settings/Displays.jsx
index 52333be..bb492b8 100644
--- a/apps/settings/Displays.jsx
+++ b/apps/settings/Displays.jsx
@@ -8,7 +8,8 @@
import {
View, Text, useTheme, useLocale, useSettings, Slider, Toggle, admin, useDisplays, applyDisplay, DisplayGlyph, addListener,
arrangeDisplay, setDisplayMirror, setMainDisplay, setCaptureAllDisplays, typeScale, spacing,
- nightPrefs, nightActive, setNightManual, previewNight, nightTick, sunTimes, formatTime,
+ nightPrefs, nightActive, setNightManual, previewNight, nightTick, sunTimes, formatTime, Button,
+ identifyDisplays, IDENTIFY_MS, displayNumbers, snapDisplay, resolveDrop, displayPlacementOk, SNAP_PREVIEW_PX,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
import { Section, SettingRow, PopUp, Note, Stack, TimeField } from './ui.jsx';
@@ -37,30 +38,57 @@ function useWidth(ref, fallback) {
return w;
}
-// The arrangement (docs/DISPLAYS.md): every active display at its place in the desktop, proportional to
-// its logical size, drawn as a small screen with its name and resolution. Drag one to move it next to
-// the others (lord-server snaps it: edges touch, no overlap); click one to choose it below. The white
-// bar marks the main display (menu bar, Dock).
-function Arrangement({ outs, sel, onSelect, mirror, t }) {
+// The arrangement (docs/DISPLAYS.md, "Numbers, identify and snapping"): every active display at its
+// place in the desktop, proportional to its logical size, drawn as a small screen with its number
+// (with several displays), name and resolution. Dragging is magnetic (sdk/displaylayout.js): edges
+// stick edge to edge and tops/bottoms, lefts/rights and centers align within 12 preview px; on drop
+// the display always touches another and never overlaps one, and lord-server keeps that position.
+// A click selects a display and shows its number on the real screen (identifyDisplays). The white bar
+// marks the main display (menu bar, Dock).
+function Arrangement({ outs, sel, onSelect, mirror, nums, t }) {
const act = outs.filter((o) => o.active && o.w);
const box = useRef(null);
const W = useWidth(box, 520), H = 180;
- const [drag, setDrag] = useState(null); // { id, x, y } in logical px while dragging
+ const [drag, setDrag] = useState(null); // { id, x, y, view } in logical px while dragging
+ const [flash, setFlash] = useState(null); // the tile just identified
const st = useRef(null);
+ const actRef = useRef(act);
+ actRef.current = act;
+ const several = act.length > 1 && !mirror;
+ const identify = (id) => {
+ if (!identifyDisplays([id])) return;
+ setFlash(id);
+ setTimeout(() => setFlash((f) => (f === id ? null : f)), IDENTIFY_MS);
+ };
useEffect(() => {
+ // where the dragged display wants to be, from the pointer, in logical px
+ const want = (d, e) => ({ x: d.ox + (e.x - d.px) / d.view.k, y: d.oy + (e.y - d.py) / d.view.k });
+ const rectsOf = (d) => {
+ const list = actRef.current;
+ return { rects: list.map((o) => ({ x: o.x, y: o.y, w: o.w, h: o.h })), i: list.findIndex((o) => o.id === d.id) };
+ };
const offMove = addListener('pointermove', (e) => {
const d = st.current;
if (!d) return;
if (!d.moved && Math.hypot(e.x - d.px, e.y - d.py) < 4) return;
d.moved = true;
- const r = arrangeDisplay(d.id, d.ox + (e.x - d.px) / d.k, d.oy + (e.y - d.py) / d.k, false);
- if (r) setDrag({ id: d.id, x: r.x, y: r.y });
+ const { rects, i } = rectsOf(d);
+ if (i < 0) return;
+ const w = want(d, e);
+ const p = snapDisplay(rects, i, w.x, w.y, SNAP_PREVIEW_PX / d.view.k);
+ setDrag({ id: d.id, x: p.x, y: p.y, ok: displayPlacementOk(rects, i, p.x, p.y), view: d.view });
});
const offUp = addListener('pointerup', (e) => {
const d = st.current;
st.current = null;
if (!d) return;
- if (d.moved) arrangeDisplay(d.id, d.ox + (e.x - d.px) / d.k, d.oy + (e.y - d.py) / d.k, true);
+ if (!d.moved) { if (d.identify) d.identify(d.id); return; }
+ const { rects, i } = rectsOf(d);
+ if (i < 0) { setDrag(null); return; }
+ const w = want(d, e);
+ const p = resolveDrop(rects, i, w.x, w.y, SNAP_PREVIEW_PX / d.view.k);
+ setDrag({ id: d.id, x: p.x, y: p.y, ok: true, view: d.view });
+ arrangeDisplay(d.id, p.x, p.y, true);
setTimeout(() => setDrag(null), 400); // until the new list arrives
});
return () => { offMove(); offUp(); };
@@ -72,26 +100,36 @@ function Arrangement({ outs, sel, onSelect, mirror, t }) {
// mirror: the displays are drawn one behind the other; extend: at their place
const pos = (o, i) => (mirror ? { x: i * 18, y: i * 14 } : drag && drag.id === o.id ? drag : { x: o.x, y: o.y });
const boxes = act.map((o, i) => ({ o, ...pos(o, i) }));
- const x0 = Math.min(...boxes.map((b) => b.x)), y0 = Math.min(...boxes.map((b) => b.y));
- const x1 = Math.max(...boxes.map((b) => b.x + b.o.w)), y1 = Math.max(...boxes.map((b) => b.y + b.o.h));
- const k = Math.min((W - 56) / Math.max(1, x1 - x0), (H - 40) / Math.max(1, y1 - y0));
- const offX = (W - (x1 - x0) * k) / 2, offY = (H - (y1 - y0) * k) / 2;
- const movable = !mirror && act.length > 1;
+ // the preview's scale and offset: frozen while dragging, so the tile follows the pointer
+ let view = drag && drag.view;
+ if (!view) {
+ const x0 = Math.min(...boxes.map((b) => b.x)), y0 = Math.min(...boxes.map((b) => b.y));
+ const x1 = Math.max(...boxes.map((b) => b.x + b.o.w)), y1 = Math.max(...boxes.map((b) => b.y + b.o.h));
+ const k = Math.min((W - 56) / Math.max(1, x1 - x0), (H - 40) / Math.max(1, y1 - y0));
+ view = { k, x0, y0, offX: (W - (x1 - x0) * k) / 2, offY: (H - (y1 - y0) * k) / 2 };
+ }
+ const { k, x0, y0, offX, offY } = view;
+ const movable = several;
return (
<View ref={box} style={frame}>
{boxes.map(({ o, x, y }) => {
- const on = o.id === sel;
+ const on = o.id === sel, lit = o.id === flash, moving = drag && drag.id === o.id;
const w = Math.max(28, o.w * k - 3), h = Math.max(18, o.h * k - 3);
+ const n = several ? nums[o.id] : 0;
return (
<View key={o.id}
- onMouseDown={(e) => { onSelect(o.id); if (movable) st.current = { id: o.id, px: e.x, py: e.y, ox: o.x, oy: o.y, k, moved: false }; }}
+ onMouseDown={(e) => { onSelect(o.id); if (several) st.current = { id: o.id, px: e.x, py: e.y, ox: o.x, oy: o.y, view, moved: false, identify: movable ? identify : null }; }}
style={{ position: 'absolute', left: offX + (x - x0) * k - 3, top: offY + (y - y0) * k - 3, width: w + 6, height: h + 6, padding: 1,
- borderRadius: 8, cursor: movable ? 'grab' : 'pointer', border: `2px solid ${on ? t.accent : 'transparent'}` }}>
+ borderRadius: 8, cursor: movable ? 'grab' : 'pointer', zIndex: moving ? 2 : 1, opacity: moving && !drag.ok ? 0.7 : 1,
+ border: `2px solid ${on || lit ? t.accent : 'transparent'}` }}>
<View style={{ flex: 1, borderRadius: 5, overflow: 'hidden', alignItems: 'center', justifyContent: 'center', gap: 1,
- background: on ? 'linear-gradient(160deg, #3d7be0, #7b46cf)' : 'linear-gradient(160deg, #4f6fae, #5d4790)',
- boxShadow: '0 3px 10px rgba(0,0,0,0.3)' }}>
+ background: lit ? 'linear-gradient(160deg, #6aa4ff, #a57cf0)' : on ? 'linear-gradient(160deg, #3d7be0, #7b46cf)' : 'linear-gradient(160deg, #4f6fae, #5d4790)',
+ boxShadow: lit ? '0 0 0 3px rgba(255,255,255,0.55), 0 3px 10px rgba(0,0,0,0.3)' : '0 3px 10px rgba(0,0,0,0.3)' }}>
{o.main ? <View style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 5, backgroundColor: 'rgba(255,255,255,0.85)' }} /> : null}
- <Text style={{ fontSize: 11, fontWeight: 600, color: '#fff', textAlign: 'center', whiteSpace: 'nowrap' }}>{o.name}</Text>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4, maxWidth: w - 6 }}>
+ {n ? <NumberBadge n={n} size={16} /> : null}
+ {w > 54 || !n ? <Text style={{ fontSize: 11, fontWeight: 600, color: '#fff', textAlign: 'center', whiteSpace: 'nowrap', overflow: 'hidden' }}>{o.name}</Text> : null}
+ </View>
{h > 44 ? <Text style={{ fontSize: 10, color: 'rgba(255,255,255,0.82)', textAlign: 'center', whiteSpace: 'nowrap' }}>{`${o.mode.w} × ${o.mode.h}`}</Text> : null}
</View>
</View>
@@ -101,6 +139,15 @@ function Arrangement({ outs, sel, onSelect, mirror, t }) {
);
}
+// A display's number in a small white circle (the arrangement's tiles and the display's header).
+function NumberBadge({ n, size = 16, color = '#fff', textColor = '#2c3e70' }) {
+ return (
+ <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: color, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: Math.round(size * 0.66), fontWeight: 700, color: textColor, textAlign: 'center' }}>{String(n)}</Text>
+ </View>
+ );
+}
+
// One scale as a picture of the screen with a window: the larger the scale, the bigger the window
// ("Larger text … More space"). A 2 px accent ring marks the current one.
function ScaleTile({ n, on, rec, label, onPick, t, tr }) {
@@ -142,13 +189,18 @@ function ScaleTiles({ value, rec, onPick, t, tr }) {
}
// The selected display: its picture, name and size line (first row of its box).
-function DisplayHeader({ cur, sizeLine, several, t, tr }) {
+function DisplayHeader({ cur, sizeLine, several, n, t, tr }) {
return (
<View style={{ minHeight: 56, flexDirection: 'row', alignItems: 'center', gap: spacing.m, paddingVertical: spacing.s }}>
<DisplayGlyph size={36} color={t.accent} />
<View style={{ flex: 1, minWidth: 0, gap: 2 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.s }}>
<Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text, textAlign: 'start', whiteSpace: 'nowrap' }}>{cur.name}</Text>
+ {n ? (
+ <View style={{ height: 16, paddingHorizontal: 6, borderRadius: 8, justifyContent: 'center', backgroundColor: t.mode === 'dark' ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.07)' }}>
+ <Text style={{ fontSize: 10, fontWeight: 500, color: t.textDim, whiteSpace: 'nowrap' }}>{tr('prefs.display.number', { n })}</Text>
+ </View>
+ ) : null}
{cur.main && several ? (
<View style={{ height: 16, paddingHorizontal: 6, borderRadius: 8, justifyContent: 'center', backgroundColor: t.mode === 'dark' ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.07)' }}>
<Text style={{ fontSize: 10, fontWeight: 500, color: t.textDim, whiteSpace: 'nowrap' }}>{tr('prefs.display.mainLabel')}</Text>
@@ -268,13 +320,14 @@ export function DisplaysSettings() {
const sizeLine = [cur.connector, cur.diagonal ? tr('prefs.display.inches', { n: (cur.diagonal / 10).toFixed(1) }) : '', `${mode.w} × ${mode.h}`, looks].filter(Boolean).join(' · ');
const scales = [100, 125, 150, 175, 200].map((n) => [n, n === rec ? tr('prefs.display.scaleRecommended', { n }) : tr('prefs.display.scaleN', { n })]);
const several = act.length > 1 || outs.length > 1;
+ const nums = displayNumbers(outs);
return (
<Stack>
- <ArrangementBlock outs={outs} sel={cur.id} onSelect={setSel} mirror={d.mirror} t={t}
- hint={act.length > 1 && !d.mirror ? tr('prefs.display.arrangeHint') : ''} />
+ <ArrangementBlock outs={outs} sel={cur.id} onSelect={setSel} mirror={d.mirror} nums={nums} t={t} tr={tr}
+ hint={act.length > 1 && !d.mirror ? tr('prefs.display.arrangeHint') : ''} canIdentify={act.length > 1 && !d.mirror} />
<Section>
- <DisplayHeader cur={cur} sizeLine={sizeLine} several={several} t={t} tr={tr} />
+ <DisplayHeader cur={cur} sizeLine={sizeLine} several={several} n={act.length > 1 && !d.mirror ? nums[cur.id] : 0} t={t} tr={tr} />
{several ? (
<SettingRow label={tr('prefs.display.useAsMain')} hint={cur.main ? tr('prefs.display.mainHint') : ''} disabled={!cur.active || d.mirror}>
<Toggle small on={!!cur.main} onChange={(on) => { if (on && !cur.main) setMainDisplay(cur.id); }} />
@@ -335,12 +388,17 @@ export function DisplaysSettings() {
);
}
-// The arrangement with its hint under it (like a section footer).
-function ArrangementBlock({ hint, ...p }) {
+// The arrangement with its hint and the Identify button under it (like a section footer).
+function ArrangementBlock({ hint, canIdentify, tr, ...p }) {
return (
<View style={{ gap: 6 }}>
<Arrangement {...p} />
- {hint ? <Note>{hint}</Note> : null}
+ {hint || canIdentify ? (
+ <View style={{ flexDirection: 'row', alignItems: 'flex-start', gap: spacing.s }}>
+ <View style={{ flex: 1, minWidth: 0 }}>{hint ? <Note>{hint}</Note> : null}</View>
+ {canIdentify ? <Button small label={tr('prefs.display.identify')} onClick={() => identifyDisplays()} /> : null}
+ </View>
+ ) : null}
</View>
);
}
diff --git a/assets/help/en/settings.md b/assets/help/en/settings.md
index 9d2ae8c..fa58e1c 100644
--- a/assets/help/en/settings.md
+++ b/assets/help/en/settings.md
@@ -14,6 +14,7 @@ Everything you can configure in LordOS is in Settings. The field at the top sear
| [General](settings:general) | This computer: name, software and storage |
| [Appearance](settings:appearance) | Desktop style (Lord Flow or Lord Classic), dark or light mode, accent color, transparency |
| [Wallpaper](settings:wallpaper) | The desktop background |
+| [Displays](settings:displays) | Resolution, scale, arrangement of several displays, Night Light |
| [Network](settings:network) | Wired, Wi-Fi and VPN (see [Network](help:network)) |
| [Sound](settings:sound) | Outputs, inputs, per-app volume (see [Sound](help:sound)) |
| [Printers & Scanners](settings:printers) | See [Printing](help:printing) |
@@ -29,3 +30,15 @@ Everything you can configure in LordOS is in Settings. The field at the top sear
Changes save by themselves. What affects the whole computer (network, users, time zone, packages)
requires an administrator.
+
+## Several displays
+
+In [Displays](settings:displays), with more than one display connected, each display in the
+arrangement shows its number: the main display (the one with the menu bar and the Dock) is 1.
+
+- **Identify:** click a display in the arrangement, or the **Identify** button, and its number
+ appears big on the real screen for a moment, so you know which monitor is 1 and which is 2.
+- **Arrange:** drag the displays to match how they sit on your desk. They snap edge to edge and
+ line up their tops, bottoms, sides or centers when close. When you let go, a display always
+ touches another one and never overlaps it; if you drop it in empty space it moves to the nearest
+ edge.
diff --git a/assets/help/es/settings.md b/assets/help/es/settings.md
index 34722d6..05bf40c 100644
--- a/assets/help/es/settings.md
+++ b/assets/help/es/settings.md
@@ -14,6 +14,7 @@ Todo lo que se configura de LordOS está en Ajustes. El campo de arriba busca en
| [General](settings:general) | Este equipo: nombre, software y almacenamiento |
| [Apariencia](settings:appearance) | Estilo de escritorio (Lord Flow o Lord Classic), modo oscuro o claro, color de acento, transparencias |
| [Fondo de pantalla](settings:wallpaper) | El fondo del escritorio |
+| [Pantallas](settings:displays) | Resolución, escala, disposición de varias pantallas, Luz nocturna |
| [Red](settings:network) | Cable, Wi-Fi y VPN (ver [Red](help:network)) |
| [Sonido](settings:sound) | Salidas, entradas, volumen por app (ver [Sonido](help:sound)) |
| [Impresoras y escáneres](settings:printers) | Ver [Imprimir](help:printing) |
@@ -29,3 +30,15 @@ Todo lo que se configura de LordOS está en Ajustes. El campo de arriba busca en
Los cambios se guardan solos. Lo que afecta a todo el equipo (red, usuarios, zona horaria,
paquetes) pide ser administrador.
+
+## Varias pantallas
+
+En [Pantallas](settings:displays), con más de una pantalla conectada, cada pantalla de la
+disposición muestra su número: la principal (la que tiene la barra de menú y el Dock) es la 1.
+
+- **Identificar:** hacé clic en una pantalla de la disposición, o en el botón **Identificar**, y su
+ número aparece grande en la pantalla real por un momento, para saber qué monitor es el 1 y cuál el 2.
+- **Ordenar:** arrastrá las pantallas para que coincidan con cómo están en tu escritorio. Se pegan
+ borde con borde y alinean sus bordes superiores, inferiores, laterales o sus centros cuando están
+ cerca. Al soltarla, una pantalla siempre toca a otra y nunca se superpone; si la soltás en un
+ espacio vacío, se mueve al borde más cercano.
diff --git a/assets/help/pt/settings.md b/assets/help/pt/settings.md
index 2ada5ea..49444c8 100644
--- a/assets/help/pt/settings.md
+++ b/assets/help/pt/settings.md
@@ -14,6 +14,7 @@ Tudo o que se configura no LordOS está nos Ajustes. O campo no alto busca entre
| [Geral](settings:general) | Este computador: nome, software e armazenamento |
| [Aparência](settings:appearance) | Estilo da área de trabalho (Lord Flow ou Lord Classic), modo escuro ou claro, cor de destaque, transparências |
| [Fundo de tela](settings:wallpaper) | O fundo da área de trabalho |
+| [Telas](settings:displays) | Resolução, escala, disposição de várias telas, Luz noturna |
| [Rede](settings:network) | Cabo, Wi-Fi e VPN (veja [Rede](help:network)) |
| [Som](settings:sound) | Saídas, entradas, volume por app (veja [Som](help:sound)) |
| [Impressoras e scanners](settings:printers) | Veja [Imprimir](help:printing) |
@@ -29,3 +30,15 @@ Tudo o que se configura no LordOS está nos Ajustes. O campo no alto busca entre
As mudanças se salvam sozinhas. O que afeta o computador inteiro (rede, usuários, fuso horário,
pacotes) exige ser administrador.
+
+## Várias telas
+
+Em [Telas](settings:displays), com mais de uma tela conectada, cada tela da disposição mostra seu
+número: a principal (a que tem a barra de menus e o Dock) é a 1.
+
+- **Identificar:** clique em uma tela da disposição, ou no botão **Identificar**, e o número dela
+ aparece grande na tela real por um momento, para você saber qual monitor é o 1 e qual é o 2.
+- **Organizar:** arraste as telas para que fiquem como estão na sua mesa. Elas se encaixam borda
+ com borda e alinham as bordas de cima, de baixo, dos lados ou os centros quando estão perto. Ao
+ soltar, uma tela sempre toca outra e nunca fica por cima dela; se você soltar em um espaço vazio,
+ ela vai para a borda mais próxima.
diff --git a/assets/locales/en/prefs.json b/assets/locales/en/prefs.json
index 69d0816..ceee1a5 100644
--- a/assets/locales/en/prefs.json
+++ b/assets/locales/en/prefs.json
@@ -69,7 +69,7 @@
"defaults.none": "No installed app can open these",
"defaults.other": "{id}",
"defaults.tag": "{name} (default)",
- "display.arrangeHint": "Drag a display to place it next to the others. The white bar marks the main display (menu bar and Dock).",
+ "display.arrangeHint": "Drag the displays to arrange them; they snap edge to edge. Click one to identify it. The white bar marks the main display (menu bar and Dock).",
"display.arrangement": "Arrangement",
"display.brightness": "Brightness",
"display.capture": "Screenshots and sharing",
@@ -80,6 +80,7 @@
"display.failed": "That mode could not be used. The previous one is still active.",
"display.hz": "{hz} Hz",
"display.inches": "{n}-inch",
+ "display.identify": "Identify",
"display.keep": "Keep",
"display.keepBody": {
"one": "Your display settings will go back to the previous ones in {count} second.",
@@ -101,6 +102,7 @@
"display.noBacklight": "This display does not offer brightness control (external monitors and virtual machines).",
"display.noCrtc": "{connector}: connected, but the graphics card cannot drive another display",
"display.notOnMonitor": "This session is not on the monitor right now (it is being viewed from the network), so its displays cannot be changed. Night Light settings still apply when it returns.",
+ "display.number": "Display {n}",
"display.recommended": "Recommended",
"display.refresh": "Refresh rate",
"display.resolution": "Resolution",
diff --git a/assets/locales/es/prefs.json b/assets/locales/es/prefs.json
index d7ead97..9f86173 100644
--- a/assets/locales/es/prefs.json
+++ b/assets/locales/es/prefs.json
@@ -69,7 +69,7 @@
"defaults.none": "Ninguna app instalada abre estos archivos",
"defaults.other": "{id}",
"defaults.tag": "{name} (por defecto)",
- "display.arrangeHint": "Arrastrá una pantalla para ubicarla junto a las otras. La barra blanca marca la pantalla principal (barra de menú y Dock).",
+ "display.arrangeHint": "Arrastrá las pantallas para ordenarlas; se pegan borde con borde. Hacé clic en una para identificarla. La barra blanca marca la pantalla principal (barra de menú y Dock).",
"display.arrangement": "Disposición",
"display.brightness": "Brillo",
"display.capture": "Capturas y compartir",
@@ -80,6 +80,7 @@
"display.failed": "No se pudo usar ese modo. Sigue el anterior.",
"display.hz": "{hz} Hz",
"display.inches": "{n} pulgadas",
+ "display.identify": "Identificar",
"display.keep": "Mantener",
"display.keepBody": {
"one": "La pantalla vuelve a la configuración anterior en {count} segundo.",
@@ -101,6 +102,7 @@
"display.noBacklight": "Esta pantalla no permite cambiar el brillo (monitores externos y máquinas virtuales).",
"display.noCrtc": "{connector}: conectada, pero la placa de video no puede manejar otra pantalla",
"display.notOnMonitor": "Esta sesión no está en el monitor ahora (se está mirando desde la red), así que no se pueden cambiar sus pantallas. La Luz nocturna se aplica cuando vuelva.",
+ "display.number": "Pantalla {n}",
"display.recommended": "Recomendado",
"display.refresh": "Frecuencia de actualización",
"display.resolution": "Resolución",
diff --git a/assets/locales/pt/prefs.json b/assets/locales/pt/prefs.json
index b2c251d..81f5cd1 100644
--- a/assets/locales/pt/prefs.json
+++ b/assets/locales/pt/prefs.json
@@ -69,7 +69,7 @@
"defaults.none": "Nenhum app instalado abre estes arquivos",
"defaults.other": "{id}",
"defaults.tag": "{name} (padrão)",
- "display.arrangeHint": "Arraste uma tela para colocá-la ao lado das outras. A barra branca marca a tela principal (barra de menus e Dock).",
+ "display.arrangeHint": "Arraste as telas para organizá-las; elas se encaixam borda com borda. Clique em uma para identificá-la. A barra branca marca a tela principal (barra de menus e Dock).",
"display.arrangement": "Disposição",
"display.brightness": "Brilho",
"display.capture": "Capturas e compartilhamento",
@@ -80,6 +80,7 @@
"display.failed": "Não foi possível usar esse modo. O anterior continua.",
"display.hz": "{hz} Hz",
"display.inches": "{n} polegadas",
+ "display.identify": "Identificar",
"display.keep": "Manter",
"display.keepBody": {
"one": "A tela volta à configuração anterior em {count} segundo.",
@@ -101,6 +102,7 @@
"display.noBacklight": "Esta tela não permite mudar o brilho (monitores externos e máquinas virtuais).",
"display.noCrtc": "{connector}: conectada, mas a placa de vídeo não consegue controlar outra tela",
"display.notOnMonitor": "Esta sessão não está no monitor agora (está sendo vista pela rede), então suas telas não podem ser alteradas. A Luz noturna vale quando ela voltar.",
+ "display.number": "Tela {n}",
"display.recommended": "Recomendado",
"display.refresh": "Taxa de atualização",
"display.resolution": "Resolução",
diff --git a/docs/DISPLAYS.md b/docs/DISPLAYS.md
index 80d1092..6b50e6c 100644
--- a/docs/DISPLAYS.md
+++ b/docs/DISPLAYS.md
@@ -40,11 +40,61 @@ shows in the captures.
- The **main display** gets the menu bar and the Dock; with "Show menu bar on all displays" the
menu bar is drawn on each one. The work area is per display.
-The math is in `server/src/outputs.c` (pure functions, `build/outputs-test`, 119 checks): scale
+The math is in `server/src/outputs.c` (pure functions, `build/outputs-test`, 131 checks): scale
rounding and the recommended scale, logical ↔ physical, damage rectangles, mirrored views,
-snapping, fixing overlaps after a change, normalizing, the pointer across displays and the
+snapping, checking a dropped position (`out_fits`) and a whole arrangement (`out_valid`), fixing overlaps after a change, normalizing, the pointer across displays and the
display with most of a window.
+## Numbers, identify and snapping (Settings → Displays)
+
+Like macOS's "Arrange Displays", with more than one display (extend mode):
+
+- **Numbers.** Every active display gets a number: the main display is **1**, the others follow in
+ the order `lord.display.list()` gives them (connector order). `displayNumbers(outputs)` in
+ `sdk/displaylayout.js` computes them; the arrangement's tiles show the number in a small circle
+ next to the name, and the selected display's header shows "Display 2" next to its name. Making
+ another display the main one renumbers them (the main one is always 1). No numbers in mirror mode
+ or with a single display.
+- **Identify.** Clicking a tile (without dragging it) or the **Identify** button under the
+ arrangement calls `identifyDisplays(ids?)` (`sdk/displaysui.jsx`, exported by `@lordos/sdk`): the
+ number is drawn big (a 120–240 px rounded badge, 30 % of the display's short side) centered on
+ the real display for 1.5 s, fading in (120 ms) and out (the last 450 ms) with `lord.setStyle`
+ on the overlay's opacity (no React render per frame; no fade with "Reduce motion"). The clicked
+ tile flashes (lighter fill, accent ring) for the same time. The badges are `<DisplayIdentify />`,
+ mounted by `startShell` in the `notification` layer (`sdk/index.js`, see `LAYERS.md`), so both
+ themes get it without code of their own. Each badge sits at its display's global logical
+ rectangle (`lord.screen.displays`, matched by connector), since the desktop is one space across
+ displays; it takes no clicks (`pointerEvents: 'none'`).
+- **Magnetic arrangement.** While a tile is dragged, `snapDisplay(rects, i, x, y, threshold)`
+ moves each axis independently to the nearest of these targets within 12 preview px (converted
+ to logical px with the preview's scale): edge to edge (its left on the other's right, its right
+ on the other's left, the same for top/bottom), starts aligned (tops or lefts), ends aligned
+ (bottoms or rights) and centers aligned. Only displays near on the other axis (no further than
+ the threshold) attract an axis, so a display far below another doesn't stick to its side. The
+ preview's scale is frozen during the drag, so the tile follows the pointer; it is dimmed while
+ its position would not be valid.
+- **On drop**, `resolveDrop(...)` returns the snapped position when it is valid (it overlaps no
+ display and shares an edge, at least one pixel and not just a corner, with one of them); otherwise
+ the nearest valid position: beside, above or below each display, with the position along that
+ edge kept (clamped so the edges share a pixel), aligned to the start, end or center when within
+ the threshold, or slid just past a display that is in the way. Any relative position is allowed:
+ side by side, stacked, or offset diagonally as long as edges touch.
+- **lord-server keeps it exactly.** `lord.display.arrange(conn, x, y, true)` (`display_arrange`)
+ checks the position with `out_fits` (the same rule as `placementOk` in the SDK); a fitting
+ position is kept as is (`out_snap` with no alignment), anything else is still snapped next to a
+ display with the old 24 px alignment. `out_fix`, run on every plan, leaves a valid arrangement
+ alone (`out_valid`: no overlaps and every display joined through shared edges), so a chain such as
+ main ← display 3 ← display 2 is no longer re-snapped onto the main display; only an arrangement
+ that overlaps or has floating displays (after a scale or resolution change, an unplug, or dragging
+ away the display in the middle of a chain) is re-snapped in order.
+- Tests: `server/tests/display_layout_test.mjs` (numbers, touching, the snap targets, drops on top,
+ in empty space, corner-only, three displays, and a sweep of about 25,000 drops that must all touch and
+ never overlap; run by `make -C server test` through `run_suites.sh` when node exists) and the
+ `out_fits`/`out_valid`/chain checks in `build/outputs-test`.
+- **Untested on real hardware:** the identify badges and the drag were not run on two displays yet
+ (no multi-display machine where this was written); VM 118's two virtio-gpu heads are the
+ intended check.
+
## How it is drawn
```
diff --git a/sdk/displaylayout.js b/sdk/displaylayout.js
new file mode 100644
index 0000000..20076e8
--- /dev/null
+++ b/sdk/displaylayout.js
@@ -0,0 +1,133 @@
+// displaylayout.js — the pure math of Settings → Displays' arrangement (docs/DISPLAYS.md,
+// "Numbers, identify and snapping"). No React, no lord.*: tested by server/tests/display_layout_test.mjs.
+//
+// displayNumbers(outputs) { [id]: 1, 2, 3… }: main display first, then the others in
+// the order lord.display.list() gives them (connector order)
+// snapDisplay(rects, i, x, y, threshold) while dragging: the "magnetic" position of rects[i] at (x, y)
+// resolveDrop(rects, i, x, y, threshold) on drop: a position that touches another display edge to edge
+// and overlaps none (the nearest one to the snapped position)
+// placementOk(rects, i, x, y) the rule lord-server checks too (out_fits in outputs.c)
+//
+// Every rect is { x, y, w, h } in the desktop's logical px (integers). `threshold` is in the same
+// units: Settings converts its 12 preview px with the preview's scale.
+
+export const SNAP_PREVIEW_PX = 12;
+
+const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
+const shared = (a0, a1, b0, b1) => Math.min(a1, b1) - Math.max(a0, b0);
+const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
+
+// Two displays touch when an edge of one lies on an edge of the other along at least one pixel
+// (a corner alone is not enough: the pointer could not cross there).
+export function touches(a, b) {
+ if ((a.x + a.w === b.x || b.x + b.w === a.x) && shared(a.y, a.y + a.h, b.y, b.y + b.h) > 0) return true;
+ if ((a.y + a.h === b.y || b.y + b.h === a.y) && shared(a.x, a.x + a.w, b.x, b.x + b.w) > 0) return true;
+ return false;
+}
+
+// rects[i] at (x, y): overlaps no other display and touches at least one (always fine when alone).
+export function placementOk(rects, i, x, y) {
+ const m = { x, y, w: rects[i].w, h: rects[i].h };
+ let touching = rects.length < 2;
+ for (let j = 0; j < rects.length; j++) {
+ if (j === i) continue;
+ if (overlaps(m, rects[j])) return false;
+ if (touches(m, rects[j])) touching = true;
+ }
+ return touching;
+}
+
+// Numbers like macOS's "Identify": the main display is 1, the others follow in the server's order.
+// Only active displays with a size get one.
+export function displayNumbers(outputs) {
+ const act = (outputs || []).filter((o) => o && o.active && o.w);
+ const main = act.find((o) => o.main);
+ const order = main ? [main, ...act.filter((o) => o !== main)] : act;
+ const out = {};
+ order.forEach((o, k) => { out[o.id] = k + 1; });
+ return out;
+}
+
+// The targets one axis can snap to against another display `o`: edge to edge (both sides), then
+// starts aligned, ends aligned and centers aligned.
+function targets(p, len, op, olen) {
+ return [op + olen, op - len, op, op + olen - len, Math.round(op + (olen - len) / 2)];
+}
+
+// While dragging: each axis independently jumps to the nearest target within `threshold`, taken
+// from the displays that are near on the other axis (no further than `threshold` away), so a
+// display far below another doesn't stick to its side.
+export function snapDisplay(rects, i, x, y, threshold) {
+ const { w, h } = rects[i];
+ let bx = Math.round(x), by = Math.round(y), dx = threshold + 1, dy = threshold + 1;
+ for (let j = 0; j < rects.length; j++) {
+ if (j === i) continue;
+ const o = rects[j];
+ const gapY = Math.max(0, o.y - (y + h), y - (o.y + o.h));
+ const gapX = Math.max(0, o.x - (x + w), x - (o.x + o.w));
+ if (gapY <= threshold) {
+ for (const t of targets(x, w, o.x, o.w)) {
+ const d = Math.abs(x - t);
+ if (d <= threshold && d < dx) { dx = d; bx = t; }
+ }
+ }
+ if (gapX <= threshold) {
+ for (const t of targets(y, h, o.y, o.h)) {
+ const d = Math.abs(y - t);
+ if (d <= threshold && d < dy) { dy = d; by = t; }
+ }
+ }
+ }
+ return { x: bx, y: by };
+}
+
+// Along an edge of `o`, the coordinate `v` (length `len`) is kept so the edges share at least one
+// pixel, and pulled to o's start, end or center when within `threshold`.
+function alongEdge(v, len, op, olen, threshold) {
+ const c = clamp(v, op - len + 1, op + olen - 1);
+ let best = c, bd = threshold + 1;
+ for (const t of [op, op + olen - len, Math.round(op + (olen - len) / 2)]) {
+ const d = Math.abs(c - t);
+ if (d <= threshold && d < bd && t >= op - len + 1 && t <= op + olen - 1) { bd = d; best = t; }
+ }
+ return [best, c];
+}
+
+// On drop: the snapped position if it is a valid one; otherwise the nearest position that touches a
+// display edge to edge without overlapping any (beside it, aligned when close, or slid along its edge
+// past a display in the way). lord-server keeps such a position exactly (display_arrange, out_fits).
+export function resolveDrop(rects, i, x, y, threshold) {
+ if (rects.length < 2) return { x: Math.round(x), y: Math.round(y) };
+ const s = snapDisplay(rects, i, x, y, threshold);
+ if (placementOk(rects, i, s.x, s.y)) return s;
+ const { w, h } = rects[i];
+ let best = null, bd = Infinity;
+ const consider = (cx, cy) => {
+ if (!placementOk(rects, i, cx, cy)) return;
+ const d = (cx - s.x) ** 2 + (cy - s.y) ** 2;
+ if (d < bd) { bd = d; best = { x: cx, y: cy }; }
+ };
+ for (let j = 0; j < rects.length; j++) {
+ if (j === i) continue;
+ const o = rects[j];
+ // the positions along an edge: where it was dropped, plus just past every other display (to slide
+ // around one that is in the way)
+ const ys = [s.y], xs = [s.x];
+ for (let q = 0; q < rects.length; q++) {
+ if (q === i || q === j) continue;
+ ys.push(rects[q].y + rects[q].h, rects[q].y - h);
+ xs.push(rects[q].x + rects[q].w, rects[q].x - w);
+ }
+ for (const sx of [o.x + o.w, o.x - w]) { // right of it, left of it
+ for (const v of ys) for (const yy of alongEdge(v, h, o.y, o.h, threshold)) consider(sx, yy);
+ }
+ for (const sy of [o.y + o.h, o.y - h]) { // below it, above it
+ for (const v of xs) for (const xx of alongEdge(v, w, o.x, o.w, threshold)) consider(xx, sy);
+ }
+ }
+ if (best) return best;
+ // nothing free next to anyone (can't happen with a few displays): right of the rightmost one
+ let r = null;
+ for (let j = 0; j < rects.length; j++) if (j !== i && (!r || rects[j].x + rects[j].w > r.x + r.w)) r = rects[j];
+ return { x: r.x + r.w, y: r.y };
+}
diff --git a/sdk/displaysui.jsx b/sdk/displaysui.jsx
new file mode 100644
index 0000000..c7c59e6
--- /dev/null
+++ b/sdk/displaysui.jsx
@@ -0,0 +1,75 @@
+// displaysui.jsx — "Identify" for Settings → Displays (docs/DISPLAYS.md, "Numbers, identify and snapping"):
+//
+// identifyDisplays(ids?) shows each display's number (1, 2, 3…; sdk/displaylayout.js displayNumbers),
+// big, centered on that real display for 1.5 s, then fades it out. `ids` are
+// lord.display.list() output ids (one or an array); none = every active display.
+// Returns false when there is nothing to show (no display API, mirror mode).
+// <DisplayIdentify /> the badges; startShell mounts it in the `notification` layer (sdk/index.js,
+// docs/LAYERS.md), so every theme has it. It never takes clicks.
+//
+// The desktop is one logical space across displays: each badge is placed at its display's global
+// rectangle (lord.screen.displays, matched by connector; the list's own rectangle otherwise).
+import { createElement as h, useEffect, useRef } from 'react';
+import { View, Text, displays as screenDisplays } from '@lordos/runtime';
+import { createStore, useStore } from './store.js';
+import { settings } from './settings.js';
+import { displays } from './hardware.jsx';
+import { displayNumbers } from './displaylayout.js';
+
+export const IDENTIFY_MS = 1500;
+const FADE_IN_MS = 120, FADE_OUT_MS = 450;
+
+export const identifying = createStore(null); // { seq, items: [{ id, n, x, y, w, h }] }
+let seq = 0, timer = 0;
+
+export function identifyDisplays(ids) {
+ const d = displays.get();
+ if (!d || d.mirror) return false;
+ const outs = (d.outputs || []).filter((o) => o.active && o.w);
+ const nums = displayNumbers(outs);
+ let screen = [];
+ try { screen = screenDisplays() || []; } catch (e) { screen = []; }
+ const want = ids == null ? null : new Set([].concat(ids));
+ const items = outs.filter((o) => !want || want.has(o.id)).map((o) => {
+ const s = screen.find((x) => x.connector && x.connector === o.connector);
+ const r = s && s.w ? s : o;
+ return { id: o.id, n: nums[o.id], x: r.x, y: r.y, w: r.w, h: r.h };
+ }).filter((it) => it.n && it.w > 0 && it.h > 0);
+ if (!items.length) return false;
+ clearTimeout(timer);
+ identifying.set({ seq: ++seq, items });
+ timer = setTimeout(() => identifying.set(null), IDENTIFY_MS);
+ return true;
+}
+
+// One big rounded badge with the number, centered on its display.
+function Badge({ it }) {
+ const size = Math.round(Math.max(120, Math.min(240, Math.min(it.w, it.h) * 0.3)));
+ return h(View, { style: { position: 'absolute', left: it.x, top: it.y, width: it.w, height: it.h, alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' } },
+ h(View, { style: { width: size, height: size, borderRadius: Math.round(size * 0.24), alignItems: 'center', justifyContent: 'center',
+ backgroundColor: 'rgba(28,28,32,0.78)', border: '1px solid rgba(255,255,255,0.18)', boxShadow: '0 18px 50px rgba(0,0,0,0.45)', pointerEvents: 'none' } },
+ h(Text, { style: { fontSize: Math.round(size * 0.6), fontWeight: 700, color: '#ffffff', textAlign: 'center', pointerEvents: 'none' } }, String(it.n))));
+}
+
+export function DisplayIdentify() {
+ const c = useStore(identifying);
+ const reduce = useStore(settings, (s) => !!s.reduceMotion);
+ const root = useRef(null);
+ useEffect(() => {
+ if (!c || reduce || typeof lord === 'undefined' || !lord.setStyle) return undefined;
+ // opacity through lord.setStyle (no React render per frame): in quickly, hold, out at the end
+ const t0 = Date.now();
+ const set = (o) => { try { if (root.current) lord.setStyle(root.current.id, 'opacity', o); } catch (e) { /* unmounted */ } };
+ set(0);
+ const id = setInterval(() => {
+ const t = Date.now() - t0;
+ const o = t < FADE_IN_MS ? t / FADE_IN_MS : t > IDENTIFY_MS - FADE_OUT_MS ? Math.max(0, (IDENTIFY_MS - t) / FADE_OUT_MS) : 1;
+ set(Math.round(o * 100) / 100);
+ if (t >= IDENTIFY_MS) clearInterval(id);
+ }, 33);
+ return () => clearInterval(id);
+ }, [c && c.seq, reduce]);
+ if (!c) return null;
+ return h(View, { ref: root, key: c.seq, style: { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, pointerEvents: 'none' } },
+ ...c.items.map((it) => h(Badge, { key: it.id, it })));
+}
diff --git a/sdk/index.js b/sdk/index.js
index e838a95..71e62b0 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -121,6 +121,10 @@ export {
CLOCK_DEFAULTS, applyIdle,
} from './hardware.jsx';
import { DisplayConfirm, BluetoothPrompt, startHardware } from './hardware.jsx';
+// Settings → Displays: numbering, Identify (a big number on each real display) and magnetic arrangement
+export { identifyDisplays, identifying as identifyingDisplays, IDENTIFY_MS } from './displaysui.jsx';
+import { DisplayIdentify } from './displaysui.jsx';
+export { displayNumbers, snapDisplay, resolveDrop, placementOk as displayPlacementOk, SNAP_PREVIEW_PX } from './displaylayout.js';
// Fans and cooling (lord-fand, docs/FANS.md): Settings → Cooling and Monitor → Cooling
export { useFan, fanStatus, fanHistory, fanCase, fanControl, refreshFan, coolingVariant, heatColor, CoolingArt, FanCurveChart, formatTemp, FAN_HISTORY } from './cooling.jsx';
export { DEFAULT_CATEGORIES, defaultFor, setDefaultFor, candidatesFor, defaultOpenerId, nativeOf } from './defaults.js';
@@ -234,7 +238,7 @@ function LocaleRoot({ children }) {
at('overlay', SpotlightPanel),
at('popover', ClipboardPanel, EmojiPanel),
at('modal', PrintDialog),
- at('notification', NotificationBanner, ClipboardToast, RemoteBadge),
+ at('notification', NotificationBanner, ClipboardToast, RemoteBadge, DisplayIdentify),
at('system', PermissionPrompt, Powerbox, KeyringPrompt, BluetoothPrompt, DisplayConfirm),
at('input', ImeOverlay));
}
diff --git a/server/src/hw/display.c b/server/src/hw/display.c
index b180bb6..821966a 100644
--- a/server/src/hw/display.c
+++ b/server/src/hw/display.c
@@ -582,7 +582,9 @@ int display_arrange(uint32_t conn, int x, int y, int apply, int *sx, int *sy) {
if (mv < 0) return -1;
ORect r[OUT_MAX];
for (int j = 0; j < D.cur.n; j++) r[j] = (ORect){ D.cur.o[j].v.x, D.cur.o[j].v.y, D.cur.o[j].v.w, D.cur.o[j].v.h };
- int snap = 24;
+ /* a position that already touches and doesn't overlap (Settings snaps it, sdk/displaylayout.js)
+ * is kept exactly; anything else is snapped next to a display */
+ int snap = out_fits(r, D.cur.n, mv, x, y) ? 0 : 24;
out_snap(r, D.cur.n, mv, x, y, snap, &r[mv].x, &r[mv].y);
*sx = r[mv].x;
*sy = r[mv].y;
diff --git a/server/src/outputs.c b/server/src/outputs.c
index 5d48be9..4d2c464 100644
--- a/server/src/outputs.c
+++ b/server/src/outputs.c
@@ -147,7 +147,45 @@ void out_snap(const ORect *r, int n, int moving, int want_x, int want_y, int sna
*y = by;
}
+/* An edge of one on an edge of the other, along at least one pixel. */
+static int touching(ORect a, ORect b) {
+ if ((a.x + a.w == b.x || b.x + b.w == a.x) && (a.y < b.y + b.h && b.y < a.y + a.h)) return 1;
+ if ((a.y + a.h == b.y || b.y + b.h == a.y) && (a.x < b.x + b.w && b.x < a.x + a.w)) return 1;
+ return 0;
+}
+
+int out_fits(const ORect *r, int n, int moving, int x, int y) {
+ if (n < 2) return 1;
+ ORect m = { x, y, r[moving].w, r[moving].h };
+ int touch = 0;
+ for (int j = 0; j < n; j++) {
+ if (j == moving) continue;
+ if (overlaps(m, r[j])) return 0;
+ if (touching(m, r[j])) touch = 1;
+ }
+ return touch;
+}
+
+int out_valid(const ORect *r, int n) {
+ if (n <= 1) return 1;
+ if (n > 64) return 0;
+ for (int i = 0; i < n; i++)
+ for (int j = i + 1; j < n; j++) if (overlaps(r[i], r[j])) return 0;
+ /* joined: grow the set reached from r[0] through shared edges */
+ unsigned long long seen = 1;
+ for (int grew = 1; grew;) {
+ grew = 0;
+ for (int i = 0; i < n; i++) {
+ if (seen >> i & 1) continue;
+ for (int j = 0; j < n; j++)
+ if ((seen >> j & 1) && touching(r[i], r[j])) { seen |= 1ULL << i; grew = 1; break; }
+ }
+ }
+ return seen == (n == 64 ? ~0ULL : (1ULL << n) - 1);
+}
+
void out_fix(ORect *r, int n) {
+ if (out_valid(r, n)) return;
for (int i = 1; i < n; i++) out_snap(r, i + 1, i, r[i].x, r[i].y, 0, &r[i].x, &r[i].y);
}
diff --git a/server/src/outputs.h b/server/src/outputs.h
index e9b77ee..5ccadcb 100644
--- a/server/src/outputs.h
+++ b/server/src/outputs.h
@@ -55,8 +55,14 @@ void out_logical_box(const OutView *v, Rect r, float *x0, float *y0, float *x1,
* another display along an edge, never overlapping, edges aligned when within `snap` px. Others
* stay where they are. Returns the position in *x, *y. */
void out_snap(const ORect *r, int n, int moving, int want_x, int want_y, int snap, int *x, int *y);
+/* 1 if display `moving` at (x, y) overlaps no other and shares an edge (at least one pixel, not a
+ * corner) with one of them: a position Settings computed (sdk/displaylayout.js) that is kept as is. */
+int out_fits(const ORect *r, int n, int moving, int x, int y);
+/* 1 if no two displays overlap and every display is joined to the others through shared edges. */
+int out_valid(const ORect *r, int n);
/* Displays that overlap or float apart (a scale or resolution changed, a display unplugged):
- * keep r[0] (the main one) and re-snap the others in order, each at its current position. */
+ * keep r[0] (the main one) and re-snap the others in order, each at its current position. A valid
+ * arrangement (out_valid) is left alone, so a chain like main ← 2 ← 1 is kept. */
void out_fix(ORect *r, int n);
/* Shift every display so the arrangement's top-left corner is (0, 0). Returns the bounding size. */
void out_normalize(ORect *r, int n, int *bw, int *bh);
diff --git a/server/tests/display_layout_test.mjs b/server/tests/display_layout_test.mjs
new file mode 100644
index 0000000..3a8d670
--- /dev/null
+++ b/server/tests/display_layout_test.mjs
@@ -0,0 +1,80 @@
+// display_layout_test.mjs — Settings → Displays' arrangement math (sdk/displaylayout.js): numbering,
+// the magnetic snap while dragging and the drop that always touches and never overlaps.
+//
+// node tests/display_layout_test.mjs (from server/; run_suites.sh runs it when node exists)
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const { displayNumbers, snapDisplay, resolveDrop, placementOk, touches } = await import(path.join(here, '../../sdk/displaylayout.js'));
+
+let n = 0, bad = 0;
+const eq = (name, got, want) => {
+ n++;
+ const g = JSON.stringify(got), w = JSON.stringify(want);
+ if (g !== w) { bad++; console.log(`✗ ${name}: want ${w}, got ${g}`); }
+};
+const ok = (name, v) => eq(name, !!v, true);
+const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
+
+// ---- numbers ----
+eq('numbers: main first, then list order', displayNumbers([
+ { id: 40, active: true, w: 1280 }, { id: 41, active: true, w: 1920, main: true }, { id: 42, active: false }, { id: 43, active: true, w: 800 },
+]), { 41: 1, 40: 2, 43: 3 });
+eq('numbers: one display', displayNumbers([{ id: 7, active: true, w: 1280, main: true }]), { 7: 1 });
+eq('numbers: nothing', displayNumbers(null), {});
+
+// ---- touching ----
+const A = { x: 0, y: 0, w: 1280, h: 800 };
+ok('side by side touches', touches(A, { x: 1280, y: 0, w: 100, h: 100 }));
+ok('stacked touches', touches(A, { x: 100, y: 800, w: 100, h: 100 }));
+eq('a corner alone does not touch', touches(A, { x: 1280, y: 800, w: 100, h: 100 }), false);
+eq('a gap does not touch', touches(A, { x: 1281, y: 0, w: 100, h: 100 }), false);
+
+// ---- snapping while dragging (threshold 120 logical px ≈ 12 preview px at k = 0.1) ----
+const two = [A, { x: 1280, y: 0, w: 1920, h: 1080 }];
+const T = 120;
+eq('near the right edge, slightly low: edge to edge, tops aligned', snapDisplay(two, 1, 1330, 60, T), { x: 1280, y: 0 });
+eq('bottoms aligned when closer than tops', snapDisplay(two, 1, 1300, -250, T), { x: 1280, y: -280 });
+eq('centers aligned', snapDisplay(two, 1, 1290, -130, T), { x: 1280, y: -140 });
+eq('left of it', snapDisplay(two, 1, -1900, 10, T), { x: -1920, y: 0 });
+eq('below it, lefts aligned', snapDisplay(two, 1, 50, 850, T), { x: 0, y: 800 });
+eq('below it, centered', snapDisplay(two, 1, -300, 820, T), { x: -320, y: 800 });
+eq('far away: no snap', snapDisplay(two, 1, 3000, 3000, T), { x: 3000, y: 3000 });
+eq('far below: x does not stick to its side', snapDisplay(two, 1, 1300, 2000, T), { x: 1300, y: 2000 });
+
+// ---- drop: always touching, never overlapping ----
+const valid = (rects, i, p) => placementOk(rects, i, p.x, p.y);
+eq('valid snapped drop is kept', resolveDrop(two, 1, 1330, 60, T), { x: 1280, y: 0 });
+const p1 = resolveDrop(two, 1, 400, 200, T); // dropped on top of the main display
+ok('dropped on top: valid', valid(two, 1, p1));
+const p2 = resolveDrop(two, 1, 4000, 3000, T); // dropped in empty space
+ok('dropped far away: valid', valid(two, 1, p2));
+eq('dropped far away: lands at the nearest corner region', p2, { x: 1280, y: 799 });
+const p3 = resolveDrop(two, 1, 1280, 900, 0); // corner-only touch, no snapping
+ok('corner only: slides to share an edge', valid(two, 1, p3));
+eq('diagonal offset allowed while edges touch', resolveDrop(two, 1, 1280, 500, 0), { x: 1280, y: 500 });
+// three displays in a row: dropping the third into the middle one slides it out
+const three = [A, { x: 1280, y: 0, w: 1920, h: 1080 }, { x: 3200, y: 0, w: 1024, h: 768 }];
+const p4 = resolveDrop(three, 2, 1500, 100, T);
+ok('three: valid', valid(three, 2, p4));
+for (let j = 0; j < 2; j++) eq(`three: no overlap with ${j}`, overlap({ ...p4, w: 1024, h: 768 }, three[j]), false);
+// stacked under the main one, centered
+eq('stacked, centered', resolveDrop(two, 1, -310, 805, T), { x: -320, y: 800 });
+
+// a sweep: every drop over a grid is valid, for 2 and 3 displays and both thresholds
+let sweepBad = 0;
+for (const [rects, i] of [[two, 1], [two, 0], [three, 2], [three, 1], [three, 0]]) {
+ for (let x = -5000; x <= 6000; x += 173) {
+ for (let y = -3000; y <= 3000; y += 157) {
+ for (const th of [0, T]) {
+ const p = resolveDrop(rects, i, x, y, th);
+ if (!valid(rects, i, p) || !Number.isInteger(p.x) || !Number.isInteger(p.y)) sweepBad++;
+ }
+ }
+ }
+}
+eq('sweep: every drop touches and never overlaps', sweepBad, 0);
+
+console.log(`display-layout: ${n - bad}/${n} checks passed`);
+process.exit(bad ? 1 : 0);
diff --git a/server/tests/outputs_test.c b/server/tests/outputs_test.c
index 29b7a9c..3d6036e 100644
--- a/server/tests/outputs_test.c
+++ b/server/tests/outputs_test.c
@@ -130,6 +130,28 @@ static void arrange_tests(void) {
ORect g[2] = { { 0, 0, 1024, 768 }, { 1280, 0, 1920, 1080 } };
out_fix(g, 2);
CHECK(g[1].x == 1024 && g[1].y == 0);
+ /* fits: Settings' drops (sdk/displaylayout.js) touch an edge and overlap nothing */
+ ORect q[2] = { { 0, 0, 1280, 800 }, { 0, 0, 1920, 1080 } };
+ CHECK(out_fits(q, 2, 1, 1280, 0));
+ CHECK(out_fits(q, 2, 1, 1280, 799)); /* one shared pixel */
+ CHECK(out_fits(q, 2, 1, -320, 800)); /* stacked, centered */
+ CHECK(!out_fits(q, 2, 1, 1280, 800)); /* a corner only */
+ CHECK(!out_fits(q, 2, 1, 1281, 0)); /* a gap */
+ CHECK(!out_fits(q, 2, 1, 1000, 0)); /* overlapping */
+ /* such a position is kept exactly by out_snap without alignment (display_arrange uses snap 0) */
+ out_snap(q, 2, 1, -320, 800, 0, &x, &y);
+ CHECK(x == -320 && y == 800);
+ out_snap(q, 2, 1, 1280, 500, 0, &x, &y);
+ CHECK(x == 1280 && y == 500);
+ /* valid: joined through shared edges; a chain main ← 2 ← 1 is kept by out_fix */
+ ORect c[3] = { { 0, 0, 1280, 800 }, { 3200, 0, 1024, 768 }, { 1280, 0, 1920, 1080 } };
+ CHECK(out_valid(c, 3));
+ out_fix(c, 3);
+ CHECK(c[1].x == 3200 && c[1].y == 0 && c[2].x == 1280 && c[2].y == 0);
+ ORect gap[2] = { { 0, 0, 1280, 800 }, { 1300, 0, 1920, 1080 } };
+ CHECK(!out_valid(gap, 2));
+ ORect ov[2] = { { 0, 0, 1280, 800 }, { 1200, 0, 1920, 1080 } };
+ CHECK(!out_valid(ov, 2));
/* normalize: the arrangement's corner becomes (0, 0) */
ORect n[2] = { { 0, 0, 1280, 800 }, { -2560, -200, 2560, 1440 } };
int bw, bh;
diff --git a/server/tests/run_suites.sh b/server/tests/run_suites.sh
index 8eee4bc..8ab105b 100644
--- a/server/tests/run_suites.sh
+++ b/server/tests/run_suites.sh
@@ -174,6 +174,9 @@ EOF
# (0.8.5) System Information's model (apps/sysinfo/model.js): GPU layers, CPU reasons, Compatibility
if have node; then run "sysinfo-model-test (apps/sysinfo/model.js)" node tests/sysinfo_model_test.mjs
else skip "sysinfo-model-test" "node"; fi
+ # (0.8.5) Settings → Displays' arrangement (sdk/displaylayout.js): numbers, magnetic snap, valid drops
+ if have node; then run "display-layout-test (sdk/displaylayout.js)" node tests/display_layout_test.mjs
+ else skip "display-layout-test" "node"; fi
}
full() {